title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What is the digest cycle in AngularJs?
28 May, 2020 AngularJs watch: It is provided by AngularJs Framework to keep track of scope variables and the change in their values. Watches are automatically created by AngularJs Framework. It is usually done for data bindings and for which variables are decided by AngularJs Framework. Custom functions that are created for watches are called watch listeners. Watch counts: If watch count is below 2000, performance is better. We may use Angular watchers extension to count them. Angular performs watching on data-binded variables but if we want we can perform watch on normal variables as well, using watch function. It takes parameter the variable that we explicitly want to watch. Watch list: Maintains a list of all the watches associated with an angular application. i.e all the data bindings being monitored. A watch list is maintained for all scopes including root. Digest cycle Watch listeners are automatically executed whenever the digest process finds any modifications in the variables. It keeps note of changes and then notifies AngularJs Framework to update DOM. Thus at the end of every digest process, DOM is updated. Angular Context is a runtime environment of AngularJs Framework. First digest process performs a dirty check on watches, and checks if there are any modificationsIt again performs the second cycle of dirty checking on the previous cycle, watches listeners. Because there may have been variables that have got changed by others. Minimum 2 iterations are performed and the maximum 10 can run. Although it is preferred to minimize the digest cycle for better performance. Error is thrown after maximum. First level and second level updating First level updates: Suppose the variable b was updated by any event, then during the first cycle Digest cycle informs the AngularJs Framework about the changes and goes through the second cycle after that. Since there are no more updates, it thus updates DOM and completes it. Second level watch updates: Whenever there is a change encountered in the first cycle for any particular watch say c, digest process executes watch listener for it. Now watch listener further modifies variable a to a new value. After the first cycle, c gets updated. During the second cycle, we encounter changes in a and thus update takes place for a. Now a third cycle takes place and there are no more modifications encountered. DOM gets updated.An example for second level updates:$scope.a = 1;$scope.b = 2;$scope.c = 3; $scope.$watch('a', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("a is modified to " +newValue );}}); $scope.$watch('b', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("b is modified to " +newValue );}}); $scope.$watch('c', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("c is modified to " +newValue ); if( $scope.c > 50 ) { $scope.a = 1000; }}}); $rootscope.$watch( function() { console.log(" digest iteration started ");});Considering scope variables a, b, c are data binded and are eligible for the digest process. If we inspect the angular application in the browser and open the console. We can track the changes as the print statements will help us. Suppose there was a two way binding for c with an input box we could easily track the number of times it gets modified. In fact, we can inspect the digest process too, by applying $watch function on $rootscope.$watch: This function takes three parameters- watch expression, listener and object equality. Except for expression the other two are optional. $scope.a = 1;$scope.b = 2;$scope.c = 3; $scope.$watch('a', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("a is modified to " +newValue );}}); $scope.$watch('b', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("b is modified to " +newValue );}}); $scope.$watch('c', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log("c is modified to " +newValue ); if( $scope.c > 50 ) { $scope.a = 1000; }}}); $rootscope.$watch( function() { console.log(" digest iteration started ");}); Considering scope variables a, b, c are data binded and are eligible for the digest process. If we inspect the angular application in the browser and open the console. We can track the changes as the print statements will help us. Suppose there was a two way binding for c with an input box we could easily track the number of times it gets modified. In fact, we can inspect the digest process too, by applying $watch function on $rootscope.$watch: This function takes three parameters- watch expression, listener and object equality. Except for expression the other two are optional. The digest process starts with the root scope and later on identifies the other scopes. If our code uses DOM events (ng-click), ajax with callback, timer with callback, Browser location changes, manual invocations like $apply then it is bound to have Digest process for all of them. As we know, the browser is responsible to render the DOM and it may have events like Timer, On-click. The browser maintains a queue for these events called Event Queue. And it sends those to Javascript. Consequently, a digest takes place for them. If events are not related to Javascript i.e written in Jquery or other languages, then it is our duty to write $apply function for maintaining digest for them.$scope.$apply(function() { }); $scope.$apply(function() { }); Complete scenario of Digest cycle: AngularJS-Misc Picked AngularJS 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": "\n28 May, 2020" }, { "code": null, "e": 377, "s": 28, "text": "AngularJs watch: It is provided by AngularJs Framework to keep track of scope variables and the change in their values. Watches are automatically created by AngularJs Framework. It is usually done for data bindings and for which variables are decided by AngularJs Framework. Custom functions that are created for watches are called watch listeners." }, { "code": null, "e": 701, "s": 377, "text": "Watch counts: If watch count is below 2000, performance is better. We may use Angular watchers extension to count them. Angular performs watching on data-binded variables but if we want we can perform watch on normal variables as well, using watch function. It takes parameter the variable that we explicitly want to watch." }, { "code": null, "e": 890, "s": 701, "text": "Watch list: Maintains a list of all the watches associated with an angular application. i.e all the data bindings being monitored. A watch list is maintained for all scopes including root." }, { "code": null, "e": 903, "s": 890, "text": "Digest cycle" }, { "code": null, "e": 1151, "s": 903, "text": "Watch listeners are automatically executed whenever the digest process finds any modifications in the variables. It keeps note of changes and then notifies AngularJs Framework to update DOM. Thus at the end of every digest process, DOM is updated." }, { "code": null, "e": 1216, "s": 1151, "text": "Angular Context is a runtime environment of AngularJs Framework." }, { "code": null, "e": 1651, "s": 1216, "text": "First digest process performs a dirty check on watches, and checks if there are any modificationsIt again performs the second cycle of dirty checking on the previous cycle, watches listeners. Because there may have been variables that have got changed by others. Minimum 2 iterations are performed and the maximum 10 can run. Although it is preferred to minimize the digest cycle for better performance. Error is thrown after maximum." }, { "code": null, "e": 1689, "s": 1651, "text": "First level and second level updating" }, { "code": null, "e": 1967, "s": 1689, "text": "First level updates: Suppose the variable b was updated by any event, then during the first cycle Digest cycle informs the AngularJs Framework about the changes and goes through the second cycle after that. Since there are no more updates, it thus updates DOM and completes it." }, { "code": null, "e": 3696, "s": 1967, "text": "Second level watch updates: Whenever there is a change encountered in the first cycle for any particular watch say c, digest process executes watch listener for it. Now watch listener further modifies variable a to a new value. After the first cycle, c gets updated. During the second cycle, we encounter changes in a and thus update takes place for a. Now a third cycle takes place and there are no more modifications encountered. DOM gets updated.An example for second level updates:$scope.a = 1;$scope.b = 2;$scope.c = 3; $scope.$watch('a', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"a is modified to \" +newValue );}}); $scope.$watch('b', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"b is modified to \" +newValue );}}); $scope.$watch('c', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"c is modified to \" +newValue ); if( $scope.c > 50 ) { $scope.a = 1000; }}}); $rootscope.$watch( function() { console.log(\" digest iteration started \");});Considering scope variables a, b, c are data binded and are eligible for the digest process. If we inspect the angular application in the browser and open the console. We can track the changes as the print statements will help us. Suppose there was a two way binding for c with an input box we could easily track the number of times it gets modified. In fact, we can inspect the digest process too, by applying $watch function on $rootscope.$watch: This function takes three parameters- watch expression, listener and object equality. Except for expression the other two are optional." }, { "code": "$scope.a = 1;$scope.b = 2;$scope.c = 3; $scope.$watch('a', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"a is modified to \" +newValue );}}); $scope.$watch('b', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"b is modified to \" +newValue );}}); $scope.$watch('c', function( newValue, oldValue ) { if( newValue != oldValue ) { console.log(\"c is modified to \" +newValue ); if( $scope.c > 50 ) { $scope.a = 1000; }}}); $rootscope.$watch( function() { console.log(\" digest iteration started \");});", "e": 4356, "s": 3696, "text": null }, { "code": null, "e": 4941, "s": 4356, "text": "Considering scope variables a, b, c are data binded and are eligible for the digest process. If we inspect the angular application in the browser and open the console. We can track the changes as the print statements will help us. Suppose there was a two way binding for c with an input box we could easily track the number of times it gets modified. In fact, we can inspect the digest process too, by applying $watch function on $rootscope.$watch: This function takes three parameters- watch expression, listener and object equality. Except for expression the other two are optional." }, { "code": null, "e": 5224, "s": 4941, "text": "The digest process starts with the root scope and later on identifies the other scopes. If our code uses DOM events (ng-click), ajax with callback, timer with callback, Browser location changes, manual invocations like $apply then it is bound to have Digest process for all of them." }, { "code": null, "e": 5667, "s": 5224, "text": "As we know, the browser is responsible to render the DOM and it may have events like Timer, On-click. The browser maintains a queue for these events called Event Queue. And it sends those to Javascript. Consequently, a digest takes place for them. If events are not related to Javascript i.e written in Jquery or other languages, then it is our duty to write $apply function for maintaining digest for them.$scope.$apply(function() { \n}); " }, { "code": null, "e": 5703, "s": 5667, "text": "$scope.$apply(function() { \n}); " }, { "code": null, "e": 5738, "s": 5703, "text": "Complete scenario of Digest cycle:" }, { "code": null, "e": 5753, "s": 5738, "text": "AngularJS-Misc" }, { "code": null, "e": 5760, "s": 5753, "text": "Picked" }, { "code": null, "e": 5770, "s": 5760, "text": "AngularJS" }, { "code": null, "e": 5787, "s": 5770, "text": "Web Technologies" } ]
C# | ToolTip Class
05 Sep, 2019 In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you place your pointer or cursor on the control and the purpose of this control is it provides a brief description about the control present in the windows form. The ToolTip class is used to create ToolTip control and also provide different types of properties, methods, events and also provides run time status of the controls.You are allowed to use a ToolTip class in any container or control. With the help of a single ToolTip component, you are allowed to create multiple tooltips for multiple controls. the ToolTip class defined under System.Windows.Forms namespace. In C# you can create a ToolTip in the windows form by using two different ways: 1. Design-Time: It is the easiest way to create a ToolTip as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ToolTip from the ToolBox and drop it on the form. When you drag and drop this ToolTip on the form it will automatically add to the properties(named as ToolTip on ToolTip1) of every controls present in the current windows from. Step 3: After drag and drop you will go to the properties of the ToolTip control to modify ToolTip according to your requirement.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a ToolTip control programmatically with the help of syntax provided by the ToolTip class. The following steps show how to set the create ToolTip dynamically: Step 1: Create a ToolTip control using the ToolTip() constructor is provided by the ToolTip class.// Creating a ToolTip control ToolTip t_Tip = new ToolTip(); // Creating a ToolTip control ToolTip t_Tip = new ToolTip(); Step 2: After creating ToolTip control, set the property of the ToolTip control provided by the ToolTip class.// Seting the properties of ToolTip t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, "Name should start with Capital letter"); t_Tip.SetToolTip(box2, "Password should be greater than 8 words"); 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 WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = "Name"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = "Password"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t_Tip = new ToolTip(); t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, "Name should start with Capital letter"); t_Tip.SetToolTip(box2, "Password should be greater than 8 words"); }}}Output: // Seting the properties of ToolTip t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, "Name should start with Capital letter"); t_Tip.SetToolTip(box2, "Password should be greater than 8 words"); 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 WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = "Name"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = "Password"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t_Tip = new ToolTip(); t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, "Name should start with Capital letter"); t_Tip.SetToolTip(box2, "Password should be greater than 8 words"); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2019" }, { "code": null, "e": 758, "s": 28, "text": "In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you place your pointer or cursor on the control and the purpose of this control is it provides a brief description about the control present in the windows form. The ToolTip class is used to create ToolTip control and also provide different types of properties, methods, events and also provides run time status of the controls.You are allowed to use a ToolTip class in any container or control. With the help of a single ToolTip component, you are allowed to create multiple tooltips for multiple controls. the ToolTip class defined under System.Windows.Forms namespace. In C# you can create a ToolTip in the windows form by using two different ways:" }, { "code": null, "e": 849, "s": 758, "text": "1. Design-Time: It is the easiest way to create a ToolTip as shown in the following steps:" }, { "code": null, "e": 965, "s": 849, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1209, "s": 965, "text": "Step 2: Drag the ToolTip from the ToolBox and drop it on the form. When you drag and drop this ToolTip on the form it will automatically add to the properties(named as ToolTip on ToolTip1) of every controls present in the current windows from." }, { "code": null, "e": 1346, "s": 1209, "text": "Step 3: After drag and drop you will go to the properties of the ToolTip control to modify ToolTip according to your requirement.Output:" }, { "code": null, "e": 1354, "s": 1346, "text": "Output:" }, { "code": null, "e": 1607, "s": 1354, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a ToolTip control programmatically with the help of syntax provided by the ToolTip class. The following steps show how to set the create ToolTip dynamically:" }, { "code": null, "e": 1768, "s": 1607, "text": "Step 1: Create a ToolTip control using the ToolTip() constructor is provided by the ToolTip class.// Creating a ToolTip control\nToolTip t_Tip = new ToolTip(); \n" }, { "code": null, "e": 1831, "s": 1768, "text": "// Creating a ToolTip control\nToolTip t_Tip = new ToolTip(); \n" }, { "code": null, "e": 4212, "s": 1831, "text": "Step 2: After creating ToolTip control, set the property of the ToolTip control provided by the ToolTip class.// Seting the properties of ToolTip\nt_Tip.Active = true; \nt_Tip.AutoPopDelay = 4000; \nt_Tip.InitialDelay = 600; \nt_Tip.IsBalloon = true; \nt_Tip.ToolTipIcon = ToolTipIcon.Info; \nt_Tip.SetToolTip(box1, \"Name should start with Capital letter\"); \nt_Tip.SetToolTip(box2, \"Password should be greater than 8 words\"); \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 WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = \"Name\"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = \"Password\"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t_Tip = new ToolTip(); t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, \"Name should start with Capital letter\"); t_Tip.SetToolTip(box2, \"Password should be greater than 8 words\"); }}}Output:" }, { "code": null, "e": 4524, "s": 4212, "text": "// Seting the properties of ToolTip\nt_Tip.Active = true; \nt_Tip.AutoPopDelay = 4000; \nt_Tip.InitialDelay = 600; \nt_Tip.IsBalloon = true; \nt_Tip.ToolTipIcon = ToolTipIcon.Info; \nt_Tip.SetToolTip(box1, \"Name should start with Capital letter\"); \nt_Tip.SetToolTip(box2, \"Password should be greater than 8 words\"); \n" }, { "code": null, "e": 4533, "s": 4524, "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 WindowsFormsApp34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(140, 122); l1.Text = \"Name\"; // Adding this Label // control to the form this.Controls.Add(l1); // Creating and setting the // properties of the TextBox TextBox box1 = new TextBox(); box1.Location = new Point(248, 119); box1.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(140, 152); l2.Text = \"Password\"; // Adding this Label // control to the form this.Controls.Add(l2); // Creating and setting the // properties of the TextBox TextBox box2 = new TextBox(); box2.Location = new Point(248, 145); box2.BorderStyle = BorderStyle.FixedSingle; // Adding this TextBox // control to the form this.Controls.Add(box2); // Creating and setting the // properties of the ToolTip ToolTip t_Tip = new ToolTip(); t_Tip.Active = true; t_Tip.AutoPopDelay = 4000; t_Tip.InitialDelay = 600; t_Tip.IsBalloon = true; t_Tip.ToolTipIcon = ToolTipIcon.Info; t_Tip.SetToolTip(box1, \"Name should start with Capital letter\"); t_Tip.SetToolTip(box2, \"Password should be greater than 8 words\"); }}}", "e": 6478, "s": 4533, "text": null }, { "code": null, "e": 6486, "s": 6478, "text": "Output:" }, { "code": null, "e": 6517, "s": 6486, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 6520, "s": 6517, "text": "C#" } ]
JavaScript | Check the existence of variable
30 Aug, 2021 JavaScript has a built-in function to check whether a variable is defined/initialized or undefined.Note: The typeof operator will check whether a variable is defined or not. The typeof operator doesn’t throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object. So, check for null also. Example 1: This example checks whether a variable is defined or not. html <!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick="myGeeks()"> Check </button> <h3 id = "div" style="color:green;"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var; var h3 = document.getElementById("div"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = "Variable is Undefined"; } else { h3.innerHTML = "Variable is defined and" + " value is " + GFG_Var; } } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example also checks whether a variable is defined or not. html <!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick="myGeeks()"> Check </button> <h3 id = "div" style="color:green;"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var = "GFG"; var h3 = document.getElementById("div"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = "Variable is Undefined"; } else { h3.innerHTML = "Variable is defined and" + " value is " + GFG_Var; } } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 3: The previous example doesn’t check for null value of variable. This example also checks a variable is null or not. html <!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick="myGeeks()"> Check </button> <h3 id = "div" style="color:green;"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var = null; var h3 = document.getElementById("div"); if (typeof GFG_Var === 'undefined' || GFG_Var === null ) { h3.innerHTML = "Variable is Undefined"; } else { h3.innerHTML = "Variable is defined and value is " + GFG_Var; } } </script></body> </html> Output: Before clicking the button: After clicking the button: ruhelaa48 javascript-basics JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Aug, 2021" }, { "code": null, "e": 159, "s": 52, "text": "JavaScript has a built-in function to check whether a variable is defined/initialized or undefined.Note: " }, { "code": null, "e": 228, "s": 159, "text": "The typeof operator will check whether a variable is defined or not." }, { "code": null, "e": 334, "s": 228, "text": "The typeof operator doesn’t throw a ReferenceError exception when it is used with an undeclared variable." }, { "code": null, "e": 398, "s": 334, "text": "The typeof null will return an object. So, check for null also." }, { "code": null, "e": 469, "s": 398, "text": "Example 1: This example checks whether a variable is defined or not. " }, { "code": null, "e": 474, "s": 469, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick=\"myGeeks()\"> Check </button> <h3 id = \"div\" style=\"color:green;\"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var; var h3 = document.getElementById(\"div\"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = \"Variable is Undefined\"; } else { h3.innerHTML = \"Variable is defined and\" + \" value is \" + GFG_Var; } } </script></body> </html> ", "e": 1373, "s": 474, "text": null }, { "code": null, "e": 1383, "s": 1373, "text": "Output: " }, { "code": null, "e": 1413, "s": 1383, "text": "Before clicking the button: " }, { "code": null, "e": 1442, "s": 1413, "text": "After clicking the button: " }, { "code": null, "e": 1518, "s": 1442, "text": "Example 2: This example also checks whether a variable is defined or not. " }, { "code": null, "e": 1523, "s": 1518, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick=\"myGeeks()\"> Check </button> <h3 id = \"div\" style=\"color:green;\"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var = \"GFG\"; var h3 = document.getElementById(\"div\"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = \"Variable is Undefined\"; } else { h3.innerHTML = \"Variable is defined and\" + \" value is \" + GFG_Var; } } </script></body> </html> ", "e": 2426, "s": 1523, "text": null }, { "code": null, "e": 2436, "s": 2426, "text": "Output: " }, { "code": null, "e": 2466, "s": 2436, "text": "Before clicking the button: " }, { "code": null, "e": 2495, "s": 2466, "text": "After clicking the button: " }, { "code": null, "e": 2623, "s": 2495, "text": "Example 3: The previous example doesn’t check for null value of variable. This example also checks a variable is null or not. " }, { "code": null, "e": 2628, "s": 2623, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript to check existence of variable </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p> variable-name : GFG_Var </p> <button onclick=\"myGeeks()\"> Check </button> <h3 id = \"div\" style=\"color:green;\"></h3> <!-- Script to check existence of variable --> <script> function myGeeks() { var GFG_Var = null; var h3 = document.getElementById(\"div\"); if (typeof GFG_Var === 'undefined' || GFG_Var === null ) { h3.innerHTML = \"Variable is Undefined\"; } else { h3.innerHTML = \"Variable is defined and value is \" + GFG_Var; } } </script></body> </html> ", "e": 3547, "s": 2628, "text": null }, { "code": null, "e": 3557, "s": 3547, "text": "Output: " }, { "code": null, "e": 3587, "s": 3557, "text": "Before clicking the button: " }, { "code": null, "e": 3616, "s": 3587, "text": "After clicking the button: " }, { "code": null, "e": 3628, "s": 3618, "text": "ruhelaa48" }, { "code": null, "e": 3646, "s": 3628, "text": "javascript-basics" }, { "code": null, "e": 3657, "s": 3646, "text": "JavaScript" }, { "code": null, "e": 3674, "s": 3657, "text": "Web Technologies" }, { "code": null, "e": 3701, "s": 3674, "text": "Web technologies Questions" }, { "code": null, "e": 3799, "s": 3701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3860, "s": 3799, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3932, "s": 3860, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3972, "s": 3932, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4014, "s": 3972, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4055, "s": 4014, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4088, "s": 4055, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4150, "s": 4088, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4211, "s": 4150, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4261, "s": 4211, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
The yield Keyword in Ruby
18 Oct, 2019 We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method. Simple Yield: When the yield keyword used inside the body of a method, will allow us to call that method with a block of code. Below is simple yield program to understand. # Ruby program of using yield keyworddef geeks puts "In the geeks method" # using yield keyword yield puts "Again back to the geeks method" yieldendgeeks {puts "This is block"} Output: In the geeks method This is block Again back to the geeks method This is block Yield with argument: Below is the program of yield with argument. # Ruby program of using yield keyword # with argumentdef gfg yield 2*3 puts "In the method gfg" yield 100endgfg {|i| puts "block #{i}"} Output : block 6 In the method gfg block 100 In above example, the yield statement is written followed by parameters. we can even pass more than one parameter after yield. To accept the parameters we placed a variable(i) between two vertical lines (||). Yield with Return value: It is possible to get the return value of a block by simply assigning the return value of a yield to a variable. if we use yield with an argument, it will pass that argument to the block. # Ruby program of using yield keyword# with return valuedef yield_with_return_value geeks_for_geeks = yield puts geeks_for_geeksend yield_with_return_value { "Welcome to geeksforgeeks" } Output: Welcome to geeksforgeeks The geeks_for_geeks variable get the “Welcome to geeksforgeeks” returned by the block and display it by using puts. Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 490, "s": 28, "text": "We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method." }, { "code": null, "e": 662, "s": 490, "text": "Simple Yield: When the yield keyword used inside the body of a method, will allow us to call that method with a block of code. Below is simple yield program to understand." }, { "code": "# Ruby program of using yield keyworddef geeks puts \"In the geeks method\" # using yield keyword yield puts \"Again back to the geeks method\" yieldendgeeks {puts \"This is block\"}", "e": 851, "s": 662, "text": null }, { "code": null, "e": 859, "s": 851, "text": "Output:" }, { "code": null, "e": 938, "s": 859, "text": "In the geeks method\nThis is block\nAgain back to the geeks method\nThis is block" }, { "code": null, "e": 1005, "s": 938, "text": " Yield with argument: Below is the program of yield with argument." }, { "code": "# Ruby program of using yield keyword # with argumentdef gfg yield 2*3 puts \"In the method gfg\" yield 100endgfg {|i| puts \"block #{i}\"}", "e": 1147, "s": 1005, "text": null }, { "code": null, "e": 1156, "s": 1147, "text": "Output :" }, { "code": null, "e": 1192, "s": 1156, "text": "block 6\nIn the method gfg\nblock 100" }, { "code": null, "e": 1401, "s": 1192, "text": "In above example, the yield statement is written followed by parameters. we can even pass more than one parameter after yield. To accept the parameters we placed a variable(i) between two vertical lines (||)." }, { "code": null, "e": 1614, "s": 1401, "text": "Yield with Return value: It is possible to get the return value of a block by simply assigning the return value of a yield to a variable. if we use yield with an argument, it will pass that argument to the block." }, { "code": "# Ruby program of using yield keyword# with return valuedef yield_with_return_value geeks_for_geeks = yield puts geeks_for_geeksend yield_with_return_value { \"Welcome to geeksforgeeks\" } ", "e": 1807, "s": 1614, "text": null }, { "code": null, "e": 1815, "s": 1807, "text": "Output:" }, { "code": null, "e": 1840, "s": 1815, "text": "Welcome to geeksforgeeks" }, { "code": null, "e": 1956, "s": 1840, "text": "The geeks_for_geeks variable get the “Welcome to geeksforgeeks” returned by the block and display it by using puts." }, { "code": null, "e": 1961, "s": 1956, "text": "Ruby" } ]
Process Synchronization in C/C++
Process synchronization is the technique to overcome the problem of concurrent access to shared data which can result in data inconsistency. A cooperating process is the one which can affect or be affected by other process which will lead to inconsistency in processes data therefore Process synchronization is required for consistency of data. Every process has a reserved segment of code which is known as Critical Section. In this section, process can change common variables, update tables, write files, etc. The key point to note about critical section is that when one process is executing in its critical section, no other process can execute in its critical section. Each process must request for permission before entering into its critical section and the section of a code implementing this request is the Entry Section, the end of the code is the Exit Section and the remaining code is the remainder section. Given below is the structure of a critical section of a particular process P1 There are three requirements that must be satisfied for a critical section Mutual Exclusion − If one process let’s say P1 is executing in its critical section than any other process let’s say P2 can’t execute in its critical section. Progress − If there is no process executing in its critical section and there are processes who wants to enter in its critical section, then only those processes who are not executing in their remainder section can request to enter the critical section and the selection can be postponed indefinitely. Bounded Waiting − In bounded waiting, there are limits or bounds on the number of times a process can enter its critical section after a process has made a request to enter its critical section and before that request is granted. There are two approaches that are commonly used in operating system to handle critical section. Preemptive Kernel − A preemptive kernel allows a process to be preempted while it is running in kernel mode. Non-Preemptive Kernels − A non-preemptive kernel doesn’t allow a process running in kernel mode to be preempted. Peterson’s solution is a classic based software solution to the critical-section problem. It is restricted to two processes that alternate execution between their critical sections and remainder sections. Peterson’ section requires two data items to be shared between the two processes i.e. Int turn; Boolean flag[2]; Here, variable turn indicates whose turn is to enter its critical section and flag array indicated whether the process is ready to enter its critical section. If turn == i, it means process Pi is allowed to enter in its critical section. If flag[j] is TRUE, it means process j is ready to enter in its critical section Given below is the structure of process P in Peterson’s solution Peterson’s Solution preserves all three conditions − Mutual Exclusion − one process at a time can access the critical section. Progress − A process outside the critical section does not block other processes from entering the critical section. Bounded Waiting − Every process will get a chance to enter its critical section without waiting indefinitely. It is implemented using two types of instructions − Test and Set() swap() Test and Set () is a hardware solution to solve the problem of synchronization. In this, there is a shared variable which is shared by multiple processes known as Lock which can have one value from 0 and 1 where 1 represents Lock gained and 0 represents Lock released. Whenever the process is trying to enter their critical sections they need to enquire about the value of lock. If the value of lock is 1 then they have to wait until the value of lock won't get changed to 0. Given below is the mutual-exclusion implementation with TestAndSet() Semaphore is a synchronization tool that is used to overcome the problems generated by TestAndSet() and Swap() instructions. A semaphore S is an integer variable that can be accessed through two standard atomic operations that are wait() and signal() Function for wait(): wait(S) { While S <= 0 ; // no operation S--; } Function for Signal(): signal(S) { S++; } When one process is modifying the value of semaphore then no other process can simultaneously manipulate the same semaphore value. Given below is the mutual-exclusion implementation with semaphore Operating system use two types of semsphores that are − Counting Semaphore − the value of this type of semaphore can over an unrestricted domain Binary Semaphore − the value of this type of semaphore can over between 0 and 1. They are also known as Mutex Locks. Operating system makes use of this for resolving the issues with critical section in multiple processes.
[ { "code": null, "e": 1532, "s": 1187, "text": "Process synchronization is the technique to overcome the problem of concurrent access to shared data which can result in data inconsistency. A cooperating process is the one which can affect or be affected by other process which will lead to inconsistency in processes data therefore Process synchronization is required for consistency of data." }, { "code": null, "e": 2108, "s": 1532, "text": "Every process has a reserved segment of code which is known as Critical Section. In this section, process can change common variables, update tables, write files, etc. The key point to note about critical section is that when one process is executing in its critical section, no other process can execute in its critical section. Each process must request for permission before entering into its critical section and the section of a code implementing this request is the Entry Section, the end of the code is the Exit Section and the remaining code is the remainder section." }, { "code": null, "e": 2186, "s": 2108, "text": "Given below is the structure of a critical section of a particular process P1" }, { "code": null, "e": 2261, "s": 2186, "text": "There are three requirements that must be satisfied for a critical section" }, { "code": null, "e": 2420, "s": 2261, "text": "Mutual Exclusion − If one process let’s say P1 is executing in its critical section than any other process let’s say P2 can’t execute in its critical section." }, { "code": null, "e": 2722, "s": 2420, "text": "Progress − If there is no process executing in its critical section and there are processes who wants to enter in its critical section, then only those processes who are not executing in their remainder section can request to enter the critical section and the selection can be postponed indefinitely." }, { "code": null, "e": 2952, "s": 2722, "text": "Bounded Waiting − In bounded waiting, there are limits or bounds on the number of times a process can enter its critical section after a process has made a request to enter its critical section and before that request is granted." }, { "code": null, "e": 3048, "s": 2952, "text": "There are two approaches that are commonly used in operating system to handle critical section." }, { "code": null, "e": 3157, "s": 3048, "text": "Preemptive Kernel − A preemptive kernel allows a process to be preempted while it is running in kernel mode." }, { "code": null, "e": 3270, "s": 3157, "text": "Non-Preemptive Kernels − A non-preemptive kernel doesn’t allow a process running in kernel mode to be preempted." }, { "code": null, "e": 3561, "s": 3270, "text": "Peterson’s solution is a classic based software solution to the critical-section problem. It is restricted to two processes that alternate execution between their critical sections and remainder sections. Peterson’ section requires two data items to be shared between the two processes i.e." }, { "code": null, "e": 3571, "s": 3561, "text": "Int turn;" }, { "code": null, "e": 3588, "s": 3571, "text": "Boolean flag[2];" }, { "code": null, "e": 3747, "s": 3588, "text": "Here, variable turn indicates whose turn is to enter its critical section and flag array indicated whether the process is ready to enter its critical section." }, { "code": null, "e": 3826, "s": 3747, "text": "If turn == i, it means process Pi is allowed to enter in its critical section." }, { "code": null, "e": 3907, "s": 3826, "text": "If flag[j] is TRUE, it means process j is ready to enter in its critical section" }, { "code": null, "e": 3972, "s": 3907, "text": "Given below is the structure of process P in Peterson’s solution" }, { "code": null, "e": 4025, "s": 3972, "text": "Peterson’s Solution preserves all three conditions −" }, { "code": null, "e": 4099, "s": 4025, "text": "Mutual Exclusion − one process at a time can access the critical section." }, { "code": null, "e": 4216, "s": 4099, "text": "Progress − A process outside the critical section does not block other processes from entering the critical section." }, { "code": null, "e": 4326, "s": 4216, "text": "Bounded Waiting − Every process will get a chance to enter its critical section without waiting indefinitely." }, { "code": null, "e": 4378, "s": 4326, "text": "It is implemented using two types of instructions −" }, { "code": null, "e": 4393, "s": 4378, "text": "Test and Set()" }, { "code": null, "e": 4400, "s": 4393, "text": "swap()" }, { "code": null, "e": 4669, "s": 4400, "text": "Test and Set () is a hardware solution to solve the problem of synchronization. In this, there is a shared variable which is shared by multiple processes known as Lock which can have one value from 0 and 1 where 1 represents Lock gained and 0 represents Lock released." }, { "code": null, "e": 4876, "s": 4669, "text": "Whenever the process is trying to enter their critical sections they need to enquire about the value of lock. If the value of lock is 1 then they have to wait until the value of lock won't get changed to 0." }, { "code": null, "e": 4945, "s": 4876, "text": "Given below is the mutual-exclusion implementation with TestAndSet()" }, { "code": null, "e": 5196, "s": 4945, "text": "Semaphore is a synchronization tool that is used to overcome the problems generated by TestAndSet() and Swap() instructions. A semaphore S is an integer variable that can be accessed through two standard atomic operations that are wait() and signal()" }, { "code": null, "e": 5217, "s": 5196, "text": "Function for wait():" }, { "code": null, "e": 5274, "s": 5217, "text": "wait(S) {\n While S <= 0\n ; // no operation\n S--;\n}" }, { "code": null, "e": 5297, "s": 5274, "text": "Function for Signal():" }, { "code": null, "e": 5319, "s": 5297, "text": "signal(S) {\n S++;\n}" }, { "code": null, "e": 5450, "s": 5319, "text": "When one process is modifying the value of semaphore then no other process can simultaneously manipulate the same semaphore value." }, { "code": null, "e": 5516, "s": 5450, "text": "Given below is the mutual-exclusion implementation with semaphore" }, { "code": null, "e": 5572, "s": 5516, "text": "Operating system use two types of semsphores that are −" }, { "code": null, "e": 5661, "s": 5572, "text": "Counting Semaphore − the value of this type of semaphore can over an unrestricted domain" }, { "code": null, "e": 5883, "s": 5661, "text": "Binary Semaphore − the value of this type of semaphore can over between 0 and 1. They are also known as Mutex Locks. Operating system makes use of this for resolving the issues with critical section in multiple processes." } ]
Python | Zip different sized list
07 Feb, 2019 In Python, zipping is a utility where we pair one list with the other. Usually, this task is successful only in the cases when the sizes of both the lists to be zipped are of the same size. But sometimes we require that different sized lists also to be zipped. Let’s discuss certain ways in which this problem can be solved if it occurs. Method #1 : Using enumerate() + loopThis is the way in which we use the brute force method to achieve this particular task. In this process, we loop both the list and when one becomes larger than other we cycle the elements to begin them from the beginning. # Python3 code to demonstrate # zipping of two different size list # using enumerate() + loop # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using enumerate() + loop# zipping of two different size list res = []for i, j in enumerate(test_list1): res.append((j, test_list2[i % len(test_list2)])) # printing result print ("The zipped list is : " + str(res)) The original list 1 is : [7, 8, 4, 5, 9, 10] The original list 2 is : [1, 5, 6] The zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)] Method #2 : Using itertools.cycle()This is yet another way to perform this particular task, in this we cycle the smaller list so that it can begin zipping from beginning in case the smaller list gets exhausted using a zip function. # Python3 code to demonstrate # zipping of two different size list # using itertools.cycle()from itertools import cycle # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using itertools.cycle()# zipping of two different size list res = list(zip(test_list1, cycle(test_list2)) if len(test_list1) > len(test_list2) else zip(cycle(test_list1), test_list2)) # printing result print ("The zipped list is : " + str(res)) The original list 1 is : [7, 8, 4, 5, 9, 10] The original list 2 is : [1, 5, 6] The zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2019" }, { "code": null, "e": 366, "s": 28, "text": "In Python, zipping is a utility where we pair one list with the other. Usually, this task is successful only in the cases when the sizes of both the lists to be zipped are of the same size. But sometimes we require that different sized lists also to be zipped. Let’s discuss certain ways in which this problem can be solved if it occurs." }, { "code": null, "e": 624, "s": 366, "text": "Method #1 : Using enumerate() + loopThis is the way in which we use the brute force method to achieve this particular task. In this process, we loop both the list and when one becomes larger than other we cycle the elements to begin them from the beginning." }, { "code": "# Python3 code to demonstrate # zipping of two different size list # using enumerate() + loop # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using enumerate() + loop# zipping of two different size list res = []for i, j in enumerate(test_list1): res.append((j, test_list2[i % len(test_list2)])) # printing result print (\"The zipped list is : \" + str(res))", "e": 1149, "s": 624, "text": null }, { "code": null, "e": 1301, "s": 1149, "text": "The original list 1 is : [7, 8, 4, 5, 9, 10]\nThe original list 2 is : [1, 5, 6]\nThe zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]\n" }, { "code": null, "e": 1534, "s": 1301, "text": " Method #2 : Using itertools.cycle()This is yet another way to perform this particular task, in this we cycle the smaller list so that it can begin zipping from beginning in case the smaller list gets exhausted using a zip function." }, { "code": "# Python3 code to demonstrate # zipping of two different size list # using itertools.cycle()from itertools import cycle # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using itertools.cycle()# zipping of two different size list res = list(zip(test_list1, cycle(test_list2)) if len(test_list1) > len(test_list2) else zip(cycle(test_list1), test_list2)) # printing result print (\"The zipped list is : \" + str(res))", "e": 2135, "s": 1534, "text": null }, { "code": null, "e": 2287, "s": 2135, "text": "The original list 1 is : [7, 8, 4, 5, 9, 10]\nThe original list 2 is : [1, 5, 6]\nThe zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]\n" }, { "code": null, "e": 2308, "s": 2287, "text": "Python list-programs" }, { "code": null, "e": 2320, "s": 2308, "text": "python-list" }, { "code": null, "e": 2327, "s": 2320, "text": "Python" }, { "code": null, "e": 2343, "s": 2327, "text": "Python Programs" }, { "code": null, "e": 2355, "s": 2343, "text": "python-list" }, { "code": null, "e": 2453, "s": 2355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2471, "s": 2453, "text": "Python Dictionary" }, { "code": null, "e": 2513, "s": 2471, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2548, "s": 2513, "text": "Read a file line by line in Python" }, { "code": null, "e": 2574, "s": 2548, "text": "Python String | replace()" }, { "code": null, "e": 2606, "s": 2574, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2649, "s": 2606, "text": "Python program to convert a list to string" }, { "code": null, "e": 2671, "s": 2649, "text": "Defaultdict in Python" }, { "code": null, "e": 2710, "s": 2671, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2748, "s": 2710, "text": "Python | Convert a list to dictionary" } ]
How to zip a Python Dictionary and List together?
The zip() function can be used to zip one key-value pair from dictionary and correspoinding item in a list together >>> dictionary = {'A':1, 'B':2, 'C':3} >>> num_list = [1, 2, 3] >>> zipped = zip(dictionary.items(), num_list) >>> zipped <zip object at 0x000000886641B9C8> This zipped object when converted to list, shows following output >>> list(zipped) [(('A', 1), 1), (('B', 2), 2), (('C', 3), 3)]
[ { "code": null, "e": 1303, "s": 1187, "text": "The zip() function can be used to zip one key-value pair from dictionary and correspoinding item in a list together" }, { "code": null, "e": 1460, "s": 1303, "text": ">>> dictionary = {'A':1, 'B':2, 'C':3}\n>>> num_list = [1, 2, 3]\n>>> zipped = zip(dictionary.items(), num_list)\n>>> zipped\n<zip object at 0x000000886641B9C8>" }, { "code": null, "e": 1526, "s": 1460, "text": "This zipped object when converted to list, shows following output" }, { "code": null, "e": 1589, "s": 1526, "text": ">>> list(zipped)\n[(('A', 1), 1), (('B', 2), 2), (('C', 3), 3)]" } ]
How to use Typography Component in ReactJS?
05 Mar, 2021 Use typography to present your design and content as clearly and efficiently as possible. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Typography 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 foldernam. 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 Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import Typography from "@material-ui/core/Typography"; export default function App() { return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Typography Component in ReactJS?</h4> <Typography variant="h4" gutterBottom> GeeksforGeeks with Typography Component </Typography> <h4>GeeksforGeeks without Typography Component</h4> </div> );} 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. Reference: https://material-ui.com/components/typography/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2021" }, { "code": null, "e": 288, "s": 28, "text": "Use typography to present your design and content as clearly and efficiently as possible. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Typography Component in ReactJS using the following approach." }, { "code": null, "e": 338, "s": 288, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 402, "s": 338, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 434, "s": 402, "text": "npx create-react-app foldernam." }, { "code": null, "e": 534, "s": 434, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 548, "s": 534, "text": "cd foldername" }, { "code": null, "e": 657, "s": 548, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 687, "s": 657, "text": "npm install @material-ui/core" }, { "code": null, "e": 739, "s": 687, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 757, "s": 739, "text": "Project Structure" }, { "code": null, "e": 887, "s": 757, "text": "Example: 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": 894, "s": 887, "text": "App.js" }, { "code": "import React from \"react\";import Typography from \"@material-ui/core/Typography\"; export default function App() { return ( <div style={{ display: \"block\", padding: 30 }}> <h4>How to use Typography Component in ReactJS?</h4> <Typography variant=\"h4\" gutterBottom> GeeksforGeeks with Typography Component </Typography> <h4>GeeksforGeeks without Typography Component</h4> </div> );}", "e": 1311, "s": 894, "text": null }, { "code": null, "e": 1424, "s": 1311, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 1434, "s": 1424, "text": "npm start" }, { "code": null, "e": 1533, "s": 1434, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 1591, "s": 1533, "text": "Reference: https://material-ui.com/components/typography/" }, { "code": null, "e": 1603, "s": 1591, "text": "Material-UI" }, { "code": null, "e": 1619, "s": 1603, "text": "React-Questions" }, { "code": null, "e": 1627, "s": 1619, "text": "ReactJS" }, { "code": null, "e": 1644, "s": 1627, "text": "Web Technologies" }, { "code": null, "e": 1742, "s": 1644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1780, "s": 1742, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 1799, "s": 1780, "text": "ReactJS setState()" }, { "code": null, "e": 1867, "s": 1799, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 1902, "s": 1867, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 1923, "s": 1902, "text": "ReactJS defaultProps" }, { "code": null, "e": 1985, "s": 1923, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2018, "s": 1985, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2079, "s": 2018, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2129, "s": 2079, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Internet Relay Chat (IRC)
29 Jun, 2022 Prerequisite – Chat Conferencing Protocols Internet Relay Chat (IRC) is an Internet application that was developed by Jakko Oikarinen in Finland. Chat is the most convenient immediate way to communicate with others via Internet. There are a number of topics called “channels” through which you can chat with many people all over the world. After joining channel, you can see what other people on this channel type on their keyboards. In that situation, everyone on this channel can see whatever you type on your keyboard. You can also hold individual conversations with someone. Channels get live on different servers around the world. Some servers have only a few channels, while others have many of them. Model used for IRC : IRC follows client-server model. It means that both client and server software are required in order to use it. Many IT (Information Technology) clients are available for different kinds of computers, so whether you have a PC, Macintosh, or UNIX work-section, you will be able to use IRC. Chatting on IRC : IRC client connects/communicates with IRC server on Internet. First, you have to log on to the server using a client and then pick the channel on which you want to chat. They are sent to your server when you type words on your keyboard. Now your server is part of global IRC server network. Your server sends your messages to other servers, which in turn, sends your messages to people who are part of your channel. They can then read and respond to your messages. Many websites use proprietary chat software that does not use IRC protocol but enables you to chat when you are on site. There is another kind of chat, called Instant Messaging. In this kind of chatting, you communicate privately, one-to-one, with another person. You can create special lists so that you are informed when your “buddies” come online, ready to chat, and they are informed when you come online. Working on IRC : When you want to chat, first you have to make a connection to Internet and then start your client software. After that, you need to log on to IRC server which is located on Internet. There are many IRC servers are located all over the world. Those IRC servers are connected together in network so that they can communicate with each other. Servers are connected in spanning tree architecture. In this case, each server is connected to several others, but these servers are not directly connected to one another. When you connect to server, first you have to choose a specific channel to join and then choose a user name to identify yourself when you at chat. Many channels are available that cover different topics. Your message is sent from client software on your PC to IRC server to which you are connected. Then message is sent from one server to other servers where all users on this channel are logged on. In this network, messages are transferred from one server to another server. Under a spanning-tree server architecture, a message always takes the shortest route through network to reach its final destination. Each server sends messages to client software of their respected users who are connected to channel/network. Then people/users can read and respond to your message on their computers. Client Software for Chat : Chat Servers : Communication servers permit you to give your information to large number of users in environment that is just like Internet newsgroups. The most advanced servers have recently started augmenting the text-based medium of conversation with dynamic voice and video support. There are three major types of communication servers : 1. EFnet servers 2. UnderNet Servers 3. DALnet servers Each server has its own hostname, which mostly consists of the name of the server and Internet that it accesses. As servers already might have maximum number of user connections, you may not be allowed to connect to the server of your choice. Smileys : When we talk to people face-to-face, the tone of your voice and your facial expressions impart great meaning to what you say. You can personalize your written messages by using smileys you create with your keyboard. Maximum time the main use of smileys is to indicate joke. When text might not be clear. There are different types of smileys which are as follows : 1. Basic Smileys2. Widely Used Smileys3. Midget Smileys4. Mega Smileys5. Usenet Smileys6. Emotional Smileys Advantages of IRC: It is decentralized.It allows chat and file sharing.Flexible and robust which allows real time discussion.It has the concept of access levels for better privacy. It is decentralized. It allows chat and file sharing. Flexible and robust which allows real time discussion. It has the concept of access levels for better privacy. Disadvantages of IRC: It consumes bandwidth.Concern is there with flooding.Fear of security incidents are there.Concern with Cyberbullying. It consumes bandwidth. Concern is there with flooding. Fear of security incidents are there. Concern with Cyberbullying. Satyabrata_Jena Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 72, "s": 28, "text": "Prerequisite – Chat Conferencing Protocols " }, { "code": null, "e": 737, "s": 72, "text": "Internet Relay Chat (IRC) is an Internet application that was developed by Jakko Oikarinen in Finland. Chat is the most convenient immediate way to communicate with others via Internet. There are a number of topics called “channels” through which you can chat with many people all over the world. After joining channel, you can see what other people on this channel type on their keyboards. In that situation, everyone on this channel can see whatever you type on your keyboard. You can also hold individual conversations with someone. Channels get live on different servers around the world. Some servers have only a few channels, while others have many of them. " }, { "code": null, "e": 758, "s": 737, "text": "Model used for IRC :" }, { "code": null, "e": 1048, "s": 758, "text": "IRC follows client-server model. It means that both client and server software are required in order to use it. Many IT (Information Technology) clients are available for different kinds of computers, so whether you have a PC, Macintosh, or UNIX work-section, you will be able to use IRC. " }, { "code": null, "e": 1067, "s": 1048, "text": "Chatting on IRC : " }, { "code": null, "e": 1484, "s": 1067, "text": "IRC client connects/communicates with IRC server on Internet. First, you have to log on to the server using a client and then pick the channel on which you want to chat. They are sent to your server when you type words on your keyboard. Now your server is part of global IRC server network. Your server sends your messages to other servers, which in turn, sends your messages to people who are part of your channel. " }, { "code": null, "e": 1944, "s": 1484, "text": "They can then read and respond to your messages. Many websites use proprietary chat software that does not use IRC protocol but enables you to chat when you are on site. There is another kind of chat, called Instant Messaging. In this kind of chatting, you communicate privately, one-to-one, with another person. You can create special lists so that you are informed when your “buddies” come online, ready to chat, and they are informed when you come online. " }, { "code": null, "e": 1962, "s": 1944, "text": "Working on IRC : " }, { "code": null, "e": 2303, "s": 1962, "text": "When you want to chat, first you have to make a connection to Internet and then start your client software. After that, you need to log on to IRC server which is located on Internet. There are many IRC servers are located all over the world. Those IRC servers are connected together in network so that they can communicate with each other. " }, { "code": null, "e": 2876, "s": 2303, "text": "Servers are connected in spanning tree architecture. In this case, each server is connected to several others, but these servers are not directly connected to one another. When you connect to server, first you have to choose a specific channel to join and then choose a user name to identify yourself when you at chat. Many channels are available that cover different topics. Your message is sent from client software on your PC to IRC server to which you are connected. Then message is sent from one server to other servers where all users on this channel are logged on. " }, { "code": null, "e": 3271, "s": 2876, "text": "In this network, messages are transferred from one server to another server. Under a spanning-tree server architecture, a message always takes the shortest route through network to reach its final destination. Each server sends messages to client software of their respected users who are connected to channel/network. Then people/users can read and respond to your message on their computers. " }, { "code": null, "e": 3298, "s": 3271, "text": "Client Software for Chat :" }, { "code": null, "e": 3314, "s": 3298, "text": "Chat Servers : " }, { "code": null, "e": 3641, "s": 3314, "text": "Communication servers permit you to give your information to large number of users in environment that is just like Internet newsgroups. The most advanced servers have recently started augmenting the text-based medium of conversation with dynamic voice and video support. There are three major types of communication servers :" }, { "code": null, "e": 3697, "s": 3641, "text": "1. EFnet servers\n2. UnderNet Servers\n3. DALnet servers " }, { "code": null, "e": 3941, "s": 3697, "text": "Each server has its own hostname, which mostly consists of the name of the server and Internet that it accesses. As servers already might have maximum number of user connections, you may not be allowed to connect to the server of your choice. " }, { "code": null, "e": 3952, "s": 3941, "text": "Smileys : " }, { "code": null, "e": 4316, "s": 3952, "text": "When we talk to people face-to-face, the tone of your voice and your facial expressions impart great meaning to what you say. You can personalize your written messages by using smileys you create with your keyboard. Maximum time the main use of smileys is to indicate joke. When text might not be clear. There are different types of smileys which are as follows :" }, { "code": null, "e": 4425, "s": 4316, "text": "1. Basic Smileys2. Widely Used Smileys3. Midget Smileys4. Mega Smileys5. Usenet Smileys6. Emotional Smileys " }, { "code": null, "e": 4444, "s": 4425, "text": "Advantages of IRC:" }, { "code": null, "e": 4606, "s": 4444, "text": "It is decentralized.It allows chat and file sharing.Flexible and robust which allows real time discussion.It has the concept of access levels for better privacy." }, { "code": null, "e": 4627, "s": 4606, "text": "It is decentralized." }, { "code": null, "e": 4660, "s": 4627, "text": "It allows chat and file sharing." }, { "code": null, "e": 4715, "s": 4660, "text": "Flexible and robust which allows real time discussion." }, { "code": null, "e": 4771, "s": 4715, "text": "It has the concept of access levels for better privacy." }, { "code": null, "e": 4793, "s": 4771, "text": "Disadvantages of IRC:" }, { "code": null, "e": 4911, "s": 4793, "text": "It consumes bandwidth.Concern is there with flooding.Fear of security incidents are there.Concern with Cyberbullying." }, { "code": null, "e": 4934, "s": 4911, "text": "It consumes bandwidth." }, { "code": null, "e": 4966, "s": 4934, "text": "Concern is there with flooding." }, { "code": null, "e": 5004, "s": 4966, "text": "Fear of security incidents are there." }, { "code": null, "e": 5032, "s": 5004, "text": "Concern with Cyberbullying." }, { "code": null, "e": 5048, "s": 5032, "text": "Satyabrata_Jena" }, { "code": null, "e": 5066, "s": 5048, "text": "Computer Networks" }, { "code": null, "e": 5084, "s": 5066, "text": "Computer Networks" } ]
ReactJS MDBootstrap Card Component
12 Jan, 2022 Reactstrap is a bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component. In this article, we will know how to use Card Component in ReactJS MDBootstrap. A card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. It replaces the use panels, wells, and thumbnails. As all of it can be used in a single container called a card. Properties: tag: It is used to define tags in Cards. className: It is used to define a custom class to a Cards. border: It is used to set the border of the cards. shadow: It is used to set cards shadow. background: it is used to set the background color of Cards. alignment: It is used to set the alignment of text inside the cards. Syntax: <MDBCard> GeeksforGeeks </MDBCard> 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: Install ReactJS MDBootstrap in your given directory. npm i mdb-ui-kit npm i mdb-react-ui-kit Step 4: Import the element to be used in the project. import { MDBBtnGroup } from 'mdb-react-ui-kit' Project Structure: It will look like the following. Step to Run Application: Run the application from the root directory of the project, using the following command. npm start Example 1: This is the basic example that shows how to use the Card module App.js import React from "react";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardImage, MDBBtn} from "mdb-react-ui-kit"; export default function App() { return ( <center> <MDBCard style={{ maxWidth: "15rem" }}> <MDBCardImage src= "https://media.geeksforgeeks.org/wp-content/uploads/20220106105832/gfg200X2001.png" position="top" /> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> <MDBBtn href="www.geeksforgeeks.org">Button</MDBBtn> </MDBCardBody> </MDBCard> </center> );} Output: Example 2: In this example, we will know how to use the header and footer in a card component. App.js import React from "react";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardHeader, MDBCardFooter} from "mdb-react-ui-kit"; export default function App() { return ( <center> <br/> <MDBCard style={{ maxWidth: "15rem" }}> <MDBCardHeader>Card Header</MDBCardHeader> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> </MDBCardBody> <MDBCardFooter >Card Footer</MDBCardFooter> </MDBCard> </center> );} Output: Example 3: In this example, we will know how to use border property in a Card component. App.js import React from "react";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardHeader, MDBCardFooter} from "mdb-react-ui-kit"; export default function App() { return ( <center> <br/> <MDBCard style={{ maxWidth: "15rem" }} border='danger'> <MDBCardHeader>Danger Border</MDBCardHeader> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> </MDBCardBody> </MDBCard> </center> );} Output: Reference: https://mdbootstrap.com/docs/b5/react/components/cards/ MDBootstrap ReactJS 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": "\n12 Jan, 2022" }, { "code": null, "e": 165, "s": 28, "text": "Reactstrap is a bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component." }, { "code": null, "e": 246, "s": 165, "text": "In this article, we will know how to use Card Component in ReactJS MDBootstrap. " }, { "code": null, "e": 547, "s": 246, "text": "A card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. It replaces the use panels, wells, and thumbnails. As all of it can be used in a single container called a card." }, { "code": null, "e": 559, "s": 547, "text": "Properties:" }, { "code": null, "e": 600, "s": 559, "text": "tag: It is used to define tags in Cards." }, { "code": null, "e": 659, "s": 600, "text": "className: It is used to define a custom class to a Cards." }, { "code": null, "e": 710, "s": 659, "text": "border: It is used to set the border of the cards." }, { "code": null, "e": 750, "s": 710, "text": "shadow: It is used to set cards shadow." }, { "code": null, "e": 811, "s": 750, "text": "background: it is used to set the background color of Cards." }, { "code": null, "e": 880, "s": 811, "text": "alignment: It is used to set the alignment of text inside the cards." }, { "code": null, "e": 890, "s": 882, "text": "Syntax:" }, { "code": null, "e": 926, "s": 890, "text": "<MDBCard>\n GeeksforGeeks\n</MDBCard>" }, { "code": null, "e": 976, "s": 926, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1040, "s": 976, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 1072, "s": 1040, "text": "npx create-react-app foldername" }, { "code": null, "e": 1172, "s": 1072, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 1186, "s": 1172, "text": "cd foldername" }, { "code": null, "e": 1247, "s": 1186, "text": "Step 3: Install ReactJS MDBootstrap in your given directory." }, { "code": null, "e": 1287, "s": 1247, "text": "npm i mdb-ui-kit\nnpm i mdb-react-ui-kit" }, { "code": null, "e": 1341, "s": 1287, "text": "Step 4: Import the element to be used in the project." }, { "code": null, "e": 1388, "s": 1341, "text": "import { MDBBtnGroup } from 'mdb-react-ui-kit'" }, { "code": null, "e": 1440, "s": 1388, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1554, "s": 1440, "text": "Step to Run Application: Run the application from the root directory of the project, using the following command." }, { "code": null, "e": 1564, "s": 1554, "text": "npm start" }, { "code": null, "e": 1640, "s": 1564, "text": "Example 1: This is the basic example that shows how to use the Card module" }, { "code": null, "e": 1647, "s": 1640, "text": "App.js" }, { "code": "import React from \"react\";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardImage, MDBBtn} from \"mdb-react-ui-kit\"; export default function App() { return ( <center> <MDBCard style={{ maxWidth: \"15rem\" }}> <MDBCardImage src= \"https://media.geeksforgeeks.org/wp-content/uploads/20220106105832/gfg200X2001.png\" position=\"top\" /> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> <MDBBtn href=\"www.geeksforgeeks.org\">Button</MDBBtn> </MDBCardBody> </MDBCard> </center> );}", "e": 2470, "s": 1647, "text": null }, { "code": null, "e": 2478, "s": 2470, "text": "Output:" }, { "code": null, "e": 2573, "s": 2478, "text": "Example 2: In this example, we will know how to use the header and footer in a card component." }, { "code": null, "e": 2580, "s": 2573, "text": "App.js" }, { "code": "import React from \"react\";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardHeader, MDBCardFooter} from \"mdb-react-ui-kit\"; export default function App() { return ( <center> <br/> <MDBCard style={{ maxWidth: \"15rem\" }}> <MDBCardHeader>Card Header</MDBCardHeader> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> </MDBCardBody> <MDBCardFooter >Card Footer</MDBCardFooter> </MDBCard> </center> );}", "e": 3308, "s": 2580, "text": null }, { "code": null, "e": 3316, "s": 3308, "text": "Output:" }, { "code": null, "e": 3405, "s": 3316, "text": "Example 3: In this example, we will know how to use border property in a Card component." }, { "code": null, "e": 3412, "s": 3405, "text": "App.js" }, { "code": "import React from \"react\";import { MDBCard, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardHeader, MDBCardFooter} from \"mdb-react-ui-kit\"; export default function App() { return ( <center> <br/> <MDBCard style={{ maxWidth: \"15rem\" }} border='danger'> <MDBCardHeader>Danger Border</MDBCardHeader> <MDBCardBody> <MDBCardTitle>GeeksforGeeks</MDBCardTitle> <MDBCardText> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </MDBCardText> </MDBCardBody> </MDBCard> </center> );}", "e": 4107, "s": 3412, "text": null }, { "code": null, "e": 4115, "s": 4107, "text": "Output:" }, { "code": null, "e": 4182, "s": 4115, "text": "Reference: https://mdbootstrap.com/docs/b5/react/components/cards/" }, { "code": null, "e": 4194, "s": 4182, "text": "MDBootstrap" }, { "code": null, "e": 4202, "s": 4194, "text": "ReactJS" }, { "code": null, "e": 4219, "s": 4202, "text": "Web Technologies" } ]
Scala | Option
01 Apr, 2019 The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The instance of an Option that is returned here can be an instance of Some class or None class in Scala, where Some and None are the children of Option class. When the value of a given key is obtained then Some class is generated. When the value of a given key is not obtained then None class is generated. Example : // Scala program for Option // Creating objectobject option{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map("Nidhi" -> "author", "Geeta" -> "coder") // Accessing keys of the map val x = name.get("Nidhi") val y = name.get("Rahul") // Displays Some if the key is // found else None println(x) println(y) }} Some(author) None Here, key of the value Nidhi is found so, Some is returned for it but key of the value Rahul is not found so, None is returned for it. Using Pattern Matching :Example :// Scala program for Option// with Pattern matching // Creating objectobject pattern{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map("Nidhi" -> "author", "Geeta" -> "coder") //Accessing keys of the map println(patrn(name.get("Nidhi"))) println(patrn(name.get("Rahul"))) } // Using Option with Pattern // matching def patrn(z: Option[String]) = z match { // for 'Some' class the key for // the given value is displayed case Some(s) => (s) // for 'None' class the below string // is displayed case None => ("key not found") }}Output:author key not found Here, we have used Option with Pattern Matching in Scala. Example : // Scala program for Option// with Pattern matching // Creating objectobject pattern{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map("Nidhi" -> "author", "Geeta" -> "coder") //Accessing keys of the map println(patrn(name.get("Nidhi"))) println(patrn(name.get("Rahul"))) } // Using Option with Pattern // matching def patrn(z: Option[String]) = z match { // for 'Some' class the key for // the given value is displayed case Some(s) => (s) // for 'None' class the below string // is displayed case None => ("key not found") }} author key not found Here, we have used Option with Pattern Matching in Scala. getOrElse() Method:This method is utilized in returning either a value if it is present or a default value when its not present. Here, For Some class a value is returned and for None class a default value is returned.Example:// Scala program of using// getOrElse method // Creating objectobject get{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(15) // Using None class val none:Option[Int] = None // Applying getOrElse method val x = some.getOrElse(0) val y = none.getOrElse(17) // Displays the key in the // class Some println(x) // Displays default value println(y) }}Output:15 17 Here, the default value assigned to the None is 17 so, it is returned for the None class. // Scala program of using// getOrElse method // Creating objectobject get{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(15) // Using None class val none:Option[Int] = None // Applying getOrElse method val x = some.getOrElse(0) val y = none.getOrElse(17) // Displays the key in the // class Some println(x) // Displays default value println(y) }} 15 17 Here, the default value assigned to the None is 17 so, it is returned for the None class. isEmpty() Method:This method is utilized to check if the Option has a value or not.Example:// Scala program of using// isEmpty method // Creating objectobject check{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(20) // Using None class val none:Option[Int] = None // Applying isEmpty method val x = some.isEmpty val y = none.isEmpty // Displays true if there // is a value else false println(x) println(y) }}Output:false true Here, isEmpty returns false for Some class as it non-empty but returns true for None as its empty. // Scala program of using// isEmpty method // Creating objectobject check{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(20) // Using None class val none:Option[Int] = None // Applying isEmpty method val x = some.isEmpty val y = none.isEmpty // Displays true if there // is a value else false println(x) println(y) }} false true Here, isEmpty returns false for Some class as it non-empty but returns true for None as its empty. Picked Scala scala-collection Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Type Casting in Scala Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example Enumeration in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 300, "s": 28, "text": "The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null." }, { "code": null, "e": 319, "s": 300, "text": "Important points :" }, { "code": null, "e": 478, "s": 319, "text": "The instance of an Option that is returned here can be an instance of Some class or None class in Scala, where Some and None are the children of Option class." }, { "code": null, "e": 550, "s": 478, "text": "When the value of a given key is obtained then Some class is generated." }, { "code": null, "e": 626, "s": 550, "text": "When the value of a given key is not obtained then None class is generated." }, { "code": null, "e": 636, "s": 626, "text": "Example :" }, { "code": "// Scala program for Option // Creating objectobject option{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map(\"Nidhi\" -> \"author\", \"Geeta\" -> \"coder\") // Accessing keys of the map val x = name.get(\"Nidhi\") val y = name.get(\"Rahul\") // Displays Some if the key is // found else None println(x) println(y) }}", "e": 1083, "s": 636, "text": null }, { "code": null, "e": 1102, "s": 1083, "text": "Some(author)\nNone\n" }, { "code": null, "e": 1237, "s": 1102, "text": "Here, key of the value Nidhi is found so, Some is returned for it but key of the value Rahul is not found so, None is returned for it." }, { "code": null, "e": 2057, "s": 1237, "text": "Using Pattern Matching :Example :// Scala program for Option// with Pattern matching // Creating objectobject pattern{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map(\"Nidhi\" -> \"author\", \"Geeta\" -> \"coder\") //Accessing keys of the map println(patrn(name.get(\"Nidhi\"))) println(patrn(name.get(\"Rahul\"))) } // Using Option with Pattern // matching def patrn(z: Option[String]) = z match { // for 'Some' class the key for // the given value is displayed case Some(s) => (s) // for 'None' class the below string // is displayed case None => (\"key not found\") }}Output:author\nkey not found\nHere, we have used Option with Pattern Matching in Scala." }, { "code": null, "e": 2067, "s": 2057, "text": "Example :" }, { "code": "// Scala program for Option// with Pattern matching // Creating objectobject pattern{ // Main method def main(args: Array[String]) { // Creating a Map val name = Map(\"Nidhi\" -> \"author\", \"Geeta\" -> \"coder\") //Accessing keys of the map println(patrn(name.get(\"Nidhi\"))) println(patrn(name.get(\"Rahul\"))) } // Using Option with Pattern // matching def patrn(z: Option[String]) = z match { // for 'Some' class the key for // the given value is displayed case Some(s) => (s) // for 'None' class the below string // is displayed case None => (\"key not found\") }}", "e": 2769, "s": 2067, "text": null }, { "code": null, "e": 2791, "s": 2769, "text": "author\nkey not found\n" }, { "code": null, "e": 2849, "s": 2791, "text": "Here, we have used Option with Pattern Matching in Scala." }, { "code": null, "e": 3684, "s": 2849, "text": "getOrElse() Method:This method is utilized in returning either a value if it is present or a default value when its not present. Here, For Some class a value is returned and for None class a default value is returned.Example:// Scala program of using// getOrElse method // Creating objectobject get{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(15) // Using None class val none:Option[Int] = None // Applying getOrElse method val x = some.getOrElse(0) val y = none.getOrElse(17) // Displays the key in the // class Some println(x) // Displays default value println(y) }}Output:15\n17\nHere, the default value assigned to the None is 17 so, it is returned for the None class." }, { "code": "// Scala program of using// getOrElse method // Creating objectobject get{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(15) // Using None class val none:Option[Int] = None // Applying getOrElse method val x = some.getOrElse(0) val y = none.getOrElse(17) // Displays the key in the // class Some println(x) // Displays default value println(y) }}", "e": 4192, "s": 3684, "text": null }, { "code": null, "e": 4199, "s": 4192, "text": "15\n17\n" }, { "code": null, "e": 4289, "s": 4199, "text": "Here, the default value assigned to the None is 17 so, it is returned for the None class." }, { "code": null, "e": 4964, "s": 4289, "text": "isEmpty() Method:This method is utilized to check if the Option has a value or not.Example:// Scala program of using// isEmpty method // Creating objectobject check{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(20) // Using None class val none:Option[Int] = None // Applying isEmpty method val x = some.isEmpty val y = none.isEmpty // Displays true if there // is a value else false println(x) println(y) }}Output:false\ntrue\nHere, isEmpty returns false for Some class as it non-empty but returns true for None as its empty." }, { "code": "// Scala program of using// isEmpty method // Creating objectobject check{ // Main method def main(args: Array[String]) { // Using Some class val some:Option[Int] = Some(20) // Using None class val none:Option[Int] = None // Applying isEmpty method val x = some.isEmpty val y = none.isEmpty // Displays true if there // is a value else false println(x) println(y) }}", "e": 5432, "s": 4964, "text": null }, { "code": null, "e": 5444, "s": 5432, "text": "false\ntrue\n" }, { "code": null, "e": 5543, "s": 5444, "text": "Here, isEmpty returns false for Some class as it non-empty but returns true for None as its empty." }, { "code": null, "e": 5550, "s": 5543, "text": "Picked" }, { "code": null, "e": 5556, "s": 5550, "text": "Scala" }, { "code": null, "e": 5573, "s": 5556, "text": "scala-collection" }, { "code": null, "e": 5579, "s": 5573, "text": "Scala" }, { "code": null, "e": 5677, "s": 5579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5695, "s": 5677, "text": "For Loop in Scala" }, { "code": null, "e": 5716, "s": 5695, "text": "Scala | map() method" }, { "code": null, "e": 5739, "s": 5716, "text": "Scala | flatMap Method" }, { "code": null, "e": 5769, "s": 5739, "text": "String concatenation in Scala" }, { "code": null, "e": 5795, "s": 5769, "text": "Scala | reduce() Function" }, { "code": null, "e": 5817, "s": 5795, "text": "Type Casting in Scala" }, { "code": null, "e": 5857, "s": 5817, "text": "Scala List filter() method with example" }, { "code": null, "e": 5910, "s": 5857, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 5955, "s": 5910, "text": "Scala String substring() method with example" } ]
Hadoop - MapReduce
MapReduce is a framework using which we can write applications to process huge amounts of data, in parallel, on large clusters of commodity hardware in a reliable manner. MapReduce is a processing technique and a program model for distributed computing based on java. The MapReduce algorithm contains two important tasks, namely Map and Reduce. Map takes a set of data and converts it into another set of data, where individual elements are broken down into tuples (key/value pairs). Secondly, reduce task, which takes the output from a map as an input and combines those data tuples into a smaller set of tuples. As the sequence of the name MapReduce implies, the reduce task is always performed after the map job. The major advantage of MapReduce is that it is easy to scale data processing over multiple computing nodes. Under the MapReduce model, the data processing primitives are called mappers and reducers. Decomposing a data processing application into mappers and reducers is sometimes nontrivial. But, once we write an application in the MapReduce form, scaling the application to run over hundreds, thousands, or even tens of thousands of machines in a cluster is merely a configuration change. This simple scalability is what has attracted many programmers to use the MapReduce model. Generally MapReduce paradigm is based on sending the computer to where the data resides! Generally MapReduce paradigm is based on sending the computer to where the data resides! MapReduce program executes in three stages, namely map stage, shuffle stage, and reduce stage. Map stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. Reduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS. MapReduce program executes in three stages, namely map stage, shuffle stage, and reduce stage. Map stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. Map stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. Reduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS. Reduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS. During a MapReduce job, Hadoop sends the Map and Reduce tasks to the appropriate servers in the cluster. During a MapReduce job, Hadoop sends the Map and Reduce tasks to the appropriate servers in the cluster. The framework manages all the details of data-passing such as issuing tasks, verifying task completion, and copying data around the cluster between the nodes. The framework manages all the details of data-passing such as issuing tasks, verifying task completion, and copying data around the cluster between the nodes. Most of the computing takes place on nodes with data on local disks that reduces the network traffic. Most of the computing takes place on nodes with data on local disks that reduces the network traffic. After completion of the given tasks, the cluster collects and reduces the data to form an appropriate result, and sends it back to the Hadoop server. After completion of the given tasks, the cluster collects and reduces the data to form an appropriate result, and sends it back to the Hadoop server. The MapReduce framework operates on <key, value> pairs, that is, the framework views the input to the job as a set of <key, value> pairs and produces a set of <key, value> pairs as the output of the job, conceivably of different types. The key and the value classes should be in serialized manner by the framework and hence, need to implement the Writable interface. Additionally, the key classes have to implement the Writable-Comparable interface to facilitate sorting by the framework. Input and Output types of a MapReduce job − (Input) <k1, v1> → map → <k2, v2> → reduce → <k3, v3>(Output). PayLoad − Applications implement the Map and the Reduce functions, and form the core of the job. PayLoad − Applications implement the Map and the Reduce functions, and form the core of the job. Mapper − Mapper maps the input key/value pairs to a set of intermediate key/value pair. Mapper − Mapper maps the input key/value pairs to a set of intermediate key/value pair. NamedNode − Node that manages the Hadoop Distributed File System (HDFS). NamedNode − Node that manages the Hadoop Distributed File System (HDFS). DataNode − Node where data is presented in advance before any processing takes place. DataNode − Node where data is presented in advance before any processing takes place. MasterNode − Node where JobTracker runs and which accepts job requests from clients. MasterNode − Node where JobTracker runs and which accepts job requests from clients. SlaveNode − Node where Map and Reduce program runs. SlaveNode − Node where Map and Reduce program runs. JobTracker − Schedules jobs and tracks the assign jobs to Task tracker. JobTracker − Schedules jobs and tracks the assign jobs to Task tracker. Task Tracker − Tracks the task and reports status to JobTracker. Task Tracker − Tracks the task and reports status to JobTracker. Job − A program is an execution of a Mapper and Reducer across a dataset. Job − A program is an execution of a Mapper and Reducer across a dataset. Task − An execution of a Mapper or a Reducer on a slice of data. Task − An execution of a Mapper or a Reducer on a slice of data. Task Attempt − A particular instance of an attempt to execute a task on a SlaveNode. Task Attempt − A particular instance of an attempt to execute a task on a SlaveNode. Given below is the data regarding the electrical consumption of an organization. It contains the monthly electrical consumption and the annual average for various years. If the above data is given as input, we have to write applications to process it and produce results such as finding the year of maximum usage, year of minimum usage, and so on. This is a walkover for the programmers with finite number of records. They will simply write the logic to produce the required output, and pass the data to the application written. But, think of the data representing the electrical consumption of all the largescale industries of a particular state, since its formation. When we write applications to process such bulk data, They will take a lot of time to execute. They will take a lot of time to execute. There will be a heavy network traffic when we move data from source to network server and so on. There will be a heavy network traffic when we move data from source to network server and so on. To solve these problems, we have the MapReduce framework. The above data is saved as sample.txtand given as input. The input file looks as shown below. 1979 23 23 2 43 24 25 26 26 26 26 25 26 25 1980 26 27 28 28 28 30 31 31 31 30 30 30 29 1981 31 32 32 32 33 34 35 36 36 34 34 34 34 1984 39 38 39 39 39 41 42 43 40 39 38 38 40 1985 38 39 39 39 39 41 41 41 00 40 39 39 45 Given below is the program to the sample data using MapReduce framework. package hadoop; import java.util.*; import java.io.IOException; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.util.*; public class ProcessUnits { //Mapper class public static class E_EMapper extends MapReduceBase implements Mapper<LongWritable ,/*Input key Type */ Text, /*Input value Type*/ Text, /*Output key Type*/ IntWritable> /*Output value Type*/ { //Map function public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { String line = value.toString(); String lasttoken = null; StringTokenizer s = new StringTokenizer(line,"\t"); String year = s.nextToken(); while(s.hasMoreTokens()) { lasttoken = s.nextToken(); } int avgprice = Integer.parseInt(lasttoken); output.collect(new Text(year), new IntWritable(avgprice)); } } //Reducer class public static class E_EReduce extends MapReduceBase implements Reducer< Text, IntWritable, Text, IntWritable > { //Reduce function public void reduce( Text key, Iterator <IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int maxavg = 30; int val = Integer.MIN_VALUE; while (values.hasNext()) { if((val = values.next().get())>maxavg) { output.collect(key, new IntWritable(val)); } } } } //Main function public static void main(String args[])throws Exception { JobConf conf = new JobConf(ProcessUnits.class); conf.setJobName("max_eletricityunits"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(E_EMapper.class); conf.setCombinerClass(E_EReduce.class); conf.setReducerClass(E_EReduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); JobClient.runJob(conf); } } Save the above program as ProcessUnits.java. The compilation and execution of the program is explained below. Let us assume we are in the home directory of a Hadoop user (e.g. /home/hadoop). Follow the steps given below to compile and execute the above program. The following command is to create a directory to store the compiled java classes. $ mkdir units Download Hadoop-core-1.2.1.jar, which is used to compile and execute the MapReduce program. Visit the following link mvnrepository.com to download the jar. Let us assume the downloaded folder is /home/hadoop/. The following commands are used for compiling the ProcessUnits.java program and creating a jar for the program. $ javac -classpath hadoop-core-1.2.1.jar -d units ProcessUnits.java $ jar -cvf units.jar -C units/ . The following command is used to create an input directory in HDFS. $HADOOP_HOME/bin/hadoop fs -mkdir input_dir The following command is used to copy the input file named sample.txtin the input directory of HDFS. $HADOOP_HOME/bin/hadoop fs -put /home/hadoop/sample.txt input_dir The following command is used to verify the files in the input directory. $HADOOP_HOME/bin/hadoop fs -ls input_dir/ The following command is used to run the Eleunit_max application by taking the input files from the input directory. $HADOOP_HOME/bin/hadoop jar units.jar hadoop.ProcessUnits input_dir output_dir Wait for a while until the file is executed. After execution, as shown below, the output will contain the number of input splits, the number of Map tasks, the number of reducer tasks, etc. INFO mapreduce.Job: Job job_1414748220717_0002 completed successfully 14/10/31 06:02:52 INFO mapreduce.Job: Counters: 49 File System Counters FILE: Number of bytes read = 61 FILE: Number of bytes written = 279400 FILE: Number of read operations = 0 FILE: Number of large read operations = 0 FILE: Number of write operations = 0 HDFS: Number of bytes read = 546 HDFS: Number of bytes written = 40 HDFS: Number of read operations = 9 HDFS: Number of large read operations = 0 HDFS: Number of write operations = 2 Job Counters Launched map tasks = 2 Launched reduce tasks = 1 Data-local map tasks = 2 Total time spent by all maps in occupied slots (ms) = 146137 Total time spent by all reduces in occupied slots (ms) = 441 Total time spent by all map tasks (ms) = 14613 Total time spent by all reduce tasks (ms) = 44120 Total vcore-seconds taken by all map tasks = 146137 Total vcore-seconds taken by all reduce tasks = 44120 Total megabyte-seconds taken by all map tasks = 149644288 Total megabyte-seconds taken by all reduce tasks = 45178880 Map-Reduce Framework Map input records = 5 Map output records = 5 Map output bytes = 45 Map output materialized bytes = 67 Input split bytes = 208 Combine input records = 5 Combine output records = 5 Reduce input groups = 5 Reduce shuffle bytes = 6 Reduce input records = 5 Reduce output records = 5 Spilled Records = 10 Shuffled Maps = 2 Failed Shuffles = 0 Merged Map outputs = 2 GC time elapsed (ms) = 948 CPU time spent (ms) = 5160 Physical memory (bytes) snapshot = 47749120 Virtual memory (bytes) snapshot = 2899349504 Total committed heap usage (bytes) = 277684224 File Output Format Counters Bytes Written = 40 The following command is used to verify the resultant files in the output folder. $HADOOP_HOME/bin/hadoop fs -ls output_dir/ The following command is used to see the output in Part-00000 file. This file is generated by HDFS. $HADOOP_HOME/bin/hadoop fs -cat output_dir/part-00000 Below is the output generated by the MapReduce program. 1981 34 1984 40 1985 45 The following command is used to copy the output folder from HDFS to the local file system for analyzing. $HADOOP_HOME/bin/hadoop fs -cat output_dir/part-00000/bin/hadoop dfs get output_dir /home/hadoop All Hadoop commands are invoked by the $HADOOP_HOME/bin/hadoop command. Running the Hadoop script without any arguments prints the description for all commands. Usage − hadoop [--config confdir] COMMAND The following table lists the options available and their description. namenode -format Formats the DFS filesystem. secondarynamenode Runs the DFS secondary namenode. namenode Runs the DFS namenode. datanode Runs a DFS datanode. dfsadmin Runs a DFS admin client. mradmin Runs a Map-Reduce admin client. fsck Runs a DFS filesystem checking utility. fs Runs a generic filesystem user client. balancer Runs a cluster balancing utility. oiv Applies the offline fsimage viewer to an fsimage. fetchdt Fetches a delegation token from the NameNode. jobtracker Runs the MapReduce job Tracker node. pipes Runs a Pipes job. tasktracker Runs a MapReduce task Tracker node. historyserver Runs job history servers as a standalone daemon. job Manipulates the MapReduce jobs. queue Gets information regarding JobQueues. version Prints the version. jar <jar> Runs a jar file. distcp <srcurl> <desturl> Copies file or directories recursively. distcp2 <srcurl> <desturl> DistCp version 2. archive -archiveName NAME -p <parent path> <src>* <dest> Creates a hadoop archive. classpath Prints the class path needed to get the Hadoop jar and the required libraries. daemonlog Get/Set the log level for each daemon Usage − hadoop job [GENERIC_OPTIONS] The following are the Generic Options available in a Hadoop job. -submit <job-file> Submits the job. -status <job-id> Prints the map and reduce completion percentage and all job counters. -counter <job-id> <group-name> <countername> Prints the counter value. -kill <job-id> Kills the job. -events <job-id> <fromevent-#> <#-of-events> Prints the events' details received by jobtracker for the given range. -history [all] <jobOutputDir> - history < jobOutputDir> Prints job details, failed and killed tip details. More details about the job such as successful tasks and task attempts made for each task can be viewed by specifying the [all] option. -list[all] Displays all jobs. -list displays only jobs which are yet to complete. -kill-task <task-id> Kills the task. Killed tasks are NOT counted against failed attempts. -fail-task <task-id> Fails the task. Failed tasks are counted against failed attempts. -set-priority <job-id> <priority> Changes the priority of the job. Allowed priority values are VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW $ $HADOOP_HOME/bin/hadoop job -status <JOB-ID> e.g. $ $HADOOP_HOME/bin/hadoop job -status job_201310191043_0004 $ $HADOOP_HOME/bin/hadoop job -history <DIR-NAME> e.g. $ $HADOOP_HOME/bin/hadoop job -history /user/expert/output $ $HADOOP_HOME/bin/hadoop job -kill <JOB-ID> e.g. $ $HADOOP_HOME/bin/hadoop job -kill job_201310191043_0004
[ { "code": null, "e": 2156, "s": 1985, "text": "MapReduce is a framework using which we can write applications to process huge amounts of data, in parallel, on large clusters of commodity hardware in a reliable manner." }, { "code": null, "e": 2701, "s": 2156, "text": "MapReduce is a processing technique and a program model for distributed computing based on java. The MapReduce algorithm contains two important tasks, namely Map and Reduce. Map takes a set of data and converts it into another set of data, where individual elements are broken down into tuples (key/value pairs). Secondly, reduce task, which takes the output from a map as an input and combines those data tuples into a smaller set of tuples. As the sequence of the name MapReduce implies, the reduce task is always performed after the map job." }, { "code": null, "e": 3283, "s": 2701, "text": "The major advantage of MapReduce is that it is easy to scale data processing over multiple computing nodes. Under the MapReduce model, the data processing primitives are called mappers and reducers. Decomposing a data processing application into mappers and reducers is sometimes nontrivial. But, once we write an application in the MapReduce form, scaling the application to run over hundreds, thousands, or even tens of thousands of machines in a cluster is merely a configuration change. This simple scalability is what has attracted many programmers to use the MapReduce model." }, { "code": null, "e": 3372, "s": 3283, "text": "Generally MapReduce paradigm is based on sending the computer to where the data resides!" }, { "code": null, "e": 3461, "s": 3372, "text": "Generally MapReduce paradigm is based on sending the computer to where the data resides!" }, { "code": null, "e": 4113, "s": 3461, "text": "MapReduce program executes in three stages, namely map stage, shuffle stage, and reduce stage.\n\nMap stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. \nReduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS.\n\n" }, { "code": null, "e": 4208, "s": 4113, "text": "MapReduce program executes in three stages, namely map stage, shuffle stage, and reduce stage." }, { "code": null, "e": 4518, "s": 4208, "text": "Map stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. " }, { "code": null, "e": 4828, "s": 4518, "text": "Map stage − The map or mapper’s job is to process the input data. Generally the input data is in the form of file or directory and is stored in the Hadoop file system (HDFS). The input file is passed to the mapper function line by line. The mapper processes the data and creates several small chunks of data. " }, { "code": null, "e": 5072, "s": 4828, "text": "Reduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS." }, { "code": null, "e": 5316, "s": 5072, "text": "Reduce stage − This stage is the combination of the Shuffle stage and the Reduce stage. The Reducer’s job is to process the data that comes from the mapper. After processing, it produces a new set of output, which will be stored in the HDFS." }, { "code": null, "e": 5421, "s": 5316, "text": "During a MapReduce job, Hadoop sends the Map and Reduce tasks to the appropriate servers in the cluster." }, { "code": null, "e": 5526, "s": 5421, "text": "During a MapReduce job, Hadoop sends the Map and Reduce tasks to the appropriate servers in the cluster." }, { "code": null, "e": 5685, "s": 5526, "text": "The framework manages all the details of data-passing such as issuing tasks, verifying task completion, and copying data around the cluster between the nodes." }, { "code": null, "e": 5844, "s": 5685, "text": "The framework manages all the details of data-passing such as issuing tasks, verifying task completion, and copying data around the cluster between the nodes." }, { "code": null, "e": 5946, "s": 5844, "text": "Most of the computing takes place on nodes with data on local disks that reduces the network traffic." }, { "code": null, "e": 6048, "s": 5946, "text": "Most of the computing takes place on nodes with data on local disks that reduces the network traffic." }, { "code": null, "e": 6198, "s": 6048, "text": "After completion of the given tasks, the cluster collects and reduces the data to form an appropriate result, and sends it back to the Hadoop server." }, { "code": null, "e": 6348, "s": 6198, "text": "After completion of the given tasks, the cluster collects and reduces the data to form an appropriate result, and sends it back to the Hadoop server." }, { "code": null, "e": 6584, "s": 6348, "text": "The MapReduce framework operates on <key, value> pairs, that is, the framework views the input to the job as a set of <key, value> pairs and produces a set of <key, value> pairs as the output of the job, conceivably of different types." }, { "code": null, "e": 6944, "s": 6584, "text": "The key and the value classes should be in serialized manner by the framework and hence, need to implement the Writable interface. Additionally, the key classes have to implement the Writable-Comparable interface to facilitate sorting by the framework. Input and Output types of a MapReduce job − (Input) <k1, v1> → map → <k2, v2> → reduce → <k3, v3>(Output)." }, { "code": null, "e": 7041, "s": 6944, "text": "PayLoad − Applications implement the Map and the Reduce functions, and form the core of the job." }, { "code": null, "e": 7138, "s": 7041, "text": "PayLoad − Applications implement the Map and the Reduce functions, and form the core of the job." }, { "code": null, "e": 7226, "s": 7138, "text": "Mapper − Mapper maps the input key/value pairs to a set of intermediate key/value pair." }, { "code": null, "e": 7314, "s": 7226, "text": "Mapper − Mapper maps the input key/value pairs to a set of intermediate key/value pair." }, { "code": null, "e": 7387, "s": 7314, "text": "NamedNode − Node that manages the Hadoop Distributed File System (HDFS)." }, { "code": null, "e": 7460, "s": 7387, "text": "NamedNode − Node that manages the Hadoop Distributed File System (HDFS)." }, { "code": null, "e": 7546, "s": 7460, "text": "DataNode − Node where data is presented in advance before any processing takes place." }, { "code": null, "e": 7632, "s": 7546, "text": "DataNode − Node where data is presented in advance before any processing takes place." }, { "code": null, "e": 7717, "s": 7632, "text": "MasterNode − Node where JobTracker runs and which accepts job requests from clients." }, { "code": null, "e": 7802, "s": 7717, "text": "MasterNode − Node where JobTracker runs and which accepts job requests from clients." }, { "code": null, "e": 7854, "s": 7802, "text": "SlaveNode − Node where Map and Reduce program runs." }, { "code": null, "e": 7906, "s": 7854, "text": "SlaveNode − Node where Map and Reduce program runs." }, { "code": null, "e": 7978, "s": 7906, "text": "JobTracker − Schedules jobs and tracks the assign jobs to Task tracker." }, { "code": null, "e": 8050, "s": 7978, "text": "JobTracker − Schedules jobs and tracks the assign jobs to Task tracker." }, { "code": null, "e": 8116, "s": 8050, "text": "Task Tracker − Tracks the task and reports status to JobTracker. " }, { "code": null, "e": 8182, "s": 8116, "text": "Task Tracker − Tracks the task and reports status to JobTracker. " }, { "code": null, "e": 8256, "s": 8182, "text": "Job − A program is an execution of a Mapper and Reducer across a dataset." }, { "code": null, "e": 8330, "s": 8256, "text": "Job − A program is an execution of a Mapper and Reducer across a dataset." }, { "code": null, "e": 8396, "s": 8330, "text": "Task − An execution of a Mapper or a Reducer on a slice of data. " }, { "code": null, "e": 8462, "s": 8396, "text": "Task − An execution of a Mapper or a Reducer on a slice of data. " }, { "code": null, "e": 8547, "s": 8462, "text": "Task Attempt − A particular instance of an attempt to execute a task on a SlaveNode." }, { "code": null, "e": 8632, "s": 8547, "text": "Task Attempt − A particular instance of an attempt to execute a task on a SlaveNode." }, { "code": null, "e": 8802, "s": 8632, "text": "Given below is the data regarding the electrical consumption of an organization. It contains the monthly electrical consumption and the annual average for various years." }, { "code": null, "e": 9161, "s": 8802, "text": "If the above data is given as input, we have to write applications to process it and produce results such as finding the year of maximum usage, year of minimum usage, and so on. This is a walkover for the programmers with finite number of records. They will simply write the logic to produce the required output, and pass the data to the application written." }, { "code": null, "e": 9301, "s": 9161, "text": "But, think of the data representing the electrical consumption of all the largescale industries of a particular state, since its formation." }, { "code": null, "e": 9355, "s": 9301, "text": "When we write applications to process such bulk data," }, { "code": null, "e": 9396, "s": 9355, "text": "They will take a lot of time to execute." }, { "code": null, "e": 9437, "s": 9396, "text": "They will take a lot of time to execute." }, { "code": null, "e": 9534, "s": 9437, "text": "There will be a heavy network traffic when we move data from source to network server and so on." }, { "code": null, "e": 9631, "s": 9534, "text": "There will be a heavy network traffic when we move data from source to network server and so on." }, { "code": null, "e": 9689, "s": 9631, "text": "To solve these problems, we have the MapReduce framework." }, { "code": null, "e": 9783, "s": 9689, "text": "The above data is saved as sample.txtand given as input. The input file looks as shown below." }, { "code": null, "e": 10129, "s": 9783, "text": "1979 23 23 2 43 24 25 26 26 26 26 25 26 25 \n1980 26 27 28 28 28 30 31 31 31 30 30 30 29 \n1981 31 32 32 32 33 34 35 36 36 34 34 34 34 \n1984 39 38 39 39 39 41 42 43 40 39 38 38 40 \n1985 38 39 39 39 39 41 41 41 00 40 39 39 45 \n" }, { "code": null, "e": 10202, "s": 10129, "text": "Given below is the program to the sample data using MapReduce framework." }, { "code": null, "e": 12670, "s": 10202, "text": "package hadoop; \n\nimport java.util.*; \n\nimport java.io.IOException; \nimport java.io.IOException; \n\nimport org.apache.hadoop.fs.Path; \nimport org.apache.hadoop.conf.*; \nimport org.apache.hadoop.io.*; \nimport org.apache.hadoop.mapred.*; \nimport org.apache.hadoop.util.*; \n\npublic class ProcessUnits {\n //Mapper class \n public static class E_EMapper extends MapReduceBase implements \n Mapper<LongWritable ,/*Input key Type */ \n Text, /*Input value Type*/ \n Text, /*Output key Type*/ \n IntWritable> /*Output value Type*/ \n {\n //Map function \n public void map(LongWritable key, Text value, \n OutputCollector<Text, IntWritable> output, \n \n Reporter reporter) throws IOException { \n String line = value.toString(); \n String lasttoken = null; \n StringTokenizer s = new StringTokenizer(line,\"\\t\"); \n String year = s.nextToken(); \n \n while(s.hasMoreTokens()) {\n lasttoken = s.nextToken();\n }\n int avgprice = Integer.parseInt(lasttoken); \n output.collect(new Text(year), new IntWritable(avgprice)); \n } \n }\n \n //Reducer class \n public static class E_EReduce extends MapReduceBase implements Reducer< Text, IntWritable, Text, IntWritable > {\n \n //Reduce function \n public void reduce( Text key, Iterator <IntWritable> values, \n OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { \n int maxavg = 30; \n int val = Integer.MIN_VALUE; \n \n while (values.hasNext()) { \n if((val = values.next().get())>maxavg) { \n output.collect(key, new IntWritable(val)); \n } \n }\n } \n }\n\n //Main function \n public static void main(String args[])throws Exception { \n JobConf conf = new JobConf(ProcessUnits.class); \n \n conf.setJobName(\"max_eletricityunits\"); \n conf.setOutputKeyClass(Text.class);\n conf.setOutputValueClass(IntWritable.class); \n conf.setMapperClass(E_EMapper.class); \n conf.setCombinerClass(E_EReduce.class); \n conf.setReducerClass(E_EReduce.class); \n conf.setInputFormat(TextInputFormat.class); \n conf.setOutputFormat(TextOutputFormat.class); \n \n FileInputFormat.setInputPaths(conf, new Path(args[0])); \n FileOutputFormat.setOutputPath(conf, new Path(args[1])); \n \n JobClient.runJob(conf); \n } \n} " }, { "code": null, "e": 12780, "s": 12670, "text": "Save the above program as ProcessUnits.java. The compilation and execution of the program is explained below." }, { "code": null, "e": 12861, "s": 12780, "text": "Let us assume we are in the home directory of a Hadoop user (e.g. /home/hadoop)." }, { "code": null, "e": 12932, "s": 12861, "text": "Follow the steps given below to compile and execute the above program." }, { "code": null, "e": 13015, "s": 12932, "text": "The following command is to create a directory to store the compiled java classes." }, { "code": null, "e": 13031, "s": 13015, "text": "$ mkdir units \n" }, { "code": null, "e": 13242, "s": 13031, "text": "Download Hadoop-core-1.2.1.jar, which is used to compile and execute the MapReduce program. Visit the following link mvnrepository.com to download the jar. Let us assume the downloaded folder is /home/hadoop/." }, { "code": null, "e": 13354, "s": 13242, "text": "The following commands are used for compiling the ProcessUnits.java program and creating a jar for the program." }, { "code": null, "e": 13458, "s": 13354, "text": "$ javac -classpath hadoop-core-1.2.1.jar -d units ProcessUnits.java \n$ jar -cvf units.jar -C units/ . \n" }, { "code": null, "e": 13526, "s": 13458, "text": "The following command is used to create an input directory in HDFS." }, { "code": null, "e": 13572, "s": 13526, "text": "$HADOOP_HOME/bin/hadoop fs -mkdir input_dir \n" }, { "code": null, "e": 13673, "s": 13572, "text": "The following command is used to copy the input file named sample.txtin the input directory of HDFS." }, { "code": null, "e": 13741, "s": 13673, "text": "$HADOOP_HOME/bin/hadoop fs -put /home/hadoop/sample.txt input_dir \n" }, { "code": null, "e": 13815, "s": 13741, "text": "The following command is used to verify the files in the input directory." }, { "code": null, "e": 13859, "s": 13815, "text": "$HADOOP_HOME/bin/hadoop fs -ls input_dir/ \n" }, { "code": null, "e": 13976, "s": 13859, "text": "The following command is used to run the Eleunit_max application by taking the input files from the input directory." }, { "code": null, "e": 14057, "s": 13976, "text": "$HADOOP_HOME/bin/hadoop jar units.jar hadoop.ProcessUnits input_dir output_dir \n" }, { "code": null, "e": 14246, "s": 14057, "text": "Wait for a while until the file is executed. After execution, as shown below, the output will contain the number of input splits, the number of Map tasks, the number of reducer tasks, etc." }, { "code": null, "e": 16097, "s": 14246, "text": "INFO mapreduce.Job: Job job_1414748220717_0002 \ncompleted successfully \n14/10/31 06:02:52 \nINFO mapreduce.Job: Counters: 49 \n File System Counters \n \nFILE: Number of bytes read = 61 \nFILE: Number of bytes written = 279400 \nFILE: Number of read operations = 0 \nFILE: Number of large read operations = 0 \nFILE: Number of write operations = 0 \nHDFS: Number of bytes read = 546 \nHDFS: Number of bytes written = 40 \nHDFS: Number of read operations = 9 \nHDFS: Number of large read operations = 0 \nHDFS: Number of write operations = 2 Job Counters \n\n\n Launched map tasks = 2 \n Launched reduce tasks = 1 \n Data-local map tasks = 2 \n Total time spent by all maps in occupied slots (ms) = 146137 \n Total time spent by all reduces in occupied slots (ms) = 441 \n Total time spent by all map tasks (ms) = 14613 \n Total time spent by all reduce tasks (ms) = 44120 \n Total vcore-seconds taken by all map tasks = 146137 \n Total vcore-seconds taken by all reduce tasks = 44120 \n Total megabyte-seconds taken by all map tasks = 149644288 \n Total megabyte-seconds taken by all reduce tasks = 45178880 \n \nMap-Reduce Framework \n \n Map input records = 5 \n Map output records = 5 \n Map output bytes = 45 \n Map output materialized bytes = 67 \n Input split bytes = 208 \n Combine input records = 5 \n Combine output records = 5 \n Reduce input groups = 5 \n Reduce shuffle bytes = 6 \n Reduce input records = 5 \n Reduce output records = 5 \n Spilled Records = 10 \n Shuffled Maps = 2 \n Failed Shuffles = 0 \n Merged Map outputs = 2 \n GC time elapsed (ms) = 948 \n CPU time spent (ms) = 5160 \n Physical memory (bytes) snapshot = 47749120 \n Virtual memory (bytes) snapshot = 2899349504 \n Total committed heap usage (bytes) = 277684224\n \nFile Output Format Counters \n \n Bytes Written = 40 \n" }, { "code": null, "e": 16179, "s": 16097, "text": "The following command is used to verify the resultant files in the output folder." }, { "code": null, "e": 16224, "s": 16179, "text": "$HADOOP_HOME/bin/hadoop fs -ls output_dir/ \n" }, { "code": null, "e": 16326, "s": 16224, "text": "The following command is used to see the output in Part-00000 file. This file is generated by HDFS." }, { "code": null, "e": 16382, "s": 16326, "text": "$HADOOP_HOME/bin/hadoop fs -cat output_dir/part-00000 \n" }, { "code": null, "e": 16438, "s": 16382, "text": "Below is the output generated by the MapReduce program." }, { "code": null, "e": 16475, "s": 16438, "text": "1981 34 \n1984 40 \n1985 45 \n" }, { "code": null, "e": 16581, "s": 16475, "text": "The following command is used to copy the output folder from HDFS to the local file system for analyzing." }, { "code": null, "e": 16680, "s": 16581, "text": "$HADOOP_HOME/bin/hadoop fs -cat output_dir/part-00000/bin/hadoop dfs get output_dir /home/hadoop \n" }, { "code": null, "e": 16841, "s": 16680, "text": "All Hadoop commands are invoked by the $HADOOP_HOME/bin/hadoop command. Running the Hadoop script without any arguments prints the description for all commands." }, { "code": null, "e": 16883, "s": 16841, "text": "Usage − hadoop [--config confdir] COMMAND" }, { "code": null, "e": 16954, "s": 16883, "text": "The following table lists the options available and their description." }, { "code": null, "e": 16971, "s": 16954, "text": "namenode -format" }, { "code": null, "e": 16999, "s": 16971, "text": "Formats the DFS filesystem." }, { "code": null, "e": 17017, "s": 16999, "text": "secondarynamenode" }, { "code": null, "e": 17050, "s": 17017, "text": "Runs the DFS secondary namenode." }, { "code": null, "e": 17059, "s": 17050, "text": "namenode" }, { "code": null, "e": 17082, "s": 17059, "text": "Runs the DFS namenode." }, { "code": null, "e": 17091, "s": 17082, "text": "datanode" }, { "code": null, "e": 17112, "s": 17091, "text": "Runs a DFS datanode." }, { "code": null, "e": 17121, "s": 17112, "text": "dfsadmin" }, { "code": null, "e": 17146, "s": 17121, "text": "Runs a DFS admin client." }, { "code": null, "e": 17154, "s": 17146, "text": "mradmin" }, { "code": null, "e": 17186, "s": 17154, "text": "Runs a Map-Reduce admin client." }, { "code": null, "e": 17191, "s": 17186, "text": "fsck" }, { "code": null, "e": 17231, "s": 17191, "text": "Runs a DFS filesystem checking utility." }, { "code": null, "e": 17234, "s": 17231, "text": "fs" }, { "code": null, "e": 17273, "s": 17234, "text": "Runs a generic filesystem user client." }, { "code": null, "e": 17282, "s": 17273, "text": "balancer" }, { "code": null, "e": 17316, "s": 17282, "text": "Runs a cluster balancing utility." }, { "code": null, "e": 17320, "s": 17316, "text": "oiv" }, { "code": null, "e": 17370, "s": 17320, "text": "Applies the offline fsimage viewer to an fsimage." }, { "code": null, "e": 17378, "s": 17370, "text": "fetchdt" }, { "code": null, "e": 17424, "s": 17378, "text": "Fetches a delegation token from the NameNode." }, { "code": null, "e": 17435, "s": 17424, "text": "jobtracker" }, { "code": null, "e": 17472, "s": 17435, "text": "Runs the MapReduce job Tracker node." }, { "code": null, "e": 17478, "s": 17472, "text": "pipes" }, { "code": null, "e": 17496, "s": 17478, "text": "Runs a Pipes job." }, { "code": null, "e": 17508, "s": 17496, "text": "tasktracker" }, { "code": null, "e": 17544, "s": 17508, "text": "Runs a MapReduce task Tracker node." }, { "code": null, "e": 17558, "s": 17544, "text": "historyserver" }, { "code": null, "e": 17607, "s": 17558, "text": "Runs job history servers as a standalone daemon." }, { "code": null, "e": 17611, "s": 17607, "text": "job" }, { "code": null, "e": 17643, "s": 17611, "text": "Manipulates the MapReduce jobs." }, { "code": null, "e": 17649, "s": 17643, "text": "queue" }, { "code": null, "e": 17687, "s": 17649, "text": "Gets information regarding JobQueues." }, { "code": null, "e": 17695, "s": 17687, "text": "version" }, { "code": null, "e": 17715, "s": 17695, "text": "Prints the version." }, { "code": null, "e": 17725, "s": 17715, "text": "jar <jar>" }, { "code": null, "e": 17742, "s": 17725, "text": "Runs a jar file." }, { "code": null, "e": 17768, "s": 17742, "text": "distcp <srcurl> <desturl>" }, { "code": null, "e": 17808, "s": 17768, "text": "Copies file or directories recursively." }, { "code": null, "e": 17835, "s": 17808, "text": "distcp2 <srcurl> <desturl>" }, { "code": null, "e": 17853, "s": 17835, "text": "DistCp version 2." }, { "code": null, "e": 17910, "s": 17853, "text": "archive -archiveName NAME -p <parent path> <src>* <dest>" }, { "code": null, "e": 17936, "s": 17910, "text": "Creates a hadoop archive." }, { "code": null, "e": 17946, "s": 17936, "text": "classpath" }, { "code": null, "e": 18025, "s": 17946, "text": "Prints the class path needed to get the Hadoop jar and the required libraries." }, { "code": null, "e": 18035, "s": 18025, "text": "daemonlog" }, { "code": null, "e": 18073, "s": 18035, "text": "Get/Set the log level for each daemon" }, { "code": null, "e": 18110, "s": 18073, "text": "Usage − hadoop job [GENERIC_OPTIONS]" }, { "code": null, "e": 18175, "s": 18110, "text": "The following are the Generic Options available in a Hadoop job." }, { "code": null, "e": 18194, "s": 18175, "text": "-submit <job-file>" }, { "code": null, "e": 18211, "s": 18194, "text": "Submits the job." }, { "code": null, "e": 18228, "s": 18211, "text": "-status <job-id>" }, { "code": null, "e": 18298, "s": 18228, "text": "Prints the map and reduce completion percentage and all job counters." }, { "code": null, "e": 18343, "s": 18298, "text": "-counter <job-id> <group-name> <countername>" }, { "code": null, "e": 18369, "s": 18343, "text": "Prints the counter value." }, { "code": null, "e": 18384, "s": 18369, "text": "-kill <job-id>" }, { "code": null, "e": 18399, "s": 18384, "text": "Kills the job." }, { "code": null, "e": 18444, "s": 18399, "text": "-events <job-id> <fromevent-#> <#-of-events>" }, { "code": null, "e": 18515, "s": 18444, "text": "Prints the events' details received by jobtracker for the given range." }, { "code": null, "e": 18571, "s": 18515, "text": "-history [all] <jobOutputDir> - history < jobOutputDir>" }, { "code": null, "e": 18757, "s": 18571, "text": "Prints job details, failed and killed tip details. More details about the job such as successful tasks and task attempts made for each task can be viewed by specifying the [all] option." }, { "code": null, "e": 18768, "s": 18757, "text": "-list[all]" }, { "code": null, "e": 18839, "s": 18768, "text": "Displays all jobs. -list displays only jobs which are yet to complete." }, { "code": null, "e": 18860, "s": 18839, "text": "-kill-task <task-id>" }, { "code": null, "e": 18930, "s": 18860, "text": "Kills the task. Killed tasks are NOT counted against failed attempts." }, { "code": null, "e": 18951, "s": 18930, "text": "-fail-task <task-id>" }, { "code": null, "e": 19017, "s": 18951, "text": "Fails the task. Failed tasks are counted against failed attempts." }, { "code": null, "e": 19051, "s": 19017, "text": "-set-priority <job-id> <priority>" }, { "code": null, "e": 19151, "s": 19051, "text": "Changes the priority of the job. Allowed priority values are VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW" }, { "code": null, "e": 19267, "s": 19151, "text": "$ $HADOOP_HOME/bin/hadoop job -status <JOB-ID> \ne.g. \n$ $HADOOP_HOME/bin/hadoop job -status job_201310191043_0004 \n" }, { "code": null, "e": 19385, "s": 19267, "text": "$ $HADOOP_HOME/bin/hadoop job -history <DIR-NAME> \ne.g. \n$ $HADOOP_HOME/bin/hadoop job -history /user/expert/output \n" } ]
Merge a linked list into another linked list at alternate positions
03 Jul, 2022 Given two linked lists, insert nodes of second list into first list at alternate positions of first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The nodes of second list should only be inserted when there are positions available. For example, if the first list is 1->2->3 and second list is 4->5->6->7->8, then first list should become 1->4->2->5->3->6 and second list to 7->8. Use of extra space is not allowed (Not allowed to create additional nodes), i.e., insertion must be done in-place. Expected time complexity is O(n) where n is number of nodes in first list. The idea is to run a loop while there are available positions in first loop and insert nodes of second list by changing pointers. Following are implementations of this approach. C++ C Java Python3 C# Javascript // C++ program to merge a linked list into another at // alternate positions #include <bits/stdc++.h>using namespace std; // A nexted list node class Node { public: int data; Node *next; }; /* Function to insert a node at the beginning */void push(Node ** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } /* Utility function to print a singly linked list */void printList(Node *head) { Node *temp = head; while (temp != NULL) { cout<<temp->data<<" "; temp = temp->next; } cout<<endl;} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer // for first list and double pointer for second list. void merge(Node *p, Node **q) { Node *p_curr = p, *q_curr = *q; Node *p_next, *q_next; // While there are available positions in p while (p_curr != NULL && q_curr != NULL) { // Save next pointers p_next = p_curr->next; q_next = q_curr->next; // Make q_curr as next of p_curr q_curr->next = p_next; // Change next pointer of q_curr p_curr->next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } *q = q_curr; // Update head pointer of second list } // Driver code int main() { Node *p = NULL, *q = NULL; push(&p, 3); push(&p, 2); push(&p, 1); cout<<"First Linked List:\n"; printList(p); push(&q, 8); push(&q, 7); push(&q, 6); push(&q, 5); push(&q, 4); cout<<"Second Linked List:\n"; printList(q); merge(p, &q); cout<<"Modified First Linked List:\n"; printList(p); cout<<"Modified Second Linked List:\n"; printList(q); return 0; } // This code is contributed by rathbhupendra // C program to merge a linked list into another at// alternate positions#include <stdio.h>#include <stdlib.h> // A nexted list nodestruct Node{ int data; struct Node *next;}; /* Function to insert a node at the beginning */void push(struct Node ** head_ref, int new_data){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer// for first list and double pointer for second list.void merge(struct Node *p, struct Node **q){ struct Node *p_curr = p, *q_curr = *q; struct Node *p_next, *q_next; // While there are available positions in p while (p_curr != NULL && q_curr != NULL) { // Save next pointers p_next = p_curr->next; q_next = q_curr->next; // Make q_curr as next of p_curr q_curr->next = p_next; // Change next pointer of q_curr p_curr->next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } *q = q_curr; // Update head pointer of second list} // Driver program to test above functionsint main(){ struct Node *p = NULL, *q = NULL; push(&p, 3); push(&p, 2); push(&p, 1); printf("First Linked List:\n"); printList(p); push(&q, 8); push(&q, 7); push(&q, 6); push(&q, 5); push(&q, 4); printf("Second Linked List:\n"); printList(q); merge(p, &q); printf("Modified First Linked List:\n"); printList(p); printf("Modified Second Linked List:\n"); printList(q); getchar(); return 0;} // Java program to merge a linked list into another at// alternate positionsclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list/ may change, we need single pointer // for first list and double pointer for second list. void merge(LinkedList q) { Node p_curr = head, q_curr = q.head; Node p_next, q_next; // While there are available positions in p; while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // make q_curr as next of p_curr q_curr.next = p_next; // change next pointer of q_curr p_curr.next = q_curr; // change next pointer of p_curr // update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q.head = q_curr; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); llist1.push(3); llist1.push(2); llist1.push(1); System.out.println("First Linked List:"); llist1.printList(); llist2.push(8); llist2.push(7); llist2.push(6); llist2.push(5); llist2.push(4); System.out.println("Second Linked List:"); llist1.merge(llist2); System.out.println("Modified first linked list:"); llist1.printList(); System.out.println("Modified second linked list:"); llist2.printList(); }} /* This code is contributed by Rajat Mishra */ # Python program to merge a linked list into another at# alternate positions class Node(object): def __init__(self, data:int): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None def push(self, new_data:int): new_node = Node(new_data) new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list from the Head def printList(self): temp = self.head while temp != None: print(temp.data) temp = temp.next # Main function that inserts nodes of linked list q into p at alternate positions. # Since head of first list never changes # but head of second list/ may change, # we need single pointer for first list and double pointer for second list. def merge(self, p, q): p_curr = p.head q_curr = q.head # swap their positions until one finishes off while p_curr != None and q_curr != None: # Save next pointers p_next = p_curr.next q_next = q_curr.next # make q_curr as next of p_curr q_curr.next = p_next # change next pointer of q_curr p_curr.next = q_curr # change next pointer of p_curr # update current pointers for next iteration p_curr = p_next q_curr = q_next q.head = q_curr # Driver program to test above functionsllist1 = LinkedList()llist2 = LinkedList() # Creating LLs # 1.llist1.push(3)llist1.push(2)llist1.push(1)llist1.push(0) # 2.for i in range(8, 3, -1): llist2.push(i) print("First Linked List:")llist1.printList() print("Second Linked List:")llist2.printList() # Merging the LLsllist1.merge(p=llist1, q=llist2) print("Modified first linked list:")llist1.printList() print("Modified second linked list:")llist2.printList() # This code is contributed by Deepanshu Mehta // C# program to merge a linked list into// another at alternate positionsusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Main function that inserts nodes // of linked list q into p at alternate // positions. Since head of first list // never changes and head of second // list/ may change, we need single // pointer for first list and double // pointer for second list. void merge(LinkedList q) { Node p_curr = head, q_curr = q.head; Node p_next, q_next; // While there are available positions in p; while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // make q_curr as next of p_curr q_curr.next = p_next; // change next pointer of q_curr p_curr.next = q_curr; // change next pointer of p_curr // update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q.head = q_curr; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data+" "); temp = temp.next; } Console.WriteLine(); } /* Driver code*/ public static void Main() { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); llist1.push(3); llist1.push(2); llist1.push(1); Console.WriteLine("First Linked List:"); llist1.printList(); llist2.push(8); llist2.push(7); llist2.push(6); llist2.push(5); llist2.push(4); Console.WriteLine("Second Linked List:"); llist1.merge(llist2); Console.WriteLine("Modified first linked list:"); llist1.printList(); Console.WriteLine("Modified second linked list:"); llist2.printList(); } } /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to merge a linked list into another at // alternate positions // A nexted list node class Node { constructor() { this.data = 0; this.next = null; }}; /* Function to insert a node at the beginning */function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } /* Utility function to print a singly linked list */function printList(head) { var temp = head; while (temp != null) { document.write( temp.data + " "); temp = temp.next; } document.write("<br>");} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer // for first list and double pointer for second list. function merge(p, q) { var p_curr = p, q_curr = q; var p_next, q_next; // While there are available positions in p while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // Make q_curr as next of p_curr q_curr.next = p_next; // Change next pointer of q_curr p_curr.next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q = q_curr; // Update head pointer of second list return q;} // Driver code var p = null, q = null; p = push(p, 3); p = push(p, 2); p = push(p, 1); document.write( "First Linked List:<br>"); printList(p); q = push(q, 8); q = push(q, 7); q = push(q, 6); q = push(q, 5); q = push(q, 4); document.write( "Second Linked List:<br>"); printList(q); q = merge(p, q); document.write( "Modified First Linked List:<br>"); printList(p); document.write( "Modified Second Linked List:<br>"); printList(q); // This code is contributed by rrrtnx.</script> First Linked List: 1 2 3 Second Linked List: 4 5 6 7 8 Modified First Linked List: 1 4 2 5 3 6 Modified Second Linked List: 7 8 Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists.Auxiliary Space: O(1), no extra space is required, so it is a constant. princiraj1992 rathbhupendra nidhi_biet rrrtnx Deepanshu_mehta sagartomar9927 sagar0719kumar simmytarika5 samim2000 hardikkoriintern Amazon Linked List Amazon Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Detect and Remove Loop in a Linked List Add two numbers represented by linked lists | Set 1 Queue - Linked List Implementation Function to check if a singly linked list is palindrome Implement a stack using singly linked list
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jul, 2022" }, { "code": null, "e": 569, "s": 52, "text": "Given two linked lists, insert nodes of second list into first list at alternate positions of first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The nodes of second list should only be inserted when there are positions available. For example, if the first list is 1->2->3 and second list is 4->5->6->7->8, then first list should become 1->4->2->5->3->6 and second list to 7->8." }, { "code": null, "e": 760, "s": 569, "text": "Use of extra space is not allowed (Not allowed to create additional nodes), i.e., insertion must be done in-place. Expected time complexity is O(n) where n is number of nodes in first list. " }, { "code": null, "e": 890, "s": 760, "text": "The idea is to run a loop while there are available positions in first loop and insert nodes of second list by changing pointers." }, { "code": null, "e": 939, "s": 890, "text": "Following are implementations of this approach. " }, { "code": null, "e": 943, "s": 939, "text": "C++" }, { "code": null, "e": 945, "s": 943, "text": "C" }, { "code": null, "e": 950, "s": 945, "text": "Java" }, { "code": null, "e": 958, "s": 950, "text": "Python3" }, { "code": null, "e": 961, "s": 958, "text": "C#" }, { "code": null, "e": 972, "s": 961, "text": "Javascript" }, { "code": "// C++ program to merge a linked list into another at // alternate positions #include <bits/stdc++.h>using namespace std; // A nexted list node class Node { public: int data; Node *next; }; /* Function to insert a node at the beginning */void push(Node ** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } /* Utility function to print a singly linked list */void printList(Node *head) { Node *temp = head; while (temp != NULL) { cout<<temp->data<<\" \"; temp = temp->next; } cout<<endl;} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer // for first list and double pointer for second list. void merge(Node *p, Node **q) { Node *p_curr = p, *q_curr = *q; Node *p_next, *q_next; // While there are available positions in p while (p_curr != NULL && q_curr != NULL) { // Save next pointers p_next = p_curr->next; q_next = q_curr->next; // Make q_curr as next of p_curr q_curr->next = p_next; // Change next pointer of q_curr p_curr->next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } *q = q_curr; // Update head pointer of second list } // Driver code int main() { Node *p = NULL, *q = NULL; push(&p, 3); push(&p, 2); push(&p, 1); cout<<\"First Linked List:\\n\"; printList(p); push(&q, 8); push(&q, 7); push(&q, 6); push(&q, 5); push(&q, 4); cout<<\"Second Linked List:\\n\"; printList(q); merge(p, &q); cout<<\"Modified First Linked List:\\n\"; printList(p); cout<<\"Modified Second Linked List:\\n\"; printList(q); return 0; } // This code is contributed by rathbhupendra", "e": 3003, "s": 972, "text": null }, { "code": "// C program to merge a linked list into another at// alternate positions#include <stdio.h>#include <stdlib.h> // A nexted list nodestruct Node{ int data; struct Node *next;}; /* Function to insert a node at the beginning */void push(struct Node ** head_ref, int new_data){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer// for first list and double pointer for second list.void merge(struct Node *p, struct Node **q){ struct Node *p_curr = p, *q_curr = *q; struct Node *p_next, *q_next; // While there are available positions in p while (p_curr != NULL && q_curr != NULL) { // Save next pointers p_next = p_curr->next; q_next = q_curr->next; // Make q_curr as next of p_curr q_curr->next = p_next; // Change next pointer of q_curr p_curr->next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } *q = q_curr; // Update head pointer of second list} // Driver program to test above functionsint main(){ struct Node *p = NULL, *q = NULL; push(&p, 3); push(&p, 2); push(&p, 1); printf(\"First Linked List:\\n\"); printList(p); push(&q, 8); push(&q, 7); push(&q, 6); push(&q, 5); push(&q, 4); printf(\"Second Linked List:\\n\"); printList(q); merge(p, &q); printf(\"Modified First Linked List:\\n\"); printList(p); printf(\"Modified Second Linked List:\\n\"); printList(q); getchar(); return 0;}", "e": 5109, "s": 3003, "text": null }, { "code": "// Java program to merge a linked list into another at// alternate positionsclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list/ may change, we need single pointer // for first list and double pointer for second list. void merge(LinkedList q) { Node p_curr = head, q_curr = q.head; Node p_next, q_next; // While there are available positions in p; while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // make q_curr as next of p_curr q_curr.next = p_next; // change next pointer of q_curr p_curr.next = q_curr; // change next pointer of p_curr // update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q.head = q_curr; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+\" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); llist1.push(3); llist1.push(2); llist1.push(1); System.out.println(\"First Linked List:\"); llist1.printList(); llist2.push(8); llist2.push(7); llist2.push(6); llist2.push(5); llist2.push(4); System.out.println(\"Second Linked List:\"); llist1.merge(llist2); System.out.println(\"Modified first linked list:\"); llist1.printList(); System.out.println(\"Modified second linked list:\"); llist2.printList(); }} /* This code is contributed by Rajat Mishra */", "e": 7625, "s": 5109, "text": null }, { "code": "# Python program to merge a linked list into another at# alternate positions class Node(object): def __init__(self, data:int): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None def push(self, new_data:int): new_node = Node(new_data) new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list from the Head def printList(self): temp = self.head while temp != None: print(temp.data) temp = temp.next # Main function that inserts nodes of linked list q into p at alternate positions. # Since head of first list never changes # but head of second list/ may change, # we need single pointer for first list and double pointer for second list. def merge(self, p, q): p_curr = p.head q_curr = q.head # swap their positions until one finishes off while p_curr != None and q_curr != None: # Save next pointers p_next = p_curr.next q_next = q_curr.next # make q_curr as next of p_curr q_curr.next = p_next # change next pointer of q_curr p_curr.next = q_curr # change next pointer of p_curr # update current pointers for next iteration p_curr = p_next q_curr = q_next q.head = q_curr # Driver program to test above functionsllist1 = LinkedList()llist2 = LinkedList() # Creating LLs # 1.llist1.push(3)llist1.push(2)llist1.push(1)llist1.push(0) # 2.for i in range(8, 3, -1): llist2.push(i) print(\"First Linked List:\")llist1.printList() print(\"Second Linked List:\")llist2.printList() # Merging the LLsllist1.merge(p=llist1, q=llist2) print(\"Modified first linked list:\")llist1.printList() print(\"Modified second linked list:\")llist2.printList() # This code is contributed by Deepanshu Mehta", "e": 9629, "s": 7625, "text": null }, { "code": "// C# program to merge a linked list into// another at alternate positionsusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Main function that inserts nodes // of linked list q into p at alternate // positions. Since head of first list // never changes and head of second // list/ may change, we need single // pointer for first list and double // pointer for second list. void merge(LinkedList q) { Node p_curr = head, q_curr = q.head; Node p_next, q_next; // While there are available positions in p; while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // make q_curr as next of p_curr q_curr.next = p_next; // change next pointer of q_curr p_curr.next = q_curr; // change next pointer of p_curr // update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q.head = q_curr; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data+\" \"); temp = temp.next; } Console.WriteLine(); } /* Driver code*/ public static void Main() { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); llist1.push(3); llist1.push(2); llist1.push(1); Console.WriteLine(\"First Linked List:\"); llist1.printList(); llist2.push(8); llist2.push(7); llist2.push(6); llist2.push(5); llist2.push(4); Console.WriteLine(\"Second Linked List:\"); llist1.merge(llist2); Console.WriteLine(\"Modified first linked list:\"); llist1.printList(); Console.WriteLine(\"Modified second linked list:\"); llist2.printList(); } } /* This code contributed by PrinciRaj1992 */", "e": 12280, "s": 9629, "text": null }, { "code": "<script> // Javascript program to merge a linked list into another at // alternate positions // A nexted list node class Node { constructor() { this.data = 0; this.next = null; }}; /* Function to insert a node at the beginning */function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } /* Utility function to print a singly linked list */function printList(head) { var temp = head; while (temp != null) { document.write( temp.data + \" \"); temp = temp.next; } document.write(\"<br>\");} // Main function that inserts nodes of linked list q into p at // alternate positions. Since head of first list never changes // and head of second list may change, we need single pointer // for first list and double pointer for second list. function merge(p, q) { var p_curr = p, q_curr = q; var p_next, q_next; // While there are available positions in p while (p_curr != null && q_curr != null) { // Save next pointers p_next = p_curr.next; q_next = q_curr.next; // Make q_curr as next of p_curr q_curr.next = p_next; // Change next pointer of q_curr p_curr.next = q_curr; // Change next pointer of p_curr // Update current pointers for next iteration p_curr = p_next; q_curr = q_next; } q = q_curr; // Update head pointer of second list return q;} // Driver code var p = null, q = null; p = push(p, 3); p = push(p, 2); p = push(p, 1); document.write( \"First Linked List:<br>\"); printList(p); q = push(q, 8); q = push(q, 7); q = push(q, 6); q = push(q, 5); q = push(q, 4); document.write( \"Second Linked List:<br>\"); printList(q); q = merge(p, q); document.write( \"Modified First Linked List:<br>\"); printList(p); document.write( \"Modified Second Linked List:<br>\"); printList(q); // This code is contributed by rrrtnx.</script>", "e": 14303, "s": 12280, "text": null }, { "code": null, "e": 14436, "s": 14303, "text": "First Linked List:\n1 2 3 \nSecond Linked List:\n4 5 6 7 8 \nModified First Linked List:\n1 4 2 5 3 6 \nModified Second Linked List:\n7 8 \n" }, { "code": null, "e": 14610, "s": 14436, "text": "Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 14624, "s": 14610, "text": "princiraj1992" }, { "code": null, "e": 14638, "s": 14624, "text": "rathbhupendra" }, { "code": null, "e": 14649, "s": 14638, "text": "nidhi_biet" }, { "code": null, "e": 14656, "s": 14649, "text": "rrrtnx" }, { "code": null, "e": 14672, "s": 14656, "text": "Deepanshu_mehta" }, { "code": null, "e": 14687, "s": 14672, "text": "sagartomar9927" }, { "code": null, "e": 14702, "s": 14687, "text": "sagar0719kumar" }, { "code": null, "e": 14715, "s": 14702, "text": "simmytarika5" }, { "code": null, "e": 14725, "s": 14715, "text": "samim2000" }, { "code": null, "e": 14742, "s": 14725, "text": "hardikkoriintern" }, { "code": null, "e": 14749, "s": 14742, "text": "Amazon" }, { "code": null, "e": 14761, "s": 14749, "text": "Linked List" }, { "code": null, "e": 14768, "s": 14761, "text": "Amazon" }, { "code": null, "e": 14780, "s": 14768, "text": "Linked List" }, { "code": null, "e": 14878, "s": 14780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14926, "s": 14878, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 14945, "s": 14926, "text": "LinkedList in Java" }, { "code": null, "e": 14977, "s": 14945, "text": "Introduction to Data Structures" }, { "code": null, "e": 15041, "s": 14977, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15088, "s": 15041, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 15128, "s": 15088, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 15180, "s": 15128, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 15215, "s": 15180, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 15271, "s": 15215, "text": "Function to check if a singly linked list is palindrome" } ]
Sentence that contains all the given phrases
07 Jul, 2022 Given a list of sentences and a list of phrases. The task is to find which sentence(s) contain all the words in a phrase and for every phrase print the sentences number that contains the given phrase. Constraint: A word cannot be a part of more than 10 sentences. Examples: Input: Sentences: 1. Strings are an array of characters. 2. Sentences are an array of words. Phrases: 1. an array of 2. sentences are strings Output: Phrase1 is present in sentences: 1,2 Phrase2 is present in sentences: None Since each word in phrase 1 exists in both the sentences, but all the words in second phrase do not exist in either. Input: Sentences: 1. Sets in python are a hash table representation of arrays. 2. Searching in Sets are a function of time complexity O(1). 3. Sets only contain unique elements, and have no order. Phrases: 1. Sets are a 2. Searching in Output: Phrase1 is present in sentences: 1, 2 Phrase2 is present in sentences: 2 Approach: For each Phrase, we have to find the sentences which contain all the words of the phrase. So, for each word in the given phrase, we check if a sentence contains it. We do this for each sentence. This process of searching may become faster if the words in the sentence are stored in a set instead of a list. Below is the implementation of above approach: Java Python3 // Java program to find the sentence// that contains all the given phrasesimport java.io.*;import java.util.*; class GFG { static void getRes(String[] sent, String[] ph) { HashMap<String, HashSet<String> > sentHash = new HashMap<>(); // Loop for adding hashed sentences to sentHash for (String s : sent) { HashSet<String> set = new HashSet<>( Arrays.asList(s.split(" "))); sentHash.put(s, set); } for (int p = 0; p < ph.length; p++) { System.out.println("Phrase" + (p + 1) + ":"); // Get the list of Words String[] wordList = ph[p].split(" "); ArrayList<Integer> res = new ArrayList<>(); // Then Check in every Sentence for (int s = 1; s <= sent.length; s++) { int wCount = wordList.length; // Every word in the Phrase for (String w : wordList) { if (sentHash.get(sent[s - 1]) .contains(w)) { wCount--; } } // If every word in phrase matches if (wCount == 0) { // add Sentence Index to result Array res.add(s); } } if (res.size() == 0) { System.out.println("NONE"); } else { for (Integer i : res) { System.out.print(i + " "); } System.out.println(); } } } // Driver Code public static void main(String[] args) { String[] sent = { "Strings are an array of characters", "Sentences are an array of words" }; String[] ph = { "an array of", "sentences are strings" }; getRes(sent, ph); }}// This code is contributed by Karandeep1234 # Python program to find the sentence# that contains all the given phrasesdef getRes(sent, ph): sentHash = dict() # Loop for adding hashed sentences to sentHash for s in range(1, len(sent)+1): sentHash[s] = set(sent[s-1].split()) # For Each Phrase for p in range(0, len(ph)): print("Phrase"+str(p + 1)+":") # Get the list of Words wordList = ph[p].split() res = [] # Then Check in every Sentence for s in range(1, len(sentHash)+1): wCount = len(wordList) # Every word in the Phrase for w in wordList: if w in sentHash[s]: wCount -= 1 # If every word in phrase matches if wCount == 0: # add Sentence Index to result Array res.append(s) if(len(res) == 0): print("NONE") else: print('% s' % ' '.join(map(str, res))) # Driver Functiondef main(): sent = ["Strings are an array of characters", "Sentences are an array of words"] ph = ["an array of", "sentences are strings"] getRes(sent, ph) main() Phrase1: 1 2 Phrase2: NONE simmytarika5 karandeep1234 Flipkart Hash Picked python-dict Data Structures Flipkart Data Structures python-dict Hash 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 Amazon Interview Experience for SDE-II Data Structures | Hash | Question 5 Difference between Singly linked list and Doubly linked list Data Structures | Linked List | Question 16 Data Structures | Linked List | Question 4
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 326, "s": 52, "text": "Given a list of sentences and a list of phrases. The task is to find which sentence(s) contain all the words in a phrase and for every phrase print the sentences number that contains the given phrase. Constraint: A word cannot be a part of more than 10 sentences. Examples:" }, { "code": null, "e": 334, "s": 326, "text": "Input: " }, { "code": null, "e": 421, "s": 334, "text": "Sentences: 1. Strings are an array of characters. 2. Sentences are an array of words. " }, { "code": null, "e": 471, "s": 421, "text": "Phrases: 1. an array of 2. sentences are strings " }, { "code": null, "e": 671, "s": 471, "text": "Output: Phrase1 is present in sentences: 1,2 Phrase2 is present in sentences: None Since each word in phrase 1 exists in both the sentences, but all the words in second phrase do not exist in either." }, { "code": null, "e": 680, "s": 671, "text": " Input: " }, { "code": null, "e": 871, "s": 680, "text": "Sentences: 1. Sets in python are a hash table representation of arrays. 2. Searching in Sets are a function of time complexity O(1). 3. Sets only contain unique elements, and have no order. " }, { "code": null, "e": 911, "s": 871, "text": "Phrases: 1. Sets are a 2. Searching in " }, { "code": null, "e": 992, "s": 911, "text": "Output: Phrase1 is present in sentences: 1, 2 Phrase2 is present in sentences: 2" }, { "code": null, "e": 1357, "s": 992, "text": "Approach: For each Phrase, we have to find the sentences which contain all the words of the phrase. So, for each word in the given phrase, we check if a sentence contains it. We do this for each sentence. This process of searching may become faster if the words in the sentence are stored in a set instead of a list. Below is the implementation of above approach: " }, { "code": null, "e": 1362, "s": 1357, "text": "Java" }, { "code": null, "e": 1370, "s": 1362, "text": "Python3" }, { "code": "// Java program to find the sentence// that contains all the given phrasesimport java.io.*;import java.util.*; class GFG { static void getRes(String[] sent, String[] ph) { HashMap<String, HashSet<String> > sentHash = new HashMap<>(); // Loop for adding hashed sentences to sentHash for (String s : sent) { HashSet<String> set = new HashSet<>( Arrays.asList(s.split(\" \"))); sentHash.put(s, set); } for (int p = 0; p < ph.length; p++) { System.out.println(\"Phrase\" + (p + 1) + \":\"); // Get the list of Words String[] wordList = ph[p].split(\" \"); ArrayList<Integer> res = new ArrayList<>(); // Then Check in every Sentence for (int s = 1; s <= sent.length; s++) { int wCount = wordList.length; // Every word in the Phrase for (String w : wordList) { if (sentHash.get(sent[s - 1]) .contains(w)) { wCount--; } } // If every word in phrase matches if (wCount == 0) { // add Sentence Index to result Array res.add(s); } } if (res.size() == 0) { System.out.println(\"NONE\"); } else { for (Integer i : res) { System.out.print(i + \" \"); } System.out.println(); } } } // Driver Code public static void main(String[] args) { String[] sent = { \"Strings are an array of characters\", \"Sentences are an array of words\" }; String[] ph = { \"an array of\", \"sentences are strings\" }; getRes(sent, ph); }}// This code is contributed by Karandeep1234", "e": 3302, "s": 1370, "text": null }, { "code": "# Python program to find the sentence# that contains all the given phrasesdef getRes(sent, ph): sentHash = dict() # Loop for adding hashed sentences to sentHash for s in range(1, len(sent)+1): sentHash[s] = set(sent[s-1].split()) # For Each Phrase for p in range(0, len(ph)): print(\"Phrase\"+str(p + 1)+\":\") # Get the list of Words wordList = ph[p].split() res = [] # Then Check in every Sentence for s in range(1, len(sentHash)+1): wCount = len(wordList) # Every word in the Phrase for w in wordList: if w in sentHash[s]: wCount -= 1 # If every word in phrase matches if wCount == 0: # add Sentence Index to result Array res.append(s) if(len(res) == 0): print(\"NONE\") else: print('% s' % ' '.join(map(str, res))) # Driver Functiondef main(): sent = [\"Strings are an array of characters\", \"Sentences are an array of words\"] ph = [\"an array of\", \"sentences are strings\"] getRes(sent, ph) main()", "e": 4437, "s": 3302, "text": null }, { "code": null, "e": 4464, "s": 4437, "text": "Phrase1:\n1 2\nPhrase2:\nNONE" }, { "code": null, "e": 4477, "s": 4464, "text": "simmytarika5" }, { "code": null, "e": 4491, "s": 4477, "text": "karandeep1234" }, { "code": null, "e": 4500, "s": 4491, "text": "Flipkart" }, { "code": null, "e": 4505, "s": 4500, "text": "Hash" }, { "code": null, "e": 4512, "s": 4505, "text": "Picked" }, { "code": null, "e": 4524, "s": 4512, "text": "python-dict" }, { "code": null, "e": 4540, "s": 4524, "text": "Data Structures" }, { "code": null, "e": 4549, "s": 4540, "text": "Flipkart" }, { "code": null, "e": 4565, "s": 4549, "text": "Data Structures" }, { "code": null, "e": 4577, "s": 4565, "text": "python-dict" }, { "code": null, "e": 4582, "s": 4577, "text": "Hash" }, { "code": null, "e": 4680, "s": 4582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4712, "s": 4680, "text": "Introduction to Data Structures" }, { "code": null, "e": 4756, "s": 4712, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 4793, "s": 4756, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 4844, "s": 4793, "text": "Data Structures | Binary Search Trees | Question 8" }, { "code": null, "e": 4881, "s": 4844, "text": "Data Structures | Queue | Question 2" }, { "code": null, "e": 4920, "s": 4881, "text": "Amazon Interview Experience for SDE-II" }, { "code": null, "e": 4956, "s": 4920, "text": "Data Structures | Hash | Question 5" }, { "code": null, "e": 5017, "s": 4956, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 5061, "s": 5017, "text": "Data Structures | Linked List | Question 16" } ]
Maximum even sum subsequence of length K
18 Apr, 2022 Given an array arr[] consisting of N positive integers, and an integer K, the task is to find the maximum possible even sum of any subsequence of size K. If it is not possible to find any even sum subsequence of size K, then print -1. Examples: Input: arr[] ={4, 2, 6, 7, 8}, K = 3Output: 18Explanation: Subsequence having maximum even sum of size K( = 3 ) is {4, 6, 8}.Therefore, the required output is 4 + 6 + 8 = 18. Input: arr[] = {5, 5, 1, 1, 3}, K = 3Output: -1 Naive Approach: The simplest approach to solve this problem to generate all possible subsequences of size K from the given array and print the value of the maximum possible even sum the possible subsequences of the given array. Time Complexity: O(K * NK)Auxiliary Space: O(K) Efficient Approach: To optimize the above approach the idea is to store all even and odd numbers of the given array into two separate arrays and sort both these arrays. Finally, use the Greedy technique to calculate the maximum sum even subsequence of size K. Follow the steps below to solve the problem: Initialize a variable, say maxSum to store the maximum even sum of a subsequence of the given array. Initialize two arrays, say Even[] and Odd[] to store all the even numbers and odd numbers of the given array respectively. Traverse the given array and store all the even numbers and odd numbers of the given array into Even[] and Odd[] array respectively. Sort Even[] and Odd[] arrays. Initialize two variables, say i and j to store the index of Even[] and Odd[] array respectively. Traverse Even[], Odd[] arrays and check the following conditions:If K % 2 == 1 then increment the value of maxSum by Even[i].Otherwise, increment the value of maxSum by max(Even[i] + Even[i – 1], Odd[j] + Odd[j – 1]). If K % 2 == 1 then increment the value of maxSum by Even[i]. Otherwise, increment the value of maxSum by max(Even[i] + Even[i – 1], Odd[j] + Odd[j – 1]). Finally, print the value of maxSum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the// maximum even sum of any// subsequence of length Kint evenSumK(int arr[], int N, int K){ // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum // even subsequence sum int maxSum = 0; // Stores Even numbers vector<int> Even; // Stores Odd numbers vector<int> Odd; // Traverse the array for (int i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2) { // Insert odd number Odd.push_back(arr[i]); } else { // Insert even numbers Even.push_back(arr[i]); } } // Sort Odd[] array sort(Odd.begin(), Odd.end()); // Sort Even[] array sort(Even.begin(), Even.end()); // Stores current index // Of Even[] array int i = Even.size() - 1; // Stores current index // Of Odd[] array int j = Odd.size() - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j. j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i. i -= 2; // Update K. K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else { return -1; } } return maxSum;} // Driver Codeint main(){ int arr[] = { 2, 4, 10, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; cout << evenSumK(arr, N, K);} // Java program to implement// the above approachimport java.util.*; class GFG { // Function to find the // maximum even sum of any // subsequence of length K static int evenSumK(int arr[], int N, int K) { // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum even // subsequence sum int maxSum = 0; // Stores Even numbers ArrayList<Integer> Even = new ArrayList<Integer>(); // Stores Odd numbers ArrayList<Integer> Odd = new ArrayList<Integer>(); // Traverse the array for (int i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2 == 1) { // Insert odd number Odd.add(arr[i]); } else { // Insert even numbers Even.add(arr[i]); } } // Sort Odd[] array Collections.sort(Odd); // Sort Even[] array Collections.sort(Even); // Stores current index // Of Even[] array int i = Even.size() - 1; // Stores current index // Of Odd[] array int j = Odd.size() - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even.get(i); // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even.get(i) + Even.get(i - 1) <= Odd.get(j) + Odd.get(j - 1)) { // Update maxSum maxSum += Odd.get(j) + Odd.get(j - 1); // Update j j -= 2; } else { // Update maxSum maxSum += Even.get(i) + Even.get(i - 1); // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even.get(i) + Even.get(i - 1); // Update i i -= 2; // Update K K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd.get(j) + Odd.get(j - 1); // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum; } // Driver code public static void main(String[] args) { int arr[] = { 2, 4, 10, 3, 5 }; int N = arr.length; int K = 3; System.out.println(evenSumK(arr, N, K)); }} // This code is contributed by offbeat # Python3 program to implement# the above approach # Function to find the# maximum even sum of any# subsequence of length K def evenSumK(arr, N, K): # If count of elements # is less than K if (K > N): return -1 # Stores maximum # even subsequence sum maxSum = 0 # Stores Even numbers Even = [] # Stores Odd numbers Odd = [] # Traverse the array for i in range(N): # If current element # is an odd number if (arr[i] % 2): # Insert odd number Odd.append(arr[i]) else: # Insert even numbers Even.append(arr[i]) # Sort Odd[] array Odd.sort(reverse=False) # Sort Even[] array Even.sort(reverse=False) # Stores current index # Of Even[] array i = len(Even) - 1 # Stores current index # Of Odd[] array j = len(Odd) - 1 while (K > 0): # If K is odd if (K % 2 == 1): # If count of elements # in Even[] >= 1 if (i >= 0): # Update maxSum maxSum += Even[i] # Update i i -= 1 # If count of elements # in Even[] array is 0. else: return -1 # Update K K -= 1 # If count of elements # in Even[] and odd[] >= 2 elif (i >= 1 and j >= 1): if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]): # Update maxSum maxSum += Odd[j] + Odd[j - 1] # Update j. j -= 2 else: # Update maxSum maxSum += Even[i] + Even[i - 1] # Update i i -= 2 # Update K K -= 2 # If count of elements # in Even[] array >= 2. elif (i >= 1): # Update maxSum maxSum += Even[i] + Even[i - 1] # Update i. i -= 2 # Update K. K -= 2 # If count of elements # in Odd[] array >= 2 elif (j >= 1): # Update maxSum maxSum += Odd[j] + Odd[j - 1] # Update i. j -= 2 # Update K. K -= 2 else: return -1; return maxSum # Driver Codeif __name__ == '__main__': arr = [2, 4, 9] N = len(arr) K = 3 print(evenSumK(arr, N, K)) # This code is contributed by ipg2016107 // C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to find the // maximum even sum of any // subsequence of length K static int evenSumK(int[] arr, int N, int K) { // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum even // subsequence sum int maxSum = 0; // Stores Even numbers List<int> Even = new List<int>(); // Stores Odd numbers List<int> Odd = new List<int>(); // Traverse the array for (int l = 0; l < N; l++) { // If current element // is an odd number if (arr[l] % 2 == 1) { // Insert odd number Odd.Add(arr[l]); } else { // Insert even numbers Even.Add(arr[l]); } } // Sort Odd[] array Odd.Sort(); // Sort Even[] array Even.Sort(); // Stores current index // Of Even[] array int i = Even.Count - 1; // Stores current index // Of Odd[] array int j = Odd.Count - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; // Update K K -= 2; } // If count of elements // in Odd[] array >= 2 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum; } // Driver code public static void Main(String[] args) { int[] arr = { 2, 4, 10, 3, 5 }; int N = arr.Length; int K = 3; Console.WriteLine(evenSumK(arr, N, K)); }} // This code is contributed by gauravrajput1 <script> // Javascript program to implement// the above approach // Function to find the// maximum even sum of any// subsequence of length Kfunction evenSumK(arr, N, K){ // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum // even subsequence sum var maxSum = 0; // Stores Even numbers var Even = []; // Stores Odd numbers var Odd = []; // Traverse the array for (var i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2) { // Insert odd number Odd.push(arr[i]); } else { // Insert even numbers Even.push(arr[i]); } } // Sort Odd[] array Odd.sort((a,b)=> a-b); Even.sort((a,b)=> a-b); // Stores current index // Of Even[] array var i = Even.length - 1; // Stores current index // Of Odd[] array var j = Odd.length - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j. j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i. i -= 2; // Update K. K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum;} // Driver Codevar arr = [2, 4, 10, 3, 5];var N = arr.length;var K = 3;document.write( evenSumK(arr, N, K)); </script> 18 Time Complexity: O(N * log N)Auxiliary Space: O(N) offbeat ipg2016107 GauravRajput1 awesomestar rutvik_56 2018hs11521 Microsoft subsequence Arrays Heap Mathematical Sorting Microsoft Arrays Mathematical Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Apr, 2022" }, { "code": null, "e": 289, "s": 54, "text": "Given an array arr[] consisting of N positive integers, and an integer K, the task is to find the maximum possible even sum of any subsequence of size K. If it is not possible to find any even sum subsequence of size K, then print -1." }, { "code": null, "e": 299, "s": 289, "text": "Examples:" }, { "code": null, "e": 474, "s": 299, "text": "Input: arr[] ={4, 2, 6, 7, 8}, K = 3Output: 18Explanation: Subsequence having maximum even sum of size K( = 3 ) is {4, 6, 8}.Therefore, the required output is 4 + 6 + 8 = 18." }, { "code": null, "e": 522, "s": 474, "text": "Input: arr[] = {5, 5, 1, 1, 3}, K = 3Output: -1" }, { "code": null, "e": 750, "s": 522, "text": "Naive Approach: The simplest approach to solve this problem to generate all possible subsequences of size K from the given array and print the value of the maximum possible even sum the possible subsequences of the given array." }, { "code": null, "e": 798, "s": 750, "text": "Time Complexity: O(K * NK)Auxiliary Space: O(K)" }, { "code": null, "e": 1103, "s": 798, "text": "Efficient Approach: To optimize the above approach the idea is to store all even and odd numbers of the given array into two separate arrays and sort both these arrays. Finally, use the Greedy technique to calculate the maximum sum even subsequence of size K. Follow the steps below to solve the problem:" }, { "code": null, "e": 1204, "s": 1103, "text": "Initialize a variable, say maxSum to store the maximum even sum of a subsequence of the given array." }, { "code": null, "e": 1327, "s": 1204, "text": "Initialize two arrays, say Even[] and Odd[] to store all the even numbers and odd numbers of the given array respectively." }, { "code": null, "e": 1460, "s": 1327, "text": "Traverse the given array and store all the even numbers and odd numbers of the given array into Even[] and Odd[] array respectively." }, { "code": null, "e": 1490, "s": 1460, "text": "Sort Even[] and Odd[] arrays." }, { "code": null, "e": 1587, "s": 1490, "text": "Initialize two variables, say i and j to store the index of Even[] and Odd[] array respectively." }, { "code": null, "e": 1806, "s": 1587, "text": "Traverse Even[], Odd[] arrays and check the following conditions:If K % 2 == 1 then increment the value of maxSum by Even[i].Otherwise, increment the value of maxSum by max(Even[i] + Even[i – 1], Odd[j] + Odd[j – 1])." }, { "code": null, "e": 1867, "s": 1806, "text": "If K % 2 == 1 then increment the value of maxSum by Even[i]." }, { "code": null, "e": 1961, "s": 1867, "text": "Otherwise, increment the value of maxSum by max(Even[i] + Even[i – 1], Odd[j] + Odd[j – 1])." }, { "code": null, "e": 1998, "s": 1961, "text": "Finally, print the value of maxSum. " }, { "code": null, "e": 2049, "s": 1998, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2053, "s": 2049, "text": "C++" }, { "code": null, "e": 2058, "s": 2053, "text": "Java" }, { "code": null, "e": 2066, "s": 2058, "text": "Python3" }, { "code": null, "e": 2069, "s": 2066, "text": "C#" }, { "code": null, "e": 2080, "s": 2069, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the// maximum even sum of any// subsequence of length Kint evenSumK(int arr[], int N, int K){ // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum // even subsequence sum int maxSum = 0; // Stores Even numbers vector<int> Even; // Stores Odd numbers vector<int> Odd; // Traverse the array for (int i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2) { // Insert odd number Odd.push_back(arr[i]); } else { // Insert even numbers Even.push_back(arr[i]); } } // Sort Odd[] array sort(Odd.begin(), Odd.end()); // Sort Even[] array sort(Even.begin(), Even.end()); // Stores current index // Of Even[] array int i = Even.size() - 1; // Stores current index // Of Odd[] array int j = Odd.size() - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j. j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i. i -= 2; // Update K. K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else { return -1; } } return maxSum;} // Driver Codeint main(){ int arr[] = { 2, 4, 10, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; cout << evenSumK(arr, N, K);}", "e": 4856, "s": 2080, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG { // Function to find the // maximum even sum of any // subsequence of length K static int evenSumK(int arr[], int N, int K) { // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum even // subsequence sum int maxSum = 0; // Stores Even numbers ArrayList<Integer> Even = new ArrayList<Integer>(); // Stores Odd numbers ArrayList<Integer> Odd = new ArrayList<Integer>(); // Traverse the array for (int i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2 == 1) { // Insert odd number Odd.add(arr[i]); } else { // Insert even numbers Even.add(arr[i]); } } // Sort Odd[] array Collections.sort(Odd); // Sort Even[] array Collections.sort(Even); // Stores current index // Of Even[] array int i = Even.size() - 1; // Stores current index // Of Odd[] array int j = Odd.size() - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even.get(i); // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even.get(i) + Even.get(i - 1) <= Odd.get(j) + Odd.get(j - 1)) { // Update maxSum maxSum += Odd.get(j) + Odd.get(j - 1); // Update j j -= 2; } else { // Update maxSum maxSum += Even.get(i) + Even.get(i - 1); // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even.get(i) + Even.get(i - 1); // Update i i -= 2; // Update K K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd.get(j) + Odd.get(j - 1); // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum; } // Driver code public static void main(String[] args) { int arr[] = { 2, 4, 10, 3, 5 }; int N = arr.length; int K = 3; System.out.println(evenSumK(arr, N, K)); }} // This code is contributed by offbeat", "e": 8220, "s": 4856, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the# maximum even sum of any# subsequence of length K def evenSumK(arr, N, K): # If count of elements # is less than K if (K > N): return -1 # Stores maximum # even subsequence sum maxSum = 0 # Stores Even numbers Even = [] # Stores Odd numbers Odd = [] # Traverse the array for i in range(N): # If current element # is an odd number if (arr[i] % 2): # Insert odd number Odd.append(arr[i]) else: # Insert even numbers Even.append(arr[i]) # Sort Odd[] array Odd.sort(reverse=False) # Sort Even[] array Even.sort(reverse=False) # Stores current index # Of Even[] array i = len(Even) - 1 # Stores current index # Of Odd[] array j = len(Odd) - 1 while (K > 0): # If K is odd if (K % 2 == 1): # If count of elements # in Even[] >= 1 if (i >= 0): # Update maxSum maxSum += Even[i] # Update i i -= 1 # If count of elements # in Even[] array is 0. else: return -1 # Update K K -= 1 # If count of elements # in Even[] and odd[] >= 2 elif (i >= 1 and j >= 1): if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]): # Update maxSum maxSum += Odd[j] + Odd[j - 1] # Update j. j -= 2 else: # Update maxSum maxSum += Even[i] + Even[i - 1] # Update i i -= 2 # Update K K -= 2 # If count of elements # in Even[] array >= 2. elif (i >= 1): # Update maxSum maxSum += Even[i] + Even[i - 1] # Update i. i -= 2 # Update K. K -= 2 # If count of elements # in Odd[] array >= 2 elif (j >= 1): # Update maxSum maxSum += Odd[j] + Odd[j - 1] # Update i. j -= 2 # Update K. K -= 2 else: return -1; return maxSum # Driver Codeif __name__ == '__main__': arr = [2, 4, 9] N = len(arr) K = 3 print(evenSumK(arr, N, K)) # This code is contributed by ipg2016107", "e": 10699, "s": 8220, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to find the // maximum even sum of any // subsequence of length K static int evenSumK(int[] arr, int N, int K) { // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum even // subsequence sum int maxSum = 0; // Stores Even numbers List<int> Even = new List<int>(); // Stores Odd numbers List<int> Odd = new List<int>(); // Traverse the array for (int l = 0; l < N; l++) { // If current element // is an odd number if (arr[l] % 2 == 1) { // Insert odd number Odd.Add(arr[l]); } else { // Insert even numbers Even.Add(arr[l]); } } // Sort Odd[] array Odd.Sort(); // Sort Even[] array Even.Sort(); // Stores current index // Of Even[] array int i = Even.Count - 1; // Stores current index // Of Odd[] array int j = Odd.Count - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; // Update K K -= 2; } // If count of elements // in Odd[] array >= 2 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum; } // Driver code public static void Main(String[] args) { int[] arr = { 2, 4, 10, 3, 5 }; int N = arr.Length; int K = 3; Console.WriteLine(evenSumK(arr, N, K)); }} // This code is contributed by gauravrajput1", "e": 13968, "s": 10699, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to find the// maximum even sum of any// subsequence of length Kfunction evenSumK(arr, N, K){ // If count of elements // is less than K if (K > N) { return -1; } // Stores maximum // even subsequence sum var maxSum = 0; // Stores Even numbers var Even = []; // Stores Odd numbers var Odd = []; // Traverse the array for (var i = 0; i < N; i++) { // If current element // is an odd number if (arr[i] % 2) { // Insert odd number Odd.push(arr[i]); } else { // Insert even numbers Even.push(arr[i]); } } // Sort Odd[] array Odd.sort((a,b)=> a-b); Even.sort((a,b)=> a-b); // Stores current index // Of Even[] array var i = Even.length - 1; // Stores current index // Of Odd[] array var j = Odd.length - 1; while (K > 0) { // If K is odd if (K % 2 == 1) { // If count of elements // in Even[] >= 1 if (i >= 0) { // Update maxSum maxSum += Even[i]; // Update i i--; } // If count of elements // in Even[] array is 0. else { return -1; } // Update K K--; } // If count of elements // in Even[] and odd[] >= 2 else if (i >= 1 && j >= 1) { if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update j. j -= 2; } else { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i i -= 2; } // Update K K -= 2; } // If count of elements // in Even[] array >= 2. else if (i >= 1) { // Update maxSum maxSum += Even[i] + Even[i - 1]; // Update i. i -= 2; // Update K. K -= 2; } // If count of elements // in Odd[] array >= 1 else if (j >= 1) { // Update maxSum maxSum += Odd[j] + Odd[j - 1]; // Update i. j -= 2; // Update K. K -= 2; } else return -1; } return maxSum;} // Driver Codevar arr = [2, 4, 10, 3, 5];var N = arr.length;var K = 3;document.write( evenSumK(arr, N, K)); </script>", "e": 16617, "s": 13968, "text": null }, { "code": null, "e": 16620, "s": 16617, "text": "18" }, { "code": null, "e": 16671, "s": 16620, "text": "Time Complexity: O(N * log N)Auxiliary Space: O(N)" }, { "code": null, "e": 16679, "s": 16671, "text": "offbeat" }, { "code": null, "e": 16690, "s": 16679, "text": "ipg2016107" }, { "code": null, "e": 16704, "s": 16690, "text": "GauravRajput1" }, { "code": null, "e": 16716, "s": 16704, "text": "awesomestar" }, { "code": null, "e": 16726, "s": 16716, "text": "rutvik_56" }, { "code": null, "e": 16738, "s": 16726, "text": "2018hs11521" }, { "code": null, "e": 16748, "s": 16738, "text": "Microsoft" }, { "code": null, "e": 16760, "s": 16748, "text": "subsequence" }, { "code": null, "e": 16767, "s": 16760, "text": "Arrays" }, { "code": null, "e": 16772, "s": 16767, "text": "Heap" }, { "code": null, "e": 16785, "s": 16772, "text": "Mathematical" }, { "code": null, "e": 16793, "s": 16785, "text": "Sorting" }, { "code": null, "e": 16803, "s": 16793, "text": "Microsoft" }, { "code": null, "e": 16810, "s": 16803, "text": "Arrays" }, { "code": null, "e": 16823, "s": 16810, "text": "Mathematical" }, { "code": null, "e": 16831, "s": 16823, "text": "Sorting" }, { "code": null, "e": 16836, "s": 16831, "text": "Heap" }, { "code": null, "e": 16934, "s": 16836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16966, "s": 16934, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 16989, "s": 16966, "text": "Introduction to Arrays" }, { "code": null, "e": 17045, "s": 16989, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 17072, "s": 17045, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 17104, "s": 17072, "text": "Introduction to Data Structures" }, { "code": null, "e": 17113, "s": 17104, "text": "HeapSort" }, { "code": null, "e": 17169, "s": 17113, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 17181, "s": 17169, "text": "Binary Heap" }, { "code": null, "e": 17213, "s": 17181, "text": "Introduction to Data Structures" } ]
PyQt5 – QTableWidget
11 May, 2020 In this article, we will learn how to add and work with a table in our PyQt5 application. A table is an arrangement of data in rows and columns and widely used in communication, research, and data analysis. We can add one or more tables in our PyQt application using QTableWidget. For a better understanding of the concept, we will take an example where we want to display the name and the city of different people in a table in our application. We can extract the data from a database, JSON file, or any other storage platform. Example: import sysfrom PyQt5.QtWidgets import * #Main Windowclass App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 - QTableWidget' self.left = 0 self.top = 0 self.width = 300 self.height = 200 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.createTable() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) #Show window self.show() #Create table def createTable(self): self.tableWidget = QTableWidget() #Row count self.tableWidget.setRowCount(4) #Column count self.tableWidget.setColumnCount(2) self.tableWidget.setItem(0,0, QTableWidgetItem("Name")) self.tableWidget.setItem(0,1, QTableWidgetItem("City")) self.tableWidget.setItem(1,0, QTableWidgetItem("Aloysius")) self.tableWidget.setItem(1,1, QTableWidgetItem("Indore")) self.tableWidget.setItem(2,0, QTableWidgetItem("Alan")) self.tableWidget.setItem(2,1, QTableWidgetItem("Bhopal")) self.tableWidget.setItem(3,0, QTableWidgetItem("Arnavi")) self.tableWidget.setItem(3,1, QTableWidgetItem("Mandsaur")) #Table will fit the screen horizontally self.tableWidget.horizontalHeader().setStretchLastSection(True) self.tableWidget.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) Output: Python-gui Python-PyQt Project Python Python Programs Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 10 Best Web Development Projects For Your Resume OpenCV C++ Program for Face Detection Simple Chat Room using Python Twitter Sentiment Analysis using Python Student Information Management System Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2020" }, { "code": null, "e": 335, "s": 54, "text": "In this article, we will learn how to add and work with a table in our PyQt5 application. A table is an arrangement of data in rows and columns and widely used in communication, research, and data analysis. We can add one or more tables in our PyQt application using QTableWidget." }, { "code": null, "e": 583, "s": 335, "text": "For a better understanding of the concept, we will take an example where we want to display the name and the city of different people in a table in our application. We can extract the data from a database, JSON file, or any other storage platform." }, { "code": null, "e": 592, "s": 583, "text": "Example:" }, { "code": "import sysfrom PyQt5.QtWidgets import * #Main Windowclass App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 - QTableWidget' self.left = 0 self.top = 0 self.width = 300 self.height = 200 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.createTable() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) #Show window self.show() #Create table def createTable(self): self.tableWidget = QTableWidget() #Row count self.tableWidget.setRowCount(4) #Column count self.tableWidget.setColumnCount(2) self.tableWidget.setItem(0,0, QTableWidgetItem(\"Name\")) self.tableWidget.setItem(0,1, QTableWidgetItem(\"City\")) self.tableWidget.setItem(1,0, QTableWidgetItem(\"Aloysius\")) self.tableWidget.setItem(1,1, QTableWidgetItem(\"Indore\")) self.tableWidget.setItem(2,0, QTableWidgetItem(\"Alan\")) self.tableWidget.setItem(2,1, QTableWidgetItem(\"Bhopal\")) self.tableWidget.setItem(3,0, QTableWidgetItem(\"Arnavi\")) self.tableWidget.setItem(3,1, QTableWidgetItem(\"Mandsaur\")) #Table will fit the screen horizontally self.tableWidget.horizontalHeader().setStretchLastSection(True) self.tableWidget.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())", "e": 2224, "s": 592, "text": null }, { "code": null, "e": 2232, "s": 2224, "text": "Output:" }, { "code": null, "e": 2243, "s": 2232, "text": "Python-gui" }, { "code": null, "e": 2255, "s": 2243, "text": "Python-PyQt" }, { "code": null, "e": 2263, "s": 2255, "text": "Project" }, { "code": null, "e": 2270, "s": 2263, "text": "Python" }, { "code": null, "e": 2286, "s": 2270, "text": "Python Programs" }, { "code": null, "e": 2302, "s": 2286, "text": "Write From Home" }, { "code": null, "e": 2400, "s": 2302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2449, "s": 2400, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 2487, "s": 2449, "text": "OpenCV C++ Program for Face Detection" }, { "code": null, "e": 2517, "s": 2487, "text": "Simple Chat Room using Python" }, { "code": null, "e": 2557, "s": 2517, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 2595, "s": 2557, "text": "Student Information Management System" }, { "code": null, "e": 2623, "s": 2595, "text": "Read JSON file using Python" }, { "code": null, "e": 2673, "s": 2623, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2695, "s": 2673, "text": "Python map() function" }, { "code": null, "e": 2713, "s": 2695, "text": "Python Dictionary" } ]
PyQt5 - QComboBox Widget
A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item. A Combo box can be set to be editable; it can also store pixmap objects. The following methods are commonly used − addItem() Adds string to collection addItems() Adds items in a list object Clear() Deletes all items in the collection count() Retrieves number of items in the collection currentText() Retrieves the text of currently selected item itemText() Displays text belonging to specific index currentIndex() Returns index of selected item setItemText() Changes text of specified index The following methods are commonly used in QComboBox Signals − activated() When the user chooses an item currentIndexChanged() Whenever the current index is changed either by the user or programmatically highlighted() When an item in the list is highlighted Let us see how some features of QComboBox widget are implemented in the following example. Items are added in the collection individually by addItem() method or items in a List object by addItems() method. self.cb.addItem("C++") self.cb.addItems(["Java", "C#", "Python"]) QComboBox object emits currentIndexChanged() signal. It is connected to selectionchange() method. Items in a combo box are listed using itemText() method for each item. Label belonging to the currently chosen item is accessed by currentText() method. def selectionchange(self,i): print "Items in the list are :" for count in range(self.cb.count()): print self.cb.itemText(count) print "Current index",i,"selection changed ",self.cb.currentText() The entire code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class combodemo(QWidget): def __init__(self, parent = None): super(combodemo, self).__init__(parent) layout = QHBoxLayout() self.cb = QComboBox() self.cb.addItem("C") self.cb.addItem("C++") self.cb.addItems(["Java", "C#", "Python"]) self.cb.currentIndexChanged.connect(self.selectionchange) layout.addWidget(self.cb) self.setLayout(layout) self.setWindowTitle("combo box demo") def selectionchange(self,i): print "Items in the list are :" for count in range(self.cb.count()): print self.cb.itemText(count) print "Current index",i,"selection changed ",self.cb.currentText() def main(): app = QApplication(sys.argv) ex = combodemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − Items in the list are − C C++ Java C# Python Current selection index 4 selection changed Python
[ { "code": null, "e": 2262, "s": 2097, "text": "A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item." }, { "code": null, "e": 2377, "s": 2262, "text": "A Combo box can be set to be editable; it can also store pixmap objects. The following methods are commonly used −" }, { "code": null, "e": 2387, "s": 2377, "text": "addItem()" }, { "code": null, "e": 2413, "s": 2387, "text": "Adds string to collection" }, { "code": null, "e": 2424, "s": 2413, "text": "addItems()" }, { "code": null, "e": 2452, "s": 2424, "text": "Adds items in a list object" }, { "code": null, "e": 2460, "s": 2452, "text": "Clear()" }, { "code": null, "e": 2496, "s": 2460, "text": "Deletes all items in the collection" }, { "code": null, "e": 2504, "s": 2496, "text": "count()" }, { "code": null, "e": 2548, "s": 2504, "text": "Retrieves number of items in the collection" }, { "code": null, "e": 2562, "s": 2548, "text": "currentText()" }, { "code": null, "e": 2608, "s": 2562, "text": "Retrieves the text of currently selected item" }, { "code": null, "e": 2619, "s": 2608, "text": "itemText()" }, { "code": null, "e": 2661, "s": 2619, "text": "Displays text belonging to specific index" }, { "code": null, "e": 2676, "s": 2661, "text": "currentIndex()" }, { "code": null, "e": 2707, "s": 2676, "text": "Returns index of selected item" }, { "code": null, "e": 2721, "s": 2707, "text": "setItemText()" }, { "code": null, "e": 2753, "s": 2721, "text": "Changes text of specified index" }, { "code": null, "e": 2816, "s": 2753, "text": "The following methods are commonly used in QComboBox Signals −" }, { "code": null, "e": 2828, "s": 2816, "text": "activated()" }, { "code": null, "e": 2858, "s": 2828, "text": "When the user chooses an item" }, { "code": null, "e": 2880, "s": 2858, "text": "currentIndexChanged()" }, { "code": null, "e": 2957, "s": 2880, "text": "Whenever the current index is changed either by the user or programmatically" }, { "code": null, "e": 2971, "s": 2957, "text": "highlighted()" }, { "code": null, "e": 3011, "s": 2971, "text": "When an item in the list is highlighted" }, { "code": null, "e": 3102, "s": 3011, "text": "Let us see how some features of QComboBox widget are implemented in the following example." }, { "code": null, "e": 3217, "s": 3102, "text": "Items are added in the collection individually by addItem() method or items in a List object by addItems() method." }, { "code": null, "e": 3284, "s": 3217, "text": "self.cb.addItem(\"C++\")\nself.cb.addItems([\"Java\", \"C#\", \"Python\"])\n" }, { "code": null, "e": 3382, "s": 3284, "text": "QComboBox object emits currentIndexChanged() signal. It is connected to selectionchange() method." }, { "code": null, "e": 3535, "s": 3382, "text": "Items in a combo box are listed using itemText() method for each item. Label belonging to the currently chosen item is accessed by currentText() method." }, { "code": null, "e": 3747, "s": 3535, "text": "def selectionchange(self,i):\n print \"Items in the list are :\"\n\t\n for count in range(self.cb.count()):\n print self.cb.itemText(count)\n print \"Current index\",i,\"selection changed \",self.cb.currentText()" }, { "code": null, "e": 3779, "s": 3747, "text": "The entire code is as follows −" }, { "code": null, "e": 4697, "s": 3779, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass combodemo(QWidget):\n def __init__(self, parent = None):\n super(combodemo, self).__init__(parent)\n \n layout = QHBoxLayout()\n self.cb = QComboBox()\n self.cb.addItem(\"C\")\n self.cb.addItem(\"C++\")\n self.cb.addItems([\"Java\", \"C#\", \"Python\"])\n self.cb.currentIndexChanged.connect(self.selectionchange)\n\t\t\n layout.addWidget(self.cb)\n self.setLayout(layout)\n self.setWindowTitle(\"combo box demo\")\n\n def selectionchange(self,i):\n print \"Items in the list are :\"\n\t\t\n for count in range(self.cb.count()):\n print self.cb.itemText(count)\n print \"Current index\",i,\"selection changed \",self.cb.currentText()\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = combodemo()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4744, "s": 4697, "text": "The above code produces the following output −" }, { "code": null, "e": 4768, "s": 4744, "text": "Items in the list are −" } ]
Gdu – Faster Disk Usage Analyzer for Linux - GeeksforGeeks
06 Jun, 2021 GDU is a disk usage analyzer written in Go language for the Linux Operating systems. Gdu was actually made for SSD disks where it can totally utilize parallel processing. Although it works for HDDs too, but the performance gain is not so good.GDU can run in two modes one is interactive and another is non-interactive. It is a good tool to analyze disk but it has many alternatives like the ncdu, godu, du, duc. Now let’s see how to install the GDU on a Linux system. GDU provides multiple ways to install the GDU on your system according to your Linux distro, you can check all methods from their GitHub repository. But for now, let’s see the common method to install the GDU using the curl command. Use the following commands to install GDU curl -L https://github.com/dundee/gdu/releases/latest/download/gdu_linux_amd64.tgz | tar xz chmod +x gdu_linux_amd64 mv gdu_linux_amd64 /usr/bin/gdu Now we have installed the GDU on our Linux system. You can verify the installation of GDU using the following command: gdu --version Then you will see the installed version of the GDU Now let’s see how to analyze the disk using the GDU To analyze the current working directory just run the gdu command on the terminal. Then it will show the disk usage by files in the current directory. Now I am in the /home/nishant/codes/bash directory. gdu Then you will see output like the: To analyze the specific directory you can mention the path of the directory after the gdu command like this:- gdu /lib/apt/ Then you will see the output:- Note that we can provide only one argument to the gdu. Now let’s see options to use interactive mode. GDU provides the options to use GDU more effectively in interactive mode. To see all options press ? Key on the keyboard. Now we can see the options using which we can move the cursor up/down, select and delete directories or files using keys like J , G , l , h , etc . We can delete the selected file by pressing the d key on the keyboard You can also view the content of a file by pressing the v key on the keyboard Did you observe the flags like e , ! , . , @, H,e before the file names ? Each of the flags has a different meaning, let us see the meaning of each flag ! -> An Error appeared while reading directory . -> An Error appeared while reading subdirectory. @ -> File is a socket or simlink. H -> Hardlink(File) which was already counted. e -> An Empty directory. Now let’s see some other options provided by GDU. We can see all option provided by the GDU using the help command as follows: gdu --help Now let’s see how to use these options -c options By using this option we can print the output in black and white color. gdu -c directory_path -n options If you want the outputs in the non-interactive form then you can use the flag “n” gdu -n directory_path Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24483, "s": 24015, "text": "GDU is a disk usage analyzer written in Go language for the Linux Operating systems. Gdu was actually made for SSD disks where it can totally utilize parallel processing. Although it works for HDDs too, but the performance gain is not so good.GDU can run in two modes one is interactive and another is non-interactive. It is a good tool to analyze disk but it has many alternatives like the ncdu, godu, du, duc. Now let’s see how to install the GDU on a Linux system." }, { "code": null, "e": 24716, "s": 24483, "text": "GDU provides multiple ways to install the GDU on your system according to your Linux distro, you can check all methods from their GitHub repository. But for now, let’s see the common method to install the GDU using the curl command." }, { "code": null, "e": 24760, "s": 24716, "text": "Use the following commands to install GDU " }, { "code": null, "e": 24852, "s": 24760, "text": "curl -L https://github.com/dundee/gdu/releases/latest/download/gdu_linux_amd64.tgz | tar xz" }, { "code": null, "e": 24877, "s": 24852, "text": "chmod +x gdu_linux_amd64" }, { "code": null, "e": 24909, "s": 24877, "text": "mv gdu_linux_amd64 /usr/bin/gdu" }, { "code": null, "e": 25028, "s": 24909, "text": "Now we have installed the GDU on our Linux system. You can verify the installation of GDU using the following command:" }, { "code": null, "e": 25043, "s": 25028, "text": " gdu --version" }, { "code": null, "e": 25094, "s": 25043, "text": "Then you will see the installed version of the GDU" }, { "code": null, "e": 25146, "s": 25094, "text": "Now let’s see how to analyze the disk using the GDU" }, { "code": null, "e": 25349, "s": 25146, "text": "To analyze the current working directory just run the gdu command on the terminal. Then it will show the disk usage by files in the current directory. Now I am in the /home/nishant/codes/bash directory." }, { "code": null, "e": 25353, "s": 25349, "text": "gdu" }, { "code": null, "e": 25388, "s": 25353, "text": "Then you will see output like the:" }, { "code": null, "e": 25498, "s": 25388, "text": "To analyze the specific directory you can mention the path of the directory after the gdu command like this:-" }, { "code": null, "e": 25514, "s": 25498, "text": "gdu /lib/apt/" }, { "code": null, "e": 25545, "s": 25514, "text": "Then you will see the output:-" }, { "code": null, "e": 25647, "s": 25545, "text": "Note that we can provide only one argument to the gdu. Now let’s see options to use interactive mode." }, { "code": null, "e": 25918, "s": 25647, "text": "GDU provides the options to use GDU more effectively in interactive mode. To see all options press ? Key on the keyboard. Now we can see the options using which we can move the cursor up/down, select and delete directories or files using keys like J , G , l , h , etc ." }, { "code": null, "e": 25988, "s": 25918, "text": "We can delete the selected file by pressing the d key on the keyboard" }, { "code": null, "e": 26066, "s": 25988, "text": "You can also view the content of a file by pressing the v key on the keyboard" }, { "code": null, "e": 26221, "s": 26066, "text": " Did you observe the flags like e , ! , . , @, H,e before the file names ? Each of the flags has a different meaning, let us see the meaning of each flag" }, { "code": null, "e": 26436, "s": 26221, "text": "! -> An Error appeared while reading directory \n. -> An Error appeared while reading subdirectory.\n@ -> File is a socket or simlink.\nH -> Hardlink(File) which was already counted.\ne -> An Empty directory." }, { "code": null, "e": 26564, "s": 26436, "text": " Now let’s see some other options provided by GDU. We can see all option provided by the GDU using the help command as follows:" }, { "code": null, "e": 26575, "s": 26564, "text": "gdu --help" }, { "code": null, "e": 26614, "s": 26575, "text": "Now let’s see how to use these options" }, { "code": null, "e": 26626, "s": 26614, "text": "-c options " }, { "code": null, "e": 26711, "s": 26626, "text": " By using this option we can print the output in black and white color." }, { "code": null, "e": 26733, "s": 26711, "text": "gdu -c directory_path" }, { "code": null, "e": 26744, "s": 26733, "text": "-n options" }, { "code": null, "e": 26828, "s": 26744, "text": "If you want the outputs in the non-interactive form then you can use the flag “n” " }, { "code": null, "e": 26850, "s": 26828, "text": "gdu -n directory_path" }, { "code": null, "e": 26861, "s": 26850, "text": "Kali-Linux" }, { "code": null, "e": 26873, "s": 26861, "text": "Linux-Tools" }, { "code": null, "e": 26884, "s": 26873, "text": "Linux-Unix" }, { "code": null, "e": 26982, "s": 26884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26991, "s": 26982, "text": "Comments" }, { "code": null, "e": 27004, "s": 26991, "text": "Old Comments" }, { "code": null, "e": 27039, "s": 27004, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27076, "s": 27039, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27110, "s": 27076, "text": "mv command in Linux with examples" }, { "code": null, "e": 27136, "s": 27110, "text": "Thread functions in C/C++" }, { "code": null, "e": 27162, "s": 27136, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27199, "s": 27162, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27239, "s": 27199, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 27268, "s": 27239, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27310, "s": 27268, "text": "Named Pipe or FIFO with example C program" } ]
How to fill the area under a curve in a Seaborn distribution plot?
To fill the area under a curve in a Seaborn distribution plot, we can use distplot() and fill_between() methods. Set the figure size and adjust the padding between and around the subplots. Create a list of data points. Plot a univariate distribution of observations. To fill the area under the curve, use fill_between() method. Set or retrieve autoscaling margins, x=0 and y=0. To display the figure, use show() method. import seaborn as sns import scipy.stats as stats import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = [2.0, 7.5, 9.0, 8.5] ax = sns.distplot(x, fit_kws={"color": "red"}, kde=False, fit=stats.gamma, hist=None, label="label 1") l1 = ax.lines[0] x1 = l1.get_xydata()[:, 0] y1 = l1.get_xydata()[:, 1] ax.fill_between(x1, y1, color="red", alpha=0.3) ax.margins(x=0, y=0) plt.show()
[ { "code": null, "e": 1175, "s": 1062, "text": "To fill the area under a curve in a Seaborn distribution plot, we can use distplot() and fill_between() methods." }, { "code": null, "e": 1251, "s": 1175, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1281, "s": 1251, "text": "Create a list of data points." }, { "code": null, "e": 1329, "s": 1281, "text": "Plot a univariate distribution of observations." }, { "code": null, "e": 1390, "s": 1329, "text": "To fill the area under the curve, use fill_between() method." }, { "code": null, "e": 1440, "s": 1390, "text": "Set or retrieve autoscaling margins, x=0 and y=0." }, { "code": null, "e": 1482, "s": 1440, "text": "To display the figure, use show() method." }, { "code": null, "e": 1935, "s": 1482, "text": "import seaborn as sns\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = [2.0, 7.5, 9.0, 8.5]\nax = sns.distplot(x, fit_kws={\"color\": \"red\"}, kde=False, fit=stats.gamma, hist=None, label=\"label 1\")\nl1 = ax.lines[0]\n\nx1 = l1.get_xydata()[:, 0]\ny1 = l1.get_xydata()[:, 1]\n\nax.fill_between(x1, y1, color=\"red\", alpha=0.3)\nax.margins(x=0, y=0)\n\nplt.show()" } ]
Matplotlib - Twin Axes
It is considered useful to have dual x or y axes in a figure. Moreso, when plotting curves with different units together. Matplotlib supports this with the twinxand twiny functions. In the following example, the plot has dual y axes, one showing exp(x) and the other showing log(x) − import matplotlib.pyplot as plt import numpy as np fig = plt.figure() a1 = fig.add_axes([0,0,1,1]) x = np.arange(1,11) a1.plot(x,np.exp(x)) a1.set_ylabel('exp') a2 = a1.twinx() a2.plot(x, np.log(x),'ro-') a2.set_ylabel('log') fig.legend(labels = ('exp','log'),loc='upper left') plt.show() 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2698, "s": 2516, "text": "It is considered useful to have dual x or y axes in a figure. Moreso, when plotting curves with different units together. Matplotlib supports this with the twinxand twiny functions." }, { "code": null, "e": 2800, "s": 2698, "text": "In the following example, the plot has dual y axes, one showing exp(x) and the other showing log(x) −" }, { "code": null, "e": 3089, "s": 2800, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfig = plt.figure()\na1 = fig.add_axes([0,0,1,1])\nx = np.arange(1,11)\na1.plot(x,np.exp(x))\na1.set_ylabel('exp')\na2 = a1.twinx()\na2.plot(x, np.log(x),'ro-')\na2.set_ylabel('log')\nfig.legend(labels = ('exp','log'),loc='upper left')\nplt.show()" }, { "code": null, "e": 3122, "s": 3089, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3139, "s": 3122, "text": " Abhilash Nelson" }, { "code": null, "e": 3172, "s": 3139, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3207, "s": 3172, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3241, "s": 3207, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3276, "s": 3241, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3309, "s": 3276, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 3319, "s": 3309, "text": " Aipython" }, { "code": null, "e": 3354, "s": 3319, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3366, "s": 3354, "text": " Akbar Khan" }, { "code": null, "e": 3399, "s": 3366, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3406, "s": 3399, "text": " Anmol" }, { "code": null, "e": 3413, "s": 3406, "text": " Print" }, { "code": null, "e": 3424, "s": 3413, "text": " Add Notes" } ]
Retrieving the first document in a MongoDB collection?
To retrieve the first document in a collection, you can use findOne(). Following is the syntax var anyVariableName=db.yourCollectionName.findOne(); //To print result at MongoDB console write the variable name yourVariableName Let us first create a collection with documents > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2325966324ffac2a7dc6d") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2326266324ffac2a7dc6e") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2327566324ffac2a7dc70") } Following is the query to display all documents from a collection with the help of find() method > db.retrieveFirstDocumentDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5ca2325966324ffac2a7dc6d"), "ClientName" : "Robert", "ClientAge" : 23 } { "_id" : ObjectId("5ca2326266324ffac2a7dc6e"), "ClientName" : "Chris", "ClientAge" : 26 } { "_id" : ObjectId("5ca2326a66324ffac2a7dc6f"), "ClientName" : "Larry", "ClientAge" : 29 } { "_id" : ObjectId("5ca2327566324ffac2a7dc70"), "ClientName" : "David", "ClientAge" : 39 } Following is the query to retrieve first document in a collection > var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne(); > firstDocumentOnly; This will produce the following output { "_id" : ObjectId("5ca2325966324ffac2a7dc6d"), "ClientName" : "Robert", "ClientAge" : 23 }
[ { "code": null, "e": 1157, "s": 1062, "text": "To retrieve the first document in a collection, you can use findOne(). Following is the syntax" }, { "code": null, "e": 1288, "s": 1157, "text": "var anyVariableName=db.yourCollectionName.findOne();\n//To print result at MongoDB console write the variable name\nyourVariableName" }, { "code": null, "e": 1336, "s": 1288, "text": "Let us first create a collection with documents" }, { "code": null, "e": 2001, "s": 1336, "text": "> db.retrieveFirstDocumentDemo.insertOne({\"ClientName\":\"Robert\",\"ClientAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2325966324ffac2a7dc6d\")\n}\n> db.retrieveFirstDocumentDemo.insertOne({\"ClientName\":\"Chris\",\"ClientAge\":26});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2326266324ffac2a7dc6e\")\n}\n> db.retrieveFirstDocumentDemo.insertOne({\"ClientName\":\"Larry\",\"ClientAge\":29});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2326a66324ffac2a7dc6f\")\n}\n> db.retrieveFirstDocumentDemo.insertOne({\"ClientName\":\"David\",\"ClientAge\":39});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2327566324ffac2a7dc70\")\n}" }, { "code": null, "e": 2098, "s": 2001, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 2146, "s": 2098, "text": "> db.retrieveFirstDocumentDemo.find().pretty();" }, { "code": null, "e": 2185, "s": 2146, "text": "This will produce the following output" }, { "code": null, "e": 2586, "s": 2185, "text": "{\n \"_id\" : ObjectId(\"5ca2325966324ffac2a7dc6d\"),\n \"ClientName\" : \"Robert\",\n \"ClientAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5ca2326266324ffac2a7dc6e\"),\n \"ClientName\" : \"Chris\",\n \"ClientAge\" : 26\n}\n{\n \"_id\" : ObjectId(\"5ca2326a66324ffac2a7dc6f\"),\n \"ClientName\" : \"Larry\",\n \"ClientAge\" : 29\n}\n{\n \"_id\" : ObjectId(\"5ca2327566324ffac2a7dc70\"),\n \"ClientName\" : \"David\",\n \"ClientAge\" : 39\n}" }, { "code": null, "e": 2652, "s": 2586, "text": "Following is the query to retrieve first document in a collection" }, { "code": null, "e": 2737, "s": 2652, "text": "> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne();\n> firstDocumentOnly;" }, { "code": null, "e": 2776, "s": 2737, "text": "This will produce the following output" }, { "code": null, "e": 2877, "s": 2776, "text": "{\n \"_id\" : ObjectId(\"5ca2325966324ffac2a7dc6d\"),\n \"ClientName\" : \"Robert\",\n \"ClientAge\" : 23\n}" } ]
Haskell - Zippers
Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree. Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right? But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree. In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure. data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord) type Zipper_List a = ([a],[a]) go_Forward :: Zipper_List a -> Zipper_List a go_Forward (x:xs, bs) = (xs, x:bs) go_Back :: Zipper_List a -> Zipper_List a go_Back (xs, b:bs) = (b:xs, bs) main = do let list_Ex = [1,2,3,4] print(go_Forward (list_Ex,[])) print(go_Back([4],[3,2,1])) When you compile and execute the above program, it will produce the following output − ([2,3,4],[1]) ([3,4],[2,1]) Here we are focusing on an element of the entire string while going forward or while coming backward. Print Add Notes Bookmark this page
[ { "code": null, "e": 2030, "s": 1915, "text": "Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree." }, { "code": null, "e": 2295, "s": 2030, "text": "Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right?" }, { "code": null, "e": 2684, "s": 2295, "text": "But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree." }, { "code": null, "e": 2841, "s": 2684, "text": "In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure." }, { "code": null, "e": 3230, "s": 2841, "text": "data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)\ntype Zipper_List a = ([a],[a]) \n\ngo_Forward :: Zipper_List a -> Zipper_List a \ngo_Forward (x:xs, bs) = (xs, x:bs) \n \ngo_Back :: Zipper_List a -> Zipper_List a \ngo_Back (xs, b:bs) = (b:xs, bs) \n\nmain = do \n let list_Ex = [1,2,3,4] \n print(go_Forward (list_Ex,[])) \n print(go_Back([4],[3,2,1])) " }, { "code": null, "e": 3317, "s": 3230, "text": "When you compile and execute the above program, it will produce the following output −" }, { "code": null, "e": 3347, "s": 3317, "text": "([2,3,4],[1]) \n([3,4],[2,1])\n" }, { "code": null, "e": 3449, "s": 3347, "text": "Here we are focusing on an element of the entire string while going forward or while coming backward." }, { "code": null, "e": 3456, "s": 3449, "text": " Print" }, { "code": null, "e": 3467, "s": 3456, "text": " Add Notes" } ]
Replace all consonants with nearest vowels in a string - GeeksforGeeks
14 Apr, 2022 Given a string with lowercase English alphabets. The task is to replace all the consonants in the string with the nearest vowels. If a consonant is near to two vowels then replace it with the one that comes first in English alphabets. Note: Vowels already present in the string must be left as it is.Examples: Input : str = "geeksforgeeks" Output : eeeiueooeeeiu Input : str = "gfg" Output : eee A simple approach is to compare the consonant with vowels to determine the nearest vowel. First, check if the consonant falls between two vowels. If it falls between 2 vowels then find the absolute difference between the ASCII value of consonant with the ASCII value of both vowels. Replace it with that vowel, with which the absolute difference is minimum. However, if the ASCII code of consonant does not fall between two vowels, then the consonant can be ‘v’, ‘w’, ‘x’, ‘y’, ‘z’. Hence, the answer is ‘u’ in this case.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to replace all consonants // with nearest vowels in a string #include <bits/stdc++.h> using namespace std; // Function to check if a character is // vowel or not bool isVowel(char ch) { if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true; } // Function to replace consonant with // nearest vowels string replacingConsonants(string s) { for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (abs(s[i] - 'a') > abs(s[i] - 'e')) s[i] = 'e'; else s[i] = 'a'; } else if (s[i] > 'e' && s[i] < 'i') { if (abs(s[i] - 'e') > abs(s[i] - 'i')) s[i] = 'i'; else s[i] = 'e'; } else if (s[i] > 'i' && s[i] < 'o') { if (abs(s[i] - 'i') > abs(s[i] - 'o')) s[i] = 'o'; else s[i] = 'i'; } else if (s[i] > 'o' && s[i] < 'u') { if (abs(s[i] - 'o') > abs(s[i] - 'u')) s[i] = 'u'; else s[i] = 'o'; } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s[i] = 'u'; } } return s; } // Driver code int main() { string s = "geeksforgeeks"; cout << replacingConsonants(s); return 0; } // Java program to replace all consonants // with nearest vowels in a string import java.util.*; class Solution{ // Function to check if a character is // vowel or not static boolean isVowel(char ch) { if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true; } // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s.charAt(i))) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s.charAt(i) > 'a' && s.charAt(i) < 'e') { // here the absolute difference of // ascii value is considered if (Math.abs(s.charAt(i) - 'a') > Math.abs(s.charAt(i) - 'e')) s = s.substring(0,i)+'e'+s.substring(i+1); else s= s.substring(0,i)+'a'+s.substring(i+1); } else if (s.charAt(i) > 'e' && s.charAt(i) < 'i') { if (Math.abs(s.charAt(i) - 'e') > Math.abs(s.charAt(i) - 'i')) s = s.substring(0,i)+'i'+s.substring(i+1); else s = s.substring(0,i)+'e'+s.substring(i+1); } else if (s.charAt(i) > 'i' && s.charAt(i) < 'o') { if (Math.abs(s.charAt(i) - 'i') > Math.abs(s.charAt(i) - 'o')) s= s.substring(0,i)+'o'+s.substring(i+1); else s= s.substring(0,i)+'i'+s.substring(i+1); } else if (s.charAt(i) > 'o' && s.charAt(i) < 'u') { if (Math.abs(s.charAt(i) - 'o') > Math.abs(s.charAt(i) - 'u')) s= s.substring(0,i)+'u'+s.substring(i+1); else s= s.substring(0,i)+'o'+s.substring(i+1); } // when s.charAt(i) is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s.charAt(i) > 'u') s =s.substring(0,i)+'u'+s.substring(i+1); } } return s; } // Driver code public static void main(String args[]) { String s = "geeksforgeeks"; System.out.print( replacingConsonants(s)); } } //contributed by Arnab Kundu # Python3 program to replace all consonants # with nearest vowels in a string # Function to check if a # character is vowel or not def isVowel(ch): if (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u'): return False return True # Function to replace consonant # with nearest vowels def replacingConsonants(s): for i in range(0, len(s)): # if, string element is vowel, # jump to next element if isVowel(s[i]): continue # check if consonant lies between two vowels, # if it lies, than replace it with nearest vowel else: if s[i] > 'a' and s[i] < 'e': # here the absolute difference of # ascii value is considered if (abs(ord(s[i]) - ord('a')) > abs(ord(s[i]) - ord('e'))): s[i] = 'e' else: s[i] = 'a' elif s[i] > 'e' and s[i] < 'i': if (abs(ord(s[i]) - ord('e')) > abs(ord(s[i]) - ord('i'))): s[i] = 'i' else: s[i] = 'e' elif (s[i] > 'i' and s[i] < 'o'): if (abs(ord(s[i]) - ord('i')) > abs(ord(s[i]) - ord('o'))): s[i] = 'o' else: s[i] = 'i' elif (s[i] > 'o' and s[i] < 'u'): if (abs(ord(s[i]) - ord('o')) > abs(ord(s[i]) - ord('u'))): s[i] = 'u' else: s[i] = 'o' # when s[i] is equal to either # 'v', 'w', 'x', 'y', 'z' elif (s[i] > 'u'): s[i] = 'u' return ''.join(s) # Driver code if __name__ == "__main__": s = "geeksforgeeks" print(replacingConsonants(list(s))) # This code is contributed by Rituraj Jain // C# program to replace all consonants // with nearest vowels in a string using System; public class Solution{ // Function to check if a character is // vowel or not static bool isVowel(char ch) { if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true; } // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { for (int i = 0; i < s.Length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (Math.Abs(s[i] - 'a') > Math.Abs(s[i] - 'e')) s = s.Substring(0,i)+'e'+s.Substring(i+1); else s= s.Substring(0,i)+'a'+s.Substring(i+1); } else if (s[i] > 'e' && s[i] < 'i') { if (Math.Abs(s[i] - 'e') > Math.Abs(s[i] - 'i')) s = s.Substring(0,i)+'i'+s.Substring(i+1); else s = s.Substring(0,i)+'e'+s.Substring(i+1); } else if (s[i] > 'i' && s[i] < 'o') { if (Math.Abs(s[i] - 'i') > Math.Abs(s[i] - 'o')) s= s.Substring(0,i)+'o'+s.Substring(i+1); else s= s.Substring(0,i)+'i'+s.Substring(i+1); } else if (s[i] > 'o' && s[i] < 'u') { if (Math.Abs(s[i] - 'o') > Math.Abs(s[i] - 'u')) s= s.Substring(0,i)+'u'+s.Substring(i+1); else s= s.Substring(0,i)+'o'+s.Substring(i+1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s =s.Substring(0,i)+'u'+s.Substring(i+1); } } return s; } // Driver code public static void Main() { String s = "geeksforgeeks"; Console.WriteLine( replacingConsonants(s)); } } // This code is contributed by PrinciRaj1992 <script> // JavaScript program to replace all consonants // with nearest vowels in a string // Function to check if a character is // vowel or not function isVowel(ch) { if (ch !== "a" && ch !== "e" && ch !== "i" && ch !== "o" && ch !== "u") return false; return true; } // Function to replace consonant with // nearest vowels function replacingConsonants(s) { for (var i = 0; i < s.length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > "a" && s[i] < "e") { // here the absolute difference of // ascii value is considered if ( Math.abs(s[i].charCodeAt(0) - "a".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "e".charCodeAt(0)) ) s = s.substring(0, i) + "e" + s.substring(i + 1); else s = s.substring(0, i) + "a" + s.substring(i + 1); } else if (s[i] > "e" && s[i] < "i") { if ( Math.abs(s[i].charCodeAt(0) - "e".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "i".charCodeAt(0)) ) s = s.substring(0, i) + "i" + s.substring(i + 1); else s = s.substring(0, i) + "e" + s.substring(i + 1); } else if (s[i] > "i" && s[i] < "o") { if ( Math.abs(s[i].charCodeAt(0) - "i".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "o".charCodeAt(0)) ) s = s.substring(0, i) + "o" + s.substring(i + 1); else s = s.substring(0, i) + "i" + s.substring(i + 1); } else if (s[i] > "o" && s[i] < "u") { if ( Math.abs(s[i].charCodeAt(0) - "o".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "u".charCodeAt(0)) ) s = s.substring(0, i) + "u" + s.substring(i + 1); else s = s.substring(0, i) + "o" + s.substring(i + 1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > "u") s = s.substring(0, i) + "u" + s.substring(i + 1); } } return s; } // Driver code var s = "geeksforgeeks"; document.write(replacingConsonants(s)); </script> eeeiueooeeeiu A better approach is to make an array of size 26 that stores nearest vowel for every character. C++ Java Python3 C# Javascript // C++ program to replace all consonants // with nearest vowels in a string #include <bits/stdc++.h> using namespace std; // Function to replace consonant with // nearest vowels string replacingConsonants(string s) { char nVowel[] = "aaaeeeeiiiiioooooouuuuuuuu"; for (int i = 0; i < s.length(); i++) s[i] = nVowel[s[i] - 'a']; return s; } // Driver code int main() { string s = "geeksforgeeks"; cout << replacingConsonants(s); return 0; } // Java program to replace all consonants // with nearest vowels in a string import java.util.*; class solution { // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { String str = "aaaeeeeiiiiioooooouuuuuuuu"; char[] st = s.toCharArray(); for (int i = 0; i < s.length(); i++) { int index = st[i]-'a'; st[i] = str.charAt(index); } String str1 = new String(st); return str1; } // Driver code public static void main(String arr[]) { String s = "geeksforgeeks"; System.out.println(replacingConsonants(s)); } } // This code is contributed by Surendra_Gangwar # Python3 program to replace all consonants # with nearest vowels in a string # Function to replace consonant with # nearest vowels def replacingConsonants(s): nVowel = "aaaeeeeiiiiioooooouuuuuuuu" for i in range (0, len(s)): s = s.replace(s[i], nVowel[ord(s[i]) - 97]) return s # Driver code s = "geeksforgeeks"; print(replacingConsonants(s)); # This code is contributed by # archana_kumari. // C# program to replace all consonants // with nearest vowels in a string using System; public class solution{ // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { String str = "aaaeeeeiiiiioooooouuuuuuuu"; char[] st = s.ToCharArray(); for (int i = 0; i < s.Length; i++) { int index = st[i]-'a'; st[i] = str[index]; } String str1 = new String(st); return str1; } // Driver code public static void Main() { String s = "geeksforgeeks"; Console.WriteLine(replacingConsonants(s)); } } // This code is contributed by 29AjayKumar <script> // Javascript program to replace all consonants // with nearest vowels in a string // Function to replace consonant with // nearest vowels function replacingConsonants(s) { var nVowel = "aaaeeeeiiiiioooooouuuuuuuu"; for (var i = 0; i < s.length; i++) s[i] = nVowel[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; return s.join(''); } // Driver code var s = "geeksforgeeks".split(''); document.write( replacingConsonants(s)); </script> eeeiueooeeeiu SURENDRA_GANGWAR andrew1234 29AjayKumar princiraj1992 archana_kumari rituraj_jain itsok rdtank sweetyty Technical Scripter 2018 vowel-consonant Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Different methods to reverse a string in C/C++ KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Reverse words in a given string Caesar Cipher in Cryptography Length of the longest substring without repeating characters
[ { "code": null, "e": 24616, "s": 24585, "text": " \n14 Apr, 2022\n" }, { "code": null, "e": 24928, "s": 24616, "text": "Given a string with lowercase English alphabets. The task is to replace all the consonants in the string with the nearest vowels. If a consonant is near to two vowels then replace it with the one that comes first in English alphabets. Note: Vowels already present in the string must be left as it is.Examples: " }, { "code": null, "e": 25015, "s": 24928, "text": "Input : str = \"geeksforgeeks\"\nOutput : eeeiueooeeeiu\n\nInput : str = \"gfg\"\nOutput : eee" }, { "code": null, "e": 25591, "s": 25017, "text": "A simple approach is to compare the consonant with vowels to determine the nearest vowel. First, check if the consonant falls between two vowels. If it falls between 2 vowels then find the absolute difference between the ASCII value of consonant with the ASCII value of both vowels. Replace it with that vowel, with which the absolute difference is minimum. However, if the ASCII code of consonant does not fall between two vowels, then the consonant can be ‘v’, ‘w’, ‘x’, ‘y’, ‘z’. Hence, the answer is ‘u’ in this case.Below is the implementation of the above approach: " }, { "code": null, "e": 25595, "s": 25591, "text": "C++" }, { "code": null, "e": 25600, "s": 25595, "text": "Java" }, { "code": null, "e": 25608, "s": 25600, "text": "Python3" }, { "code": null, "e": 25611, "s": 25608, "text": "C#" }, { "code": null, "e": 25622, "s": 25611, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program to replace all consonants\n// with nearest vowels in a string\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to check if a character is\n// vowel or not\nbool isVowel(char ch)\n{\n if (ch != 'a' && ch != 'e' && ch != 'i'\n && ch != 'o' && ch != 'u')\n return false;\n \n return true;\n}\n \n// Function to replace consonant with\n// nearest vowels\nstring replacingConsonants(string s)\n{\n for (int i = 0; i < s.length(); i++) {\n \n // if, string element is vowel,\n // jump to next element\n if (isVowel(s[i]))\n continue;\n \n // check if consonant lies between two vowels,\n // if it lies, than replace it with nearest vowel\n else {\n \n if (s[i] > 'a' && s[i] < 'e') {\n \n // here the absolute difference of\n // ascii value is considered\n if (abs(s[i] - 'a') > abs(s[i] - 'e'))\n s[i] = 'e';\n else\n s[i] = 'a';\n }\n else if (s[i] > 'e' && s[i] < 'i') {\n if (abs(s[i] - 'e') > abs(s[i] - 'i'))\n s[i] = 'i';\n else\n s[i] = 'e';\n }\n else if (s[i] > 'i' && s[i] < 'o') {\n if (abs(s[i] - 'i') > abs(s[i] - 'o'))\n s[i] = 'o';\n else\n s[i] = 'i';\n }\n else if (s[i] > 'o' && s[i] < 'u') {\n if (abs(s[i] - 'o') > abs(s[i] - 'u'))\n s[i] = 'u';\n else\n s[i] = 'o';\n }\n \n // when s[i] is equal to either\n // 'v', 'w', 'x', 'y', 'z'\n else if (s[i] > 'u')\n s[i] = 'u';\n }\n }\n \n return s;\n}\n \n// Driver code\nint main()\n{\n string s = \"geeksforgeeks\";\n \n cout << replacingConsonants(s);\n \n return 0;\n}\n\n\n\n\n\n", "e": 27568, "s": 25632, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program to replace all consonants \n// with nearest vowels in a string \n \nimport java.util.*;\nclass Solution{\n \n// Function to check if a character is \n// vowel or not \nstatic boolean isVowel(char ch) \n{ \n if (ch != 'a' && ch != 'e' && ch != 'i'\n && ch != 'o' && ch != 'u') \n return false; \n \n return true; \n} \n \n// Function to replace consonant with \n// nearest vowels \nstatic String replacingConsonants(String s) \n{ \n for (int i = 0; i < s.length(); i++) { \n \n // if, string element is vowel, \n // jump to next element \n if (isVowel(s.charAt(i))) \n continue; \n \n // check if consonant lies between two vowels, \n // if it lies, than replace it with nearest vowel \n else { \n \n if (s.charAt(i) > 'a' && s.charAt(i) < 'e') { \n \n // here the absolute difference of \n // ascii value is considered \n if (Math.abs(s.charAt(i) - 'a') > Math.abs(s.charAt(i) - 'e')) \n s = s.substring(0,i)+'e'+s.substring(i+1); \n else\n s= s.substring(0,i)+'a'+s.substring(i+1);\n } \n else if (s.charAt(i) > 'e' && s.charAt(i) < 'i') { \n if (Math.abs(s.charAt(i) - 'e') > Math.abs(s.charAt(i) - 'i')) \n s = s.substring(0,i)+'i'+s.substring(i+1);\n else\n s = s.substring(0,i)+'e'+s.substring(i+1); \n } \n else if (s.charAt(i) > 'i' && s.charAt(i) < 'o') { \n if (Math.abs(s.charAt(i) - 'i') > Math.abs(s.charAt(i) - 'o')) \n s= s.substring(0,i)+'o'+s.substring(i+1);\n else\n s= s.substring(0,i)+'i'+s.substring(i+1);\n } \n else if (s.charAt(i) > 'o' && s.charAt(i) < 'u') { \n if (Math.abs(s.charAt(i) - 'o') > Math.abs(s.charAt(i) - 'u')) \n s= s.substring(0,i)+'u'+s.substring(i+1);\n else\n s= s.substring(0,i)+'o'+s.substring(i+1);\n } \n \n // when s.charAt(i) is equal to either \n // 'v', 'w', 'x', 'y', 'z' \n else if (s.charAt(i) > 'u') \n s =s.substring(0,i)+'u'+s.substring(i+1);\n } \n } \n \n return s; \n} \n \n// Driver code \npublic static void main(String args[])\n{ \n String s = \"geeksforgeeks\"; \n \n System.out.print( replacingConsonants(s)); \n \n} \n \n}\n//contributed by Arnab Kundu\n\n\n\n\n\n", "e": 30090, "s": 27578, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program to replace all consonants \n# with nearest vowels in a string \n \n# Function to check if a \n# character is vowel or not \ndef isVowel(ch): \n \n if (ch != 'a' and ch != 'e' and ch != 'i'\n and ch != 'o' and ch != 'u'):\n return False\n \n return True\n \n# Function to replace consonant \n# with nearest vowels \ndef replacingConsonants(s): \n \n for i in range(0, len(s)): \n \n # if, string element is vowel, \n # jump to next element \n if isVowel(s[i]): \n continue\n \n # check if consonant lies between two vowels, \n # if it lies, than replace it with nearest vowel \n else: \n \n if s[i] > 'a' and s[i] < 'e': \n \n # here the absolute difference of \n # ascii value is considered \n if (abs(ord(s[i]) - ord('a')) > abs(ord(s[i]) - ord('e'))): \n s[i] = 'e'\n else:\n s[i] = 'a'\n \n elif s[i] > 'e' and s[i] < 'i': \n if (abs(ord(s[i]) - ord('e')) > abs(ord(s[i]) - ord('i'))): \n s[i] = 'i'\n else:\n s[i] = 'e'\n \n elif (s[i] > 'i' and s[i] < 'o'): \n if (abs(ord(s[i]) - ord('i')) > abs(ord(s[i]) - ord('o'))):\n s[i] = 'o'\n else:\n s[i] = 'i'\n \n elif (s[i] > 'o' and s[i] < 'u'): \n if (abs(ord(s[i]) - ord('o')) > abs(ord(s[i]) - ord('u'))): \n s[i] = 'u'\n else:\n s[i] = 'o'\n \n # when s[i] is equal to either \n # 'v', 'w', 'x', 'y', 'z' \n elif (s[i] > 'u'): \n s[i] = 'u'\n \n return ''.join(s) \n \n# Driver code \nif __name__ == \"__main__\": \n \n s = \"geeksforgeeks\"\n print(replacingConsonants(list(s))) \n \n# This code is contributed by Rituraj Jain\n\n\n\n\n\n", "e": 32095, "s": 30100, "text": null }, { "code": "\n\n\n\n\n\n\n \n// C# program to replace all consonants \n// with nearest vowels in a string \nusing System;\npublic class Solution{\n \n // Function to check if a character is \n // vowel or not \n static bool isVowel(char ch) \n { \n if (ch != 'a' && ch != 'e' && ch != 'i'\n && ch != 'o' && ch != 'u') \n return false; \n \n return true; \n } \n \n // Function to replace consonant with \n // nearest vowels \n static String replacingConsonants(String s) \n { \n for (int i = 0; i < s.Length; i++) { \n \n // if, string element is vowel, \n // jump to next element \n if (isVowel(s[i])) \n continue; \n \n // check if consonant lies between two vowels, \n // if it lies, than replace it with nearest vowel \n else { \n \n if (s[i] > 'a' && s[i] < 'e') { \n \n // here the absolute difference of \n // ascii value is considered \n if (Math.Abs(s[i] - 'a') > Math.Abs(s[i] - 'e')) \n s = s.Substring(0,i)+'e'+s.Substring(i+1); \n else\n s= s.Substring(0,i)+'a'+s.Substring(i+1);\n } \n else if (s[i] > 'e' && s[i] < 'i') { \n if (Math.Abs(s[i] - 'e') > Math.Abs(s[i] - 'i')) \n s = s.Substring(0,i)+'i'+s.Substring(i+1);\n else\n s = s.Substring(0,i)+'e'+s.Substring(i+1); \n } \n else if (s[i] > 'i' && s[i] < 'o') { \n if (Math.Abs(s[i] - 'i') > Math.Abs(s[i] - 'o')) \n s= s.Substring(0,i)+'o'+s.Substring(i+1);\n else\n s= s.Substring(0,i)+'i'+s.Substring(i+1);\n } \n else if (s[i] > 'o' && s[i] < 'u') { \n if (Math.Abs(s[i] - 'o') > Math.Abs(s[i] - 'u')) \n s= s.Substring(0,i)+'u'+s.Substring(i+1);\n else\n s= s.Substring(0,i)+'o'+s.Substring(i+1);\n } \n \n // when s[i] is equal to either \n // 'v', 'w', 'x', 'y', 'z' \n else if (s[i] > 'u') \n s =s.Substring(0,i)+'u'+s.Substring(i+1);\n } \n } \n \n return s; \n } \n \n // Driver code \n public static void Main()\n { \n String s = \"geeksforgeeks\"; \n \n Console.WriteLine( replacingConsonants(s)); \n \n } \n}\n \n// This code is contributed by PrinciRaj1992\n\n\n\n\n\n", "e": 34729, "s": 32105, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n // JavaScript program to replace all consonants\n // with nearest vowels in a string\n // Function to check if a character is\n // vowel or not\n function isVowel(ch) {\n if (ch !== \"a\" && ch !== \"e\" && ch !== \"i\" && ch !== \"o\" && ch !== \"u\")\n return false;\n \n return true;\n }\n \n // Function to replace consonant with\n // nearest vowels\n function replacingConsonants(s) {\n for (var i = 0; i < s.length; i++) {\n // if, string element is vowel,\n // jump to next element\n if (isVowel(s[i])) continue;\n // check if consonant lies between two vowels,\n // if it lies, than replace it with nearest vowel\n else {\n if (s[i] > \"a\" && s[i] < \"e\") {\n // here the absolute difference of\n // ascii value is considered\n if (\n Math.abs(s[i].charCodeAt(0) - \"a\".charCodeAt(0)) >\n Math.abs(s[i].charCodeAt(0) - \"e\".charCodeAt(0))\n )\n s = s.substring(0, i) + \"e\" + s.substring(i + 1);\n else s = s.substring(0, i) + \"a\" + s.substring(i + 1);\n } else if (s[i] > \"e\" && s[i] < \"i\") {\n if (\n Math.abs(s[i].charCodeAt(0) - \"e\".charCodeAt(0)) >\n Math.abs(s[i].charCodeAt(0) - \"i\".charCodeAt(0))\n )\n s = s.substring(0, i) + \"i\" + s.substring(i + 1);\n else s = s.substring(0, i) + \"e\" + s.substring(i + 1);\n } else if (s[i] > \"i\" && s[i] < \"o\") {\n if (\n Math.abs(s[i].charCodeAt(0) - \"i\".charCodeAt(0)) >\n Math.abs(s[i].charCodeAt(0) - \"o\".charCodeAt(0))\n )\n s = s.substring(0, i) + \"o\" + s.substring(i + 1);\n else s = s.substring(0, i) + \"i\" + s.substring(i + 1);\n } else if (s[i] > \"o\" && s[i] < \"u\") {\n if (\n Math.abs(s[i].charCodeAt(0) - \"o\".charCodeAt(0)) >\n Math.abs(s[i].charCodeAt(0) - \"u\".charCodeAt(0))\n )\n s = s.substring(0, i) + \"u\" + s.substring(i + 1);\n else s = s.substring(0, i) + \"o\" + s.substring(i + 1);\n }\n \n // when s[i] is equal to either\n // 'v', 'w', 'x', 'y', 'z'\n else if (s[i] > \"u\")\n s = s.substring(0, i) + \"u\" + s.substring(i + 1);\n }\n }\n \n return s;\n }\n \n // Driver code\n \n var s = \"geeksforgeeks\";\n document.write(replacingConsonants(s));\n </script>\n\n\n\n\n\n", "e": 37350, "s": 34739, "text": null }, { "code": null, "e": 37364, "s": 37350, "text": "eeeiueooeeeiu" }, { "code": null, "e": 37464, "s": 37366, "text": "A better approach is to make an array of size 26 that stores nearest vowel for every character. " }, { "code": null, "e": 37468, "s": 37464, "text": "C++" }, { "code": null, "e": 37473, "s": 37468, "text": "Java" }, { "code": null, "e": 37481, "s": 37473, "text": "Python3" }, { "code": null, "e": 37484, "s": 37481, "text": "C#" }, { "code": null, "e": 37495, "s": 37484, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program to replace all consonants\n// with nearest vowels in a string\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to replace consonant with\n// nearest vowels\nstring replacingConsonants(string s)\n{\n char nVowel[] = \"aaaeeeeiiiiioooooouuuuuuuu\";\n for (int i = 0; i < s.length(); i++) \n s[i] = nVowel[s[i] - 'a'];\n return s;\n}\n \n// Driver code\nint main()\n{\n string s = \"geeksforgeeks\";\n \n cout << replacingConsonants(s);\n \n return 0;\n}\n\n\n\n\n\n", "e": 37998, "s": 37505, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program to replace all consonants\n// with nearest vowels in a string\nimport java.util.*;\n \nclass solution\n{\n \n// Function to replace consonant with\n// nearest vowels\nstatic String replacingConsonants(String s)\n{\n \n String str = \"aaaeeeeiiiiioooooouuuuuuuu\";\n char[] st = s.toCharArray();\n for (int i = 0; i < s.length(); i++) \n {\n int index = st[i]-'a'; \n st[i] = str.charAt(index);\n }\n String str1 = new String(st);\n return str1;\n}\n \n// Driver code\npublic static void main(String arr[])\n{\n String s = \"geeksforgeeks\";\n \n System.out.println(replacingConsonants(s));\n \n}\n \n}\n// This code is contributed by Surendra_Gangwar\n\n\n\n\n\n", "e": 38696, "s": 38008, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program to replace all consonants\n# with nearest vowels in a string\n \n# Function to replace consonant with\n# nearest vowels\ndef replacingConsonants(s):\n \n nVowel = \"aaaeeeeiiiiioooooouuuuuuuu\"\n \n for i in range (0, len(s)):\n s = s.replace(s[i], nVowel[ord(s[i]) - 97])\n \n return s\n \n# Driver code\ns = \"geeksforgeeks\";\n \nprint(replacingConsonants(s));\n \n# This code is contributed by \n# archana_kumari.\n\n\n\n\n\n", "e": 39155, "s": 38706, "text": null }, { "code": "\n\n\n\n\n\n\n \n// C# program to replace all consonants\n// with nearest vowels in a string\nusing System;\n \npublic class solution{\n \n // Function to replace consonant with\n // nearest vowels\n static String replacingConsonants(String s)\n {\n \n String str = \"aaaeeeeiiiiioooooouuuuuuuu\";\n char[] st = s.ToCharArray();\n for (int i = 0; i < s.Length; i++) \n {\n int index = st[i]-'a'; \n st[i] = str[index];\n }\n String str1 = new String(st);\n return str1;\n }\n \n // Driver code\n public static void Main()\n {\n String s = \"geeksforgeeks\";\n \n Console.WriteLine(replacingConsonants(s));\n \n }\n \n}\n \n// This code is contributed by 29AjayKumar\n\n\n\n\n\n", "e": 39916, "s": 39165, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n \n// Javascript program to replace all consonants\n// with nearest vowels in a string\n \n// Function to replace consonant with\n// nearest vowels\nfunction replacingConsonants(s)\n{\n var nVowel = \"aaaeeeeiiiiioooooouuuuuuuu\";\n for (var i = 0; i < s.length; i++) \n s[i] = nVowel[s[i].charCodeAt(0) - 'a'.charCodeAt(0)];\n return s.join('');\n}\n \n// Driver code\nvar s = \"geeksforgeeks\".split('');\ndocument.write( replacingConsonants(s));\n \n</script>\n\n\n\n\n\n", "e": 40405, "s": 39926, "text": null }, { "code": null, "e": 40419, "s": 40405, "text": "eeeiueooeeeiu" }, { "code": null, "e": 40438, "s": 40421, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 40449, "s": 40438, "text": "andrew1234" }, { "code": null, "e": 40461, "s": 40449, "text": "29AjayKumar" }, { "code": null, "e": 40475, "s": 40461, "text": "princiraj1992" }, { "code": null, "e": 40490, "s": 40475, "text": "archana_kumari" }, { "code": null, "e": 40503, "s": 40490, "text": "rituraj_jain" }, { "code": null, "e": 40509, "s": 40503, "text": "itsok" }, { "code": null, "e": 40516, "s": 40509, "text": "rdtank" }, { "code": null, "e": 40525, "s": 40516, "text": "sweetyty" }, { "code": null, "e": 40551, "s": 40525, "text": "\nTechnical Scripter 2018\n" }, { "code": null, "e": 40569, "s": 40551, "text": "\nvowel-consonant\n" }, { "code": null, "e": 40579, "s": 40569, "text": "\nStrings\n" }, { "code": null, "e": 40784, "s": 40579, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 40841, "s": 40784, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 40916, "s": 40841, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 40963, "s": 40916, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 40999, "s": 40963, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 41035, "s": 40999, "text": "Convert string to char array in C++" }, { "code": null, "e": 41088, "s": 41035, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 41126, "s": 41088, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 41158, "s": 41126, "text": "Reverse words in a given string" }, { "code": null, "e": 41188, "s": 41158, "text": "Caesar Cipher in Cryptography" } ]
Can we fetch multiple values with MySQL WHERE Clause?
Yes, we can fetch, but use MySQL OR for conditions. Let us first create a − mysql> create table DemoTable1421 -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert − mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Chris',10000); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Bob',15000); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('David',8000); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Carol',8500); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Mike',14500); Query OK, 1 row affected (0.16 sec) Display all records from the table using select − mysql> select * from DemoTable1421; This will produce the following output − +------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Chris | 10000 | | 2 | Bob | 15000 | | 3 | David | 8000 | | 4 | Carol | 8500 | | 5 | Mike | 14500 | +------------+--------------+----------------+ 5 rows in set (0.00 sec) Here is the query to fetch multiple values with OR − mysql> select * from DemoTable1421 where EmployeeId=1 OR EmployeeName='David' OR EmployeeSalary=14500; This will produce the following output − +------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Chris | 10000 | | 3 | David | 8000 | | 5 | Mike | 14500 | +------------+--------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "Yes, we can fetch, but use MySQL OR for conditions. Let us first create a −" }, { "code": null, "e": 1341, "s": 1138, "text": "mysql> create table DemoTable1421\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> EmployeeName varchar(20),\n -> EmployeeSalary int\n -> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1389, "s": 1341, "text": "Insert some records in the table using insert −" }, { "code": null, "e": 1989, "s": 1389, "text": "mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Chris',10000);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Bob',15000);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('David',8000);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Carol',8500);\nQuery OK, 1 row affected (0.39 sec)\nmysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Mike',14500);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2039, "s": 1989, "text": "Display all records from the table using select −" }, { "code": null, "e": 2075, "s": 2039, "text": "mysql> select * from DemoTable1421;" }, { "code": null, "e": 2116, "s": 2075, "text": "This will produce the following output −" }, { "code": null, "e": 2564, "s": 2116, "text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | Chris | 10000 |\n| 2 | Bob | 15000 |\n| 3 | David | 8000 |\n| 4 | Carol | 8500 |\n| 5 | Mike | 14500 |\n+------------+--------------+----------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2617, "s": 2564, "text": "Here is the query to fetch multiple values with OR −" }, { "code": null, "e": 2720, "s": 2617, "text": "mysql> select * from DemoTable1421 where EmployeeId=1 OR EmployeeName='David' OR EmployeeSalary=14500;" }, { "code": null, "e": 2761, "s": 2720, "text": "This will produce the following output −" }, { "code": null, "e": 3115, "s": 2761, "text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | Chris | 10000 |\n| 3 | David | 8000 |\n| 5 | Mike | 14500 |\n+------------+--------------+----------------+\n3 rows in set (0.00 sec)" } ]
Python - Directory Listing
Python can be used to get the list of content from a directory. We can make program to list the content of directory which is in the same machine where python is running. We can also login to the remote system and list the content from the remote directory. In the below example we use the listdir() method to get the content of the current directory. To also indicate the type of the content like file or directory, we use more functions to evaluate the nature of the content. for name in os.listdir('.'): if os.path.isfile(name): print 'file: ', name elif os.path.isdir(name): print 'dir: ', name elif os.path.islink(name): print 'link: ', name else: print 'unknown', name When we run the above program, we get the following output − file: abcl.htm dir: allbooks link: ulink Please note the content above is specific to the system where the python program was run. The result will vary depending on the system and its content. We can list the content of the remote directory by using ftp to access the remote system. Once the connection is established we can use commands that will list the directory contents in a way similar to the listing of local directories. from ftplib import FTP def main(): ftp = FTP('ftp.ibiblio.org') ftp.login() ftp.cwd('pub/academic/biology/') # change to some other subject entries = ftp.nlst() ftp.quit() print(len(entries), "entries:") for entry in sorted(entries): print(entry) if __name__ == '__main__': main() When we run the above program, we get the following output − (6, 'entries:') INDEX README acedb dna-mutations ecology+evolution molbio 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2584, "s": 2326, "text": "Python can be used to get the list of content from a directory. We can make program to list the content of directory which is in the same machine where python is running.\nWe can also login to the remote system and list the content from the remote directory." }, { "code": null, "e": 2805, "s": 2584, "text": "In the below example we use the listdir() method to get the content of the current directory. To also indicate the type of the content like \nfile or directory, we use more functions to evaluate the nature of the content." }, { "code": null, "e": 3019, "s": 2805, "text": "for name in os.listdir('.'):\n if os.path.isfile(name): print 'file: ', name\n elif os.path.isdir(name): print 'dir: ', name\n elif os.path.islink(name): print 'link: ', name\n else: print 'unknown', name" }, { "code": null, "e": 3080, "s": 3019, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3122, "s": 3080, "text": "file: abcl.htm\ndir: allbooks\nlink: ulink\n" }, { "code": null, "e": 3274, "s": 3122, "text": "Please note the content above is specific to the system where the python program was run. The result will vary depending on the system and its content." }, { "code": null, "e": 3511, "s": 3274, "text": "We can list the content of the remote directory by using ftp to access the remote system. Once the connection is established we can use commands that will\nlist the directory contents in a way similar to the listing of local directories." }, { "code": null, "e": 3834, "s": 3511, "text": "from ftplib import FTP\ndef main():\n ftp = FTP('ftp.ibiblio.org')\n ftp.login()\n ftp.cwd('pub/academic/biology/') # change to some other subject\n entries = ftp.nlst()\n ftp.quit()\n\n print(len(entries), \"entries:\")\n for entry in sorted(entries):\n print(entry)\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 3895, "s": 3834, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3970, "s": 3895, "text": "(6, 'entries:')\nINDEX\nREADME\nacedb\ndna-mutations\necology+evolution\nmolbio\n" }, { "code": null, "e": 4007, "s": 3970, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4023, "s": 4007, "text": " Malhar Lathkar" }, { "code": null, "e": 4056, "s": 4023, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4075, "s": 4056, "text": " Arnab Chakraborty" }, { "code": null, "e": 4110, "s": 4075, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4132, "s": 4110, "text": " In28Minutes Official" }, { "code": null, "e": 4166, "s": 4132, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4194, "s": 4166, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4229, "s": 4194, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4243, "s": 4229, "text": " Lets Kode It" }, { "code": null, "e": 4276, "s": 4243, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4293, "s": 4276, "text": " Abhilash Nelson" }, { "code": null, "e": 4300, "s": 4293, "text": " Print" }, { "code": null, "e": 4311, "s": 4300, "text": " Add Notes" } ]
Reader read(char[]) method in Java with Examples - GeeksforGeeks
07 Feb, 2019 The read(char[]) method of Reader Class in Java is used to read the specified characters into an array. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public int read(char[] charArray) Parameters: This method accepts a mandatory parameter charArray which is the character array to be written in the Stream. Return Value: This method returns an integer value which is the number of characters read from the stream. It returns -1 if no character has been read. Exception: This method throws IOException if some error occurs while input-output. Below methods illustrates the working of read(char[]) method: Program 1: // Java program to demonstrate// Reader read(char[]) method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character array // to be read from the stream char[] charArray = new char[5]; // Read the charArray // to this reader using read() method // This will put the str in the stream // till it is read by the reader reader.read(charArray); // Print the read charArray System.out.println( Arrays .toString(charArray)); reader.close(); } catch (Exception e) { System.out.println(e); } }} [G, e, e, k, s] Program 2: // Java program to demonstrate// Reader read(char[]) method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character array // to be read from the stream char[] charArray = new char[str.length()]; // Read the charArray // to this reader using read() method // This will put the str in the stream // till it is read by the reader reader.read(charArray); // Print the read charArray System.out.println( Arrays .toString(charArray)); reader.close(); } catch (Exception e) { System.out.println(e); } }} [G, e, e, k, s, F, o, r, G, e, e, k, s] Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read– Java-Functions Java-IO package Java-Reader 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 Stream In Java HashMap in Java with Examples Interfaces 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 Multithreading in Java
[ { "code": null, "e": 25831, "s": 25803, "text": "\n07 Feb, 2019" }, { "code": null, "e": 25971, "s": 25831, "text": "The read(char[]) method of Reader Class in Java is used to read the specified characters into an array. This method blocks the stream till:" }, { "code": null, "e": 26012, "s": 25971, "text": "It has taken some input from the stream." }, { "code": null, "e": 26042, "s": 26012, "text": "Some IOException has occurred" }, { "code": null, "e": 26094, "s": 26042, "text": "It has reached the end of the stream while reading." }, { "code": null, "e": 26102, "s": 26094, "text": "Syntax:" }, { "code": null, "e": 26136, "s": 26102, "text": "public int read(char[] charArray)" }, { "code": null, "e": 26258, "s": 26136, "text": "Parameters: This method accepts a mandatory parameter charArray which is the character array to be written in the Stream." }, { "code": null, "e": 26410, "s": 26258, "text": "Return Value: This method returns an integer value which is the number of characters read from the stream. It returns -1 if no character has been read." }, { "code": null, "e": 26493, "s": 26410, "text": "Exception: This method throws IOException if some error occurs while input-output." }, { "code": null, "e": 26555, "s": 26493, "text": "Below methods illustrates the working of read(char[]) method:" }, { "code": null, "e": 26566, "s": 26555, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Reader read(char[]) method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character array // to be read from the stream char[] charArray = new char[5]; // Read the charArray // to this reader using read() method // This will put the str in the stream // till it is read by the reader reader.read(charArray); // Print the read charArray System.out.println( Arrays .toString(charArray)); reader.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 27477, "s": 26566, "text": null }, { "code": null, "e": 27494, "s": 27477, "text": "[G, e, e, k, s]\n" }, { "code": null, "e": 27505, "s": 27494, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Reader read(char[]) method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character array // to be read from the stream char[] charArray = new char[str.length()]; // Read the charArray // to this reader using read() method // This will put the str in the stream // till it is read by the reader reader.read(charArray); // Print the read charArray System.out.println( Arrays .toString(charArray)); reader.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 28442, "s": 27505, "text": null }, { "code": null, "e": 28483, "s": 28442, "text": "[G, e, e, k, s, F, o, r, G, e, e, k, s]\n" }, { "code": null, "e": 28562, "s": 28483, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read–" }, { "code": null, "e": 28577, "s": 28562, "text": "Java-Functions" }, { "code": null, "e": 28593, "s": 28577, "text": "Java-IO package" }, { "code": null, "e": 28605, "s": 28593, "text": "Java-Reader" }, { "code": null, "e": 28610, "s": 28605, "text": "Java" }, { "code": null, "e": 28615, "s": 28610, "text": "Java" }, { "code": null, "e": 28713, "s": 28615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28764, "s": 28713, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28779, "s": 28764, "text": "Stream In Java" }, { "code": null, "e": 28809, "s": 28779, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28828, "s": 28809, "text": "Interfaces in Java" }, { "code": null, "e": 28859, "s": 28828, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28877, "s": 28859, "text": "ArrayList in Java" }, { "code": null, "e": 28909, "s": 28877, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28929, "s": 28909, "text": "Stack Class in Java" }, { "code": null, "e": 28953, "s": 28929, "text": "Singleton Class in Java" } ]
C# | How to get the HashCode for the string - GeeksforGeeks
01 Aug, 2019 GetHashCode() method is used to get the hash code of the specified string. When you apply this method to the string this method will return a 32-bit signed integer hash code of the given string. Syntax: public override int GetHashCode (); Return Value: The return type of this method is System.Int32. This method return a 32-bit signed integer hash code. Below given are some examples to understand the implementation in a better way: Example 1: // C# program to illustrate // the GetHashCode() methodusing System; public class GFG { // main method static public void Main() { int s1, s2, s3; // strings string a1 = "abc"; string a2 = "geeks"; string a3 = "gfg"; // Get hash code of the given string by // using GetHashCode() method s1 = a1.GetHashCode(); s2 = a2.GetHashCode(); s3 = a3.GetHashCode(); // display strings and their hash code Console.WriteLine("Display strings"); Console.WriteLine("string 1: {0} and hashcode: {1}", a1, s1); Console.WriteLine("string 2: {0} and hashcode: {1}", a2, s2); Console.WriteLine("string 3: {0} and hashcode: {1}", a3, s3); }} Display strings string 1: abc and hashcode: 1099313834 string 2: geeks and hashcode: -1893508949 string 3: gfg and hashcode: -870054572 Example 2: // C# program to illustrate// the GetHashCode() methodusing System; class GFG { // main method static public void Main() { // calling Hashcode method Hashcode("Hello"); Hashcode("GFG"); Hashcode("Geeks"); Hashcode("Geeksforgeeks"); Hashcode("C#"); Hashcode("Tutorial"); } // Hashcode method public static void Hashcode(String value) { int result; // get hash code of the entered strings result = value.GetHashCode(); Console.WriteLine("String : {0} and HashCode: {1}", value, result); }} String : Hello and HashCode: -327378614 String : GFG and HashCode: 1999992308 String : Geeks and HashCode: -1893476149 String : Geeksforgeeks and HashCode: -2133923457 String : C# and HashCode: -1917577788 String : Tutorial and HashCode: 1463624248 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=netframework-4.7.2#definition mayank5326 CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Constructors
[ { "code": null, "e": 26020, "s": 25992, "text": "\n01 Aug, 2019" }, { "code": null, "e": 26215, "s": 26020, "text": "GetHashCode() method is used to get the hash code of the specified string. When you apply this method to the string this method will return a 32-bit signed integer hash code of the given string." }, { "code": null, "e": 26223, "s": 26215, "text": "Syntax:" }, { "code": null, "e": 26259, "s": 26223, "text": "public override int GetHashCode ();" }, { "code": null, "e": 26375, "s": 26259, "text": "Return Value: The return type of this method is System.Int32. This method return a 32-bit signed integer hash code." }, { "code": null, "e": 26455, "s": 26375, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 26466, "s": 26455, "text": "Example 1:" }, { "code": "// C# program to illustrate // the GetHashCode() methodusing System; public class GFG { // main method static public void Main() { int s1, s2, s3; // strings string a1 = \"abc\"; string a2 = \"geeks\"; string a3 = \"gfg\"; // Get hash code of the given string by // using GetHashCode() method s1 = a1.GetHashCode(); s2 = a2.GetHashCode(); s3 = a3.GetHashCode(); // display strings and their hash code Console.WriteLine(\"Display strings\"); Console.WriteLine(\"string 1: {0} and hashcode: {1}\", a1, s1); Console.WriteLine(\"string 2: {0} and hashcode: {1}\", a2, s2); Console.WriteLine(\"string 3: {0} and hashcode: {1}\", a3, s3); }}", "e": 27226, "s": 26466, "text": null }, { "code": null, "e": 27363, "s": 27226, "text": "Display strings\nstring 1: abc and hashcode: 1099313834\nstring 2: geeks and hashcode: -1893508949\nstring 3: gfg and hashcode: -870054572\n" }, { "code": null, "e": 27374, "s": 27363, "text": "Example 2:" }, { "code": "// C# program to illustrate// the GetHashCode() methodusing System; class GFG { // main method static public void Main() { // calling Hashcode method Hashcode(\"Hello\"); Hashcode(\"GFG\"); Hashcode(\"Geeks\"); Hashcode(\"Geeksforgeeks\"); Hashcode(\"C#\"); Hashcode(\"Tutorial\"); } // Hashcode method public static void Hashcode(String value) { int result; // get hash code of the entered strings result = value.GetHashCode(); Console.WriteLine(\"String : {0} and HashCode: {1}\", value, result); }}", "e": 27976, "s": 27374, "text": null }, { "code": null, "e": 28226, "s": 27976, "text": "String : Hello and HashCode: -327378614\nString : GFG and HashCode: 1999992308\nString : Geeks and HashCode: -1893476149\nString : Geeksforgeeks and HashCode: -2133923457\nString : C# and HashCode: -1917577788\nString : Tutorial and HashCode: 1463624248\n" }, { "code": null, "e": 28237, "s": 28226, "text": "Reference:" }, { "code": null, "e": 28342, "s": 28237, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=netframework-4.7.2#definition" }, { "code": null, "e": 28353, "s": 28342, "text": "mayank5326" }, { "code": null, "e": 28367, "s": 28353, "text": "CSharp-method" }, { "code": null, "e": 28381, "s": 28367, "text": "CSharp-string" }, { "code": null, "e": 28384, "s": 28381, "text": "C#" }, { "code": null, "e": 28482, "s": 28384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28510, "s": 28482, "text": "C# Dictionary with examples" }, { "code": null, "e": 28525, "s": 28510, "text": "C# | Delegates" }, { "code": null, "e": 28548, "s": 28525, "text": "C# | Method Overriding" }, { "code": null, "e": 28570, "s": 28548, "text": "C# | Abstract Classes" }, { "code": null, "e": 28616, "s": 28570, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28639, "s": 28616, "text": "Extension Method in C#" }, { "code": null, "e": 28661, "s": 28639, "text": "C# | Class and Object" }, { "code": null, "e": 28683, "s": 28661, "text": "C# | Replace() Method" }, { "code": null, "e": 28723, "s": 28683, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
How to activate virtualenv on Linux?
When we talk about keeping our dependencies in a separate location from our logic code we are indeed creating nothing but a virtual environment, which in python, we usually use the term venv to refer to as. So a venv is nothing but a virtual environment which is in turn a tool that allows us to keep our dependencies that are required by the project to be kept in a separate folder. These separate folders that we create are known as the python virtual environments. Python venv is one of the most widely used tools. Now we know what virtualenv is and what it is used for, let’s see how we can create one in python on linux and what characteristics and features does it offer. In simpler terms, the venv tool is nothing but a module in python and it is used to provide support in creating “virtual environments” that are both leightweights and contain their own site directories. These virtual environments are isolated from the system's site directories. It should also be good to note that these virtual environments have their own python binaries and can also have their own set of python packages that came already installed in their site directories. Creating a virtual environment can be done using the command shown below − python3 -m venv /path_to_new_virtual_environment Now let’s run the above command on a Unix environment, I am using Mac OS and the command will look something like this − python3 -m venv /Users/immukul/linux-questions-code After running the command, you won’t get any message, instead the terminal will be back where it started from and now you just need to locate the directory in which you create a virtual environment and inside that directory you must have files that are similar or same to the output shown below − immukul@192 linux-questions-code % ls -ltr total 16 -rw-r--r-- 1 immukul staff 28 Jul 4 13:33 textfile.txt drwxr-xr-x 2 immukul staff 64 Jul 5 20:52 include drwxr-xr-x 3 immukul staff 96 Jul 5 20:52 lib -rw-r--r-- 1 immukul staff 90 Jul 5 20:52 pyvenv.cfg drwxr-xr-x 12 immukul staff 384 Jul 5 20:52 bin That is how to create a virtualenv in Linux. There are certain arguments that the venv module allows us to use and run and these mainly can be obtained by writing the following command to the terminal − python3 -m venv This command will output all the positional arguments along with the optional arguments that you can use in the venv module. usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] ENV_DIR [ENV_DIR ...] venv: error: the following arguments are required: ENV_DIR immukul@192 ~ % python3 -m venv -h usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] ENV_DIR [ENV_DIR ...] Creates virtual Python environments in one or more target directories. Positional arguments: ENV_DIR A directory to create the environment in. Optional arguments: -h, --help Show this help message and exit --system-site-packages Give the virtual environment access to the system site-packages dir. --symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform. --copies Try to use copies rather than symlinks, even when symlinks are the default for the platform. --clear Delete the contents of the environment directory if it already exists, before environment creation. --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place. --without-pip Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default) --prompt PROMPT Provides an alternative prompt prefix for this environment. upgrade-deps Upgrade core dependencies: pip setup tools to the latest version in PyPI
[ { "code": null, "e": 1269, "s": 1062, "text": "When we talk about keeping our dependencies in a separate location from our logic code we are indeed creating nothing but a virtual environment, which in python, we usually use the term venv to refer to as." }, { "code": null, "e": 1530, "s": 1269, "text": "So a venv is nothing but a virtual environment which is in turn a tool that allows us to keep our dependencies that are required by the project to be kept in a separate folder. These separate folders that we create are known as the python virtual environments." }, { "code": null, "e": 1580, "s": 1530, "text": "Python venv is one of the most widely used tools." }, { "code": null, "e": 1740, "s": 1580, "text": "Now we know what virtualenv is and what it is used for, let’s see how we can create one in python on linux and what characteristics and features does it offer." }, { "code": null, "e": 2219, "s": 1740, "text": "In simpler terms, the venv tool is nothing but a module in python and it is used to provide support in creating “virtual environments” that are both leightweights and contain their own site directories. These virtual environments are isolated from the system's site directories. It should also be good to note that these virtual\nenvironments have their own python binaries and can also have their own set of python packages that came already installed in their site directories." }, { "code": null, "e": 2294, "s": 2219, "text": "Creating a virtual environment can be done using the command shown below −" }, { "code": null, "e": 2343, "s": 2294, "text": "python3 -m venv /path_to_new_virtual_environment" }, { "code": null, "e": 2464, "s": 2343, "text": "Now let’s run the above command on a Unix environment, I am using Mac OS and the command will look something like this −" }, { "code": null, "e": 2516, "s": 2464, "text": "python3 -m venv /Users/immukul/linux-questions-code" }, { "code": null, "e": 2813, "s": 2516, "text": "After running the command, you won’t get any message, instead the terminal will be back where it started from and now you just need to locate the directory in which you create a virtual environment and inside that directory you must have files that are similar or same to the output shown below −" }, { "code": null, "e": 3117, "s": 2813, "text": "immukul@192 linux-questions-code % ls -ltr\ntotal 16\n-rw-r--r-- 1 immukul staff 28 Jul 4 13:33 textfile.txt\ndrwxr-xr-x 2 immukul staff 64 Jul 5 20:52 include\ndrwxr-xr-x 3 immukul staff 96 Jul 5 20:52 lib\n-rw-r--r-- 1 immukul staff 90 Jul 5 20:52 pyvenv.cfg\ndrwxr-xr-x 12 immukul staff 384 Jul 5 20:52 bin" }, { "code": null, "e": 3320, "s": 3117, "text": "That is how to create a virtualenv in Linux. There are certain arguments that the venv module allows us to use and run and these mainly can be obtained by writing the following command to the terminal −" }, { "code": null, "e": 3336, "s": 3320, "text": "python3 -m venv" }, { "code": null, "e": 3461, "s": 3336, "text": "This command will output all the positional arguments along with the optional arguments that you can use in the venv module." }, { "code": null, "e": 4920, "s": 3461, "text": "usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]\n [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]\n ENV_DIR [ENV_DIR ...]\nvenv: error: the following arguments are required: ENV_DIR\n\nimmukul@192 ~ % python3 -m venv -h\n\nusage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]\n [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]\n ENV_DIR [ENV_DIR ...]\n\nCreates virtual Python environments in one or more target directories.\n\nPositional arguments:\n ENV_DIR A directory to create the environment in.\nOptional arguments:\n -h, --help Show this help message and exit\n --system-site-packages\n Give the virtual environment access to the system site-packages dir.\n--symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform.\n--copies Try to use copies rather than symlinks, even when symlinks are the default for the platform.\n--clear Delete the contents of the environment directory if it already exists, before environment creation.\n--upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.\n--without-pip Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default)\n--prompt PROMPT Provides an alternative prompt prefix for this environment. upgrade-deps Upgrade core dependencies: pip setup tools to the latest version in PyPI" } ]
Lodash _.reject() Method - GeeksforGeeks
10 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.reject() method is opposite of _.filter() method and this method returns elements of the collection that predicate does not return true. Syntax: _.reject(collection, predicate) Parameters: This method accepts two parameters as mentioned above and described below: collection: This parameter holds the collection to iterate over. iteratee: This parameter holds the function invoked per iteration. Return Value: This method is used to return the new filtered array. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. javascript // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'user': 'Rohit', 'age': 25, 'active': false }, { 'user': 'Mohit', 'age': 26, 'active': true } ]; // Use of _.reject() method let gfg = _.reject(users, function(o) { return !o.active; }); // Printing the output console.log(gfg); Output: [ { user: 'Mohit', age: 26, active: true } ] Example 2: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.matches` iteratee shorthandlet gfg = _.reject(users, { 'salary': 55000, 'active': true }); // Printing the output console.log(gfg); Output: [ { employee: Rohit, salary: 50000, active: false } ] Example 3: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.matchesProperty` iteratee shorthandlet gfg = _.reject(users, ['active', false]); // Printing the output console.log(gfg); Output: [ { employee: Mohit, salary: 55000, active: true } ] Example 4: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.property` iteratee shorthandlet gfg = _.reject(users, 'active'); // Printing the output console.log(gfg); Output: [ { employee: Rohit, salary: 50000, active: false } ] Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26655, "s": 26627, "text": "\n10 Sep, 2020" }, { "code": null, "e": 26948, "s": 26655, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.reject() method is opposite of _.filter() method and this method returns elements of the collection that predicate does not return true." }, { "code": null, "e": 26956, "s": 26948, "text": "Syntax:" }, { "code": null, "e": 26988, "s": 26956, "text": "_.reject(collection, predicate)" }, { "code": null, "e": 27075, "s": 26988, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 27140, "s": 27075, "text": "collection: This parameter holds the collection to iterate over." }, { "code": null, "e": 27207, "s": 27140, "text": "iteratee: This parameter holds the function invoked per iteration." }, { "code": null, "e": 27275, "s": 27207, "text": "Return Value: This method is used to return the new filtered array." }, { "code": null, "e": 27370, "s": 27275, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 27381, "s": 27370, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'user': 'Rohit', 'age': 25, 'active': false }, { 'user': 'Mohit', 'age': 26, 'active': true } ]; // Use of _.reject() method let gfg = _.reject(users, function(o) { return !o.active; }); // Printing the output console.log(gfg);", "e": 27726, "s": 27381, "text": null }, { "code": null, "e": 27734, "s": 27726, "text": "Output:" }, { "code": null, "e": 27780, "s": 27734, "text": "[ { user: 'Mohit', age: 26, active: true } ]\n" }, { "code": null, "e": 27791, "s": 27780, "text": "Example 2:" }, { "code": null, "e": 27802, "s": 27791, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.matches` iteratee shorthandlet gfg = _.reject(users, { 'salary': 55000, 'active': true }); // Printing the output console.log(gfg);", "e": 28219, "s": 27802, "text": null }, { "code": null, "e": 28227, "s": 28219, "text": "Output:" }, { "code": null, "e": 28282, "s": 28227, "text": "[ { employee: Rohit, salary: 50000, active: false } ]\n" }, { "code": null, "e": 28293, "s": 28282, "text": "Example 3:" }, { "code": null, "e": 28304, "s": 28293, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.matchesProperty` iteratee shorthandlet gfg = _.reject(users, ['active', false]); // Printing the output console.log(gfg);", "e": 28707, "s": 28304, "text": null }, { "code": null, "e": 28715, "s": 28707, "text": "Output:" }, { "code": null, "e": 28769, "s": 28715, "text": "[ { employee: Mohit, salary: 55000, active: true } ]\n" }, { "code": null, "e": 28780, "s": 28769, "text": "Example 4:" }, { "code": null, "e": 28791, "s": 28780, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'employee': 'Rohit', 'salary': 50000, 'active': false }, { 'employee': 'Mohit', 'salary': 55000, 'active': true } ]; // Use of _.reject() method// The `_.property` iteratee shorthandlet gfg = _.reject(users, 'active'); // Printing the output console.log(gfg);", "e": 29178, "s": 28791, "text": null }, { "code": null, "e": 29186, "s": 29178, "text": "Output:" }, { "code": null, "e": 29241, "s": 29186, "text": "[ { employee: Rohit, salary: 50000, active: false } ]\n" }, { "code": null, "e": 29348, "s": 29241, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 29366, "s": 29348, "text": "JavaScript-Lodash" }, { "code": null, "e": 29377, "s": 29366, "text": "JavaScript" }, { "code": null, "e": 29394, "s": 29377, "text": "Web Technologies" }, { "code": null, "e": 29492, "s": 29394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29532, "s": 29492, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29593, "s": 29532, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29634, "s": 29593, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29656, "s": 29634, "text": "JavaScript | Promises" }, { "code": null, "e": 29704, "s": 29656, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29744, "s": 29704, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29777, "s": 29744, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29820, "s": 29777, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29870, "s": 29820, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Check if a number is divisible by 23 or not - GeeksforGeeks
17 May, 2021 Given a number, the task is to quickly check if the number is divisible by 23 or not.Examples: Input : x = 46 Output : Yes Input : 47 Output : No A solution to the problem is to extract the last digit and add 7 times of last digit to remaining number and repeat this process until a two digit number is obtained. If the obtained two digit number is divisible by 23, then the given number is divisible by 23.Approach: Extract the last digit of the number/truncated number every time Add 7*(last digit of the previous number) to the truncated number Repeat the above three steps as long as necessary. Illustration: 17043-->1704+7*3 = 1725-->172+7*5 = 207 which is 9*23, so 17043 is also divisible by 23. Mathematical Proof : Let be any number such that =100a+10b+c . Now assume that is divisible by 23. Then 0 (mod 23) 100a+10b+c0 (mod 23) 10(10a+b)+c0 (mod 23) 10+c0 (mod 23)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of 1. In other words, we have to find an integer such that n such that 10n1 mod 23. It can be observed that the smallest n which satisfies this property is 7 as 701 mod 23. Now we can multiply the original equation 10+c0 (mod 23) by 7 and simplify it: 70+7c0 (mod 23) +7c0 (mod 23) We have found out that if 0 (mod 23) then, +7c0 (mod 23). In other words, to check if a 3-digit number is divisible by 23, we can just remove the last digit, multiply it by 7, and then subtract it from the rest of the two digits. C++ Java Python 3 C# PHP Javascript // CPP program to validate above logic#include <iostream>using namespace std; // Function to check if the number is// divisible by 23 or notbool isDivisible(long long int n){ // While there are at least 3 digits while (n / 100) { int d = n % 10; // Extracting the last digit n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} int main(){ long long int n = 1191216; if (isDivisible(n)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java program to validate above logicclass GFG{ // Function to check if the// number is divisible by// 23 or notstatic boolean isDivisible(long n){ // While there are at // least 3 digits while (n / 100 != 0) { // Extracting the last digit long d = n % 10; n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codepublic static void main(String[] args){ long n = 1191216; if(isDivisible(n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by mits # Python 3 program to validate above logic # Function to check if the number is# divisible by 23 or notdef isDivisible(n) : # While there are at least 3 digits while n // 100 : # Extracting the last d = n % 10 # Truncating the number n //= 10 # Adding seven times the last # digit to the remaining number n += d * 7 return (n % 23 == 0) # Driver Codeif __name__ == "__main__" : n = 1191216 # function calling if (isDivisible(n)) : print("Yes") else : print("No") # This code is contributed by ANKITRAI1 // C# program to validate// above logicclass GFG{ // Function to check if the// number is divisible by// 23 or notstatic bool isDivisible(long n){ // While there are at // least 3 digits while (n / 100 != 0) { // Extracting the last digit long d = n % 10; n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codepublic static void Main(){ long n = 1191216; if(isDivisible(n)) System.Console.WriteLine("Yes"); else System.Console.WriteLine("No");}} // This code is contributed by mits <?php// PHP program to validate above logic // Function to check if the number// is divisible by 23 or notfunction isDivisible($n){ // While there are at // least 3 digits while (intval($n / 100)) { $n = intval($n); $d = $n % 10; // Extracting the last digit $n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number $n += $d * 7; } return ($n % 23 == 0);} $n = 1191216;if (isDivisible($n))echo "Yes" . "\n";elseecho "No" . "\n"; // This code is contributed// by ChitraNayal?> <script> // JavaScript program to validate above logic // Function to check if the// number is divisible by// 23 or notfunction isDivisible(n){ // While there are at // least 3 digits while (Math.floor(n / 100) != 0) { // Extracting the last digit let d = n % 10; n = Math.floor(n/10); // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codelet n = 1191216;if(isDivisible(n)) document.write("Yes");else document.write("No"); // This code is contributed by rag2127 </script> Yes Note that the above program may not make a lot of sense as could simply do n % 23 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. Mithun Kumar ankthon ukasp rag2127 divisibility Number Divisibility Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Merge two sorted arrays with O(1) extra space Singular Value Decomposition (SVD) Program to multiply two matrices
[ { "code": null, "e": 26047, "s": 26019, "text": "\n17 May, 2021" }, { "code": null, "e": 26144, "s": 26047, "text": "Given a number, the task is to quickly check if the number is divisible by 23 or not.Examples: " }, { "code": null, "e": 26197, "s": 26144, "text": "Input : x = 46\nOutput : Yes\n\nInput : 47\nOutput : No" }, { "code": null, "e": 26471, "s": 26199, "text": "A solution to the problem is to extract the last digit and add 7 times of last digit to remaining number and repeat this process until a two digit number is obtained. If the obtained two digit number is divisible by 23, then the given number is divisible by 23.Approach: " }, { "code": null, "e": 26536, "s": 26471, "text": "Extract the last digit of the number/truncated number every time" }, { "code": null, "e": 26602, "s": 26536, "text": "Add 7*(last digit of the previous number) to the truncated number" }, { "code": null, "e": 26653, "s": 26602, "text": "Repeat the above three steps as long as necessary." }, { "code": null, "e": 26669, "s": 26653, "text": "Illustration: " }, { "code": null, "e": 26762, "s": 26669, "text": " \n17043-->1704+7*3 \n= 1725-->172+7*5\n= 207 which is 9*23, \nso 17043 is also divisible by 23." }, { "code": null, "e": 27563, "s": 26764, "text": "Mathematical Proof : Let be any number such that =100a+10b+c . Now assume that is divisible by 23. Then 0 (mod 23) 100a+10b+c0 (mod 23) 10(10a+b)+c0 (mod 23) 10+c0 (mod 23)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of 1. In other words, we have to find an integer such that n such that 10n1 mod 23. It can be observed that the smallest n which satisfies this property is 7 as 701 mod 23. Now we can multiply the original equation 10+c0 (mod 23) by 7 and simplify it: 70+7c0 (mod 23) +7c0 (mod 23) We have found out that if 0 (mod 23) then, +7c0 (mod 23). In other words, to check if a 3-digit number is divisible by 23, we can just remove the last digit, multiply it by 7, and then subtract it from the rest of the two digits. " }, { "code": null, "e": 27569, "s": 27565, "text": "C++" }, { "code": null, "e": 27574, "s": 27569, "text": "Java" }, { "code": null, "e": 27583, "s": 27574, "text": "Python 3" }, { "code": null, "e": 27586, "s": 27583, "text": "C#" }, { "code": null, "e": 27590, "s": 27586, "text": "PHP" }, { "code": null, "e": 27601, "s": 27590, "text": "Javascript" }, { "code": "// CPP program to validate above logic#include <iostream>using namespace std; // Function to check if the number is// divisible by 23 or notbool isDivisible(long long int n){ // While there are at least 3 digits while (n / 100) { int d = n % 10; // Extracting the last digit n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} int main(){ long long int n = 1191216; if (isDivisible(n)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 28210, "s": 27601, "text": null }, { "code": "// Java program to validate above logicclass GFG{ // Function to check if the// number is divisible by// 23 or notstatic boolean isDivisible(long n){ // While there are at // least 3 digits while (n / 100 != 0) { // Extracting the last digit long d = n % 10; n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codepublic static void main(String[] args){ long n = 1191216; if(isDivisible(n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by mits", "e": 28890, "s": 28210, "text": null }, { "code": "# Python 3 program to validate above logic # Function to check if the number is# divisible by 23 or notdef isDivisible(n) : # While there are at least 3 digits while n // 100 : # Extracting the last d = n % 10 # Truncating the number n //= 10 # Adding seven times the last # digit to the remaining number n += d * 7 return (n % 23 == 0) # Driver Codeif __name__ == \"__main__\" : n = 1191216 # function calling if (isDivisible(n)) : print(\"Yes\") else : print(\"No\") # This code is contributed by ANKITRAI1", "e": 29486, "s": 28890, "text": null }, { "code": "// C# program to validate// above logicclass GFG{ // Function to check if the// number is divisible by// 23 or notstatic bool isDivisible(long n){ // While there are at // least 3 digits while (n / 100 != 0) { // Extracting the last digit long d = n % 10; n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codepublic static void Main(){ long n = 1191216; if(isDivisible(n)) System.Console.WriteLine(\"Yes\"); else System.Console.WriteLine(\"No\");}} // This code is contributed by mits", "e": 30162, "s": 29486, "text": null }, { "code": "<?php// PHP program to validate above logic // Function to check if the number// is divisible by 23 or notfunction isDivisible($n){ // While there are at // least 3 digits while (intval($n / 100)) { $n = intval($n); $d = $n % 10; // Extracting the last digit $n /= 10; // Truncating the number // Adding seven times the last // digit to the remaining number $n += $d * 7; } return ($n % 23 == 0);} $n = 1191216;if (isDivisible($n))echo \"Yes\" . \"\\n\";elseecho \"No\" . \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 30743, "s": 30162, "text": null }, { "code": "<script> // JavaScript program to validate above logic // Function to check if the// number is divisible by// 23 or notfunction isDivisible(n){ // While there are at // least 3 digits while (Math.floor(n / 100) != 0) { // Extracting the last digit let d = n % 10; n = Math.floor(n/10); // Truncating the number // Adding seven times the last // digit to the remaining number n += d * 7; } return (n % 23 == 0);} // Driver Codelet n = 1191216;if(isDivisible(n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by rag2127 </script>", "e": 31390, "s": 30743, "text": null }, { "code": null, "e": 31394, "s": 31390, "text": "Yes" }, { "code": null, "e": 31647, "s": 31396, "text": "Note that the above program may not make a lot of sense as could simply do n % 23 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. " }, { "code": null, "e": 31660, "s": 31647, "text": "Mithun Kumar" }, { "code": null, "e": 31668, "s": 31660, "text": "ankthon" }, { "code": null, "e": 31674, "s": 31668, "text": "ukasp" }, { "code": null, "e": 31682, "s": 31674, "text": "rag2127" }, { "code": null, "e": 31695, "s": 31682, "text": "divisibility" }, { "code": null, "e": 31715, "s": 31695, "text": "Number Divisibility" }, { "code": null, "e": 31728, "s": 31715, "text": "Mathematical" }, { "code": null, "e": 31741, "s": 31728, "text": "Mathematical" }, { "code": null, "e": 31839, "s": 31741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31883, "s": 31839, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31914, "s": 31883, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31939, "s": 31914, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31971, "s": 31939, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32013, "s": 31971, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 32057, "s": 32013, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 32121, "s": 32057, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 32167, "s": 32121, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 32202, "s": 32167, "text": "Singular Value Decomposition (SVD)" } ]
How to Build a Simple Android App with Flask Backend? - GeeksforGeeks
27 Oct, 2021 Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. The following article will demonstrate how to use Flask for the backend while developing an Android Application. Step1: Installing Flask Open the terminal and enter the following command to install the flask pip install flask Step 2: Add OkHttp Dependencies to the build.gradle file OkHttp is a library developed by Square for sending and receiving HTTP-based network requests. For making HTTP requests in the Android Application we make use of OkHttp. This library is used to make both Synchronous and Asynchronous calls. If a network call is synchronous, the code will wait till we get a response from the server we are trying to communicate with. This may give rise to latency or performance lag. If a network call is asynchronous, the execution won’t wait till the server responds, the application will be running, and if the server responds a callback will be executed. Android Dependencies Add the following dependencies to the build.gradle file in Android Studio implementation("com.squareup.okhttp3:okhttp:4.9.0") Step 3: Working with the AndroidManifest.XML file Add the following line above <application> tag <uses-permission android:name="android.permission.INTERNET"/> Add the following line inside the <application> tag android:usesCleartextTraffic="true"> Step 4: Python Script @app.route(“/”) is associated with showHomePage() function. Suppose the server is running on a system with IP address 192.168.0.113 and port number 5000. Now, if the URL “http://192.168.0.113:5000/” is entered into a browser, showHomePage function will be executed and it will return a response “This is home page”. app.run() will host the server on localhost, whereas, app.run(host=”0.0.0.0′′) will host the server on machine’s IP address By default port 5000 will be used, we can change it using ‘port’ parameter in app.run() Python from flask import Flask # Flask Constructorapp = Flask(__name__) # decorator to associate# a function with the url@app.route("/")def showHomePage(): # response from the server return "This is home page" if __name__ == "__main__": app.run(host="0.0.0.0") Running The Python Script run the python script and the server will be hosted. Step 5: Working with the activity_main.xml file Create a ConstraintLayout. Add a TextView with ID ‘pagename’ to the Constraint Layout for displaying responses from the server So, add the following code to the activity_main.xml file in android studio. 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" android:background="@color/white" tools:context=".MainActivity"> <TextView android:id="@+id/pagename" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_marginEnd="12dp" android:textAlignment="center" android:textColor="@color/black" android:textSize="16sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Firstly, we need an OkHttp Client to make a request OkHttpClient okhttpclient = new OkHttpClient(); Next, create a request with the URL of the server. In our case, it is “http://192.168.0.113:5000/”. Notice ‘/’ at the end of URL, we are sending a request for the homepage. Request request = new Request.Builder().url("http://192.168.0.113:5000/").build(); Now, make a call with the above-made request. The complete code is given below. onFailure() will be called if the server is down or unreachable, so we display a text in TextView saying ‘server down’. onResponse() will be called if the request is made successfully. We can access the response with the Response parameter we receive in onResponse() // to access the response we get from the server response.body().string; Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response; public class MainActivity extends AppCompatActivity { // declare attribute for textview private TextView pagenameTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pagenameTextView = findViewById(R.id.pagename); // creating a client OkHttpClient okHttpClient = new OkHttpClient(); // building a request Request request = new Request.Builder().url("http://192.168.0.113:5000/").build(); // making call asynchronously okHttpClient.newCall(request).enqueue(new Callback() { @Override // called if server is unreachable public void onFailure(@NotNull Call call, @NotNull IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "server down", Toast.LENGTH_SHORT).show(); pagenameTextView.setText("error connecting to the server"); } }); } @Override // called if we get a // response from the server public void onResponse( @NotNull Call call, @NotNull Response response) throws IOException {pagenameTextView.setText(response.body().string()); } }); }} Note: Make sure the Android Application runs on a device that is connected to the same network as the system which hosted the server. (if the flask server is running on a machine that is connected to ‘ABC’ WIFI, we need to connect our android device to the same ‘ABC’ network) If the Application is failing to connect to the server, make sure your firewall allows connections on port 5000. If not, create an inbound rule in firewall advanced settings. Output: Android App running Step 7: Checking Requests Made in Python Editor If a request is made, we can see the IP address of the device making the request, the time at which the request was made, and the request type(in our case the request type is GET). We can use okhttp client to send data over the server. Add the following line to the import statements from flask import request We need to set the method of a route as POST. Let’s add a method and associate a route to it. The method prints the text we entered in the android application to the console in pycharm. Add the following lines after the showHomePage() method. @app.route("/debug", methods=["POST"]) def debug(): text = request.form["sample"] print(text) return "received" The complete script is given below Python from flask import Flask # import requestfrom flask import requestapp = Flask(__name__) @app.route("/")def showHomePage(): return "This is home page" @app.route("/debug", methods=["POST"])def debug(): text = request.form["sample"] print(text) return "received" if __name__ == "__main__": app.run(host="0.0.0.0") Create a DummyActivity.java in Android Studio. This activity will be started once we get a response from the server from the showHomePage() method. Add the following lines in onResponse() callback in MainActivity.java. Intent intent = new Intent(MainActivity.this, DummyActivity.class); startActivity(intent); finish(); Step 1: Working with the activity_dummy.xml file Add an EditText with id dummy_text. Add a Button with id dummy_send and with the text “send”. 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" android:background="@color/white" tools:context=".DummyActivity"> <EditText android:id="@+id/dummy_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_marginEnd="12dp" android:backgroundTint="@color/black" android:hint="enter any text" android:textColor="@color/black" android:textColorHint="#80000000" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/dummy_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/dummy_text" app:layout_constraintVertical_bias="0.1" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 2: Working with the DummyActivity.java file We use a form to send the data using the OkHTTP client. We pass this form as a parameter to post() while building our request. Add an onClickListener() to make a POST request. If the data is sent, and we get a response, we display a toast confirming that the data has been received. Below is the code for the DummyActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response; public class DummyActivity extends AppCompatActivity { private EditText editText; private Button button; private OkHttpClient okHttpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dummy); editText = findViewById(R.id.dummy_text); button = findViewById(R.id.dummy_send); okHttpClient = new OkHttpClient(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String dummyText = editText.getText().toString(); // we add the information we want to send in // a form. each string we want to send should // have a name. in our case we sent the // dummyText with a name 'sample' RequestBody formbody = new FormBody.Builder() .add("sample", dummyText) .build(); // while building request // we give our form // as a parameter to post() Request request = new Request.Builder().url("http://192.168.0.113:5000/debug") .post(formbody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure( @NotNull Call call, @NotNull IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "server down", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { if (response.body().string().equals("received")) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "data received", Toast.LENGTH_SHORT).show(); } }); } } }); } }); }} Output: Checking Flask Console Here we can see the android application made a POST request. we can even see the data we send over the server anikakapoor Android Java Python Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 26516, "s": 26488, "text": "\n27 Oct, 2021" }, { "code": null, "e": 27196, "s": 26516, "text": "Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. The following article will demonstrate how to use Flask for the backend while developing an Android Application. " }, { "code": null, "e": 27220, "s": 27196, "text": "Step1: Installing Flask" }, { "code": null, "e": 27291, "s": 27220, "text": "Open the terminal and enter the following command to install the flask" }, { "code": null, "e": 27309, "s": 27291, "text": "pip install flask" }, { "code": null, "e": 27366, "s": 27309, "text": "Step 2: Add OkHttp Dependencies to the build.gradle file" }, { "code": null, "e": 27958, "s": 27366, "text": "OkHttp is a library developed by Square for sending and receiving HTTP-based network requests. For making HTTP requests in the Android Application we make use of OkHttp. This library is used to make both Synchronous and Asynchronous calls. If a network call is synchronous, the code will wait till we get a response from the server we are trying to communicate with. This may give rise to latency or performance lag. If a network call is asynchronous, the execution won’t wait till the server responds, the application will be running, and if the server responds a callback will be executed." }, { "code": null, "e": 27979, "s": 27958, "text": "Android Dependencies" }, { "code": null, "e": 28053, "s": 27979, "text": "Add the following dependencies to the build.gradle file in Android Studio" }, { "code": null, "e": 28105, "s": 28053, "text": "implementation(\"com.squareup.okhttp3:okhttp:4.9.0\")" }, { "code": null, "e": 28155, "s": 28105, "text": "Step 3: Working with the AndroidManifest.XML file" }, { "code": null, "e": 28202, "s": 28155, "text": "Add the following line above <application> tag" }, { "code": null, "e": 28264, "s": 28202, "text": "<uses-permission android:name=\"android.permission.INTERNET\"/>" }, { "code": null, "e": 28316, "s": 28264, "text": "Add the following line inside the <application> tag" }, { "code": null, "e": 28353, "s": 28316, "text": "android:usesCleartextTraffic=\"true\">" }, { "code": null, "e": 28375, "s": 28353, "text": "Step 4: Python Script" }, { "code": null, "e": 28691, "s": 28375, "text": "@app.route(“/”) is associated with showHomePage() function. Suppose the server is running on a system with IP address 192.168.0.113 and port number 5000. Now, if the URL “http://192.168.0.113:5000/” is entered into a browser, showHomePage function will be executed and it will return a response “This is home page”." }, { "code": null, "e": 28815, "s": 28691, "text": "app.run() will host the server on localhost, whereas, app.run(host=”0.0.0.0′′) will host the server on machine’s IP address" }, { "code": null, "e": 28903, "s": 28815, "text": "By default port 5000 will be used, we can change it using ‘port’ parameter in app.run()" }, { "code": null, "e": 28910, "s": 28903, "text": "Python" }, { "code": "from flask import Flask # Flask Constructorapp = Flask(__name__) # decorator to associate# a function with the url@app.route(\"/\")def showHomePage(): # response from the server return \"This is home page\" if __name__ == \"__main__\": app.run(host=\"0.0.0.0\")", "e": 29173, "s": 28910, "text": null }, { "code": null, "e": 29202, "s": 29176, "text": "Running The Python Script" }, { "code": null, "e": 29257, "s": 29204, "text": "run the python script and the server will be hosted." }, { "code": null, "e": 29309, "s": 29261, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 29338, "s": 29311, "text": "Create a ConstraintLayout." }, { "code": null, "e": 29438, "s": 29338, "text": "Add a TextView with ID ‘pagename’ to the Constraint Layout for displaying responses from the server" }, { "code": null, "e": 29514, "s": 29438, "text": "So, add the following code to the activity_main.xml file in android studio." }, { "code": null, "e": 29520, "s": 29516, "text": "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\" android:background=\"@color/white\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/pagename\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"12dp\" android:layout_marginEnd=\"12dp\" android:textAlignment=\"center\" android:textColor=\"@color/black\" android:textSize=\"16sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 30539, "s": 29520, "text": null }, { "code": null, "e": 30590, "s": 30542, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 30710, "s": 30592, "text": "Go to the MainActivity.java file and refer to the following code. Firstly, we need an OkHttp Client to make a request" }, { "code": null, "e": 30760, "s": 30712, "text": "OkHttpClient okhttpclient = new OkHttpClient();" }, { "code": null, "e": 30935, "s": 30762, "text": "Next, create a request with the URL of the server. In our case, it is “http://192.168.0.113:5000/”. Notice ‘/’ at the end of URL, we are sending a request for the homepage." }, { "code": null, "e": 31020, "s": 30937, "text": "Request request = new Request.Builder().url(\"http://192.168.0.113:5000/\").build();" }, { "code": null, "e": 31369, "s": 31022, "text": "Now, make a call with the above-made request. The complete code is given below. onFailure() will be called if the server is down or unreachable, so we display a text in TextView saying ‘server down’. onResponse() will be called if the request is made successfully. We can access the response with the Response parameter we receive in onResponse()" }, { "code": null, "e": 31445, "s": 31371, "text": "// to access the response we get from the server\nresponse.body().string; " }, { "code": null, "e": 31571, "s": 31447, "text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31578, "s": 31573, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response; public class MainActivity extends AppCompatActivity { // declare attribute for textview private TextView pagenameTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pagenameTextView = findViewById(R.id.pagename); // creating a client OkHttpClient okHttpClient = new OkHttpClient(); // building a request Request request = new Request.Builder().url(\"http://192.168.0.113:5000/\").build(); // making call asynchronously okHttpClient.newCall(request).enqueue(new Callback() { @Override // called if server is unreachable public void onFailure(@NotNull Call call, @NotNull IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, \"server down\", Toast.LENGTH_SHORT).show(); pagenameTextView.setText(\"error connecting to the server\"); } }); } @Override // called if we get a // response from the server public void onResponse( @NotNull Call call, @NotNull Response response) throws IOException {pagenameTextView.setText(response.body().string()); } }); }}", "e": 33387, "s": 31578, "text": null }, { "code": null, "e": 33396, "s": 33390, "text": "Note:" }, { "code": null, "e": 33667, "s": 33396, "text": "Make sure the Android Application runs on a device that is connected to the same network as the system which hosted the server. (if the flask server is running on a machine that is connected to ‘ABC’ WIFI, we need to connect our android device to the same ‘ABC’ network)" }, { "code": null, "e": 33842, "s": 33667, "text": "If the Application is failing to connect to the server, make sure your firewall allows connections on port 5000. If not, create an inbound rule in firewall advanced settings." }, { "code": null, "e": 33852, "s": 33844, "text": "Output:" }, { "code": null, "e": 33874, "s": 33854, "text": "Android App running" }, { "code": null, "e": 33924, "s": 33876, "text": "Step 7: Checking Requests Made in Python Editor" }, { "code": null, "e": 34107, "s": 33926, "text": "If a request is made, we can see the IP address of the device making the request, the time at which the request was made, and the request type(in our case the request type is GET)." }, { "code": null, "e": 34214, "s": 34111, "text": "We can use okhttp client to send data over the server. Add the following line to the import statements" }, { "code": null, "e": 34242, "s": 34216, "text": "from flask import request" }, { "code": null, "e": 34487, "s": 34244, "text": "We need to set the method of a route as POST. Let’s add a method and associate a route to it. The method prints the text we entered in the android application to the console in pycharm. Add the following lines after the showHomePage() method." }, { "code": null, "e": 34613, "s": 34489, "text": "@app.route(\"/debug\", methods=[\"POST\"])\ndef debug():\n text = request.form[\"sample\"]\n print(text)\n return \"received\"" }, { "code": null, "e": 34650, "s": 34615, "text": "The complete script is given below" }, { "code": null, "e": 34659, "s": 34652, "text": "Python" }, { "code": "from flask import Flask # import requestfrom flask import requestapp = Flask(__name__) @app.route(\"/\")def showHomePage(): return \"This is home page\" @app.route(\"/debug\", methods=[\"POST\"])def debug(): text = request.form[\"sample\"] print(text) return \"received\" if __name__ == \"__main__\": app.run(host=\"0.0.0.0\")", "e": 34986, "s": 34659, "text": null }, { "code": null, "e": 35208, "s": 34989, "text": "Create a DummyActivity.java in Android Studio. This activity will be started once we get a response from the server from the showHomePage() method. Add the following lines in onResponse() callback in MainActivity.java." }, { "code": null, "e": 35311, "s": 35210, "text": "Intent intent = new Intent(MainActivity.this, DummyActivity.class);\nstartActivity(intent);\nfinish();" }, { "code": null, "e": 35362, "s": 35313, "text": "Step 1: Working with the activity_dummy.xml file" }, { "code": null, "e": 35400, "s": 35364, "text": "Add an EditText with id dummy_text." }, { "code": null, "e": 35458, "s": 35400, "text": "Add a Button with id dummy_send and with the text “send”." }, { "code": null, "e": 35464, "s": 35460, "text": "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\" android:background=\"@color/white\" tools:context=\".DummyActivity\"> <EditText android:id=\"@+id/dummy_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"12dp\" android:layout_marginEnd=\"12dp\" android:backgroundTint=\"@color/black\" android:hint=\"enter any text\" android:textColor=\"@color/black\" android:textColorHint=\"#80000000\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/dummy_send\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Send\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/dummy_text\" app:layout_constraintVertical_bias=\"0.1\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 36944, "s": 35464, "text": null }, { "code": null, "e": 36996, "s": 36947, "text": "Step 2: Working with the DummyActivity.java file" }, { "code": null, "e": 37054, "s": 36998, "text": "We use a form to send the data using the OkHTTP client." }, { "code": null, "e": 37125, "s": 37054, "text": "We pass this form as a parameter to post() while building our request." }, { "code": null, "e": 37174, "s": 37125, "text": "Add an onClickListener() to make a POST request." }, { "code": null, "e": 37281, "s": 37174, "text": "If the data is sent, and we get a response, we display a toast confirming that the data has been received." }, { "code": null, "e": 37408, "s": 37283, "text": "Below is the code for the DummyActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 37415, "s": 37410, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response; public class DummyActivity extends AppCompatActivity { private EditText editText; private Button button; private OkHttpClient okHttpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dummy); editText = findViewById(R.id.dummy_text); button = findViewById(R.id.dummy_send); okHttpClient = new OkHttpClient(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String dummyText = editText.getText().toString(); // we add the information we want to send in // a form. each string we want to send should // have a name. in our case we sent the // dummyText with a name 'sample' RequestBody formbody = new FormBody.Builder() .add(\"sample\", dummyText) .build(); // while building request // we give our form // as a parameter to post() Request request = new Request.Builder().url(\"http://192.168.0.113:5000/debug\") .post(formbody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure( @NotNull Call call, @NotNull IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), \"server down\", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { if (response.body().string().equals(\"received\")) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), \"data received\", Toast.LENGTH_SHORT).show(); } }); } } }); } }); }}", "e": 40392, "s": 37415, "text": null }, { "code": null, "e": 40403, "s": 40395, "text": "Output:" }, { "code": null, "e": 40430, "s": 40407, "text": "Checking Flask Console" }, { "code": null, "e": 40542, "s": 40432, "text": "Here we can see the android application made a POST request. we can even see the data we send over the server" }, { "code": null, "e": 40558, "s": 40546, "text": "anikakapoor" }, { "code": null, "e": 40566, "s": 40558, "text": "Android" }, { "code": null, "e": 40571, "s": 40566, "text": "Java" }, { "code": null, "e": 40578, "s": 40571, "text": "Python" }, { "code": null, "e": 40583, "s": 40578, "text": "Java" }, { "code": null, "e": 40591, "s": 40583, "text": "Android" }, { "code": null, "e": 40689, "s": 40591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40727, "s": 40689, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 40766, "s": 40727, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 40816, "s": 40766, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 40842, "s": 40816, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 40893, "s": 40842, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 40908, "s": 40893, "text": "Arrays in Java" }, { "code": null, "e": 40952, "s": 40908, "text": "Split() String method in Java with examples" }, { "code": null, "e": 40974, "s": 40952, "text": "For-each loop in Java" }, { "code": null, "e": 41025, "s": 40974, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Building Your Own Quantum Circuits in Python (With Colorful Diagrams) | by Rishabh Anand | Towards Data Science
For a crash course on Quantum Computing, do check out the previous article. TLDR: Here, I talk about Qiskit, an open-source Python module for building quantum circuits and simulating operations on Qubits. We’ll look through sample code and then move on to an in-depth explanation of what the code does with very intuitive, colorful diagrams! In my previous article, I mentioned that models can be built to simulate processes of interest in the universe. In order to build these models, we make use of quantum circuits, for which we need a module to manipulate and run quantum programs on quantum devices. In this article, we’ll look at Qiskit — a Python module that makes quantum prototyping a stress-free task owing to its simple and easily-readable syntax. Qiskit was developed by IBM Research to make it easier for anyone to interface with a Quantum Computer. In my previous article, I spoke about the Hadamard, Controlled-NOT and the Pauli-X Gates. The Hadamard Gate takes in a single Qubit and outputs a bit with an equal probability of becoming a 1 or 0. The Controlled-NOT (CNOT) Gate takes in 2 Qubits and flips a Qubit from one state of ket 0 to ket 1 only if the control Qubit is ket 1. Otherwise, it leaves it unchanged. Now that we have recapped what the gates do, we can finally go on to defining our own circuit and simulating it to get the final state of the Qubits and bits! Note: the Pauli X and Y Gates are not covered in this tutorial. Building your own Quantum Circuits is easy because of Qiskit’s great documentation and resources. Before moving on to something complex, let’s run through the basics of building a circuit from scratch. Here, we’ll decompose the circuit code into digestible parts. Let’s begin! Before writing Quantum Circuits, we need to install Qiskit. To do so, you can simply install the package via pip: $ pip install qiskit To test out your installation, open up the Python console and type in import qiskit as qk. If it runs without any errors, you’re good to go! Note: If you run into any problems, the Qiskit GitHub Issues page has the solutions to most beginner problems. However, if you still have any burning questions, feel free to drop a comment down below or contact me via Twitter or LinkedIn. Now that we have Qiskit configured, let’s work some Qubits and Bits. To instantiate Qubits and Bits in Qiskit, we can use the QuantumRegister and ClassicalRegister objects to create them. Here, we create 2 of each type: The registers hold a record of the Qubits and Bits that are being used by our circuit. Having the Qubits and Bits in our hands, let’s construct our circuit: Let’s add some gates into our circuit to manipulate and work with our Qubits and Bits and finally measure the final Qubits: Let’s visualize our circuit so we have a rough idea of the transformations applied to our Qubits: If we print this circuit to console, we can see a circuit diagram printed for convenience purposes (Thanks IBM!). It should look something like this: Congrats! You have just built a Quantum Circuit. Now that we have that in place, let’s simulate the circuit and run it using a simulator. Qiskit provides components that have various simulator backends that manipulate the Qubits in different ways. The components are Aer, Ignis, Terra, and Aqua. To simulate the circuit, let’s use Aer’s QasmSimulator that aims to mimic a real Quantum Device. To use Aer’s simulator, we can simply create a simulation job and collect the results at the end. The Qasm Simulator runs the circuit for 1024 times (by default). ‘Qasm Simulator’ sounds like something out of a video game. Don’t worry if it sounds intimidating. All it does is create a classical simulation on your local machine to mimic what would happen in an actual quantum machine. Invariably, it is a pseudo-simulation, as the Qiskit documentation calls it. In the end, we can see that there is a 0.481 (492/1024) probability that the circuit outputs ‘00’ as the bitstring while there is a 0.519 (532/1024) probability that the output bitstring is ‘11’. This way, by simulating our circuits, we can convert this bitstring into their decimal or hexadecimal counterparts and see the values they give out. After doing all this, you may ask, what’s the point of all this? We have some idea on how to build circuits and what the individual components do. How do they go together? How do they all fit in? Those are valid questions. Quantum Computing deals with probabilities ie. the chance of an event occurring. For this, we assume that the event is completely random. Quantum Circuits enable us to take Qubits, put them into superpositions, measure them and get the final outcome. To illustrate one such application of complete randomness without bias, let’s build a random number generator! This way, we can see the power of Superposition and how the final result is a completely random number without any one-sidedness. Additionally, instead of running it on a local simulation that is classical in nature (cannot reflect the sheer awesomeness of a quantum computer), let’s hook up our circuit and run it on the actual IBM Quantum Computers located nearest to you! Before we perform any Quantum magic, we need to connect to the IBM Quantum Computer nearest to your region. To do so, visit the IBM Q website and login or create an account if you’re new. When logged in, click the profile icon located at the top right-hand corner. Go to the My Account page and go to the Advanced tab. There, you’ll see an area for your API Token. If you don’t have one go ahead and generate one. We can finally start writing a client-side circuit that interfaces with the IBM Q Machine closest to you, shown on the panel to the left. For this tutorial, I’ll be using the ibmqx4 system which can hold and manipulate a maximum of 4 Qubits. You might see other available machines on your dashboard depending on your location so don’t worry if you don’t see mine. Choose the one you like (pick the coolest sounding one 😎). Next up, let’s connect to the quantum computer using the following lines of code: Before we build a circuit, let’s create a record of Qubits and Classical Bits for our random number generator that generates numbers between 0 and 7 (n=3). Now, we need to construct a circuit that returns a Superposition of a Qubit and collapses it to a bitstring that represents an integer between 0 and 2^n — 1. To do that, we can apply the Hadamard Gate on the 3 Qubits to put them all in a Superposition with a 50–50 chance of being a 1 or 0. If we visualize this circuit, it’ll look like this: Now, it’s time for the exciting part. Let’s instantiate the Quantum Backend that’s going to run our circuit. Remember you used the Qasm Simulator up above? In the same way, my ibmqx4 machine is the simulator here (here, it’s the real deal!). Let’s connect our backend simulator: Shots here refers to the number of times the circuit is being run. Here we only want 1 randomly generated number, so we set it to 1. Note: You can play around with the number and set it to something like 1000 to see a histogram of the generated numbers over the 1000 runs. Next up is the main event function the runs a job on the ibmqx4 Quantum Computer and returns a completely random number between 0 and 7: Now, it’s the moment of truth. Let’s run the complete circuit on our Quantum Computer allocated to us: The code here will take a few minutes to run and took 3 credits from my account (you’re given 15, to begin with). When I ran the circuit, the final output was 6. With that, congrats for coming this far! You’ve just built a Quantum Circuit. Let’s revisit the steps to successfully run a quantum program: Note: The full code for the Quantum Random Number Generator can be found here. You’ve just built a Quantum Circuit! That’s awesome! You are taking one step forward on your journey to becoming an expert. By thinking of simple processes that require manipulation of bits and converting the problem into one that can be solved by a Quantum Computer, it’s good practice to getting a firm grasp over the concepts. Learning about the principles behind Quantum Computing was surely very demanding! There’s so much theory floating around that having a grounded understanding of what’s going on is very important. Learning about Qiskit was really fun and the documentation and resources provided by IBM Research went a long way in helping me understand what’s going on. Of all the quantum processors including Google Cirq and QuTiP, Qiskit was the most enjoyable to learn and implement circuits with. Quantum Computing is gaining pace at a promising rate. Researchers are making progress in democratizing the usage of Quantum Computers to perform tasks and tackle problems that were once considered impossible to solve. However, Quantum Computing theory has not reached a stage where it is fully accessible to everyone. It may be due to the clunkiness of Quantum Computers, the colossal facilities and the enormous amount of resources that are needed to keep the field active. Notwithstanding this, hopefully, this article has given some insight into what’s going on in the field and has sparked some interest in you! If you have any questions or want to talk about anything, you can catch me blatantly procrastinating on Twitter or LinkedIn. My next article will probably be focussed on the mathematics behind Quantum Computing and how the different gates and logic manipulate the Qubits. We’ll be doing a rundown of the quantum algorithms and how they go about doing what they do! Till then I’ll see you in the next one! Original article by Rishabh Anand Do check out my other articles on technology and Machine Learning, and reviews of up-and-coming software innovations.
[ { "code": null, "e": 248, "s": 172, "text": "For a crash course on Quantum Computing, do check out the previous article." }, { "code": null, "e": 514, "s": 248, "text": "TLDR: Here, I talk about Qiskit, an open-source Python module for building quantum circuits and simulating operations on Qubits. We’ll look through sample code and then move on to an in-depth explanation of what the code does with very intuitive, colorful diagrams!" }, { "code": null, "e": 777, "s": 514, "text": "In my previous article, I mentioned that models can be built to simulate processes of interest in the universe. In order to build these models, we make use of quantum circuits, for which we need a module to manipulate and run quantum programs on quantum devices." }, { "code": null, "e": 1035, "s": 777, "text": "In this article, we’ll look at Qiskit — a Python module that makes quantum prototyping a stress-free task owing to its simple and easily-readable syntax. Qiskit was developed by IBM Research to make it easier for anyone to interface with a Quantum Computer." }, { "code": null, "e": 1233, "s": 1035, "text": "In my previous article, I spoke about the Hadamard, Controlled-NOT and the Pauli-X Gates. The Hadamard Gate takes in a single Qubit and outputs a bit with an equal probability of becoming a 1 or 0." }, { "code": null, "e": 1404, "s": 1233, "text": "The Controlled-NOT (CNOT) Gate takes in 2 Qubits and flips a Qubit from one state of ket 0 to ket 1 only if the control Qubit is ket 1. Otherwise, it leaves it unchanged." }, { "code": null, "e": 1563, "s": 1404, "text": "Now that we have recapped what the gates do, we can finally go on to defining our own circuit and simulating it to get the final state of the Qubits and bits!" }, { "code": null, "e": 1627, "s": 1563, "text": "Note: the Pauli X and Y Gates are not covered in this tutorial." }, { "code": null, "e": 1904, "s": 1627, "text": "Building your own Quantum Circuits is easy because of Qiskit’s great documentation and resources. Before moving on to something complex, let’s run through the basics of building a circuit from scratch. Here, we’ll decompose the circuit code into digestible parts. Let’s begin!" }, { "code": null, "e": 2018, "s": 1904, "text": "Before writing Quantum Circuits, we need to install Qiskit. To do so, you can simply install the package via pip:" }, { "code": null, "e": 2039, "s": 2018, "text": "$ pip install qiskit" }, { "code": null, "e": 2180, "s": 2039, "text": "To test out your installation, open up the Python console and type in import qiskit as qk. If it runs without any errors, you’re good to go!" }, { "code": null, "e": 2419, "s": 2180, "text": "Note: If you run into any problems, the Qiskit GitHub Issues page has the solutions to most beginner problems. However, if you still have any burning questions, feel free to drop a comment down below or contact me via Twitter or LinkedIn." }, { "code": null, "e": 2639, "s": 2419, "text": "Now that we have Qiskit configured, let’s work some Qubits and Bits. To instantiate Qubits and Bits in Qiskit, we can use the QuantumRegister and ClassicalRegister objects to create them. Here, we create 2 of each type:" }, { "code": null, "e": 2796, "s": 2639, "text": "The registers hold a record of the Qubits and Bits that are being used by our circuit. Having the Qubits and Bits in our hands, let’s construct our circuit:" }, { "code": null, "e": 2920, "s": 2796, "text": "Let’s add some gates into our circuit to manipulate and work with our Qubits and Bits and finally measure the final Qubits:" }, { "code": null, "e": 3018, "s": 2920, "text": "Let’s visualize our circuit so we have a rough idea of the transformations applied to our Qubits:" }, { "code": null, "e": 3168, "s": 3018, "text": "If we print this circuit to console, we can see a circuit diagram printed for convenience purposes (Thanks IBM!). It should look something like this:" }, { "code": null, "e": 3464, "s": 3168, "text": "Congrats! You have just built a Quantum Circuit. Now that we have that in place, let’s simulate the circuit and run it using a simulator. Qiskit provides components that have various simulator backends that manipulate the Qubits in different ways. The components are Aer, Ignis, Terra, and Aqua." }, { "code": null, "e": 3724, "s": 3464, "text": "To simulate the circuit, let’s use Aer’s QasmSimulator that aims to mimic a real Quantum Device. To use Aer’s simulator, we can simply create a simulation job and collect the results at the end. The Qasm Simulator runs the circuit for 1024 times (by default)." }, { "code": null, "e": 4024, "s": 3724, "text": "‘Qasm Simulator’ sounds like something out of a video game. Don’t worry if it sounds intimidating. All it does is create a classical simulation on your local machine to mimic what would happen in an actual quantum machine. Invariably, it is a pseudo-simulation, as the Qiskit documentation calls it." }, { "code": null, "e": 4220, "s": 4024, "text": "In the end, we can see that there is a 0.481 (492/1024) probability that the circuit outputs ‘00’ as the bitstring while there is a 0.519 (532/1024) probability that the output bitstring is ‘11’." }, { "code": null, "e": 4369, "s": 4220, "text": "This way, by simulating our circuits, we can convert this bitstring into their decimal or hexadecimal counterparts and see the values they give out." }, { "code": null, "e": 4592, "s": 4369, "text": "After doing all this, you may ask, what’s the point of all this? We have some idea on how to build circuits and what the individual components do. How do they go together? How do they all fit in? Those are valid questions." }, { "code": null, "e": 4843, "s": 4592, "text": "Quantum Computing deals with probabilities ie. the chance of an event occurring. For this, we assume that the event is completely random. Quantum Circuits enable us to take Qubits, put them into superpositions, measure them and get the final outcome." }, { "code": null, "e": 5084, "s": 4843, "text": "To illustrate one such application of complete randomness without bias, let’s build a random number generator! This way, we can see the power of Superposition and how the final result is a completely random number without any one-sidedness." }, { "code": null, "e": 5329, "s": 5084, "text": "Additionally, instead of running it on a local simulation that is classical in nature (cannot reflect the sheer awesomeness of a quantum computer), let’s hook up our circuit and run it on the actual IBM Quantum Computers located nearest to you!" }, { "code": null, "e": 5517, "s": 5329, "text": "Before we perform any Quantum magic, we need to connect to the IBM Quantum Computer nearest to your region. To do so, visit the IBM Q website and login or create an account if you’re new." }, { "code": null, "e": 5743, "s": 5517, "text": "When logged in, click the profile icon located at the top right-hand corner. Go to the My Account page and go to the Advanced tab. There, you’ll see an area for your API Token. If you don’t have one go ahead and generate one." }, { "code": null, "e": 5881, "s": 5743, "text": "We can finally start writing a client-side circuit that interfaces with the IBM Q Machine closest to you, shown on the panel to the left." }, { "code": null, "e": 6166, "s": 5881, "text": "For this tutorial, I’ll be using the ibmqx4 system which can hold and manipulate a maximum of 4 Qubits. You might see other available machines on your dashboard depending on your location so don’t worry if you don’t see mine. Choose the one you like (pick the coolest sounding one 😎)." }, { "code": null, "e": 6248, "s": 6166, "text": "Next up, let’s connect to the quantum computer using the following lines of code:" }, { "code": null, "e": 6404, "s": 6248, "text": "Before we build a circuit, let’s create a record of Qubits and Classical Bits for our random number generator that generates numbers between 0 and 7 (n=3)." }, { "code": null, "e": 6695, "s": 6404, "text": "Now, we need to construct a circuit that returns a Superposition of a Qubit and collapses it to a bitstring that represents an integer between 0 and 2^n — 1. To do that, we can apply the Hadamard Gate on the 3 Qubits to put them all in a Superposition with a 50–50 chance of being a 1 or 0." }, { "code": null, "e": 6747, "s": 6695, "text": "If we visualize this circuit, it’ll look like this:" }, { "code": null, "e": 7026, "s": 6747, "text": "Now, it’s time for the exciting part. Let’s instantiate the Quantum Backend that’s going to run our circuit. Remember you used the Qasm Simulator up above? In the same way, my ibmqx4 machine is the simulator here (here, it’s the real deal!). Let’s connect our backend simulator:" }, { "code": null, "e": 7159, "s": 7026, "text": "Shots here refers to the number of times the circuit is being run. Here we only want 1 randomly generated number, so we set it to 1." }, { "code": null, "e": 7299, "s": 7159, "text": "Note: You can play around with the number and set it to something like 1000 to see a histogram of the generated numbers over the 1000 runs." }, { "code": null, "e": 7436, "s": 7299, "text": "Next up is the main event function the runs a job on the ibmqx4 Quantum Computer and returns a completely random number between 0 and 7:" }, { "code": null, "e": 7539, "s": 7436, "text": "Now, it’s the moment of truth. Let’s run the complete circuit on our Quantum Computer allocated to us:" }, { "code": null, "e": 7701, "s": 7539, "text": "The code here will take a few minutes to run and took 3 credits from my account (you’re given 15, to begin with). When I ran the circuit, the final output was 6." }, { "code": null, "e": 7842, "s": 7701, "text": "With that, congrats for coming this far! You’ve just built a Quantum Circuit. Let’s revisit the steps to successfully run a quantum program:" }, { "code": null, "e": 7921, "s": 7842, "text": "Note: The full code for the Quantum Random Number Generator can be found here." }, { "code": null, "e": 8251, "s": 7921, "text": "You’ve just built a Quantum Circuit! That’s awesome! You are taking one step forward on your journey to becoming an expert. By thinking of simple processes that require manipulation of bits and converting the problem into one that can be solved by a Quantum Computer, it’s good practice to getting a firm grasp over the concepts." }, { "code": null, "e": 8447, "s": 8251, "text": "Learning about the principles behind Quantum Computing was surely very demanding! There’s so much theory floating around that having a grounded understanding of what’s going on is very important." }, { "code": null, "e": 8734, "s": 8447, "text": "Learning about Qiskit was really fun and the documentation and resources provided by IBM Research went a long way in helping me understand what’s going on. Of all the quantum processors including Google Cirq and QuTiP, Qiskit was the most enjoyable to learn and implement circuits with." }, { "code": null, "e": 8953, "s": 8734, "text": "Quantum Computing is gaining pace at a promising rate. Researchers are making progress in democratizing the usage of Quantum Computers to perform tasks and tackle problems that were once considered impossible to solve." }, { "code": null, "e": 9210, "s": 8953, "text": "However, Quantum Computing theory has not reached a stage where it is fully accessible to everyone. It may be due to the clunkiness of Quantum Computers, the colossal facilities and the enormous amount of resources that are needed to keep the field active." }, { "code": null, "e": 9476, "s": 9210, "text": "Notwithstanding this, hopefully, this article has given some insight into what’s going on in the field and has sparked some interest in you! If you have any questions or want to talk about anything, you can catch me blatantly procrastinating on Twitter or LinkedIn." }, { "code": null, "e": 9716, "s": 9476, "text": "My next article will probably be focussed on the mathematics behind Quantum Computing and how the different gates and logic manipulate the Qubits. We’ll be doing a rundown of the quantum algorithms and how they go about doing what they do!" }, { "code": null, "e": 9756, "s": 9716, "text": "Till then I’ll see you in the next one!" }, { "code": null, "e": 9790, "s": 9756, "text": "Original article by Rishabh Anand" } ]
Multiply any Number with 4 using Bitwise Operator
09 Mar, 2022 We are a Number n and our task is multiply the number with 4 using bit-wise Operator.Examples: Input : 4 Output :16 Input :5 Output :20 Explanation Case 1:- n=4 the binary of 4 is 100 and now shift two bit right then 10000 now the number is 16 that is multiply 4*4=16 ans. Approach :- (n<<2) shift two bit right C++ Java Python 3 C# PHP Javascript // C++ program to multiply a number with// 4 using Bitwise Operator#include <bits/stdc++.h>using namespace std; // function the return multiply a number// with 4 using bitwise operatorint multiplyWith4(int n){ // returning a number with multiply // with 4 using2 bit shifting right return (n << 2);} // derive functionint main(){ int n = 4; cout << multiplyWith4(n) << endl; return 0;} // Java program to multiply a number// with 4 using Bitwise Operator class GFG { // function the return// multiply a number// with 4 using bitwise// operatorstatic int multiplyWith4(int n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(multiplyWith4(n));}} // This code is contributed by Smitha. # Python 3 program to multiply# a number with 4 using Bitwise# Operator # function the return multiply# a number with 4 using bitwise# operatordef multiplyWith4(n): # returning a number with # multiply with 4 using2 # bit shifting right return (n << 2) # derive functionn = 4print(multiplyWith4(n)) # This code is contributed# by Smitha // C# program to multiply a number// with 4 using Bitwise Operatorusing System; class GFG { // function the return// multiply a number// with 4 using bitwise// operatorstatic int multiplyWith4(int n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(multiplyWith4(n));}} // This code is contributed by Smitha. <?php// PHP program to multiply// a number with 4 using// Bitwise Operator // function the return// multiply a number// with 4 using bitwise// operatorfunction multiplyWith4($n){ // returning a number // with multiply with // 4 using2 bit // shifting right return ($n << 2);} // Driver Code $n = 4; echo multiplyWith4($n),"\n"; // This code is contributed by Ajit.?> <script>// javascript program to multiply a number// with 4 using Bitwise Operator // function the return// multiply a number// with 4 using bitwise// operatorfunction multiplyWith4(n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codevar n = 4;document.write(multiplyWith4(n)); // This code is contributed by Amit Katiyar</script> Output :- 16 Generalization : In general, we can multiply with a power of 2 using bitwise operators. For example, suppose we wish to multiply with 16 (which is 24), we can do it by left shifting by 4. Smitha Dinesh Semwal jit_t amit143katiyar simmytarika5 sumitgumber28 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Builtin functions of GCC compiler Calculate XOR from 1 to n. Google Online Challenge 2020 Find two numbers from their sum and XOR Highest power of 2 less than or equal to given number Calculate square of a number without using *, / and pow() Reverse actual bits of the given number Find XOR of two number without using XOR operator Count number of bits to be flipped to convert A to B
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Mar, 2022" }, { "code": null, "e": 150, "s": 53, "text": "We are a Number n and our task is multiply the number with 4 using bit-wise Operator.Examples: " }, { "code": null, "e": 192, "s": 150, "text": "Input : 4\nOutput :16\n\nInput :5\nOutput :20" }, { "code": null, "e": 371, "s": 194, "text": "Explanation Case 1:- n=4 the binary of 4 is 100 and now shift two bit right then 10000 now the number is 16 that is multiply 4*4=16 ans. Approach :- (n<<2) shift two bit right " }, { "code": null, "e": 375, "s": 371, "text": "C++" }, { "code": null, "e": 380, "s": 375, "text": "Java" }, { "code": null, "e": 389, "s": 380, "text": "Python 3" }, { "code": null, "e": 392, "s": 389, "text": "C#" }, { "code": null, "e": 396, "s": 392, "text": "PHP" }, { "code": null, "e": 407, "s": 396, "text": "Javascript" }, { "code": "// C++ program to multiply a number with// 4 using Bitwise Operator#include <bits/stdc++.h>using namespace std; // function the return multiply a number// with 4 using bitwise operatorint multiplyWith4(int n){ // returning a number with multiply // with 4 using2 bit shifting right return (n << 2);} // derive functionint main(){ int n = 4; cout << multiplyWith4(n) << endl; return 0;}", "e": 812, "s": 407, "text": null }, { "code": "// Java program to multiply a number// with 4 using Bitwise Operator class GFG { // function the return// multiply a number// with 4 using bitwise// operatorstatic int multiplyWith4(int n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(multiplyWith4(n));}} // This code is contributed by Smitha.", "e": 1271, "s": 812, "text": null }, { "code": "# Python 3 program to multiply# a number with 4 using Bitwise# Operator # function the return multiply# a number with 4 using bitwise# operatordef multiplyWith4(n): # returning a number with # multiply with 4 using2 # bit shifting right return (n << 2) # derive functionn = 4print(multiplyWith4(n)) # This code is contributed# by Smitha", "e": 1621, "s": 1271, "text": null }, { "code": "// C# program to multiply a number// with 4 using Bitwise Operatorusing System; class GFG { // function the return// multiply a number// with 4 using bitwise// operatorstatic int multiplyWith4(int n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(multiplyWith4(n));}} // This code is contributed by Smitha.", "e": 2088, "s": 1621, "text": null }, { "code": "<?php// PHP program to multiply// a number with 4 using// Bitwise Operator // function the return// multiply a number// with 4 using bitwise// operatorfunction multiplyWith4($n){ // returning a number // with multiply with // 4 using2 bit // shifting right return ($n << 2);} // Driver Code $n = 4; echo multiplyWith4($n),\"\\n\"; // This code is contributed by Ajit.?>", "e": 2485, "s": 2088, "text": null }, { "code": "<script>// javascript program to multiply a number// with 4 using Bitwise Operator // function the return// multiply a number// with 4 using bitwise// operatorfunction multiplyWith4(n){ // returning a number // with multiply with // 4 using 2 bit shifting // right return (n << 2);} // Driver Codevar n = 4;document.write(multiplyWith4(n)); // This code is contributed by Amit Katiyar</script>", "e": 2900, "s": 2485, "text": null }, { "code": null, "e": 2912, "s": 2900, "text": "Output :- " }, { "code": null, "e": 2915, "s": 2912, "text": "16" }, { "code": null, "e": 3104, "s": 2915, "text": "Generalization : In general, we can multiply with a power of 2 using bitwise operators. For example, suppose we wish to multiply with 16 (which is 24), we can do it by left shifting by 4. " }, { "code": null, "e": 3125, "s": 3104, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 3131, "s": 3125, "text": "jit_t" }, { "code": null, "e": 3146, "s": 3131, "text": "amit143katiyar" }, { "code": null, "e": 3159, "s": 3146, "text": "simmytarika5" }, { "code": null, "e": 3173, "s": 3159, "text": "sumitgumber28" }, { "code": null, "e": 3183, "s": 3173, "text": "Bit Magic" }, { "code": null, "e": 3193, "s": 3183, "text": "Bit Magic" }, { "code": null, "e": 3291, "s": 3193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3342, "s": 3291, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 3376, "s": 3342, "text": "Builtin functions of GCC compiler" }, { "code": null, "e": 3403, "s": 3376, "text": "Calculate XOR from 1 to n." }, { "code": null, "e": 3432, "s": 3403, "text": "Google Online Challenge 2020" }, { "code": null, "e": 3472, "s": 3432, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 3526, "s": 3472, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 3584, "s": 3526, "text": "Calculate square of a number without using *, / and pow()" }, { "code": null, "e": 3624, "s": 3584, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 3674, "s": 3624, "text": "Find XOR of two number without using XOR operator" } ]
Plotly - Plotting Inline with Jupyter Notebook
In this chapter, we will study how to do inline plotting with the Jupyter Notebook. In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows − from plotly.offline import init_notebook_mode init_notebook_mode(connected = True) Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself. import plotly plotly.tools.set_credentials_file(username = 'lathkar', api_key = '************') from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import plotly import plotly.graph_objs as go import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] plotly.offline.iplot({ "data": data,"layout": go.Layout(title="Sine wave")}) Jupyter notebook output will be as shown below − The plot output shows a tool bar at top right. It contains buttons for download as png, zoom in and out, box and lasso, select and hover.
[ { "code": null, "e": 2578, "s": 2494, "text": "In this chapter, we will study how to do inline plotting with the Jupyter Notebook." }, { "code": null, "e": 2685, "s": 2578, "text": "In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows −" }, { "code": null, "e": 2769, "s": 2685, "text": "from plotly.offline import init_notebook_mode\ninit_notebook_mode(connected = True)\n" }, { "code": null, "e": 2913, "s": 2769, "text": "Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself." }, { "code": null, "e": 3416, "s": 2913, "text": "import plotly\nplotly.tools.set_credentials_file(username = 'lathkar', api_key = '************')\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\n\nimport plotly\nimport plotly.graph_objs as go\nimport numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\nypoints = np.sin(xpoints)\ntrace0 = go.Scatter(\n x = xpoints, y = ypoints\n)\ndata = [trace0]\nplotly.offline.iplot({ \"data\": data,\"layout\": go.Layout(title=\"Sine wave\")})" }, { "code": null, "e": 3465, "s": 3416, "text": "Jupyter notebook output will be as shown below −" } ]
How to create Tinder card swipe gesture using React and framer-motion ?
28 Oct, 2021 We can create a simple tinder app like swipe gesture using the following approach using the Framer module in ReactJS. Prerequisites: Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS. Knowledge of JavaScript (ES6) Knowledge of HTML/CSS. Basic knowledge of ReactJS. Framer hooks used in building this application are: Framer useMotionValueFramer useTransformFramer useAnimation Framer useMotionValue Framer useTransform Framer useAnimation Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app tinder-swipe Step 2: After creating your project folder i.e. tinder-swipe, move to it using the following command. cd tinder-swipe Step 3: After creating the ReactJS application, Install the framer modules using the following command. npm install framer Project structure: Our project structure tree should look like this: Project structure Approach: We are going to use useMotionValue() to move the card as the user drags the cursor as all motion components internally use motionValues to track the state and velocity of an animating value which we’re going to get through this hook. We are going to use useTransform() hook to rotate the card as the card moves on drag by chaining motionValue of the card with it. Also, we are going to use useTransform() hook to change the opacity of the card as it moves by chaining it to the motionValue. useAnimation() is a utility hook and is used to create animation controls (animControls) which can be used to manually start, stop and sequence animations on the card. Example 1: index.js import React from "react";import ReactDOM from "react-dom";import "./index.css";import { Frame, useMotionValue, useTransform, useAnimation } from "framer"; // Some styling for the cardconst style = { backgroundImage: "URL(https://img.icons8.com/color/452/GeeksforGeeks.png)", backgroundRepeat: "no-repeat", backgroundSize: "contain", backgroundColor: "#55ccff", boxShadow: "5px 10px 18px #888888", borderRadius: 10, height: 300,}; const App = () => { // To move the card as the user drags the cursor const motionValue = useMotionValue(0); // To rotate the card as the card moves on drag const rotateValue = useTransform(motionValue, [-200, 200], [-50, 50]); // To decrease opacity of the card when swiped // on dragging card to left(-200) or right(200) // opacity gradually changes to 0 // and when the card is in center opacity = 1 const opacityValue = useTransform( motionValue, [-200, -150, 0, 150, 200], [0, 1, 1, 1, 0] ); // Framer animation hook const animControls = useAnimation(); return ( <div className="App"> <Frame center // Card can be drag only on x-axis drag="x" x={motionValue} rotate={rotateValue} opacity={opacityValue} dragConstraints={{ left: -1000, right: 1000 }} style={style} onDragEnd={(event, info) => { // If the card is dragged only upto 150 on x-axis // bring it back to initial position if (Math.abs(info.point.x) <= 150) { animControls.start({ x: 0 }); } else { // If card is dragged beyond 150 // make it disappear // making use of ternary operator animControls.start({ x: info.point.x < 0 ? -200 : 200 }); } }} /> </div> );}; ReactDOM.render(<App />, document.getElementById("root")); index.css body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;} .App { text-align: center;} code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;} 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: Tinder like card swipe gesture Example 2:Creating a deck of cards index.js import React from 'react';import ReactDOM from 'react-dom';import './index.css';import { Frame, useMotionValue, useTransform, useAnimation } from 'framer'; // Card component with destructured propsconst Card = ({ image, color }) => { // To move the card as the user drags the cursor const motionValue = useMotionValue(0); // To rotate the card as the card moves on drag const rotateValue = useTransform(motionValue, [-200, 200], [-50, 50]); // To decrease opacity of the card when swiped // on dragging card to left(-200) or right(200) // opacity gradually changes to 0 // and when the card is in center opacity = 1 const opacityValue = useTransform( motionValue, [-200, -150, 0, 150, 200], [0, 1, 1, 1, 0] ); // Framer animation hook const animControls = useAnimation(); // Some styling for the card // it is placed inside the card component // to make backgroundImage and backgroundColor dynamic const style = { backgroundImage: `url(${image})`, backgroundRepeat: 'no-repeat', backgroundSize: 'contain', backgroundColor: color, boxShadow: '5px 10px 18px #888888', borderRadius: 10, height: 300 }; return ( <div className='App'> <Frame center // Card can be drag only on x-axis drag='x' x={motionValue} rotate={rotateValue} opacity={opacityValue} dragConstraints={{ left: -1000, right: 1000 }} style={style} onDragEnd={(event, info) => { // If the card is dragged only upto 150 on x-axis // bring it back to initial position if (Math.abs(info.point.x) <= 150) { animControls.start({ x: 0 }); } else { // If card is dragged beyond 150 // make it disappear // Making use of ternary operator animControls.start({ x: info.point.x < 0 ? -200 : 200 }); } }} /> </div> );}; const App = () => { const cards = [ { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#55ccff' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#e8e8e8' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#0a043c' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: 'black' } ]; return ( <div className='App'> {/* Traversing through cards arrray using map function and populating card with different image and color */} {cards.map((card) => ( <Card image={card.image} color={card.color} /> ))} </div> );}; ReactDOM.render(<App />, document.getElementById('root')); 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: Swipeable deck of cards akshaysingh98088 React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create a multi-page website using React.js ? ReactJS useNavigate() Hook Axios in React: A Guide for Beginners How to do crud operations in ReactJS ? React-Router Hooks Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2021" }, { "code": null, "e": 170, "s": 52, "text": "We can create a simple tinder app like swipe gesture using the following approach using the Framer module in ReactJS." }, { "code": null, "e": 185, "s": 170, "text": "Prerequisites:" }, { "code": null, "e": 264, "s": 185, "text": "Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS." }, { "code": null, "e": 294, "s": 264, "text": "Knowledge of JavaScript (ES6)" }, { "code": null, "e": 317, "s": 294, "text": "Knowledge of HTML/CSS." }, { "code": null, "e": 345, "s": 317, "text": "Basic knowledge of ReactJS." }, { "code": null, "e": 397, "s": 345, "text": "Framer hooks used in building this application are:" }, { "code": null, "e": 457, "s": 397, "text": "Framer useMotionValueFramer useTransformFramer useAnimation" }, { "code": null, "e": 479, "s": 457, "text": "Framer useMotionValue" }, { "code": null, "e": 499, "s": 479, "text": "Framer useTransform" }, { "code": null, "e": 519, "s": 499, "text": "Framer useAnimation" }, { "code": null, "e": 569, "s": 519, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 633, "s": 569, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 667, "s": 633, "text": "npx create-react-app tinder-swipe" }, { "code": null, "e": 769, "s": 667, "text": "Step 2: After creating your project folder i.e. tinder-swipe, move to it using the following command." }, { "code": null, "e": 785, "s": 769, "text": "cd tinder-swipe" }, { "code": null, "e": 889, "s": 785, "text": "Step 3: After creating the ReactJS application, Install the framer modules using the following command." }, { "code": null, "e": 908, "s": 889, "text": "npm install framer" }, { "code": null, "e": 977, "s": 908, "text": "Project structure: Our project structure tree should look like this:" }, { "code": null, "e": 995, "s": 977, "text": "Project structure" }, { "code": null, "e": 1005, "s": 995, "text": "Approach:" }, { "code": null, "e": 1239, "s": 1005, "text": "We are going to use useMotionValue() to move the card as the user drags the cursor as all motion components internally use motionValues to track the state and velocity of an animating value which we’re going to get through this hook." }, { "code": null, "e": 1369, "s": 1239, "text": "We are going to use useTransform() hook to rotate the card as the card moves on drag by chaining motionValue of the card with it." }, { "code": null, "e": 1496, "s": 1369, "text": "Also, we are going to use useTransform() hook to change the opacity of the card as it moves by chaining it to the motionValue." }, { "code": null, "e": 1664, "s": 1496, "text": "useAnimation() is a utility hook and is used to create animation controls (animControls) which can be used to manually start, stop and sequence animations on the card." }, { "code": null, "e": 1676, "s": 1664, "text": "Example 1: " }, { "code": null, "e": 1685, "s": 1676, "text": "index.js" }, { "code": "import React from \"react\";import ReactDOM from \"react-dom\";import \"./index.css\";import { Frame, useMotionValue, useTransform, useAnimation } from \"framer\"; // Some styling for the cardconst style = { backgroundImage: \"URL(https://img.icons8.com/color/452/GeeksforGeeks.png)\", backgroundRepeat: \"no-repeat\", backgroundSize: \"contain\", backgroundColor: \"#55ccff\", boxShadow: \"5px 10px 18px #888888\", borderRadius: 10, height: 300,}; const App = () => { // To move the card as the user drags the cursor const motionValue = useMotionValue(0); // To rotate the card as the card moves on drag const rotateValue = useTransform(motionValue, [-200, 200], [-50, 50]); // To decrease opacity of the card when swiped // on dragging card to left(-200) or right(200) // opacity gradually changes to 0 // and when the card is in center opacity = 1 const opacityValue = useTransform( motionValue, [-200, -150, 0, 150, 200], [0, 1, 1, 1, 0] ); // Framer animation hook const animControls = useAnimation(); return ( <div className=\"App\"> <Frame center // Card can be drag only on x-axis drag=\"x\" x={motionValue} rotate={rotateValue} opacity={opacityValue} dragConstraints={{ left: -1000, right: 1000 }} style={style} onDragEnd={(event, info) => { // If the card is dragged only upto 150 on x-axis // bring it back to initial position if (Math.abs(info.point.x) <= 150) { animControls.start({ x: 0 }); } else { // If card is dragged beyond 150 // make it disappear // making use of ternary operator animControls.start({ x: info.point.x < 0 ? -200 : 200 }); } }} /> </div> );}; ReactDOM.render(<App />, document.getElementById(\"root\"));", "e": 3529, "s": 1685, "text": null }, { "code": null, "e": 3539, "s": 3529, "text": "index.css" }, { "code": "body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;} .App { text-align: center;} code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;}", "e": 3993, "s": 3539, "text": null }, { "code": null, "e": 4106, "s": 3993, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 4116, "s": 4106, "text": "npm start" }, { "code": null, "e": 4215, "s": 4116, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4246, "s": 4215, "text": "Tinder like card swipe gesture" }, { "code": null, "e": 4281, "s": 4246, "text": "Example 2:Creating a deck of cards" }, { "code": null, "e": 4290, "s": 4281, "text": "index.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import { Frame, useMotionValue, useTransform, useAnimation } from 'framer'; // Card component with destructured propsconst Card = ({ image, color }) => { // To move the card as the user drags the cursor const motionValue = useMotionValue(0); // To rotate the card as the card moves on drag const rotateValue = useTransform(motionValue, [-200, 200], [-50, 50]); // To decrease opacity of the card when swiped // on dragging card to left(-200) or right(200) // opacity gradually changes to 0 // and when the card is in center opacity = 1 const opacityValue = useTransform( motionValue, [-200, -150, 0, 150, 200], [0, 1, 1, 1, 0] ); // Framer animation hook const animControls = useAnimation(); // Some styling for the card // it is placed inside the card component // to make backgroundImage and backgroundColor dynamic const style = { backgroundImage: `url(${image})`, backgroundRepeat: 'no-repeat', backgroundSize: 'contain', backgroundColor: color, boxShadow: '5px 10px 18px #888888', borderRadius: 10, height: 300 }; return ( <div className='App'> <Frame center // Card can be drag only on x-axis drag='x' x={motionValue} rotate={rotateValue} opacity={opacityValue} dragConstraints={{ left: -1000, right: 1000 }} style={style} onDragEnd={(event, info) => { // If the card is dragged only upto 150 on x-axis // bring it back to initial position if (Math.abs(info.point.x) <= 150) { animControls.start({ x: 0 }); } else { // If card is dragged beyond 150 // make it disappear // Making use of ternary operator animControls.start({ x: info.point.x < 0 ? -200 : 200 }); } }} /> </div> );}; const App = () => { const cards = [ { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#55ccff' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#e8e8e8' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: '#0a043c' }, { image: 'https://img.icons8.com/color/452/GeeksforGeeks.png', color: 'black' } ]; return ( <div className='App'> {/* Traversing through cards arrray using map function and populating card with different image and color */} {cards.map((card) => ( <Card image={card.image} color={card.color} /> ))} </div> );}; ReactDOM.render(<App />, document.getElementById('root'));", "e": 7001, "s": 4290, "text": null }, { "code": null, "e": 7114, "s": 7001, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 7124, "s": 7114, "text": "npm start" }, { "code": null, "e": 7223, "s": 7124, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 7247, "s": 7223, "text": "Swipeable deck of cards" }, { "code": null, "e": 7264, "s": 7247, "text": "akshaysingh98088" }, { "code": null, "e": 7280, "s": 7264, "text": "React-Questions" }, { "code": null, "e": 7304, "s": 7280, "text": "Technical Scripter 2020" }, { "code": null, "e": 7312, "s": 7304, "text": "ReactJS" }, { "code": null, "e": 7331, "s": 7312, "text": "Technical Scripter" }, { "code": null, "e": 7348, "s": 7331, "text": "Web Technologies" }, { "code": null, "e": 7446, "s": 7348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7498, "s": 7446, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 7525, "s": 7498, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 7563, "s": 7525, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 7602, "s": 7563, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 7621, "s": 7602, "text": "React-Router Hooks" }, { "code": null, "e": 7654, "s": 7621, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7704, "s": 7654, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7766, "s": 7704, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7824, "s": 7766, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Java Program to Handle Checked Exception
04 Jul, 2022 Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions. I/O Exception: This Program throw I/O exception because of due FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the file system, Java forces us to handle error situations where the file is not present in the given location. Implementation: Consider GFG.txt file does not exist. Example 1-A Java // Java Program to Handle Checked Exception// Where FileInputStream Exception is thrown // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Reading content from file by passing local directory path // where file should exists FileInputStream GFG = new FileInputStream("/Desktop/GFG.txt"); // This file does not exist in the location // This constructor FileInputStream // throws FileNotFoundException which // is a checked exception }} Output: Now let us do discuss how to handle FileNotFoundException. The answer is quite simple as we can handle it with the help of a try-catch block Declare the function using the throw keyword to avoid a Compilation error. All the exceptions throw objects when they occur try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations. Using a try-catch block defined output will be shown. Example 1-B: Java // Java Program to Illustrate Handling of Checked Exception // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) throws FileNotFoundException { // Assigning null value to object of FileInputStream FileInputStream GFG = null; // Try block to check for exceptions try { // Giving path where file should exists to read // content GFG = new FileInputStream( "/home/mayur/GFG.txt"); } // Catch block to handle exceptions catch (FileNotFoundException e) { // Display message when exception occurs System.out.println("File does not exist"); } }} File does not exist Now let us discuss one more checked exception that is ClassNotFoundException. This Exception occurs when methods like Class.forName() and LoadClass Method etc. are unable to find the given class name as a parameter. Example 2-A Java // Java Program to Handle Checked Exception // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling the class gfg which is not present in the // current class temp instance of calling class Class temp = Class.forName("gfg"); // It will throw ClassNotFoundException }} Output: Again now let us handle ClassNotFoundException using try-Catch block Example 2-B Java // Java Program to Handle Checked Exceptionimport java.io.*;class GFG { public static void main(String[] args) throws ClassNotFoundException { try { Class temp = Class.forName( "gfg"); // calling the gfg class } catch (ClassNotFoundException e) { // block executes when mention exception occur System.out.println( "Class does not exist check the name of the class"); } }} Class does not exist check the name of the class solankimayank ankur035 javaguy java-file-handling Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 334, "s": 54, "text": "Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error." }, { "code": null, "e": 433, "s": 334, "text": " ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions." }, { "code": null, "e": 699, "s": 433, "text": "I/O Exception: This Program throw I/O exception because of due FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the file system, Java forces us to handle error situations where the file is not present in the given location." }, { "code": null, "e": 753, "s": 699, "text": "Implementation: Consider GFG.txt file does not exist." }, { "code": null, "e": 765, "s": 753, "text": "Example 1-A" }, { "code": null, "e": 770, "s": 765, "text": "Java" }, { "code": "// Java Program to Handle Checked Exception// Where FileInputStream Exception is thrown // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Reading content from file by passing local directory path // where file should exists FileInputStream GFG = new FileInputStream(\"/Desktop/GFG.txt\"); // This file does not exist in the location // This constructor FileInputStream // throws FileNotFoundException which // is a checked exception }}", "e": 1364, "s": 770, "text": null }, { "code": null, "e": 1373, "s": 1364, "text": " Output:" }, { "code": null, "e": 1515, "s": 1373, "text": "Now let us do discuss how to handle FileNotFoundException. The answer is quite simple as we can handle it with the help of a try-catch block " }, { "code": null, "e": 1590, "s": 1515, "text": "Declare the function using the throw keyword to avoid a Compilation error." }, { "code": null, "e": 1799, "s": 1590, "text": "All the exceptions throw objects when they occur try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations." }, { "code": null, "e": 1853, "s": 1799, "text": "Using a try-catch block defined output will be shown." }, { "code": null, "e": 1866, "s": 1853, "text": "Example 1-B:" }, { "code": null, "e": 1871, "s": 1866, "text": "Java" }, { "code": "// Java Program to Illustrate Handling of Checked Exception // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) throws FileNotFoundException { // Assigning null value to object of FileInputStream FileInputStream GFG = null; // Try block to check for exceptions try { // Giving path where file should exists to read // content GFG = new FileInputStream( \"/home/mayur/GFG.txt\"); } // Catch block to handle exceptions catch (FileNotFoundException e) { // Display message when exception occurs System.out.println(\"File does not exist\"); } }}", "e": 2660, "s": 1871, "text": null }, { "code": null, "e": 2680, "s": 2660, "text": "File does not exist" }, { "code": null, "e": 2896, "s": 2680, "text": "Now let us discuss one more checked exception that is ClassNotFoundException. This Exception occurs when methods like Class.forName() and LoadClass Method etc. are unable to find the given class name as a parameter." }, { "code": null, "e": 2908, "s": 2896, "text": "Example 2-A" }, { "code": null, "e": 2913, "s": 2908, "text": "Java" }, { "code": "// Java Program to Handle Checked Exception // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling the class gfg which is not present in the // current class temp instance of calling class Class temp = Class.forName(\"gfg\"); // It will throw ClassNotFoundException }}", "e": 3313, "s": 2913, "text": null }, { "code": null, "e": 3322, "s": 3313, "text": " Output:" }, { "code": null, "e": 3392, "s": 3322, "text": "Again now let us handle ClassNotFoundException using try-Catch block " }, { "code": null, "e": 3404, "s": 3392, "text": "Example 2-B" }, { "code": null, "e": 3409, "s": 3404, "text": "Java" }, { "code": "// Java Program to Handle Checked Exceptionimport java.io.*;class GFG { public static void main(String[] args) throws ClassNotFoundException { try { Class temp = Class.forName( \"gfg\"); // calling the gfg class } catch (ClassNotFoundException e) { // block executes when mention exception occur System.out.println( \"Class does not exist check the name of the class\"); } }}", "e": 3890, "s": 3409, "text": null }, { "code": null, "e": 3939, "s": 3890, "text": "Class does not exist check the name of the class" }, { "code": null, "e": 3953, "s": 3939, "text": "solankimayank" }, { "code": null, "e": 3962, "s": 3953, "text": "ankur035" }, { "code": null, "e": 3970, "s": 3962, "text": "javaguy" }, { "code": null, "e": 3989, "s": 3970, "text": "java-file-handling" }, { "code": null, "e": 4013, "s": 3989, "text": "Technical Scripter 2020" }, { "code": null, "e": 4018, "s": 4013, "text": "Java" }, { "code": null, "e": 4032, "s": 4018, "text": "Java Programs" }, { "code": null, "e": 4051, "s": 4032, "text": "Technical Scripter" }, { "code": null, "e": 4056, "s": 4051, "text": "Java" } ]
Zulu module in Python
04 May, 2020 Zulu is a drop-in-replacement for native DateTime. In this, all DateTime objects converted into UTC and also stored as UTC. There is an outline between UTC and time zones. Thus, time zones representation is applicable only for conversions to naive DateTime. It supports multiple string formatting using strptime strftime directives and Unicode date patterns. To install this module type the below command in the terminal. pip install zulu zulu.Zulu: The Zulu class used to represent an immutable UTC DateTime object. Any timezone information which is given to it will be converted from timezone to UTC. If there is no timezone information is given, then it is assumed that the DateTime is a UTC value. All types of arithmetic are performed on the Fundamental UTC DateTime object. In this respect, Zulu has no concept of shifting the timezone. In spite of this, localization occurs only when a Zulu object is formatted as a string.Functions or classmethods1. now():- It returns the current UTC date and time as Zulu object .import zulu dt = zulu.now()print("Today date and time is:", dt)Output:Today date and time is: 2020-04-17T16:10:15.708064+00:002. parse(obj, format=None, default_tz=None) :- It will look for an ISO8601 formatted string or a POSIX timestamp by default. While assuming UTC timezone if there is no timezone is given.It returns Zulu object parse from obj.import zulu print("Zulu object when timezone is passed:", zulu.parse('2020-04-17T16:10:15.708064+00:00')) print("Zulu object when only date is passed:", zulu.parse('2020-04-17')) print("Zulu object when date and time is passed:", zulu.parse('2020-04-17 16:10')) print("Zulu object when ISO8601 is passed as formats:", zulu.parse('2020-04-17T16:10:15.708064+00:00', zulu.ISO8601)) print("Zulu object when Default timezone is used :", zulu.parse('2020-04-17', default_tz ='US/Eastern'))Output:Zulu object when timezone is passed: 2020-04-17T16:10:15.708064+00:00Zulu object when only date is passed: 2020-04-17T00:00:00+00:00Zulu object when date and time is passed: 2020-04-17T16:10:00+00:00Zulu object when ISO8601 is passed as formats: 2020-04-17T16:10:15.708064+00:00Zulu object when Default timezone is used : 2020-04-17T04:00:00+00:003. format(format=None, tz=None, locale=’en_US_POSIX’) :Return string datetime using the format of string format. While converting to timezone tz first optionally.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The Datetime string without timezone is:", dt.format('% m/% d/% y % H:% M:% S % z')) print("The Datetime string without timezone is:", dt.format('MM / dd / YY HH:mm:ss Z')) print("The Datetime string when timezone is given is:", dt.format('% Y-% m-% d % H:% M:% S % z', tz ='US/Eastern')) print("The Datetime string when timezone is given as local is:", dt.format('%Y-%m-%d %H:%M:%S %z', tz ='local'))Output:The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string when timezone is given is: 2020-04-17 12:10:15-0400The Datetime string when timezone is given as local is: 2020-04-17 21:40:15+05304. range(frame, start, end) : Range of Zulu instances is returned from start to end and in steps of the given time frame.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') range1 = list(zulu.range('hour', dt, dt.shift(hours = 4)))range2 = list(zulu.range('minute', dt, dt.shift(minutes = 4))) print("The range when time frame is in hour:", range1)print("The range when time frame is in minute:", range2)Output:The range when time frame is in hour: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T17:10:15.708064+00:00]>,<Zulu [2020-04-17T18:10:15.708064+00:00]>,<Zulu [2020-04-17T19:10:15.708064+00:00]>]The range when time frame is in minute: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T16:11:15.708064+00:00]>,<Zulu [2020-04-17T16:12:15.708064+00:00]>,<Zulu [2020-04-17T16:13:15.708064+00:00]>]5. shift(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It can Shift the datetime forward or backward using a timedelta which is being created from the passing arguments and a new Zulu instance is returned.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.shift(hours =-5, minutes = 10) print("The shifted time is:", shifted1) shifted2 = dt.shift(minutes = 55, seconds = 11, microseconds = 10)print("The new shifted time is:", shifted2)Output:The shifted time is: 2020-04-17T11:20:15.708064+00:00 The new shifted time is: 2020-04-17T17:05:26.708074+00:00 6. add(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It add time using a timedelta created from the passed arguments and a new Zulu instance is returned. The first argument is either a ‘timedelta or dateutil.relativedelta object in that case other arguments are ignored and in this datetime object is added.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') shifted = dt.add(minutes = 5)print("The new shifted time zone is :", shifted)Output:The new shifted time zone is : 2020-04-17T16:15:15.708064+00:007. subtract(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0):It subtract time using a timedelta created from the passed arguments and a new Zulu instance is returned. A Zulu, datetime, timedelta or dateutil.relativedelta object can be the first argument in that case other arguments are ignored and in this datetime object is subtracted.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.subtract(hours = 5)shifted2 = dt.subtract(hours = 9).add(minutes = 56) print("The new shifted timezone is:", shifted1)print("The new shifted timezone using both add\ and subtract is:", shifted2)Output:The new shifted timezone is: 2020-04-17T11:10:15.708064+00:00The new shifted timezone using both add and subtract is: 2020-04-17T08:06:15.708064+00:008. replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, fold=None) :It replace the datetime attributes and a new Zulu instance is returned.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') replaced1 = dt.replace(day = 23, hour = 15)print("Replaced time is:", replaced1) replaced2 = dt.replace(minute = 10, second = 11, microsecond = 18)print("The new replaced time is:", replaced2)Output:Replaced time is: 2020-04-23T15:10:15.708064+00:00The new replaced time is: 2020-04-17T16:10:11.000018+00:009. copy() : It return a new ‘Zulu’ instance But with same datetime value.ReturnsZuluimport zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The copied datetime is:", dt.copy())Output:The copied datetime is: 2020-04-17T16:10:15.708064+00:00Since Zulu is immutable. Thus shift, replace, and copy return new Zulu instances while changing the original instance.10. span(frame, count=1) :The two new Zulu objects is returned related to the time span between this object and the time frame which is being given.By default Number of frame which is being spanned is 1.It returns a tuple (start_of_frame, end_of_frame).import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print("The span of a century:", dt.span('century'))print("The span of a month:", dt.span('month'))print("The span of a day:", dt.span('day'))print("The span of a decade:", dt.span('decade'))print("The span of a century with given count is:", dt.span('century', count = 3))Output:The span of a century: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2099-12-31T23:59:59.999999+00:00]>)The span of a month: (<Zulu [2020-04-01T00:00:00+00:00]>, <Zulu [2020-04-30T23:59:59.999999+00:00]>)The span of a day: (<Zulu [2020-04-17T00:00:00+00:00]>, <Zulu [2020-04-17T23:59:59.999999+00:00]>)The span of a decade: (<Zulu [2020-01-01T00:00:00+00:00]>, <Zulu [2029-12-31T23:59:59.999999+00:00]>)The span of a century with given count is: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2299-12-31T23:59:59.999999+00:00]>)11. span_range(frame, start, end) :A range of time spans from the given start till end in the steps of given time frame is returned.import zulu start = zulu.parse('2020-04-17T16:10:15.708064+00:00')end = zulu.parse('2020-04-17T22:10:15.708064+00:00') for span in zulu.span_range('hour', start, end): print(span)Output:(<Zulu [2020-04-17T16:00:00+00:00]>, <Zulu [2020-04-17T16:59:59.999999+00:00]>)(<Zulu [2020-04-17T17:00:00+00:00]>, <Zulu [2020-04-17T17:59:59.999999+00:00]>)(<Zulu [2020-04-17T18:00:00+00:00]>, <Zulu [2020-04-17T18:59:59.999999+00:00]>)(<Zulu [2020-04-17T19:00:00+00:00]>, <Zulu [2020-04-17T19:59:59.999999+00:00]>)(<Zulu [2020-04-17T20:00:00+00:00]>, <Zulu [2020-04-17T20:59:59.999999+00:00]>)(<Zulu [2020-04-17T21:00:00+00:00]>, <Zulu [2020-04-17T21:59:59.999999+00:00]>)12. start_of(frame) : For this datetime it returns the start of the given time frame f.13. start_of_day() :For this datetime it return a new Zulu object/set to the start of the day .import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The start of month is:", dt.start_of('month'))print("The start of day is:", dt.start_of_day())Output:The start of month is: 2020-04-01T00:00:00+00:00 The start of day is: 2020-04-17T00:00:00+00:00 Other start_of functions are:Function NameDescriptionstart_of_century()Return a new Zulu set for this datetime to the start of the century.start_of_decade()Return a new Zulu set for this datetime to the start of the decade.start_of_hour()Return a new Zulu set for this datetime to the start of the hour.start_of_minute()Return a new Zulu set for this datetime to the start of the minute.start_of_month()Return a new Zulu set for this datetime to the start of the month.start_of_second()Return a new Zulu set for this datetime to the start of the second.start_of_year()Return a new Zulu set for this datetime to the start of the year.14. end_of(frame, count=1) :For this datetime it returns the end of the given time frame f.By default Number of frame which is being spanned is 1.15. end_of_day(count=1) :For this datetime it return a new Zulu object/set to the end of the day .By default Number of frame which is being spanned is 1.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The end of month is:", dt.end_of('month', 1))print("The end of day is without count:", dt.end_of_day())print("The end of day is with the count of 2:", dt.end_of_day(2))Output:The end of month is: 2020-04-30T23:59:59.999999+00:00The end of day is without count: 2020-04-17T23:59:59.999999+00:00The end of day is with the count of 2: 2020-04-18T23:59:59.999999+00:00Other end_of functions are:Function NameDescriptionend_of_century(count=1)Return a new Zulu set for this datetime to the end of the century.end_of_decade(count=1)Return a new Zulu set for this datetime to the end of the decade.end_of_hour(count=1)Return a new Zulu set for this datetime to the end of the hour.end_of_minute(count=1)Return a new Zulu set for this datetime to the end of the minute.end_of_month(count=1)Return a new Zulu set for this datetime to the end of the month.end_of_second(count=1)Return a new Zulu set for this datetime to the end of the second.end_of_year(count=1)Return a new Zulu set for this datetime to the end of the year.16. time_from(dt, **options) : It Return the difference between this one and another given datetime in ‘time ago’ .Parametersdtime – A datetime object.Returnsstr17. time_from_now(**options) :It Return the difference between this one and now in “time ago” .18. time_to(dt, **options) :It Return the difference between this datetime and another datetime in “time to”.19. time_to_now(**options) :It Return the difference between this datetime and now in “time to” .import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The difference between this time and end of the day is:", dt.time_from(dt.end_of_day()))print("The difference between this time and end of the day is:", dt.time_to(dt.end_of_day()))print("The difference between this time and start of the day is:", dt.time_from(dt.start_of_day()))print("The difference between this time and start of the day is:", dt.time_to(dt.start_of_day())) print("The difference is", dt.time_from_now())print("The difference is", dt.time_to_now())Output:The difference between this time and end of the day is: 8 hours agoThe difference between this time and end of the day is: in 8 hoursThe difference between this time and start of the day is: in 16 hoursThe difference between this time and start of the day is: 16 hours agoThe difference is 2 days agoThe difference is in 2 days20. astimezone(tz=’local’) :It return the native datetime object shifted to given timezone.By default timezone is local.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')local = dt.astimezone() print("Local timezone is", local) pacific = dt.astimezone('US / Pacific')print("Pacific timezone is:", pacific)Output:Local timezone is 2020-04-17 21:40:15.708064+05:30Pacific timezone is: 2020-04-17 09:10:15.708064-07:0021. timetuple() :It Returns the time tuple.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The timetuple is:", dt.timetuple())OUTPUTThe timetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=-1)22. utcnow() :It return the current UTC date and time.23. utcoffset() :It return the difference in hours, minutes and seonds from corresponding universal time for a particular place.24. utctimetuple() :It Return UTC time tuple coordionated with time.localtime()import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print("The current UTC datetime is:", dt.utcnow())print("The utcoffest is:", dt.utcoffset())print("The utctimetuple is:", dt.utctimetuple())Output:The current UTC datetime is: 2020-04-19T07:17:30.162600+00:00The utcoffest is: 0:00:00The utctimetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=0)Other functions in this class is :Function NameDescriptionctime()Return a ctime() style string.date()Return a date object But with same year, month and day and in same order.datetimeReturns a native datetime object.datetimetuple()Return a datetime tuple which contain year, month, day, hour, minute, second, microsecond, tzoneinfo.datetuple()Return a date tuple which contain year, month, day.days_in_month()Return the total number of days in the monthdst()Return daylight saving timeis_after(other)Return whether this datetime is after other or notis_before(other)Return whether this datetime is before other or notis_between(start, end)Return whether this datetime is between start and end inclusively or notis_leap_year()Return whether this datetime’s year is a leap year or not.is_on_or_after(other)Return whether this datetime is on or after otheris_on_or_before(other)Return whether this datetime is on or before otherisocalendar()Return a 3-tuple which contain ISO year, week number, and weekdayisoformat()Return a string in ISO 8601 format i.e.. YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].isoweekday()Return the day of the week represented by the date E.g. Monday == 1, Tuesday == 2. . . Sunday ==7naiveReturns a native datetime object.strftime()Return format – strftime() style string.strptime()Return string, format – new datetime which is parsed from a string.time()Return a time object with the same time but with timezoneinfo=Nonetimetz()Return a time object but with same time and timezoneinfo.today()Return current date or datetime.toordinal()Return proleptic Julian/Gregorian ordinal.tzname()Return the name of timezone associated with the datetime object.utcfromtimestamp(timestamp)Return a Zulu object from a POSIX timestamp.weekday()Return the day of the week represented by the date. Monday == 0, Tuesday == 1. . . Sunday ==6fromdatetime(dt)Return a Zulu object from a native datetime object.fromgmtime(struct)Return a Zulu object from a tuple like that returned by time.gmtime which represents a UTC datetime.fromlocaltime(struct)Return a Zulu object from a tuple like that returned by time.localtime which represents a local datetime.fromordinal(ordinal)Return Zulu object from a proleptic Julian/Gregorian ordinal.fromtimestamp(timestamp, tz=tzutc())Return Zulu object from a POSIX timestamp. 1. now():- It returns the current UTC date and time as Zulu object . import zulu dt = zulu.now()print("Today date and time is:", dt) Output: Today date and time is: 2020-04-17T16:10:15.708064+00:00 2. parse(obj, format=None, default_tz=None) :- It will look for an ISO8601 formatted string or a POSIX timestamp by default. While assuming UTC timezone if there is no timezone is given.It returns Zulu object parse from obj. import zulu print("Zulu object when timezone is passed:", zulu.parse('2020-04-17T16:10:15.708064+00:00')) print("Zulu object when only date is passed:", zulu.parse('2020-04-17')) print("Zulu object when date and time is passed:", zulu.parse('2020-04-17 16:10')) print("Zulu object when ISO8601 is passed as formats:", zulu.parse('2020-04-17T16:10:15.708064+00:00', zulu.ISO8601)) print("Zulu object when Default timezone is used :", zulu.parse('2020-04-17', default_tz ='US/Eastern')) Output: Zulu object when timezone is passed: 2020-04-17T16:10:15.708064+00:00Zulu object when only date is passed: 2020-04-17T00:00:00+00:00Zulu object when date and time is passed: 2020-04-17T16:10:00+00:00Zulu object when ISO8601 is passed as formats: 2020-04-17T16:10:15.708064+00:00Zulu object when Default timezone is used : 2020-04-17T04:00:00+00:00 3. format(format=None, tz=None, locale=’en_US_POSIX’) :Return string datetime using the format of string format. While converting to timezone tz first optionally. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The Datetime string without timezone is:", dt.format('% m/% d/% y % H:% M:% S % z')) print("The Datetime string without timezone is:", dt.format('MM / dd / YY HH:mm:ss Z')) print("The Datetime string when timezone is given is:", dt.format('% Y-% m-% d % H:% M:% S % z', tz ='US/Eastern')) print("The Datetime string when timezone is given as local is:", dt.format('%Y-%m-%d %H:%M:%S %z', tz ='local')) Output: The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string when timezone is given is: 2020-04-17 12:10:15-0400The Datetime string when timezone is given as local is: 2020-04-17 21:40:15+0530 4. range(frame, start, end) : Range of Zulu instances is returned from start to end and in steps of the given time frame. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') range1 = list(zulu.range('hour', dt, dt.shift(hours = 4)))range2 = list(zulu.range('minute', dt, dt.shift(minutes = 4))) print("The range when time frame is in hour:", range1)print("The range when time frame is in minute:", range2) Output: The range when time frame is in hour: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T17:10:15.708064+00:00]>,<Zulu [2020-04-17T18:10:15.708064+00:00]>,<Zulu [2020-04-17T19:10:15.708064+00:00]>]The range when time frame is in minute: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T16:11:15.708064+00:00]>,<Zulu [2020-04-17T16:12:15.708064+00:00]>,<Zulu [2020-04-17T16:13:15.708064+00:00]>] 5. shift(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It can Shift the datetime forward or backward using a timedelta which is being created from the passing arguments and a new Zulu instance is returned. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.shift(hours =-5, minutes = 10) print("The shifted time is:", shifted1) shifted2 = dt.shift(minutes = 55, seconds = 11, microseconds = 10)print("The new shifted time is:", shifted2) Output: The shifted time is: 2020-04-17T11:20:15.708064+00:00 The new shifted time is: 2020-04-17T17:05:26.708074+00:00 6. add(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It add time using a timedelta created from the passed arguments and a new Zulu instance is returned. The first argument is either a ‘timedelta or dateutil.relativedelta object in that case other arguments are ignored and in this datetime object is added. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') shifted = dt.add(minutes = 5)print("The new shifted time zone is :", shifted) Output: The new shifted time zone is : 2020-04-17T16:15:15.708064+00:00 7. subtract(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0):It subtract time using a timedelta created from the passed arguments and a new Zulu instance is returned. A Zulu, datetime, timedelta or dateutil.relativedelta object can be the first argument in that case other arguments are ignored and in this datetime object is subtracted. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.subtract(hours = 5)shifted2 = dt.subtract(hours = 9).add(minutes = 56) print("The new shifted timezone is:", shifted1)print("The new shifted timezone using both add\ and subtract is:", shifted2) Output: The new shifted timezone is: 2020-04-17T11:10:15.708064+00:00The new shifted timezone using both add and subtract is: 2020-04-17T08:06:15.708064+00:00 8. replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, fold=None) :It replace the datetime attributes and a new Zulu instance is returned. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') replaced1 = dt.replace(day = 23, hour = 15)print("Replaced time is:", replaced1) replaced2 = dt.replace(minute = 10, second = 11, microsecond = 18)print("The new replaced time is:", replaced2) Output: Replaced time is: 2020-04-23T15:10:15.708064+00:00The new replaced time is: 2020-04-17T16:10:11.000018+00:00 9. copy() : It return a new ‘Zulu’ instance But with same datetime value.ReturnsZulu import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The copied datetime is:", dt.copy()) Output: The copied datetime is: 2020-04-17T16:10:15.708064+00:00 Since Zulu is immutable. Thus shift, replace, and copy return new Zulu instances while changing the original instance. 10. span(frame, count=1) :The two new Zulu objects is returned related to the time span between this object and the time frame which is being given.By default Number of frame which is being spanned is 1.It returns a tuple (start_of_frame, end_of_frame). import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print("The span of a century:", dt.span('century'))print("The span of a month:", dt.span('month'))print("The span of a day:", dt.span('day'))print("The span of a decade:", dt.span('decade'))print("The span of a century with given count is:", dt.span('century', count = 3)) Output: The span of a century: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2099-12-31T23:59:59.999999+00:00]>)The span of a month: (<Zulu [2020-04-01T00:00:00+00:00]>, <Zulu [2020-04-30T23:59:59.999999+00:00]>)The span of a day: (<Zulu [2020-04-17T00:00:00+00:00]>, <Zulu [2020-04-17T23:59:59.999999+00:00]>)The span of a decade: (<Zulu [2020-01-01T00:00:00+00:00]>, <Zulu [2029-12-31T23:59:59.999999+00:00]>)The span of a century with given count is: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2299-12-31T23:59:59.999999+00:00]>) 11. span_range(frame, start, end) :A range of time spans from the given start till end in the steps of given time frame is returned. import zulu start = zulu.parse('2020-04-17T16:10:15.708064+00:00')end = zulu.parse('2020-04-17T22:10:15.708064+00:00') for span in zulu.span_range('hour', start, end): print(span) Output: (<Zulu [2020-04-17T16:00:00+00:00]>, <Zulu [2020-04-17T16:59:59.999999+00:00]>)(<Zulu [2020-04-17T17:00:00+00:00]>, <Zulu [2020-04-17T17:59:59.999999+00:00]>)(<Zulu [2020-04-17T18:00:00+00:00]>, <Zulu [2020-04-17T18:59:59.999999+00:00]>)(<Zulu [2020-04-17T19:00:00+00:00]>, <Zulu [2020-04-17T19:59:59.999999+00:00]>)(<Zulu [2020-04-17T20:00:00+00:00]>, <Zulu [2020-04-17T20:59:59.999999+00:00]>)(<Zulu [2020-04-17T21:00:00+00:00]>, <Zulu [2020-04-17T21:59:59.999999+00:00]>) 12. start_of(frame) : For this datetime it returns the start of the given time frame f. 13. start_of_day() :For this datetime it return a new Zulu object/set to the start of the day . import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The start of month is:", dt.start_of('month'))print("The start of day is:", dt.start_of_day()) Output: The start of month is: 2020-04-01T00:00:00+00:00 The start of day is: 2020-04-17T00:00:00+00:00 Other start_of functions are: 14. end_of(frame, count=1) :For this datetime it returns the end of the given time frame f.By default Number of frame which is being spanned is 1. 15. end_of_day(count=1) :For this datetime it return a new Zulu object/set to the end of the day .By default Number of frame which is being spanned is 1. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The end of month is:", dt.end_of('month', 1))print("The end of day is without count:", dt.end_of_day())print("The end of day is with the count of 2:", dt.end_of_day(2)) Output: The end of month is: 2020-04-30T23:59:59.999999+00:00The end of day is without count: 2020-04-17T23:59:59.999999+00:00The end of day is with the count of 2: 2020-04-18T23:59:59.999999+00:00 Other end_of functions are: 16. time_from(dt, **options) : It Return the difference between this one and another given datetime in ‘time ago’ .Parameters dtime – A datetime object. Returnsstr 17. time_from_now(**options) :It Return the difference between this one and now in “time ago” . 18. time_to(dt, **options) :It Return the difference between this datetime and another datetime in “time to”. 19. time_to_now(**options) :It Return the difference between this datetime and now in “time to” . import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print("The difference between this time and end of the day is:", dt.time_from(dt.end_of_day()))print("The difference between this time and end of the day is:", dt.time_to(dt.end_of_day()))print("The difference between this time and start of the day is:", dt.time_from(dt.start_of_day()))print("The difference between this time and start of the day is:", dt.time_to(dt.start_of_day())) print("The difference is", dt.time_from_now())print("The difference is", dt.time_to_now()) Output: The difference between this time and end of the day is: 8 hours agoThe difference between this time and end of the day is: in 8 hoursThe difference between this time and start of the day is: in 16 hoursThe difference between this time and start of the day is: 16 hours agoThe difference is 2 days agoThe difference is in 2 days 20. astimezone(tz=’local’) :It return the native datetime object shifted to given timezone.By default timezone is local. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')local = dt.astimezone() print("Local timezone is", local) pacific = dt.astimezone('US / Pacific')print("Pacific timezone is:", pacific) Output: Local timezone is 2020-04-17 21:40:15.708064+05:30Pacific timezone is: 2020-04-17 09:10:15.708064-07:00 21. timetuple() :It Returns the time tuple. import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print("The timetuple is:", dt.timetuple()) OUTPUT The timetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=-1) 22. utcnow() :It return the current UTC date and time. 23. utcoffset() :It return the difference in hours, minutes and seonds from corresponding universal time for a particular place. 24. utctimetuple() :It Return UTC time tuple coordionated with time.localtime() import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print("The current UTC datetime is:", dt.utcnow())print("The utcoffest is:", dt.utcoffset())print("The utctimetuple is:", dt.utctimetuple()) Output: The current UTC datetime is: 2020-04-19T07:17:30.162600+00:00The utcoffest is: 0:00:00The utctimetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=0) Other functions in this class is : zulu.Delta :-It is an extended version of datetime.timedelta that provides new functionality.Functions or classmethods1. parse_delta(obj) :It return Delta object parsed from the given obj.import zulu delta1 = zulu.parse_delta('4h 45m')delta2 = zulu.parse_delta('-4h 45m') print("The delta is:", delta1)print("The delta is:", delta2)Output:The delta is: 4:45:00 The delta is: -1 day, 19:15:00 2. format(format=’long’, granularity=’second’, threshold=0.85, add_direction=False, locale=None) : Return timedelta as a formatted string.import zulu delta = zulu.parse_delta('4h 45m') print("The timedelta with given granularity is:", delta.format(granularity ='day')) print("The timedelta with given locale is:", delta.format(locale ='de')) print("The timedelta with given locale and add_direction is:", delta.format(locale ='fr', add_direction = True)) print("The timedelta with given threshold is:", delta.format(threshold = 5)) print("The timedelta with given threshold and granularity is:", delta.format(threshold = 155, granularity ='minute'))Output:The timedelta with given granularity is: 1 dayThe timedelta with given locale is: 5 StundenThe timedelta with given locale and add_direction is: dans 5 heuresThe timedelta with given threshold is: 285 minutesThe timedelta with given threshold and granularity is: 285 minutes3. fromtimedelta(delta) :From a native timedelta object it return Delta object.import zulu delta = zulu.parse_delta('4h 45m')delta1 = zulu.parse_delta('6h 42m 11s') print("The timedelta is:", delta.fromtimedelta(delta1))Output:The timedelta is: 6:42:11 1. parse_delta(obj) :It return Delta object parsed from the given obj. import zulu delta1 = zulu.parse_delta('4h 45m')delta2 = zulu.parse_delta('-4h 45m') print("The delta is:", delta1)print("The delta is:", delta2) Output: The delta is: 4:45:00 The delta is: -1 day, 19:15:00 2. format(format=’long’, granularity=’second’, threshold=0.85, add_direction=False, locale=None) : Return timedelta as a formatted string. import zulu delta = zulu.parse_delta('4h 45m') print("The timedelta with given granularity is:", delta.format(granularity ='day')) print("The timedelta with given locale is:", delta.format(locale ='de')) print("The timedelta with given locale and add_direction is:", delta.format(locale ='fr', add_direction = True)) print("The timedelta with given threshold is:", delta.format(threshold = 5)) print("The timedelta with given threshold and granularity is:", delta.format(threshold = 155, granularity ='minute')) Output: The timedelta with given granularity is: 1 dayThe timedelta with given locale is: 5 StundenThe timedelta with given locale and add_direction is: dans 5 heuresThe timedelta with given threshold is: 285 minutesThe timedelta with given threshold and granularity is: 285 minutes 3. fromtimedelta(delta) :From a native timedelta object it return Delta object. import zulu delta = zulu.parse_delta('4h 45m')delta1 = zulu.parse_delta('6h 42m 11s') print("The timedelta is:", delta.fromtimedelta(delta1)) Output: The timedelta is: 6:42:11 zulu.ParseError :-It raised Exception when an object is not able to be parsed as a datetime. python-modules 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": "\n04 May, 2020" }, { "code": null, "e": 387, "s": 28, "text": "Zulu is a drop-in-replacement for native DateTime. In this, all DateTime objects converted into UTC and also stored as UTC. There is an outline between UTC and time zones. Thus, time zones representation is applicable only for conversions to naive DateTime. It supports multiple string formatting using strptime strftime directives and Unicode date patterns." }, { "code": null, "e": 450, "s": 387, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 467, "s": 450, "text": "pip install zulu" }, { "code": null, "e": 16730, "s": 467, "text": "zulu.Zulu: The Zulu class used to represent an immutable UTC DateTime object. Any timezone information which is given to it will be converted from timezone to UTC. If there is no timezone information is given, then it is assumed that the DateTime is a UTC value. All types of arithmetic are performed on the Fundamental UTC DateTime object. In this respect, Zulu has no concept of shifting the timezone. In spite of this, localization occurs only when a Zulu object is formatted as a string.Functions or classmethods1. now():- It returns the current UTC date and time as Zulu object .import zulu dt = zulu.now()print(\"Today date and time is:\", dt)Output:Today date and time is: 2020-04-17T16:10:15.708064+00:002. parse(obj, format=None, default_tz=None) :- It will look for an ISO8601 formatted string or a POSIX timestamp by default. While assuming UTC timezone if there is no timezone is given.It returns Zulu object parse from obj.import zulu print(\"Zulu object when timezone is passed:\", zulu.parse('2020-04-17T16:10:15.708064+00:00')) print(\"Zulu object when only date is passed:\", zulu.parse('2020-04-17')) print(\"Zulu object when date and time is passed:\", zulu.parse('2020-04-17 16:10')) print(\"Zulu object when ISO8601 is passed as formats:\", zulu.parse('2020-04-17T16:10:15.708064+00:00', zulu.ISO8601)) print(\"Zulu object when Default timezone is used :\", zulu.parse('2020-04-17', default_tz ='US/Eastern'))Output:Zulu object when timezone is passed: 2020-04-17T16:10:15.708064+00:00Zulu object when only date is passed: 2020-04-17T00:00:00+00:00Zulu object when date and time is passed: 2020-04-17T16:10:00+00:00Zulu object when ISO8601 is passed as formats: 2020-04-17T16:10:15.708064+00:00Zulu object when Default timezone is used : 2020-04-17T04:00:00+00:003. format(format=None, tz=None, locale=’en_US_POSIX’) :Return string datetime using the format of string format. While converting to timezone tz first optionally.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The Datetime string without timezone is:\", dt.format('% m/% d/% y % H:% M:% S % z')) print(\"The Datetime string without timezone is:\", dt.format('MM / dd / YY HH:mm:ss Z')) print(\"The Datetime string when timezone is given is:\", dt.format('% Y-% m-% d % H:% M:% S % z', tz ='US/Eastern')) print(\"The Datetime string when timezone is given as local is:\", dt.format('%Y-%m-%d %H:%M:%S %z', tz ='local'))Output:The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string when timezone is given is: 2020-04-17 12:10:15-0400The Datetime string when timezone is given as local is: 2020-04-17 21:40:15+05304. range(frame, start, end) : Range of Zulu instances is returned from start to end and in steps of the given time frame.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') range1 = list(zulu.range('hour', dt, dt.shift(hours = 4)))range2 = list(zulu.range('minute', dt, dt.shift(minutes = 4))) print(\"The range when time frame is in hour:\", range1)print(\"The range when time frame is in minute:\", range2)Output:The range when time frame is in hour: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T17:10:15.708064+00:00]>,<Zulu [2020-04-17T18:10:15.708064+00:00]>,<Zulu [2020-04-17T19:10:15.708064+00:00]>]The range when time frame is in minute: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T16:11:15.708064+00:00]>,<Zulu [2020-04-17T16:12:15.708064+00:00]>,<Zulu [2020-04-17T16:13:15.708064+00:00]>]5. shift(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It can Shift the datetime forward or backward using a timedelta which is being created from the passing arguments and a new Zulu instance is returned.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.shift(hours =-5, minutes = 10) print(\"The shifted time is:\", shifted1) shifted2 = dt.shift(minutes = 55, seconds = 11, microseconds = 10)print(\"The new shifted time is:\", shifted2)Output:The shifted time is: 2020-04-17T11:20:15.708064+00:00\nThe new shifted time is: 2020-04-17T17:05:26.708074+00:00\n6. add(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It add time using a timedelta created from the passed arguments and a new Zulu instance is returned. The first argument is either a ‘timedelta or dateutil.relativedelta object in that case other arguments are ignored and in this datetime object is added.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') shifted = dt.add(minutes = 5)print(\"The new shifted time zone is :\", shifted)Output:The new shifted time zone is : 2020-04-17T16:15:15.708064+00:007. subtract(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0):It subtract time using a timedelta created from the passed arguments and a new Zulu instance is returned. A Zulu, datetime, timedelta or dateutil.relativedelta object can be the first argument in that case other arguments are ignored and in this datetime object is subtracted.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.subtract(hours = 5)shifted2 = dt.subtract(hours = 9).add(minutes = 56) print(\"The new shifted timezone is:\", shifted1)print(\"The new shifted timezone using both add\\ and subtract is:\", shifted2)Output:The new shifted timezone is: 2020-04-17T11:10:15.708064+00:00The new shifted timezone using both add and subtract is: 2020-04-17T08:06:15.708064+00:008. replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, fold=None) :It replace the datetime attributes and a new Zulu instance is returned.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') replaced1 = dt.replace(day = 23, hour = 15)print(\"Replaced time is:\", replaced1) replaced2 = dt.replace(minute = 10, second = 11, microsecond = 18)print(\"The new replaced time is:\", replaced2)Output:Replaced time is: 2020-04-23T15:10:15.708064+00:00The new replaced time is: 2020-04-17T16:10:11.000018+00:009. copy() : It return a new ‘Zulu’ instance But with same datetime value.ReturnsZuluimport zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The copied datetime is:\", dt.copy())Output:The copied datetime is: 2020-04-17T16:10:15.708064+00:00Since Zulu is immutable. Thus shift, replace, and copy return new Zulu instances while changing the original instance.10. span(frame, count=1) :The two new Zulu objects is returned related to the time span between this object and the time frame which is being given.By default Number of frame which is being spanned is 1.It returns a tuple (start_of_frame, end_of_frame).import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print(\"The span of a century:\", dt.span('century'))print(\"The span of a month:\", dt.span('month'))print(\"The span of a day:\", dt.span('day'))print(\"The span of a decade:\", dt.span('decade'))print(\"The span of a century with given count is:\", dt.span('century', count = 3))Output:The span of a century: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2099-12-31T23:59:59.999999+00:00]>)The span of a month: (<Zulu [2020-04-01T00:00:00+00:00]>, <Zulu [2020-04-30T23:59:59.999999+00:00]>)The span of a day: (<Zulu [2020-04-17T00:00:00+00:00]>, <Zulu [2020-04-17T23:59:59.999999+00:00]>)The span of a decade: (<Zulu [2020-01-01T00:00:00+00:00]>, <Zulu [2029-12-31T23:59:59.999999+00:00]>)The span of a century with given count is: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2299-12-31T23:59:59.999999+00:00]>)11. span_range(frame, start, end) :A range of time spans from the given start till end in the steps of given time frame is returned.import zulu start = zulu.parse('2020-04-17T16:10:15.708064+00:00')end = zulu.parse('2020-04-17T22:10:15.708064+00:00') for span in zulu.span_range('hour', start, end): print(span)Output:(<Zulu [2020-04-17T16:00:00+00:00]>, <Zulu [2020-04-17T16:59:59.999999+00:00]>)(<Zulu [2020-04-17T17:00:00+00:00]>, <Zulu [2020-04-17T17:59:59.999999+00:00]>)(<Zulu [2020-04-17T18:00:00+00:00]>, <Zulu [2020-04-17T18:59:59.999999+00:00]>)(<Zulu [2020-04-17T19:00:00+00:00]>, <Zulu [2020-04-17T19:59:59.999999+00:00]>)(<Zulu [2020-04-17T20:00:00+00:00]>, <Zulu [2020-04-17T20:59:59.999999+00:00]>)(<Zulu [2020-04-17T21:00:00+00:00]>, <Zulu [2020-04-17T21:59:59.999999+00:00]>)12. start_of(frame) : For this datetime it returns the start of the given time frame f.13. start_of_day() :For this datetime it return a new Zulu object/set to the start of the day .import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The start of month is:\", dt.start_of('month'))print(\"The start of day is:\", dt.start_of_day())Output:The start of month is: 2020-04-01T00:00:00+00:00\nThe start of day is: 2020-04-17T00:00:00+00:00\nOther start_of functions are:Function NameDescriptionstart_of_century()Return a new Zulu set for this datetime to the start of the century.start_of_decade()Return a new Zulu set for this datetime to the start of the decade.start_of_hour()Return a new Zulu set for this datetime to the start of the hour.start_of_minute()Return a new Zulu set for this datetime to the start of the minute.start_of_month()Return a new Zulu set for this datetime to the start of the month.start_of_second()Return a new Zulu set for this datetime to the start of the second.start_of_year()Return a new Zulu set for this datetime to the start of the year.14. end_of(frame, count=1) :For this datetime it returns the end of the given time frame f.By default Number of frame which is being spanned is 1.15. end_of_day(count=1) :For this datetime it return a new Zulu object/set to the end of the day .By default Number of frame which is being spanned is 1.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The end of month is:\", dt.end_of('month', 1))print(\"The end of day is without count:\", dt.end_of_day())print(\"The end of day is with the count of 2:\", dt.end_of_day(2))Output:The end of month is: 2020-04-30T23:59:59.999999+00:00The end of day is without count: 2020-04-17T23:59:59.999999+00:00The end of day is with the count of 2: 2020-04-18T23:59:59.999999+00:00Other end_of functions are:Function NameDescriptionend_of_century(count=1)Return a new Zulu set for this datetime to the end of the century.end_of_decade(count=1)Return a new Zulu set for this datetime to the end of the decade.end_of_hour(count=1)Return a new Zulu set for this datetime to the end of the hour.end_of_minute(count=1)Return a new Zulu set for this datetime to the end of the minute.end_of_month(count=1)Return a new Zulu set for this datetime to the end of the month.end_of_second(count=1)Return a new Zulu set for this datetime to the end of the second.end_of_year(count=1)Return a new Zulu set for this datetime to the end of the year.16. time_from(dt, **options) : It Return the difference between this one and another given datetime in ‘time ago’ .Parametersdtime – A datetime object.Returnsstr17. time_from_now(**options) :It Return the difference between this one and now in “time ago” .18. time_to(dt, **options) :It Return the difference between this datetime and another datetime in “time to”.19. time_to_now(**options) :It Return the difference between this datetime and now in “time to” .import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The difference between this time and end of the day is:\", dt.time_from(dt.end_of_day()))print(\"The difference between this time and end of the day is:\", dt.time_to(dt.end_of_day()))print(\"The difference between this time and start of the day is:\", dt.time_from(dt.start_of_day()))print(\"The difference between this time and start of the day is:\", dt.time_to(dt.start_of_day())) print(\"The difference is\", dt.time_from_now())print(\"The difference is\", dt.time_to_now())Output:The difference between this time and end of the day is: 8 hours agoThe difference between this time and end of the day is: in 8 hoursThe difference between this time and start of the day is: in 16 hoursThe difference between this time and start of the day is: 16 hours agoThe difference is 2 days agoThe difference is in 2 days20. astimezone(tz=’local’) :It return the native datetime object shifted to given timezone.By default timezone is local.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')local = dt.astimezone() print(\"Local timezone is\", local) pacific = dt.astimezone('US / Pacific')print(\"Pacific timezone is:\", pacific)Output:Local timezone is 2020-04-17 21:40:15.708064+05:30Pacific timezone is: 2020-04-17 09:10:15.708064-07:0021. timetuple() :It Returns the time tuple.import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The timetuple is:\", dt.timetuple())OUTPUTThe timetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=-1)22. utcnow() :It return the current UTC date and time.23. utcoffset() :It return the difference in hours, minutes and seonds from corresponding universal time for a particular place.24. utctimetuple() :It Return UTC time tuple coordionated with time.localtime()import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print(\"The current UTC datetime is:\", dt.utcnow())print(\"The utcoffest is:\", dt.utcoffset())print(\"The utctimetuple is:\", dt.utctimetuple())Output:The current UTC datetime is: 2020-04-19T07:17:30.162600+00:00The utcoffest is: 0:00:00The utctimetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=0)Other functions in this class is :Function NameDescriptionctime()Return a ctime() style string.date()Return a date object But with same year, month and day and in same order.datetimeReturns a native datetime object.datetimetuple()Return a datetime tuple which contain year, month, day, hour, minute, second, microsecond, tzoneinfo.datetuple()Return a date tuple which contain year, month, day.days_in_month()Return the total number of days in the monthdst()Return daylight saving timeis_after(other)Return whether this datetime is after other or notis_before(other)Return whether this datetime is before other or notis_between(start, end)Return whether this datetime is between start and end inclusively or notis_leap_year()Return whether this datetime’s year is a leap year or not.is_on_or_after(other)Return whether this datetime is on or after otheris_on_or_before(other)Return whether this datetime is on or before otherisocalendar()Return a 3-tuple which contain ISO year, week number, and weekdayisoformat()Return a string in ISO 8601 format i.e.. YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].isoweekday()Return the day of the week represented by the date E.g. Monday == 1, Tuesday == 2. . . Sunday ==7naiveReturns a native datetime object.strftime()Return format – strftime() style string.strptime()Return string, format – new datetime which is parsed from a string.time()Return a time object with the same time but with timezoneinfo=Nonetimetz()Return a time object but with same time and timezoneinfo.today()Return current date or datetime.toordinal()Return proleptic Julian/Gregorian ordinal.tzname()Return the name of timezone associated with the datetime object.utcfromtimestamp(timestamp)Return a Zulu object from a POSIX timestamp.weekday()Return the day of the week represented by the date. Monday == 0, Tuesday == 1. . . Sunday ==6fromdatetime(dt)Return a Zulu object from a native datetime object.fromgmtime(struct)Return a Zulu object from a tuple like that returned by time.gmtime which represents a UTC datetime.fromlocaltime(struct)Return a Zulu object from a tuple like that returned by time.localtime which represents a local datetime.fromordinal(ordinal)Return Zulu object from a proleptic Julian/Gregorian ordinal.fromtimestamp(timestamp, tz=tzutc())Return Zulu object from a POSIX timestamp." }, { "code": null, "e": 16799, "s": 16730, "text": "1. now():- It returns the current UTC date and time as Zulu object ." }, { "code": "import zulu dt = zulu.now()print(\"Today date and time is:\", dt)", "e": 16866, "s": 16799, "text": null }, { "code": null, "e": 16874, "s": 16866, "text": "Output:" }, { "code": null, "e": 16931, "s": 16874, "text": "Today date and time is: 2020-04-17T16:10:15.708064+00:00" }, { "code": null, "e": 17156, "s": 16931, "text": "2. parse(obj, format=None, default_tz=None) :- It will look for an ISO8601 formatted string or a POSIX timestamp by default. While assuming UTC timezone if there is no timezone is given.It returns Zulu object parse from obj." }, { "code": "import zulu print(\"Zulu object when timezone is passed:\", zulu.parse('2020-04-17T16:10:15.708064+00:00')) print(\"Zulu object when only date is passed:\", zulu.parse('2020-04-17')) print(\"Zulu object when date and time is passed:\", zulu.parse('2020-04-17 16:10')) print(\"Zulu object when ISO8601 is passed as formats:\", zulu.parse('2020-04-17T16:10:15.708064+00:00', zulu.ISO8601)) print(\"Zulu object when Default timezone is used :\", zulu.parse('2020-04-17', default_tz ='US/Eastern'))", "e": 17708, "s": 17156, "text": null }, { "code": null, "e": 17716, "s": 17708, "text": "Output:" }, { "code": null, "e": 18064, "s": 17716, "text": "Zulu object when timezone is passed: 2020-04-17T16:10:15.708064+00:00Zulu object when only date is passed: 2020-04-17T00:00:00+00:00Zulu object when date and time is passed: 2020-04-17T16:10:00+00:00Zulu object when ISO8601 is passed as formats: 2020-04-17T16:10:15.708064+00:00Zulu object when Default timezone is used : 2020-04-17T04:00:00+00:00" }, { "code": null, "e": 18227, "s": 18064, "text": "3. format(format=None, tz=None, locale=’en_US_POSIX’) :Return string datetime using the format of string format. While converting to timezone tz first optionally." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The Datetime string without timezone is:\", dt.format('% m/% d/% y % H:% M:% S % z')) print(\"The Datetime string without timezone is:\", dt.format('MM / dd / YY HH:mm:ss Z')) print(\"The Datetime string when timezone is given is:\", dt.format('% Y-% m-% d % H:% M:% S % z', tz ='US/Eastern')) print(\"The Datetime string when timezone is given as local is:\", dt.format('%Y-%m-%d %H:%M:%S %z', tz ='local'))", "e": 18763, "s": 18227, "text": null }, { "code": null, "e": 18771, "s": 18763, "text": "Output:" }, { "code": null, "e": 19051, "s": 18771, "text": "The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string without timezone is: 04/17/20 16:10:15 +0000The Datetime string when timezone is given is: 2020-04-17 12:10:15-0400The Datetime string when timezone is given as local is: 2020-04-17 21:40:15+0530" }, { "code": null, "e": 19173, "s": 19051, "text": "4. range(frame, start, end) : Range of Zulu instances is returned from start to end and in steps of the given time frame." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') range1 = list(zulu.range('hour', dt, dt.shift(hours = 4)))range2 = list(zulu.range('minute', dt, dt.shift(minutes = 4))) print(\"The range when time frame is in hour:\", range1)print(\"The range when time frame is in minute:\", range2)", "e": 19535, "s": 19173, "text": null }, { "code": null, "e": 19543, "s": 19535, "text": "Output:" }, { "code": null, "e": 19960, "s": 19543, "text": "The range when time frame is in hour: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T17:10:15.708064+00:00]>,<Zulu [2020-04-17T18:10:15.708064+00:00]>,<Zulu [2020-04-17T19:10:15.708064+00:00]>]The range when time frame is in minute: [<Zulu [2020-04-17T16:10:15.708064+00:00]>,<Zulu [2020-04-17T16:11:15.708064+00:00]>,<Zulu [2020-04-17T16:12:15.708064+00:00]>,<Zulu [2020-04-17T16:13:15.708064+00:00]>]" }, { "code": null, "e": 20216, "s": 19960, "text": "5. shift(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It can Shift the datetime forward or backward using a timedelta which is being created from the passing arguments and a new Zulu instance is returned." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.shift(hours =-5, minutes = 10) print(\"The shifted time is:\", shifted1) shifted2 = dt.shift(minutes = 55, seconds = 11, microseconds = 10)print(\"The new shifted time is:\", shifted2)", "e": 20498, "s": 20216, "text": null }, { "code": null, "e": 20506, "s": 20498, "text": "Output:" }, { "code": null, "e": 20619, "s": 20506, "text": "The shifted time is: 2020-04-17T11:20:15.708064+00:00\nThe new shifted time is: 2020-04-17T17:05:26.708074+00:00\n" }, { "code": null, "e": 20977, "s": 20619, "text": "6. add(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0) :It add time using a timedelta created from the passed arguments and a new Zulu instance is returned. The first argument is either a ‘timedelta or dateutil.relativedelta object in that case other arguments are ignored and in this datetime object is added." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') shifted = dt.add(minutes = 5)print(\"The new shifted time zone is :\", shifted)", "e": 21123, "s": 20977, "text": null }, { "code": null, "e": 21131, "s": 21123, "text": "Output:" }, { "code": null, "e": 21195, "s": 21131, "text": "The new shifted time zone is : 2020-04-17T16:15:15.708064+00:00" }, { "code": null, "e": 21579, "s": 21195, "text": "7. subtract(other=None, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0):It subtract time using a timedelta created from the passed arguments and a new Zulu instance is returned. A Zulu, datetime, timedelta or dateutil.relativedelta object can be the first argument in that case other arguments are ignored and in this datetime object is subtracted." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00')shifted1 = dt.subtract(hours = 5)shifted2 = dt.subtract(hours = 9).add(minutes = 56) print(\"The new shifted timezone is:\", shifted1)print(\"The new shifted timezone using both add\\ and subtract is:\", shifted2)", "e": 21855, "s": 21579, "text": null }, { "code": null, "e": 21863, "s": 21855, "text": "Output:" }, { "code": null, "e": 22014, "s": 21863, "text": "The new shifted timezone is: 2020-04-17T11:10:15.708064+00:00The new shifted timezone using both add and subtract is: 2020-04-17T08:06:15.708064+00:00" }, { "code": null, "e": 22213, "s": 22014, "text": "8. replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, fold=None) :It replace the datetime attributes and a new Zulu instance is returned." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') replaced1 = dt.replace(day = 23, hour = 15)print(\"Replaced time is:\", replaced1) replaced2 = dt.replace(minute = 10, second = 11, microsecond = 18)print(\"The new replaced time is:\", replaced2)", "e": 22497, "s": 22213, "text": null }, { "code": null, "e": 22505, "s": 22497, "text": "Output:" }, { "code": null, "e": 22614, "s": 22505, "text": "Replaced time is: 2020-04-23T15:10:15.708064+00:00The new replaced time is: 2020-04-17T16:10:11.000018+00:00" }, { "code": null, "e": 22699, "s": 22614, "text": "9. copy() : It return a new ‘Zulu’ instance But with same datetime value.ReturnsZulu" }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The copied datetime is:\", dt.copy())", "e": 22811, "s": 22699, "text": null }, { "code": null, "e": 22819, "s": 22811, "text": "Output:" }, { "code": null, "e": 22876, "s": 22819, "text": "The copied datetime is: 2020-04-17T16:10:15.708064+00:00" }, { "code": null, "e": 22995, "s": 22876, "text": "Since Zulu is immutable. Thus shift, replace, and copy return new Zulu instances while changing the original instance." }, { "code": null, "e": 23249, "s": 22995, "text": "10. span(frame, count=1) :The two new Zulu objects is returned related to the time span between this object and the time frame which is being given.By default Number of frame which is being spanned is 1.It returns a tuple (start_of_frame, end_of_frame)." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print(\"The span of a century:\", dt.span('century'))print(\"The span of a month:\", dt.span('month'))print(\"The span of a day:\", dt.span('day'))print(\"The span of a decade:\", dt.span('decade'))print(\"The span of a century with given count is:\", dt.span('century', count = 3))", "e": 23598, "s": 23249, "text": null }, { "code": null, "e": 23606, "s": 23598, "text": "Output:" }, { "code": null, "e": 24130, "s": 23606, "text": "The span of a century: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2099-12-31T23:59:59.999999+00:00]>)The span of a month: (<Zulu [2020-04-01T00:00:00+00:00]>, <Zulu [2020-04-30T23:59:59.999999+00:00]>)The span of a day: (<Zulu [2020-04-17T00:00:00+00:00]>, <Zulu [2020-04-17T23:59:59.999999+00:00]>)The span of a decade: (<Zulu [2020-01-01T00:00:00+00:00]>, <Zulu [2029-12-31T23:59:59.999999+00:00]>)The span of a century with given count is: (<Zulu [2000-01-01T00:00:00+00:00]>, <Zulu [2299-12-31T23:59:59.999999+00:00]>)" }, { "code": null, "e": 24263, "s": 24130, "text": "11. span_range(frame, start, end) :A range of time spans from the given start till end in the steps of given time frame is returned." }, { "code": "import zulu start = zulu.parse('2020-04-17T16:10:15.708064+00:00')end = zulu.parse('2020-04-17T22:10:15.708064+00:00') for span in zulu.span_range('hour', start, end): print(span)", "e": 24450, "s": 24263, "text": null }, { "code": null, "e": 24458, "s": 24450, "text": "Output:" }, { "code": null, "e": 24933, "s": 24458, "text": "(<Zulu [2020-04-17T16:00:00+00:00]>, <Zulu [2020-04-17T16:59:59.999999+00:00]>)(<Zulu [2020-04-17T17:00:00+00:00]>, <Zulu [2020-04-17T17:59:59.999999+00:00]>)(<Zulu [2020-04-17T18:00:00+00:00]>, <Zulu [2020-04-17T18:59:59.999999+00:00]>)(<Zulu [2020-04-17T19:00:00+00:00]>, <Zulu [2020-04-17T19:59:59.999999+00:00]>)(<Zulu [2020-04-17T20:00:00+00:00]>, <Zulu [2020-04-17T20:59:59.999999+00:00]>)(<Zulu [2020-04-17T21:00:00+00:00]>, <Zulu [2020-04-17T21:59:59.999999+00:00]>)" }, { "code": null, "e": 25021, "s": 24933, "text": "12. start_of(frame) : For this datetime it returns the start of the given time frame f." }, { "code": null, "e": 25117, "s": 25021, "text": "13. start_of_day() :For this datetime it return a new Zulu object/set to the start of the day ." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The start of month is:\", dt.start_of('month'))print(\"The start of day is:\", dt.start_of_day())", "e": 25287, "s": 25117, "text": null }, { "code": null, "e": 25295, "s": 25287, "text": "Output:" }, { "code": null, "e": 25392, "s": 25295, "text": "The start of month is: 2020-04-01T00:00:00+00:00\nThe start of day is: 2020-04-17T00:00:00+00:00\n" }, { "code": null, "e": 25422, "s": 25392, "text": "Other start_of functions are:" }, { "code": null, "e": 25569, "s": 25422, "text": "14. end_of(frame, count=1) :For this datetime it returns the end of the given time frame f.By default Number of frame which is being spanned is 1." }, { "code": null, "e": 25723, "s": 25569, "text": "15. end_of_day(count=1) :For this datetime it return a new Zulu object/set to the end of the day .By default Number of frame which is being spanned is 1." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The end of month is:\", dt.end_of('month', 1))print(\"The end of day is without count:\", dt.end_of_day())print(\"The end of day is with the count of 2:\", dt.end_of_day(2))", "e": 25967, "s": 25723, "text": null }, { "code": null, "e": 25975, "s": 25967, "text": "Output:" }, { "code": null, "e": 26165, "s": 25975, "text": "The end of month is: 2020-04-30T23:59:59.999999+00:00The end of day is without count: 2020-04-17T23:59:59.999999+00:00The end of day is with the count of 2: 2020-04-18T23:59:59.999999+00:00" }, { "code": null, "e": 26193, "s": 26165, "text": "Other end_of functions are:" }, { "code": null, "e": 26319, "s": 26193, "text": "16. time_from(dt, **options) : It Return the difference between this one and another given datetime in ‘time ago’ .Parameters" }, { "code": null, "e": 26346, "s": 26319, "text": "dtime – A datetime object." }, { "code": null, "e": 26357, "s": 26346, "text": "Returnsstr" }, { "code": null, "e": 26453, "s": 26357, "text": "17. time_from_now(**options) :It Return the difference between this one and now in “time ago” ." }, { "code": null, "e": 26563, "s": 26453, "text": "18. time_to(dt, **options) :It Return the difference between this datetime and another datetime in “time to”." }, { "code": null, "e": 26661, "s": 26563, "text": "19. time_to_now(**options) :It Return the difference between this datetime and now in “time to” ." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064+00:00') print(\"The difference between this time and end of the day is:\", dt.time_from(dt.end_of_day()))print(\"The difference between this time and end of the day is:\", dt.time_to(dt.end_of_day()))print(\"The difference between this time and start of the day is:\", dt.time_from(dt.start_of_day()))print(\"The difference between this time and start of the day is:\", dt.time_to(dt.start_of_day())) print(\"The difference is\", dt.time_from_now())print(\"The difference is\", dt.time_to_now())", "e": 27226, "s": 26661, "text": null }, { "code": null, "e": 27234, "s": 27226, "text": "Output:" }, { "code": null, "e": 27562, "s": 27234, "text": "The difference between this time and end of the day is: 8 hours agoThe difference between this time and end of the day is: in 8 hoursThe difference between this time and start of the day is: in 16 hoursThe difference between this time and start of the day is: 16 hours agoThe difference is 2 days agoThe difference is in 2 days" }, { "code": null, "e": 27683, "s": 27562, "text": "20. astimezone(tz=’local’) :It return the native datetime object shifted to given timezone.By default timezone is local." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')local = dt.astimezone() print(\"Local timezone is\", local) pacific = dt.astimezone('US / Pacific')print(\"Pacific timezone is:\", pacific)", "e": 27889, "s": 27683, "text": null }, { "code": null, "e": 27897, "s": 27889, "text": "Output:" }, { "code": null, "e": 28001, "s": 27897, "text": "Local timezone is 2020-04-17 21:40:15.708064+05:30Pacific timezone is: 2020-04-17 09:10:15.708064-07:00" }, { "code": null, "e": 28045, "s": 28001, "text": "21. timetuple() :It Returns the time tuple." }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00')print(\"The timetuple is:\", dt.timetuple())", "e": 28156, "s": 28045, "text": null }, { "code": null, "e": 28163, "s": 28156, "text": "OUTPUT" }, { "code": null, "e": 28305, "s": 28163, "text": "The timetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=-1)" }, { "code": null, "e": 28360, "s": 28305, "text": "22. utcnow() :It return the current UTC date and time." }, { "code": null, "e": 28489, "s": 28360, "text": "23. utcoffset() :It return the difference in hours, minutes and seonds from corresponding universal time for a particular place." }, { "code": null, "e": 28569, "s": 28489, "text": "24. utctimetuple() :It Return UTC time tuple coordionated with time.localtime()" }, { "code": "import zulu dt = zulu.parse('2020-04-17T16:10:15.708064 + 00:00') print(\"The current UTC datetime is:\", dt.utcnow())print(\"The utcoffest is:\", dt.utcoffset())print(\"The utctimetuple is:\", dt.utctimetuple())", "e": 28780, "s": 28569, "text": null }, { "code": null, "e": 28788, "s": 28780, "text": "Output:" }, { "code": null, "e": 29018, "s": 28788, "text": "The current UTC datetime is: 2020-04-19T07:17:30.162600+00:00The utcoffest is: 0:00:00The utctimetuple is: time.struct_time(tm_year=2020, tm_mon=4, tm_mday=17, tm_hour=16, tm_min=10, tm_sec=15, tm_wday=4, tm_yday=108, tm_isdst=0)" }, { "code": null, "e": 29053, "s": 29018, "text": "Other functions in this class is :" }, { "code": null, "e": 30673, "s": 29053, "text": "zulu.Delta :-It is an extended version of datetime.timedelta that provides new functionality.Functions or classmethods1. parse_delta(obj) :It return Delta object parsed from the given obj.import zulu delta1 = zulu.parse_delta('4h 45m')delta2 = zulu.parse_delta('-4h 45m') print(\"The delta is:\", delta1)print(\"The delta is:\", delta2)Output:The delta is: 4:45:00\nThe delta is: -1 day, 19:15:00\n2. format(format=’long’, granularity=’second’, threshold=0.85, add_direction=False, locale=None) : Return timedelta as a formatted string.import zulu delta = zulu.parse_delta('4h 45m') print(\"The timedelta with given granularity is:\", delta.format(granularity ='day')) print(\"The timedelta with given locale is:\", delta.format(locale ='de')) print(\"The timedelta with given locale and add_direction is:\", delta.format(locale ='fr', add_direction = True)) print(\"The timedelta with given threshold is:\", delta.format(threshold = 5)) print(\"The timedelta with given threshold and granularity is:\", delta.format(threshold = 155, granularity ='minute'))Output:The timedelta with given granularity is: 1 dayThe timedelta with given locale is: 5 StundenThe timedelta with given locale and add_direction is: dans 5 heuresThe timedelta with given threshold is: 285 minutesThe timedelta with given threshold and granularity is: 285 minutes3. fromtimedelta(delta) :From a native timedelta object it return Delta object.import zulu delta = zulu.parse_delta('4h 45m')delta1 = zulu.parse_delta('6h 42m 11s') print(\"The timedelta is:\", delta.fromtimedelta(delta1))Output:The timedelta is: 6:42:11\n" }, { "code": null, "e": 30744, "s": 30673, "text": "1. parse_delta(obj) :It return Delta object parsed from the given obj." }, { "code": "import zulu delta1 = zulu.parse_delta('4h 45m')delta2 = zulu.parse_delta('-4h 45m') print(\"The delta is:\", delta1)print(\"The delta is:\", delta2)", "e": 30893, "s": 30744, "text": null }, { "code": null, "e": 30901, "s": 30893, "text": "Output:" }, { "code": null, "e": 30955, "s": 30901, "text": "The delta is: 4:45:00\nThe delta is: -1 day, 19:15:00\n" }, { "code": null, "e": 31094, "s": 30955, "text": "2. format(format=’long’, granularity=’second’, threshold=0.85, add_direction=False, locale=None) : Return timedelta as a formatted string." }, { "code": "import zulu delta = zulu.parse_delta('4h 45m') print(\"The timedelta with given granularity is:\", delta.format(granularity ='day')) print(\"The timedelta with given locale is:\", delta.format(locale ='de')) print(\"The timedelta with given locale and add_direction is:\", delta.format(locale ='fr', add_direction = True)) print(\"The timedelta with given threshold is:\", delta.format(threshold = 5)) print(\"The timedelta with given threshold and granularity is:\", delta.format(threshold = 155, granularity ='minute'))", "e": 31642, "s": 31094, "text": null }, { "code": null, "e": 31650, "s": 31642, "text": "Output:" }, { "code": null, "e": 31925, "s": 31650, "text": "The timedelta with given granularity is: 1 dayThe timedelta with given locale is: 5 StundenThe timedelta with given locale and add_direction is: dans 5 heuresThe timedelta with given threshold is: 285 minutesThe timedelta with given threshold and granularity is: 285 minutes" }, { "code": null, "e": 32005, "s": 31925, "text": "3. fromtimedelta(delta) :From a native timedelta object it return Delta object." }, { "code": "import zulu delta = zulu.parse_delta('4h 45m')delta1 = zulu.parse_delta('6h 42m 11s') print(\"The timedelta is:\", delta.fromtimedelta(delta1))", "e": 32151, "s": 32005, "text": null }, { "code": null, "e": 32159, "s": 32151, "text": "Output:" }, { "code": null, "e": 32186, "s": 32159, "text": "The timedelta is: 6:42:11\n" }, { "code": null, "e": 32279, "s": 32186, "text": "zulu.ParseError :-It raised Exception when an object is not able to be parsed as a datetime." }, { "code": null, "e": 32294, "s": 32279, "text": "python-modules" }, { "code": null, "e": 32301, "s": 32294, "text": "Python" }, { "code": null, "e": 32399, "s": 32301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32431, "s": 32399, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32458, "s": 32431, "text": "Python Classes and Objects" }, { "code": null, "e": 32489, "s": 32458, "text": "Python | os.path.join() method" }, { "code": null, "e": 32512, "s": 32489, "text": "Introduction To PYTHON" }, { "code": null, "e": 32533, "s": 32512, "text": "Python OOPs Concepts" }, { "code": null, "e": 32589, "s": 32533, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32631, "s": 32589, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32673, "s": 32631, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32712, "s": 32673, "text": "Python | Get unique values from a list" } ]
How to set cell width and height in HTML?
To set the cell width and height, use the CSS style. The height and width attribute of the <td> cell isn’t supported in HTML5. Use the CSS property width and height to set the width and height of the cell respectively. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to set height and width to a table cell in HTML. We’re also using the <style> tag and the style attribute to style the table Live Demo <!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <h1>Tutorial</h1> <table> <tr> <th>Language</th> <th>Lessons</th> </tr> <tr> <td style="height:100px;width:100px">Java</td> <td style="height:100px;width:100px">50</td> </tr> <tr> <td>Ruby</td> <td>40</td> </tr> </table> </body> </html>
[ { "code": null, "e": 1406, "s": 1187, "text": "To set the cell width and height, use the CSS style. The height and width attribute of the <td> cell isn’t supported in HTML5. Use the CSS property width and height to set the width and height of the cell respectively." }, { "code": null, "e": 1568, "s": 1406, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1731, "s": 1568, "text": "You can try to run the following code to set height and width to a table cell in HTML. We’re also using the <style> tag and the style attribute to style the table" }, { "code": null, "e": 1741, "s": 1731, "text": "Live Demo" }, { "code": null, "e": 2285, "s": 1741, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n }\n </style>\n </head>\n \n <body>\n <h1>Tutorial</h1>\n <table>\n <tr>\n <th>Language</th>\n <th>Lessons</th>\n </tr>\n <tr>\n <td style=\"height:100px;width:100px\">Java</td>\n <td style=\"height:100px;width:100px\">50</td>\n </tr>\n <tr>\n <td>Ruby</td>\n <td>40</td>\n </tr>\n </table>\n </body>\n</html>" } ]
Difference between Software Engineering process and Conventional Engineering Process
16 Aug, 2021 1. Software Engineering Process : It is a engineering process which is mainly related to computers and programming and developing different kinds of applications through the use of information technology. 2. Conventional Engineering Process : It is a engineering process which is highly based on empirical knowledge and is about building cars, machines and hardware. Difference between Software Engineering Process and Conventional Engineering Process : clintra Difference Between Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Aug, 2021" }, { "code": null, "e": 258, "s": 52, "text": "1. Software Engineering Process : It is a engineering process which is mainly related to computers and programming and developing different kinds of applications through the use of information technology. " }, { "code": null, "e": 421, "s": 258, "text": "2. Conventional Engineering Process : It is a engineering process which is highly based on empirical knowledge and is about building cars, machines and hardware. " }, { "code": null, "e": 510, "s": 421, "text": "Difference between Software Engineering Process and Conventional Engineering Process : " }, { "code": null, "e": 518, "s": 510, "text": "clintra" }, { "code": null, "e": 537, "s": 518, "text": "Difference Between" }, { "code": null, "e": 558, "s": 537, "text": "Software Engineering" } ]
Python – Consecutive Division in List
01 Nov, 2020 Given a List, perform consecutive division from each quotient obtained in the intermediate step and treating consecutive elements as divisors. Input : test_list = [1000, 50, 5, 10, 2] Output : 0.2 Explanation : 1000 / 50 = 20 / 5 = 4 / 10 = 0.4 / 2 = 0.2. Hence solution. Input : test_list = [100, 50] Output : 2 Explanation : 100 / 50 = 2. Hence solution. Approach: Using loop + “/” operator In this, we iterate for each element and store the quotient obtained to process as a dividend for the next operation while in the loop. The end result is the final quotient of list. Python3 # Python3 code to demonstrate working of# Consecutive Division in List# Using loop + / operator # utility fnc.def conc_div(test_list): res = test_list[0] for idx in range(1, len(test_list)): # Consecutive Division res /= test_list[idx] return res # initializing listtest_list = [1000, 50, 5, 10, 2] # printing original listprint("The original list is : " + str(test_list)) # getting conc. Divisionres = conc_div(test_list) # printing result print("The Consecutive Division quotient : " + str(res)) The original list is : [1000, 50, 5, 10, 2] The Consecutive Division quotient : 0.2 Python list-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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2020" }, { "code": null, "e": 171, "s": 28, "text": "Given a List, perform consecutive division from each quotient obtained in the intermediate step and treating consecutive elements as divisors." }, { "code": null, "e": 300, "s": 171, "text": "Input : test_list = [1000, 50, 5, 10, 2] Output : 0.2 Explanation : 1000 / 50 = 20 / 5 = 4 / 10 = 0.4 / 2 = 0.2. Hence solution." }, { "code": null, "e": 387, "s": 300, "text": "Input : test_list = [100, 50] Output : 2 Explanation : 100 / 50 = 2. Hence solution. " }, { "code": null, "e": 423, "s": 387, "text": "Approach: Using loop + “/” operator" }, { "code": null, "e": 605, "s": 423, "text": "In this, we iterate for each element and store the quotient obtained to process as a dividend for the next operation while in the loop. The end result is the final quotient of list." }, { "code": null, "e": 613, "s": 605, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Consecutive Division in List# Using loop + / operator # utility fnc.def conc_div(test_list): res = test_list[0] for idx in range(1, len(test_list)): # Consecutive Division res /= test_list[idx] return res # initializing listtest_list = [1000, 50, 5, 10, 2] # printing original listprint(\"The original list is : \" + str(test_list)) # getting conc. Divisionres = conc_div(test_list) # printing result print(\"The Consecutive Division quotient : \" + str(res))", "e": 1155, "s": 613, "text": null }, { "code": null, "e": 1240, "s": 1155, "text": "The original list is : [1000, 50, 5, 10, 2]\nThe Consecutive Division quotient : 0.2\n" }, { "code": null, "e": 1261, "s": 1240, "text": "Python list-programs" }, { "code": null, "e": 1268, "s": 1261, "text": "Python" }, { "code": null, "e": 1284, "s": 1268, "text": "Python Programs" }, { "code": null, "e": 1382, "s": 1284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1414, "s": 1382, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1441, "s": 1414, "text": "Python Classes and Objects" }, { "code": null, "e": 1462, "s": 1441, "text": "Python OOPs Concepts" }, { "code": null, "e": 1485, "s": 1462, "text": "Introduction To PYTHON" }, { "code": null, "e": 1541, "s": 1485, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1563, "s": 1541, "text": "Defaultdict in Python" }, { "code": null, "e": 1602, "s": 1563, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1640, "s": 1602, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1677, "s": 1640, "text": "Python Program for Fibonacci numbers" } ]
std::string::assign() in C++
28 Oct, 2020 The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this CPP // CPP code for assign (const string& str)#include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str1, string str2){ // Assigns str2 to str1 str1.assign(str2); cout << "After assign() : "; cout << str1; } // Driver codeint main(){ string str1("Hello World!"); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; assignDemo(str1, str2); return 0;} Output: Original String : Hello World! After assign() : GeeksforGeeks Syntax 2: Assigns at most str_num characters of str starting with index str_idx. It throws out_of _range if str_idx > str. size(). string& string::assign (const string& str, size_type str_idx, size_type str_num) str : is the string to be assigned. str_idx : is the index number in str. str_num : is the number of characters picked from str_idx to assign Return : *this CPP // CPP code to illustrate// assign(const string& str, size_type// str_idx, size_type str_num) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str1, string str2){ // Assigns 8 characters from // 5th index of str2 to str1 str1.assign(str2, 5, 8); cout << "After assign() : "; cout << str1; } // Driver codeint main(){ string str1("Hello World!"); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; assignDemo(str1, str2); return 0;} Output: Original String : Hello World! After assign() : forGeeks Syntax 3: Assign the characters of the C-string cstr. It throws length_error if the resulting size exceeds the maximum number of characters. string & string::assign (const char* cstr) Assigns all characters of cstr up to but not including '\0'. Returns : *this. Note : that cstr may not be a null pointer (NULL). CPP // CPP code for assign (const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns GeeksforGeeks to str str.assign("GeeksforGeeks"); cout << "After assign() : "; cout << str; } // Driver codeint main(){ string str("Hello World!"); cout << "Original String : " << str << endl; assignDemo(str); return 0;} Output: Original String : Hello World! After assign() : GeeksforGeeks Syntax 4: Assigns chars_len characters of the character array chars. It throws length_error if the resulting size exceeds the maximum number of characters. string& string::assign (const char* chars, size_type chars_len) *chars : is the pointer to the array to be assigned. chars_len : is the number of characters to be assigned from character array. Note : that chars must have at least chars_len characters. Returns : *this. CPP // CPP code to illustrate// string& string::assign// (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns first 5 characters of // GeeksforGeeks to str str.assign("GeeksforGeeks", 5); cout << "After assign() : "; cout << str; } // Driver codeint main(){ string str("Hello World!"); cout << "Original String : " << str << endl; assignDemo(str); return 0;} Output: Original String : Hello World! After assign() : Geeks Syntax 5: Assigns num occurrences of character c. It throws length_error if num is equal to string::npos string & string::assign (size_type num, char c) num : is the number of occurrences to be assigned. c : is the character which is to be assigned repeatedly. Throws length_error if the resulting size exceeds the maximum number(max_size) of characters. Returns : *this. CPP // CPP code for string&// string::assign (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns 10 occurrences of 'x' // to str str.assign(10, 'x'); cout << "After assign() : "; cout << str; } // Driver codeint main(){ string str("#########"); cout << "Original String : " << str << endl; assignDemo(str); return 0;} Output: Original String : ######### After assign() : xxxxxxxxxx Syntax 6: Assigns all characters of the range [beg, end). It throws length_error if range outruns the actual content of string. template <class InputIterator> string& assign (InputIterator first, InputIterator last) first, last : Input iterators to the initial and final positions in a sequence. Returns : *this. CPP // CPP code for string&// string::assign (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ string str1; // Assigns all characters between // str.begin()+6 and str.end()-0 to str1 str1.assign(str.begin()+6, str.end()-0); cout << "After assign() : "; cout << str1; } // Driver codeint main(){ string str("Hello World!"); cout << "Original String : " << str << endl; assignDemo(str); return 0;} Output: Original String : Hello World! After assign() : World! This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. arynkr cpp-string cpp-strings-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2020" }, { "code": null, "e": 223, "s": 52, "text": "The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. " }, { "code": null, "e": 321, "s": 223, "text": "string& string::assign (const string& str)\n\nstr : is the string to be assigned.\nReturns : *this\n" }, { "code": null, "e": 325, "s": 321, "text": "CPP" }, { "code": "// CPP code for assign (const string& str)#include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str1, string str2){ // Assigns str2 to str1 str1.assign(str2); cout << \"After assign() : \"; cout << str1; } // Driver codeint main(){ string str1(\"Hello World!\"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; assignDemo(str1, str2); return 0;}", "e": 793, "s": 325, "text": null }, { "code": null, "e": 802, "s": 793, "text": "Output: " }, { "code": null, "e": 866, "s": 802, "text": "Original String : Hello World!\nAfter assign() : GeeksforGeeks\n\n" }, { "code": null, "e": 998, "s": 866, "text": "Syntax 2: Assigns at most str_num characters of str starting with index str_idx. It throws out_of _range if str_idx > str. size(). " }, { "code": null, "e": 1239, "s": 998, "text": "string& string::assign (const string& str, size_type str_idx, size_type str_num)\n\nstr : is the string to be assigned.\nstr_idx : is the index number in str.\nstr_num : is the number of characters picked \nfrom str_idx to assign\nReturn : *this\n" }, { "code": null, "e": 1243, "s": 1239, "text": "CPP" }, { "code": "// CPP code to illustrate// assign(const string& str, size_type// str_idx, size_type str_num) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str1, string str2){ // Assigns 8 characters from // 5th index of str2 to str1 str1.assign(str2, 5, 8); cout << \"After assign() : \"; cout << str1; } // Driver codeint main(){ string str1(\"Hello World!\"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; assignDemo(str1, str2); return 0;}", "e": 1807, "s": 1243, "text": null }, { "code": null, "e": 1816, "s": 1807, "text": "Output: " }, { "code": null, "e": 1874, "s": 1816, "text": "Original String : Hello World!\nAfter assign() : forGeeks\n" }, { "code": null, "e": 2016, "s": 1874, "text": "Syntax 3: Assign the characters of the C-string cstr. It throws length_error if the resulting size exceeds the maximum number of characters. " }, { "code": null, "e": 2190, "s": 2016, "text": "string & string::assign (const char* cstr)\n\nAssigns all characters of cstr up to but not including '\\0'.\nReturns : *this.\nNote : that cstr may not be a null pointer (NULL).\n" }, { "code": null, "e": 2194, "s": 2190, "text": "CPP" }, { "code": "// CPP code for assign (const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns GeeksforGeeks to str str.assign(\"GeeksforGeeks\"); cout << \"After assign() : \"; cout << str; } // Driver codeint main(){ string str(\"Hello World!\"); cout << \"Original String : \" << str << endl; assignDemo(str); return 0;}", "e": 2624, "s": 2194, "text": null }, { "code": null, "e": 2633, "s": 2624, "text": "Output: " }, { "code": null, "e": 2696, "s": 2633, "text": "Original String : Hello World!\nAfter assign() : GeeksforGeeks\n" }, { "code": null, "e": 2853, "s": 2696, "text": "Syntax 4: Assigns chars_len characters of the character array chars. It throws length_error if the resulting size exceeds the maximum number of characters. " }, { "code": null, "e": 3126, "s": 2853, "text": "string& string::assign (const char* chars, size_type chars_len)\n\n*chars : is the pointer to the array to be assigned.\nchars_len : is the number of characters to be assigned from \ncharacter array.\nNote : that chars must have at least chars_len characters.\nReturns : *this.\n" }, { "code": null, "e": 3130, "s": 3126, "text": "CPP" }, { "code": "// CPP code to illustrate// string& string::assign// (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns first 5 characters of // GeeksforGeeks to str str.assign(\"GeeksforGeeks\", 5); cout << \"After assign() : \"; cout << str; } // Driver codeint main(){ string str(\"Hello World!\"); cout << \"Original String : \" << str << endl; assignDemo(str); return 0;}", "e": 3643, "s": 3130, "text": null }, { "code": null, "e": 3652, "s": 3643, "text": "Output: " }, { "code": null, "e": 3707, "s": 3652, "text": "Original String : Hello World!\nAfter assign() : Geeks\n" }, { "code": null, "e": 3813, "s": 3707, "text": "Syntax 5: Assigns num occurrences of character c. It throws length_error if num is equal to string::npos " }, { "code": null, "e": 4085, "s": 3813, "text": "string & string::assign (size_type num, char c)\n\nnum : is the number of occurrences to be assigned.\nc : is the character which is to be assigned repeatedly. \nThrows length_error if the resulting size exceeds the maximum number(max_size) of characters.\nReturns : *this.\n" }, { "code": null, "e": 4089, "s": 4085, "text": "CPP" }, { "code": "// CPP code for string&// string::assign (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ // Assigns 10 occurrences of 'x' // to str str.assign(10, 'x'); cout << \"After assign() : \"; cout << str; } // Driver codeint main(){ string str(\"#########\"); cout << \"Original String : \" << str << endl; assignDemo(str); return 0;}", "e": 4545, "s": 4089, "text": null }, { "code": null, "e": 4554, "s": 4545, "text": "Output: " }, { "code": null, "e": 4611, "s": 4554, "text": "Original String : #########\nAfter assign() : xxxxxxxxxx\n" }, { "code": null, "e": 4740, "s": 4611, "text": "Syntax 6: Assigns all characters of the range [beg, end). It throws length_error if range outruns the actual content of string. " }, { "code": null, "e": 4931, "s": 4740, "text": "template <class InputIterator>\n string& assign (InputIterator first, InputIterator last)\nfirst, last : Input iterators to the initial and final positions \nin a sequence.\n\nReturns : *this.\n" }, { "code": null, "e": 4935, "s": 4931, "text": "CPP" }, { "code": "// CPP code for string&// string::assign (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate assignvoid assignDemo(string str){ string str1; // Assigns all characters between // str.begin()+6 and str.end()-0 to str1 str1.assign(str.begin()+6, str.end()-0); cout << \"After assign() : \"; cout << str1; } // Driver codeint main(){ string str(\"Hello World!\"); cout << \"Original String : \" << str << endl; assignDemo(str); return 0;}", "e": 5468, "s": 4935, "text": null }, { "code": null, "e": 5477, "s": 5468, "text": "Output: " }, { "code": null, "e": 5533, "s": 5477, "text": "Original String : Hello World!\nAfter assign() : World!\n" }, { "code": null, "e": 5975, "s": 5533, "text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5982, "s": 5975, "text": "arynkr" }, { "code": null, "e": 5993, "s": 5982, "text": "cpp-string" }, { "code": null, "e": 6013, "s": 5993, "text": "cpp-strings-library" }, { "code": null, "e": 6017, "s": 6013, "text": "STL" }, { "code": null, "e": 6021, "s": 6017, "text": "C++" }, { "code": null, "e": 6025, "s": 6021, "text": "STL" }, { "code": null, "e": 6029, "s": 6025, "text": "CPP" } ]
C Program to Compute Quotient and Remainder
17 Jun, 2022 Given two numbers A and B. The task is to write a program to find the quotient and remainder of these two numbers when A is divided by B. Examples: Input: A = 2, B = 6 Output: Quotient = 0, Remainder = 2 Input: A = 17, B = 5 Output: Quotient = 3, Remainder = 2 In the below program, to find the quotient and remainder of the two numbers, the user is first asked to enter two numbers. The inputs are scanned using the scanf() function and stored in the variables and . Then, the variables and are divided using the arithmetic operator to get the quotient as result stored in the variable quotient; and using the arithmetic operator % to get the remainder as result stored in the variable remainder. Below is the programs to find the quotient and remainder of two numbers: C++ C Java Python3 // C++ program to find quotient// and remainder of two numbers #include <iostream>using namespace std; int main(){ int A, B; // Ask user to enter the two numbers cout << "Enter two numbers A and B: "; // Read two numbers from the user || A = 17, B = 5 cin >> A >> B; // Calculate the quotient of A and B using '/' operator int quotient = A / B; // Calculate the remainder of A and B using '%' operator int remainder = A % B; // Print the result cout << "Quotient when A / B is: " << quotient << endl; cout << "Remainder when A / B is: " << remainder;} // This code is contributed by sarajadhav12052009 // C program to find quotient// and remainder of two numbers #include <stdio.h> int main(){ int A, B, quotient = 0, remainder = 0; // Ask user to enter the two numbers printf("Enter two numbers A and B : \n"); // Read two numbers from the user || A = 17, B = 5 scanf("%d%d", &A, &B); // Calculate the quotient of A and B using '/' operator quotient = A / B; // Calculate the remainder of A and B using '%' operator remainder = A % B; // Print the result printf("Quotient when A/B is: %d\n", quotient); printf("Remainder when A/B is: %d", remainder); return 0;} // java program to find quotient// and remainder of two numbers import java.io.*;import java.util.Scanner; class GFG { public static void main (String[] args) { Scanner input = new Scanner(System.in); int A = input.nextInt(); int B= input.nextInt(); int quotient = 0, remainder = 0; // Ask user to enter the two numbers System.out.println("Enter two numbers A and B : "+" "+ A+" "+ B); // Read two numbers from the user || A = 17, B = 5 // Calculate the quotient of A and B using '/' operator quotient = A / B; // Calculate the remainder of A and B using '%' operator remainder = A % B; // Print the result System.out.println("Quotient when A/B is: "+ quotient); System.out.println("Remainder when A/B is: "+ remainder); }}//this code is contributed by anuj_67.. # Python3 program to find quotient# and remainder of two numbers if __name__=='__main__': quotient = 0 remainder = 0 #Read two numbers from the user || A = 17, B = 5 A, B = [int(x) for x in input().split()] #Calculate the quotient of A and B using '/' operator quotient = int(A / B) #Calculate the remainder of A and B using '%' operator remainder = A % B #Print the result print("Quotient when A/B is:", quotient) print("Remainder when A/B is:", remainder) #this code is contributed by Shashank_Sharma Output: Enter two numbers A and B : 17 5 Quotient when A/B is: 3 Remainder when A/B is: 2 Shashank_Sharma vt_m sagar0719kumar kk773572498 sarajadhav12052009 Number Divisibility C Language C Programs School Programming 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++ Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2022" }, { "code": null, "e": 167, "s": 28, "text": "Given two numbers A and B. The task is to write a program to find the quotient and remainder of these two numbers when A is divided by B. " }, { "code": null, "e": 179, "s": 167, "text": "Examples: " }, { "code": null, "e": 293, "s": 179, "text": "Input: A = 2, B = 6\nOutput: Quotient = 0, Remainder = 2\n\nInput: A = 17, B = 5\nOutput: Quotient = 3, Remainder = 2" }, { "code": null, "e": 807, "s": 295, "text": "In the below program, to find the quotient and remainder of the two numbers, the user is first asked to enter two numbers. The inputs are scanned using the scanf() function and stored in the variables and . Then, the variables and are divided using the arithmetic operator to get the quotient as result stored in the variable quotient; and using the arithmetic operator % to get the remainder as result stored in the variable remainder. Below is the programs to find the quotient and remainder of two numbers: " }, { "code": null, "e": 811, "s": 807, "text": "C++" }, { "code": null, "e": 813, "s": 811, "text": "C" }, { "code": null, "e": 818, "s": 813, "text": "Java" }, { "code": null, "e": 826, "s": 818, "text": "Python3" }, { "code": "// C++ program to find quotient// and remainder of two numbers #include <iostream>using namespace std; int main(){ int A, B; // Ask user to enter the two numbers cout << \"Enter two numbers A and B: \"; // Read two numbers from the user || A = 17, B = 5 cin >> A >> B; // Calculate the quotient of A and B using '/' operator int quotient = A / B; // Calculate the remainder of A and B using '%' operator int remainder = A % B; // Print the result cout << \"Quotient when A / B is: \" << quotient << endl; cout << \"Remainder when A / B is: \" << remainder;} // This code is contributed by sarajadhav12052009", "e": 1453, "s": 826, "text": null }, { "code": "// C program to find quotient// and remainder of two numbers #include <stdio.h> int main(){ int A, B, quotient = 0, remainder = 0; // Ask user to enter the two numbers printf(\"Enter two numbers A and B : \\n\"); // Read two numbers from the user || A = 17, B = 5 scanf(\"%d%d\", &A, &B); // Calculate the quotient of A and B using '/' operator quotient = A / B; // Calculate the remainder of A and B using '%' operator remainder = A % B; // Print the result printf(\"Quotient when A/B is: %d\\n\", quotient); printf(\"Remainder when A/B is: %d\", remainder); return 0;}", "e": 2059, "s": 1453, "text": null }, { "code": "// java program to find quotient// and remainder of two numbers import java.io.*;import java.util.Scanner; class GFG { public static void main (String[] args) { Scanner input = new Scanner(System.in); int A = input.nextInt(); int B= input.nextInt(); int quotient = 0, remainder = 0; // Ask user to enter the two numbers System.out.println(\"Enter two numbers A and B : \"+\" \"+ A+\" \"+ B); // Read two numbers from the user || A = 17, B = 5 // Calculate the quotient of A and B using '/' operator quotient = A / B; // Calculate the remainder of A and B using '%' operator remainder = A % B; // Print the result System.out.println(\"Quotient when A/B is: \"+ quotient); System.out.println(\"Remainder when A/B is: \"+ remainder); }}//this code is contributed by anuj_67..", "e": 2893, "s": 2059, "text": null }, { "code": "# Python3 program to find quotient# and remainder of two numbers if __name__=='__main__': quotient = 0 remainder = 0 #Read two numbers from the user || A = 17, B = 5 A, B = [int(x) for x in input().split()] #Calculate the quotient of A and B using '/' operator quotient = int(A / B) #Calculate the remainder of A and B using '%' operator remainder = A % B #Print the result print(\"Quotient when A/B is:\", quotient) print(\"Remainder when A/B is:\", remainder) #this code is contributed by Shashank_Sharma", "e": 3423, "s": 2893, "text": null }, { "code": null, "e": 3433, "s": 3423, "text": "Output: " }, { "code": null, "e": 3515, "s": 3433, "text": "Enter two numbers A and B : 17 5\nQuotient when A/B is: 3\nRemainder when A/B is: 2" }, { "code": null, "e": 3533, "s": 3517, "text": "Shashank_Sharma" }, { "code": null, "e": 3538, "s": 3533, "text": "vt_m" }, { "code": null, "e": 3553, "s": 3538, "text": "sagar0719kumar" }, { "code": null, "e": 3565, "s": 3553, "text": "kk773572498" }, { "code": null, "e": 3584, "s": 3565, "text": "sarajadhav12052009" }, { "code": null, "e": 3604, "s": 3584, "text": "Number Divisibility" }, { "code": null, "e": 3615, "s": 3604, "text": "C Language" }, { "code": null, "e": 3626, "s": 3615, "text": "C Programs" }, { "code": null, "e": 3645, "s": 3626, "text": "School Programming" }, { "code": null, "e": 3743, "s": 3645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3760, "s": 3743, "text": "Substring in C++" }, { "code": null, "e": 3782, "s": 3760, "text": "Function Pointer in C" }, { "code": null, "e": 3817, "s": 3782, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 3863, "s": 3817, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3908, "s": 3863, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3921, "s": 3908, "text": "Strings in C" }, { "code": null, "e": 3962, "s": 3921, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 3991, "s": 3962, "text": "Basics of File Handling in C" }, { "code": null, "e": 4029, "s": 3991, "text": "UDP Server-Client implementation in C" } ]
Kubernetes – Concept of Containers
13 Jun, 2022 Kubernetes is an open-source container orchestration framework that was originally developed by Google. So now, the question arises, “what’s container orchestration?”. Container orchestration is automation. It can facilitate you to deploy the identical application across different environments like physical machines, virtual machines or cloud environments, or perhaps hybrid deployment environments and makes it easier for the management, scaling, and networking of containers. The original name for Kubernetes (originates from Greek) within Google was Project 7. Within the year 2014 Kubernetes was released for the primary time and made open-sourced too after using it to run production workloads at scale for quite a decade. Also, pure open-source Kubernetes is free and might be downloaded from its repository on GitHub. It is pronounced as “koo-burr-NET-eez”. It’s also referred to as k8s (k – eight characters – s), derived by replacing the eight letters with the digit 8. Following are the various features or characteristics of Kubernetes: Multi-Host Container Scheduling: Done by Kube-scheduler, it assigns containers, also referred to as pods in Kubernetes to nodes at runtime. It accounts for resources, quality of service, and policies before scheduling.Scalability and availability: The Kubernetes master is often deployed during a highly available configuration. Multi-region deployments are available as well.Flexibility and modularization: Kubernetes includes a plug-and-play architecture that permits you to increase it when you need to. There are specific add-ons from network drivers, service discovery, container runtime, visualization, and command. If there are tasks that you need to perform for your environment specifically, you’ll be able to create an add-on to suit your needs.Registration: New worker nodes can register themselves with the Kubernetes master node.Service discovery: Service discovery allows for automatic detection of new services and endpoints via DNS or environment variables.Persistent storage: It is a much-requested feature when working with containers. Pods can use persistent volumes to store data and therefore the data is retained across pod restarts and crashes.Maintenance: When it involves Kubernetes maintenance and upgrades, Kubernetes features are always backward compatible for some versions. All APIs are versioned and when upgrading or running maintenance on the host, you’ll unschedule the host so that no deployments can happen thereon. Once you’re done, you’ll simply turn the host back on and schedule deployments or jobs.Logging and Monitoring: In terms of logging and monitoring, application monitoring or health checks are also built-in, TCP, HTTP, or container exact health checks are available out of the box. There are also health checks to give you the status of the nodes and failures monitored by the node controller. Kubernetes status can also be monitored via add-ons like Metrics Server, cAdvisor, and Prometheus. And lastly, you can use the built-in logging frameworks or if you choose, you can bring your own.Secrets Management: Sensitive data is a first-class citizen in Kubernetes. Secrets mounted to data volumes or environment variables. They’re also specific to a single namespace so aren’t shared across all applications. Multi-Host Container Scheduling: Done by Kube-scheduler, it assigns containers, also referred to as pods in Kubernetes to nodes at runtime. It accounts for resources, quality of service, and policies before scheduling. Scalability and availability: The Kubernetes master is often deployed during a highly available configuration. Multi-region deployments are available as well. Flexibility and modularization: Kubernetes includes a plug-and-play architecture that permits you to increase it when you need to. There are specific add-ons from network drivers, service discovery, container runtime, visualization, and command. If there are tasks that you need to perform for your environment specifically, you’ll be able to create an add-on to suit your needs. Registration: New worker nodes can register themselves with the Kubernetes master node. Service discovery: Service discovery allows for automatic detection of new services and endpoints via DNS or environment variables. Persistent storage: It is a much-requested feature when working with containers. Pods can use persistent volumes to store data and therefore the data is retained across pod restarts and crashes. Maintenance: When it involves Kubernetes maintenance and upgrades, Kubernetes features are always backward compatible for some versions. All APIs are versioned and when upgrading or running maintenance on the host, you’ll unschedule the host so that no deployments can happen thereon. Once you’re done, you’ll simply turn the host back on and schedule deployments or jobs. Logging and Monitoring: In terms of logging and monitoring, application monitoring or health checks are also built-in, TCP, HTTP, or container exact health checks are available out of the box. There are also health checks to give you the status of the nodes and failures monitored by the node controller. Kubernetes status can also be monitored via add-ons like Metrics Server, cAdvisor, and Prometheus. And lastly, you can use the built-in logging frameworks or if you choose, you can bring your own. Secrets Management: Sensitive data is a first-class citizen in Kubernetes. Secrets mounted to data volumes or environment variables. They’re also specific to a single namespace so aren’t shared across all applications. The architecture of Kubernetes includes a master node and one or more worker nodes. Kube-apiserver: a frontend of the cluster that allows you to interact with the Kubernetes API and connects to the etcd database. Kube-scheduler: schedules pods on specific nodes supported labels, taints, and tolerations set for pods etcd: a database, stores all cluster data which includes job scheduling info, pod details, stage information, etc. Kube – controller – manager: manages the current state of the cluster cloud – controller – manager: interacts with outside cloud manager Different optional add-ons: DNS, Dashboard, cluster-level resource monitoring, cluster-level logging We wouldn’t get anywhere without Worker Nodes, though. These Worker Nodes are the Nodes where your applications operate. The Worker Nodes communicate back with the Master Node. Communication to a Worker Node is handled by the Kubelet Process. kubelet: passes requests to the container engine to ensure that pods are available Kube-proxy: runs on every node and uses iptables to provide an interface to connect to Kubernetes components container – runtime: take care of actually running container network agent: implements a software-defined networking solution Containers of an application are tightly coupled together in a Pod. By definition, a Pod is the smallest unit that can be scheduled as deployment in Kubernetes. Once Pods have been deployed, and are running, the Kubelet process communicates with the Pods to check on state and health, and therefore the Kube-proxy routes any packets to the Pods from other resources that might be wanting to communicate with them. In this section, we will learn how to install Kubernetes on the Linux platform. So, follow the given steps for installing the Kubernetes: Step 1: First of all, we have to update our apt-get repository. sudo apt-get update Step 2: Install apt transport HTTPS. This is basically used to make repositories while HTTPS. sudo apt-get install -y apt-transport-https Step 3: Install the docker dependency sudo apt install docker.io Step 4: After installing the docker we have to start and enable the docker. sudo systemctl start docker sudo systemctl enable docker Step 5: We have to install the necessary components for Kubernetes. Before that, we have to install the curl command because the curl command is used to send the data using URL syntax. Let’s install the curl command by: sudo apt-get install curl Step 6: Download an add key for Kubernetes installation from a URL. sudo curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add Step 7: We have to add a repository in a certain location. echo “deb https://apt.kubernetes.io/ kubernetes-xenial main” | sudo tee -a /etc/apt/sources.list.d/kubernetes.list Step 8: Now check for any updates available. sudo apt-get update Step 9: Now we are going to install Kubernetes components. sudo apt-get install -y kubectl kubeadm kubelet kubernetes-cni docker.io Step 10: We have to initialize the master node and to do this we have to first use a swapoff command to disable the swapping on other devices. sudo swapoff -a Step 11: Go ahead with the initialization. sudo kubeadm init Step 12: To start using your cluster, you need to run the following as a regular user: mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config Step 13: To deploy paths, use the following command: sudo kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/k8s-manifests/kube-flannel-rbac.yml Step 14: To see all the pods you have, use the command: sudo kubectl get pods --all-namespaces Using Kubernetes and its huge ecosystem can improve your productivity. It is a future-proof solution. It helps to make your application run more stable. It can be overkill for simple applications. It is very complex and can reduce productivity. It can be more expensive than its alternatives. khushb99 Picked TrueGeek-2021 Kubernetes TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Types of Distributed System How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? How to Convert Char to String in Java? Basics of API Testing Using Postman Types of Internet Protocols
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 156, "s": 52, "text": "Kubernetes is an open-source container orchestration framework that was originally developed by Google." }, { "code": null, "e": 220, "s": 156, "text": "So now, the question arises, “what’s container orchestration?”." }, { "code": null, "e": 532, "s": 220, "text": "Container orchestration is automation. It can facilitate you to deploy the identical application across different environments like physical machines, virtual machines or cloud environments, or perhaps hybrid deployment environments and makes it easier for the management, scaling, and networking of containers." }, { "code": null, "e": 879, "s": 532, "text": "The original name for Kubernetes (originates from Greek) within Google was Project 7. Within the year 2014 Kubernetes was released for the primary time and made open-sourced too after using it to run production workloads at scale for quite a decade. Also, pure open-source Kubernetes is free and might be downloaded from its repository on GitHub." }, { "code": null, "e": 1034, "s": 879, "text": "It is pronounced as “koo-burr-NET-eez”. It’s also referred to as k8s (k – eight characters – s), derived by replacing the eight letters with the digit 8. " }, { "code": null, "e": 1103, "s": 1034, "text": "Following are the various features or characteristics of Kubernetes:" }, { "code": null, "e": 3362, "s": 1103, "text": "Multi-Host Container Scheduling: Done by Kube-scheduler, it assigns containers, also referred to as pods in Kubernetes to nodes at runtime. It accounts for resources, quality of service, and policies before scheduling.Scalability and availability: The Kubernetes master is often deployed during a highly available configuration. Multi-region deployments are available as well.Flexibility and modularization: Kubernetes includes a plug-and-play architecture that permits you to increase it when you need to. There are specific add-ons from network drivers, service discovery, container runtime, visualization, and command. If there are tasks that you need to perform for your environment specifically, you’ll be able to create an add-on to suit your needs.Registration: New worker nodes can register themselves with the Kubernetes master node.Service discovery: Service discovery allows for automatic detection of new services and endpoints via DNS or environment variables.Persistent storage: It is a much-requested feature when working with containers. Pods can use persistent volumes to store data and therefore the data is retained across pod restarts and crashes.Maintenance: When it involves Kubernetes maintenance and upgrades, Kubernetes features are always backward compatible for some versions. All APIs are versioned and when upgrading or running maintenance on the host, you’ll unschedule the host so that no deployments can happen thereon. Once you’re done, you’ll simply turn the host back on and schedule deployments or jobs.Logging and Monitoring: In terms of logging and monitoring, application monitoring or health checks are also built-in, TCP, HTTP, or container exact health checks are available out of the box. There are also health checks to give you the status of the nodes and failures monitored by the node controller. Kubernetes status can also be monitored via add-ons like Metrics Server, cAdvisor, and Prometheus. And lastly, you can use the built-in logging frameworks or if you choose, you can bring your own.Secrets Management: Sensitive data is a first-class citizen in Kubernetes. Secrets mounted to data volumes or environment variables. They’re also specific to a single namespace so aren’t shared across all applications." }, { "code": null, "e": 3581, "s": 3362, "text": "Multi-Host Container Scheduling: Done by Kube-scheduler, it assigns containers, also referred to as pods in Kubernetes to nodes at runtime. It accounts for resources, quality of service, and policies before scheduling." }, { "code": null, "e": 3740, "s": 3581, "text": "Scalability and availability: The Kubernetes master is often deployed during a highly available configuration. Multi-region deployments are available as well." }, { "code": null, "e": 4120, "s": 3740, "text": "Flexibility and modularization: Kubernetes includes a plug-and-play architecture that permits you to increase it when you need to. There are specific add-ons from network drivers, service discovery, container runtime, visualization, and command. If there are tasks that you need to perform for your environment specifically, you’ll be able to create an add-on to suit your needs." }, { "code": null, "e": 4208, "s": 4120, "text": "Registration: New worker nodes can register themselves with the Kubernetes master node." }, { "code": null, "e": 4340, "s": 4208, "text": "Service discovery: Service discovery allows for automatic detection of new services and endpoints via DNS or environment variables." }, { "code": null, "e": 4535, "s": 4340, "text": "Persistent storage: It is a much-requested feature when working with containers. Pods can use persistent volumes to store data and therefore the data is retained across pod restarts and crashes." }, { "code": null, "e": 4908, "s": 4535, "text": "Maintenance: When it involves Kubernetes maintenance and upgrades, Kubernetes features are always backward compatible for some versions. All APIs are versioned and when upgrading or running maintenance on the host, you’ll unschedule the host so that no deployments can happen thereon. Once you’re done, you’ll simply turn the host back on and schedule deployments or jobs." }, { "code": null, "e": 5410, "s": 4908, "text": "Logging and Monitoring: In terms of logging and monitoring, application monitoring or health checks are also built-in, TCP, HTTP, or container exact health checks are available out of the box. There are also health checks to give you the status of the nodes and failures monitored by the node controller. Kubernetes status can also be monitored via add-ons like Metrics Server, cAdvisor, and Prometheus. And lastly, you can use the built-in logging frameworks or if you choose, you can bring your own." }, { "code": null, "e": 5629, "s": 5410, "text": "Secrets Management: Sensitive data is a first-class citizen in Kubernetes. Secrets mounted to data volumes or environment variables. They’re also specific to a single namespace so aren’t shared across all applications." }, { "code": null, "e": 5713, "s": 5629, "text": "The architecture of Kubernetes includes a master node and one or more worker nodes." }, { "code": null, "e": 5842, "s": 5713, "text": "Kube-apiserver: a frontend of the cluster that allows you to interact with the Kubernetes API and connects to the etcd database." }, { "code": null, "e": 5946, "s": 5842, "text": "Kube-scheduler: schedules pods on specific nodes supported labels, taints, and tolerations set for pods" }, { "code": null, "e": 6061, "s": 5946, "text": "etcd: a database, stores all cluster data which includes job scheduling info, pod details, stage information, etc." }, { "code": null, "e": 6131, "s": 6061, "text": "Kube – controller – manager: manages the current state of the cluster" }, { "code": null, "e": 6198, "s": 6131, "text": "cloud – controller – manager: interacts with outside cloud manager" }, { "code": null, "e": 6299, "s": 6198, "text": "Different optional add-ons: DNS, Dashboard, cluster-level resource monitoring, cluster-level logging" }, { "code": null, "e": 6542, "s": 6299, "text": "We wouldn’t get anywhere without Worker Nodes, though. These Worker Nodes are the Nodes where your applications operate. The Worker Nodes communicate back with the Master Node. Communication to a Worker Node is handled by the Kubelet Process." }, { "code": null, "e": 6625, "s": 6542, "text": "kubelet: passes requests to the container engine to ensure that pods are available" }, { "code": null, "e": 6734, "s": 6625, "text": "Kube-proxy: runs on every node and uses iptables to provide an interface to connect to Kubernetes components" }, { "code": null, "e": 6795, "s": 6734, "text": "container – runtime: take care of actually running container" }, { "code": null, "e": 6860, "s": 6795, "text": "network agent: implements a software-defined networking solution" }, { "code": null, "e": 7275, "s": 6860, "text": "Containers of an application are tightly coupled together in a Pod. By definition, a Pod is the smallest unit that can be scheduled as deployment in Kubernetes. Once Pods have been deployed, and are running, the Kubelet process communicates with the Pods to check on state and health, and therefore the Kube-proxy routes any packets to the Pods from other resources that might be wanting to communicate with them." }, { "code": null, "e": 7413, "s": 7275, "text": "In this section, we will learn how to install Kubernetes on the Linux platform. So, follow the given steps for installing the Kubernetes:" }, { "code": null, "e": 7477, "s": 7413, "text": "Step 1: First of all, we have to update our apt-get repository." }, { "code": null, "e": 7497, "s": 7477, "text": "sudo apt-get update" }, { "code": null, "e": 7591, "s": 7497, "text": "Step 2: Install apt transport HTTPS. This is basically used to make repositories while HTTPS." }, { "code": null, "e": 7635, "s": 7591, "text": "sudo apt-get install -y apt-transport-https" }, { "code": null, "e": 7673, "s": 7635, "text": "Step 3: Install the docker dependency" }, { "code": null, "e": 7700, "s": 7673, "text": "sudo apt install docker.io" }, { "code": null, "e": 7776, "s": 7700, "text": "Step 4: After installing the docker we have to start and enable the docker." }, { "code": null, "e": 7833, "s": 7776, "text": "sudo systemctl start docker\nsudo systemctl enable docker" }, { "code": null, "e": 8054, "s": 7833, "text": "Step 5: We have to install the necessary components for Kubernetes. Before that, we have to install the curl command because the curl command is used to send the data using URL syntax. Let’s install the curl command by:" }, { "code": null, "e": 8080, "s": 8054, "text": "sudo apt-get install curl" }, { "code": null, "e": 8148, "s": 8080, "text": "Step 6: Download an add key for Kubernetes installation from a URL." }, { "code": null, "e": 8234, "s": 8148, "text": "sudo curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add" }, { "code": null, "e": 8293, "s": 8234, "text": "Step 7: We have to add a repository in a certain location." }, { "code": null, "e": 8408, "s": 8293, "text": "echo “deb https://apt.kubernetes.io/ kubernetes-xenial main” | sudo tee -a /etc/apt/sources.list.d/kubernetes.list" }, { "code": null, "e": 8453, "s": 8408, "text": "Step 8: Now check for any updates available." }, { "code": null, "e": 8473, "s": 8453, "text": "sudo apt-get update" }, { "code": null, "e": 8532, "s": 8473, "text": "Step 9: Now we are going to install Kubernetes components." }, { "code": null, "e": 8605, "s": 8532, "text": "sudo apt-get install -y kubectl kubeadm kubelet kubernetes-cni docker.io" }, { "code": null, "e": 8748, "s": 8605, "text": "Step 10: We have to initialize the master node and to do this we have to first use a swapoff command to disable the swapping on other devices." }, { "code": null, "e": 8764, "s": 8748, "text": "sudo swapoff -a" }, { "code": null, "e": 8807, "s": 8764, "text": "Step 11: Go ahead with the initialization." }, { "code": null, "e": 8825, "s": 8807, "text": "sudo kubeadm init" }, { "code": null, "e": 8912, "s": 8825, "text": "Step 12: To start using your cluster, you need to run the following as a regular user:" }, { "code": null, "e": 9038, "s": 8912, "text": "mkdir -p $HOME/.kube\nsudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config\nsudo chown $(id -u):$(id -g) $HOME/.kube/config" }, { "code": null, "e": 9091, "s": 9038, "text": "Step 13: To deploy paths, use the following command:" }, { "code": null, "e": 9219, "s": 9091, "text": "sudo kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/k8s-manifests/kube-flannel-rbac.yml" }, { "code": null, "e": 9275, "s": 9219, "text": "Step 14: To see all the pods you have, use the command:" }, { "code": null, "e": 9314, "s": 9275, "text": "sudo kubectl get pods --all-namespaces" }, { "code": null, "e": 9385, "s": 9314, "text": "Using Kubernetes and its huge ecosystem can improve your productivity." }, { "code": null, "e": 9416, "s": 9385, "text": "It is a future-proof solution." }, { "code": null, "e": 9467, "s": 9416, "text": "It helps to make your application run more stable." }, { "code": null, "e": 9511, "s": 9467, "text": "It can be overkill for simple applications." }, { "code": null, "e": 9559, "s": 9511, "text": "It is very complex and can reduce productivity." }, { "code": null, "e": 9607, "s": 9559, "text": "It can be more expensive than its alternatives." }, { "code": null, "e": 9616, "s": 9607, "text": "khushb99" }, { "code": null, "e": 9623, "s": 9616, "text": "Picked" }, { "code": null, "e": 9637, "s": 9623, "text": "TrueGeek-2021" }, { "code": null, "e": 9648, "s": 9637, "text": "Kubernetes" }, { "code": null, "e": 9657, "s": 9648, "text": "TrueGeek" }, { "code": null, "e": 9755, "s": 9657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9829, "s": 9755, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 9887, "s": 9829, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 9940, "s": 9887, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 10006, "s": 9940, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 10034, "s": 10006, "text": "Types of Distributed System" }, { "code": null, "e": 10079, "s": 10034, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 10136, "s": 10079, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 10175, "s": 10136, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 10211, "s": 10175, "text": "Basics of API Testing Using Postman" } ]
Wget command in Linux/Unix
08 Sep, 2021 Wget is the non-interactive network downloader which is used to download files from the server even when the user has not logged on to the system and it can work in the background without hindering the current process. GNU wget is a free utility for non-interactive download of files from the Web. It supports HTTP, HTTPS, and FTP protocols, as well as retrieval through HTTP proxies. wget is non-interactive, meaning that it can work in the background, while the user is not logged on. This allows you to start a retrieval and disconnect from the system, letting wget finish the work. By contrast, most of the Web browsers require constant user’s presence, which can be a great hindrance when transferring a lot of data. wget can follow links in HTML and XHTML pages and create local versions of remote web sites, fully recreating the directory structure of the original site. This is sometimes referred to as recursive downloading. While doing that, wget respects the Robot Exclusion Standard (/robots.txt). wget can be instructed to convert the links in downloaded HTML files to the local files for offline viewing. wget has been designed for robustness over slow or unstable network connections; if a download fails due to a network problem, it will keep retrying until the whole file has been retrieved. If the server supports resuming, it will instruct the server to continue the download from where it left off. Syntax : wget [option] [URL] Example : 1. To simply download a webpage: wget http://example.com/sample.php 2. To download the file in background wget -b http://www.example.com/samplepage.php 3. To overwrite the log while of the wget command wget http://www.example.com/filename.txt -o /path/filename.txt 4. To resume a partially downloaded file wget -c http://example.com/samplefile.tar.gz 5. To try a given number of times wget --tries=10 http://example.com/samplefile.tar.gz Options : 1. -v / –version : This is used to display the version of the wget available on your system. Syntax $wget -v 2. -h / –help : This is used to print a help message displaying all the possible options of the line command that is available with the wget command line options Syntax $wget -h [URL] 3. -o logfile : This option is used to direct all the messages generated by the system to the logfile specified by the option and when the process is completed all the messages thus generated are available in the log file. If no log file has been specified then the output messages are redirected to the default log file i.e. wget -log Syntax $wget -o logfile [URL] 4. -b / –background : This option is used to send a process to the background as soon as the process has started so that other processes can be carried out. If no output file is specified via the -o option, output is redirected to wget-log by default. Syntax $wget -b [URL] 5. -a : This option is used to append the output messages to the current output log file without overwriting the file as in -o option the output log file is overwritten but by using this option the log of the previous command is saved and the current log is written after that of the previous ones. Syntax $wget -a logfile [URL] 6. -i : This option is used to read URLs from file. If -i is specified as file, URLs are read from the standard input.If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. The file need not be an HTML document if the URLs are just listed sequentially. Syntax $wget -i inputfile $wget -i inputfile [URL] 7. -t number / –tries=number : This option is used to set number of retries to a specified number of times. Specify 0 or inf for infinite retrying. The default is to retry 20 times, with the exception of fatal errors like connection refused or link not found, which are not retried once the error has occurred. Syntax $wget -t number [URL] 8. -c : This option is used to resume a partially downloaded file if the resume capability of the file is yes otherwise the downloading of the file cannot be resume if the resume capability of the given file is no or not specified. Syntax $wget -c [URL] 9. -w : This option is used to set the system to wait the specified number of seconds between the retrievals. Use of this option is recommended, as it lightens the server load by making the requests less frequent. Instead of in seconds, the time can be specified in minutes using the m suffix, in hours using h suffix, or in days using d suffix. Specifying a large value for this option is useful if the network or the destination host is down, so that wget can wait long enough to reasonably expect the network error to be fixed before the retry. Syntax $wget -w number in seconds [URL] 10. -r : this option is used to turn on the recursive retrieving of the link specified in case of fatal errors also. This option is a recursive call to the given link in the command line. Syntax $wget -r [URL] This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sagar0719kumar linux-command Linux-networking-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Sep, 2021" }, { "code": null, "e": 273, "s": 52, "text": "Wget is the non-interactive network downloader which is used to download files from the server even when the user has not logged on to the system and it can work in the background without hindering the current process. " }, { "code": null, "e": 441, "s": 273, "text": "GNU wget is a free utility for non-interactive download of files from the Web. It supports HTTP, HTTPS, and FTP protocols, as well as retrieval through HTTP proxies. " }, { "code": null, "e": 780, "s": 441, "text": "wget is non-interactive, meaning that it can work in the background, while the user is not logged on. This allows you to start a retrieval and disconnect from the system, letting wget finish the work. By contrast, most of the Web browsers require constant user’s presence, which can be a great hindrance when transferring a lot of data. " }, { "code": null, "e": 1179, "s": 780, "text": "wget can follow links in HTML and XHTML pages and create local versions of remote web sites, fully recreating the directory structure of the original site. This is sometimes referred to as recursive downloading. While doing that, wget respects the Robot Exclusion Standard (/robots.txt). wget can be instructed to convert the links in downloaded HTML files to the local files for offline viewing. " }, { "code": null, "e": 1481, "s": 1179, "text": "wget has been designed for robustness over slow or unstable network connections; if a download fails due to a network problem, it will keep retrying until the whole file has been retrieved. If the server supports resuming, it will instruct the server to continue the download from where it left off. " }, { "code": null, "e": 1492, "s": 1481, "text": "Syntax : " }, { "code": null, "e": 1512, "s": 1492, "text": "wget [option] [URL]" }, { "code": null, "e": 1557, "s": 1512, "text": "Example : 1. To simply download a webpage: " }, { "code": null, "e": 1592, "s": 1557, "text": "wget http://example.com/sample.php" }, { "code": null, "e": 1632, "s": 1592, "text": "2. To download the file in background " }, { "code": null, "e": 1678, "s": 1632, "text": "wget -b http://www.example.com/samplepage.php" }, { "code": null, "e": 1730, "s": 1678, "text": "3. To overwrite the log while of the wget command " }, { "code": null, "e": 1793, "s": 1730, "text": "wget http://www.example.com/filename.txt -o /path/filename.txt" }, { "code": null, "e": 1836, "s": 1793, "text": "4. To resume a partially downloaded file " }, { "code": null, "e": 1881, "s": 1836, "text": "wget -c http://example.com/samplefile.tar.gz" }, { "code": null, "e": 1917, "s": 1881, "text": "5. To try a given number of times " }, { "code": null, "e": 1970, "s": 1917, "text": "wget --tries=10 http://example.com/samplefile.tar.gz" }, { "code": null, "e": 1981, "s": 1970, "text": "Options : " }, { "code": null, "e": 2075, "s": 1981, "text": "1. -v / –version : This is used to display the version of the wget available on your system. " }, { "code": null, "e": 2084, "s": 2075, "text": "Syntax " }, { "code": null, "e": 2093, "s": 2084, "text": "$wget -v" }, { "code": null, "e": 2256, "s": 2093, "text": "2. -h / –help : This is used to print a help message displaying all the possible options of the line command that is available with the wget command line options " }, { "code": null, "e": 2265, "s": 2256, "text": "Syntax " }, { "code": null, "e": 2280, "s": 2265, "text": "$wget -h [URL]" }, { "code": null, "e": 2617, "s": 2280, "text": "3. -o logfile : This option is used to direct all the messages generated by the system to the logfile specified by the option and when the process is completed all the messages thus generated are available in the log file. If no log file has been specified then the output messages are redirected to the default log file i.e. wget -log " }, { "code": null, "e": 2626, "s": 2617, "text": "Syntax " }, { "code": null, "e": 2649, "s": 2626, "text": "$wget -o logfile [URL]" }, { "code": null, "e": 2902, "s": 2649, "text": "4. -b / –background : This option is used to send a process to the background as soon as the process has started so that other processes can be carried out. If no output file is specified via the -o option, output is redirected to wget-log by default. " }, { "code": null, "e": 2911, "s": 2902, "text": "Syntax " }, { "code": null, "e": 2926, "s": 2911, "text": "$wget -b [URL]" }, { "code": null, "e": 3226, "s": 2926, "text": "5. -a : This option is used to append the output messages to the current output log file without overwriting the file as in -o option the output log file is overwritten but by using this option the log of the previous command is saved and the current log is written after that of the previous ones. " }, { "code": null, "e": 3235, "s": 3226, "text": "Syntax " }, { "code": null, "e": 3258, "s": 3235, "text": "$wget -a logfile [URL]" }, { "code": null, "e": 3660, "s": 3258, "text": "6. -i : This option is used to read URLs from file. If -i is specified as file, URLs are read from the standard input.If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. The file need not be an HTML document if the URLs are just listed sequentially. " }, { "code": null, "e": 3669, "s": 3660, "text": "Syntax " }, { "code": null, "e": 3713, "s": 3669, "text": "$wget -i inputfile\n$wget -i inputfile [URL]" }, { "code": null, "e": 4025, "s": 3713, "text": "7. -t number / –tries=number : This option is used to set number of retries to a specified number of times. Specify 0 or inf for infinite retrying. The default is to retry 20 times, with the exception of fatal errors like connection refused or link not found, which are not retried once the error has occurred. " }, { "code": null, "e": 4034, "s": 4025, "text": "Syntax " }, { "code": null, "e": 4056, "s": 4034, "text": "$wget -t number [URL]" }, { "code": null, "e": 4289, "s": 4056, "text": "8. -c : This option is used to resume a partially downloaded file if the resume capability of the file is yes otherwise the downloading of the file cannot be resume if the resume capability of the given file is no or not specified. " }, { "code": null, "e": 4298, "s": 4289, "text": "Syntax " }, { "code": null, "e": 4313, "s": 4298, "text": "$wget -c [URL]" }, { "code": null, "e": 4862, "s": 4313, "text": "9. -w : This option is used to set the system to wait the specified number of seconds between the retrievals. Use of this option is recommended, as it lightens the server load by making the requests less frequent. Instead of in seconds, the time can be specified in minutes using the m suffix, in hours using h suffix, or in days using d suffix. Specifying a large value for this option is useful if the network or the destination host is down, so that wget can wait long enough to reasonably expect the network error to be fixed before the retry. " }, { "code": null, "e": 4871, "s": 4862, "text": "Syntax " }, { "code": null, "e": 4904, "s": 4871, "text": "$wget -w number in seconds [URL]" }, { "code": null, "e": 5093, "s": 4904, "text": "10. -r : this option is used to turn on the recursive retrieving of the link specified in case of fatal errors also. This option is a recursive call to the given link in the command line. " }, { "code": null, "e": 5102, "s": 5093, "text": "Syntax " }, { "code": null, "e": 5117, "s": 5102, "text": "$wget -r [URL]" }, { "code": null, "e": 5415, "s": 5117, "text": "This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 5541, "s": 5415, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5556, "s": 5541, "text": "sagar0719kumar" }, { "code": null, "e": 5570, "s": 5556, "text": "linux-command" }, { "code": null, "e": 5596, "s": 5570, "text": "Linux-networking-commands" }, { "code": null, "e": 5607, "s": 5596, "text": "Linux-Unix" }, { "code": null, "e": 5705, "s": 5607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5731, "s": 5705, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5766, "s": 5731, "text": "scp command in Linux with Examples" }, { "code": null, "e": 5803, "s": 5766, "text": "chown command in Linux with Examples" }, { "code": null, "e": 5832, "s": 5803, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 5866, "s": 5832, "text": "mv command in Linux with examples" }, { "code": null, "e": 5903, "s": 5866, "text": "chmod command in Linux with examples" }, { "code": null, "e": 5940, "s": 5903, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 5979, "s": 5940, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 6019, "s": 5979, "text": "Array Basics in Shell Scripting | Set 1" } ]
How to reset input type = “file” using JavaScript/jQuery?
18 Feb, 2022 Jquery: Using wrap method in jquery: The best way to reset input type=file is resetting the whole form. Wrap <input type = “file”> into <form> tags and reset the form: Example-1: html <!DOCTYPE html><html> <head> <title>reset input type = “file”</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $('#resetbtn').on('click', function(e) { var $el = $('#infileid'); $el.wrap('<form>').closest( 'form').get(0).reset(); $el.unwrap(); }); }); </script></head> <body> <center> <h2 style="color:green">GeeksforGeeks</h2> <form id="find" name="formname"> <p> <label>File</label> <input id="infileid" type="file"> </p> <p> <button id="resetbtn" type="button"> Reset file </button> </p> </form> </center></body> </html> Output: Before: After: Using file.value = ”: The simplest way to reset the input is changing the filled value with nothing. this method is workes in every browser. Example-2: HTML <!DOCTYPE html><html> <head> <title> reset input type = “file” </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> function resetFile() { const file = document.querySelector('.file'); file.value = ''; } </script></head> <body> <center> <h2 style="color:green"> GeeksforGeeks </h2> <input type="file" class="file" /> <button onclick="resetFile()"> Reset file </button> </center></body> </html> Output: Before: After: Using wrap method in jquery: Wrap <input type = “file”> in to <form> tags and reset the form: Example-3: html <!DOCTYPE html><html> <head> <title> reset input type = “file” </title> </head> <body> <center> <h2 style="color:green"> GeeksforGeeks </h2> <form id="find" name="formname"> <p> <label>File</label> <input type="file"> </p> <p> <button id="resetbtn" type="button" onClick="this.form.reset()"> Reset file </button> </p> </form> </center></body> </html> Output: Before: After: varshagumber28 JavaScript-Misc jQuery-Misc Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2022" }, { "code": null, "e": 38, "s": 28, "text": "Jquery: " }, { "code": null, "e": 211, "s": 38, "text": "Using wrap method in jquery: The best way to reset input type=file is resetting the whole form. Wrap <input type = “file”> into <form> tags and reset the form: Example-1: " }, { "code": null, "e": 216, "s": 211, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>reset input type = “file”</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $('#resetbtn').on('click', function(e) { var $el = $('#infileid'); $el.wrap('<form>').closest( 'form').get(0).reset(); $el.unwrap(); }); }); </script></head> <body> <center> <h2 style=\"color:green\">GeeksforGeeks</h2> <form id=\"find\" name=\"formname\"> <p> <label>File</label> <input id=\"infileid\" type=\"file\"> </p> <p> <button id=\"resetbtn\" type=\"button\"> Reset file </button> </p> </form> </center></body> </html>", "e": 1179, "s": 216, "text": null }, { "code": null, "e": 1197, "s": 1179, "text": "Output: Before: " }, { "code": null, "e": 1206, "s": 1197, "text": "After: " }, { "code": null, "e": 1362, "s": 1208, "text": "Using file.value = ”: The simplest way to reset the input is changing the filled value with nothing. this method is workes in every browser. Example-2: " }, { "code": null, "e": 1367, "s": 1362, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> reset input type = “file” </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> function resetFile() { const file = document.querySelector('.file'); file.value = ''; } </script></head> <body> <center> <h2 style=\"color:green\"> GeeksforGeeks </h2> <input type=\"file\" class=\"file\" /> <button onclick=\"resetFile()\"> Reset file </button> </center></body> </html>", "e": 2009, "s": 1367, "text": null }, { "code": null, "e": 2027, "s": 2009, "text": "Output: Before: " }, { "code": null, "e": 2036, "s": 2027, "text": "After: " }, { "code": null, "e": 2145, "s": 2038, "text": "Using wrap method in jquery: Wrap <input type = “file”> in to <form> tags and reset the form: Example-3: " }, { "code": null, "e": 2150, "s": 2145, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> reset input type = “file” </title> </head> <body> <center> <h2 style=\"color:green\"> GeeksforGeeks </h2> <form id=\"find\" name=\"formname\"> <p> <label>File</label> <input type=\"file\"> </p> <p> <button id=\"resetbtn\" type=\"button\" onClick=\"this.form.reset()\"> Reset file </button> </p> </form> </center></body> </html>", "e": 2729, "s": 2150, "text": null }, { "code": null, "e": 2747, "s": 2729, "text": "Output: Before: " }, { "code": null, "e": 2756, "s": 2747, "text": "After: " }, { "code": null, "e": 2775, "s": 2760, "text": "varshagumber28" }, { "code": null, "e": 2791, "s": 2775, "text": "JavaScript-Misc" }, { "code": null, "e": 2803, "s": 2791, "text": "jQuery-Misc" }, { "code": null, "e": 2810, "s": 2803, "text": "Picked" }, { "code": null, "e": 2821, "s": 2810, "text": "JavaScript" } ]
How to plot a subset of a dataframe using ggplot2 in R ?
16 May, 2021 In this article, we will discuss how to plot a subset of a dataframe using ggplot2 in the R programming language. Dataframe in use: To get a complete picture, let us first draw a complete dataframe. Example: R # Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c("17", "18", "17", "19", "18", "19", "17", "19", "18") EnrollNo <- c("05", "10", "15", "20", "25", "30", "35", "40", "45") Score <- c("70", "80", "79", "75", "85", "96", "90", "71", "83") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Create a simple Scatter Plotggplot(data, aes(Score, EnrollNo)) + geom_point(color = "green", size = 3) Output: Simple Scatter Plot Now, we will see all methods to create an R Plot using subset of DataFrame one by one. Here, we use subset() function for plotting only subset of DataFrame inside ggplot() function inplace of data DataFrame. All other things are same. Syntax: subset(obj, ...) Parameters: It takes data object to be subsetted as it’s first parameter. subset() function can have many other parameters. only obj is necessary to take. here we only use logical expression indicating rows as a second argument. Return : subset() function returns subset of DataFrame. Example: R # Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c("17", "18", "17", "19", "18", "19", "17", "19", "18") EnrollNo <- c("05", "10", "15", "20", "25", "30", "35", "40", "45") Score <- c("70", "80", "79", "75", "85", "96", "90", "71", "83") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Generate R Scatter Plot only where Age # variable has value "18"ggplot(subset(data, Age %in% "18"), aes(Score, EnrollNo)) + geom_point(color = "green", size = 3) Output: Scatter Plot using only subset of DataFrame by sunset() function In this method we are not using subset() function, but we write logical expression for retrieve subset of DataFrame in Square Brackets and assign it to subset variable. Example: R # Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c("17", "18", "17", "19", "18", "19", "17", "19", "18") EnrollNo <- c("05", "10", "15", "20", "25", "30", "35", "40", "45") Score <- c("70", "80", "79", "75", "85", "96", "90", "71", "83") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Create a Variable 'data_subset' # which has the values equal to # "19" values of Age object.data_subset <- data[data$Age %in% "19", ] # Generate R Scatter Plot only where# Age variable has value "19"ggplot(data_subset, aes(Score, EnrollNo)) + geom_point(color = "green", size = 3) Output: Scatter Plot using only subset of DataFrame by Square Brackets In this method, We use square brackets to write expression for subset of DataFrame, but we use it inside ggplot() function in place of dataframe object. Example R # Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c("17", "18", "17", "19", "18", "19", "17", "19", "18") EnrollNo <- c("05", "10", "15", "20", "25", "30", "35", "40", "45") Score <- c("70", "80", "79", "75", "85", "96", "90", "71", "83") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Generate R Scatter Plot only where# Age variable has value "17"ggplot(data[data$Age %in% "17", ], aes(Score, EnrollNo)) + geom_point(color = "green", size = 3) Output: Picked R-DataFrame R-ggplot 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 142, "s": 28, "text": "In this article, we will discuss how to plot a subset of a dataframe using ggplot2 in the R programming language." }, { "code": null, "e": 160, "s": 142, "text": "Dataframe in use:" }, { "code": null, "e": 227, "s": 160, "text": "To get a complete picture, let us first draw a complete dataframe." }, { "code": null, "e": 236, "s": 227, "text": "Example:" }, { "code": null, "e": 238, "s": 236, "text": "R" }, { "code": "# Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c(\"17\", \"18\", \"17\", \"19\", \"18\", \"19\", \"17\", \"19\", \"18\") EnrollNo <- c(\"05\", \"10\", \"15\", \"20\", \"25\", \"30\", \"35\", \"40\", \"45\") Score <- c(\"70\", \"80\", \"79\", \"75\", \"85\", \"96\", \"90\", \"71\", \"83\") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Create a simple Scatter Plotggplot(data, aes(Score, EnrollNo)) + geom_point(color = \"green\", size = 3)", "e": 713, "s": 238, "text": null }, { "code": null, "e": 721, "s": 713, "text": "Output:" }, { "code": null, "e": 741, "s": 721, "text": "Simple Scatter Plot" }, { "code": null, "e": 828, "s": 741, "text": "Now, we will see all methods to create an R Plot using subset of DataFrame one by one." }, { "code": null, "e": 976, "s": 828, "text": "Here, we use subset() function for plotting only subset of DataFrame inside ggplot() function inplace of data DataFrame. All other things are same." }, { "code": null, "e": 1001, "s": 976, "text": "Syntax: subset(obj, ...)" }, { "code": null, "e": 1013, "s": 1001, "text": "Parameters:" }, { "code": null, "e": 1075, "s": 1013, "text": "It takes data object to be subsetted as it’s first parameter." }, { "code": null, "e": 1230, "s": 1075, "text": "subset() function can have many other parameters. only obj is necessary to take. here we only use logical expression indicating rows as a second argument." }, { "code": null, "e": 1286, "s": 1230, "text": "Return : subset() function returns subset of DataFrame." }, { "code": null, "e": 1295, "s": 1286, "text": "Example:" }, { "code": null, "e": 1297, "s": 1295, "text": "R" }, { "code": "# Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c(\"17\", \"18\", \"17\", \"19\", \"18\", \"19\", \"17\", \"19\", \"18\") EnrollNo <- c(\"05\", \"10\", \"15\", \"20\", \"25\", \"30\", \"35\", \"40\", \"45\") Score <- c(\"70\", \"80\", \"79\", \"75\", \"85\", \"96\", \"90\", \"71\", \"83\") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Generate R Scatter Plot only where Age # variable has value \"18\"ggplot(subset(data, Age %in% \"18\"), aes(Score, EnrollNo)) + geom_point(color = \"green\", size = 3)", "e": 1834, "s": 1297, "text": null }, { "code": null, "e": 1842, "s": 1834, "text": "Output:" }, { "code": null, "e": 1908, "s": 1842, "text": "Scatter Plot using only subset of DataFrame by sunset() function " }, { "code": null, "e": 2077, "s": 1908, "text": "In this method we are not using subset() function, but we write logical expression for retrieve subset of DataFrame in Square Brackets and assign it to subset variable." }, { "code": null, "e": 2086, "s": 2077, "text": "Example:" }, { "code": null, "e": 2088, "s": 2086, "text": "R" }, { "code": "# Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c(\"17\", \"18\", \"17\", \"19\", \"18\", \"19\", \"17\", \"19\", \"18\") EnrollNo <- c(\"05\", \"10\", \"15\", \"20\", \"25\", \"30\", \"35\", \"40\", \"45\") Score <- c(\"70\", \"80\", \"79\", \"75\", \"85\", \"96\", \"90\", \"71\", \"83\") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Create a Variable 'data_subset' # which has the values equal to # \"19\" values of Age object.data_subset <- data[data$Age %in% \"19\", ] # Generate R Scatter Plot only where# Age variable has value \"19\"ggplot(data_subset, aes(Score, EnrollNo)) + geom_point(color = \"green\", size = 3)", "e": 2743, "s": 2088, "text": null }, { "code": null, "e": 2751, "s": 2743, "text": "Output:" }, { "code": null, "e": 2815, "s": 2751, "text": "Scatter Plot using only subset of DataFrame by Square Brackets " }, { "code": null, "e": 2969, "s": 2815, "text": "In this method, We use square brackets to write expression for subset of DataFrame, but we use it inside ggplot() function in place of dataframe object. " }, { "code": null, "e": 2977, "s": 2969, "text": "Example" }, { "code": null, "e": 2979, "s": 2977, "text": "R" }, { "code": "# Load ggplot2 packagelibrary(ggplot2) # Create Data For plottingAge <- c(\"17\", \"18\", \"17\", \"19\", \"18\", \"19\", \"17\", \"19\", \"18\") EnrollNo <- c(\"05\", \"10\", \"15\", \"20\", \"25\", \"30\", \"35\", \"40\", \"45\") Score <- c(\"70\", \"80\", \"79\", \"75\", \"85\", \"96\", \"90\", \"71\", \"83\") # Create a DataFrame from Datadata <- data.frame(Age, EnrollNo, Score) # Generate R Scatter Plot only where# Age variable has value \"17\"ggplot(data[data$Age %in% \"17\", ], aes(Score, EnrollNo)) + geom_point(color = \"green\", size = 3)", "e": 3513, "s": 2979, "text": null }, { "code": null, "e": 3522, "s": 3513, "text": "Output: " }, { "code": null, "e": 3529, "s": 3522, "text": "Picked" }, { "code": null, "e": 3541, "s": 3529, "text": "R-DataFrame" }, { "code": null, "e": 3550, "s": 3541, "text": "R-ggplot" }, { "code": null, "e": 3561, "s": 3550, "text": "R Language" }, { "code": null, "e": 3659, "s": 3561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3711, "s": 3659, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3769, "s": 3711, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3804, "s": 3769, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3842, "s": 3804, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3891, "s": 3842, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3908, "s": 3891, "text": "R - if statement" }, { "code": null, "e": 3945, "s": 3908, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3988, "s": 3945, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 4025, "s": 3988, "text": "How to import an Excel File into R ?" } ]
Frequency of a string in an array of strings
16 Jun, 2022 You are given a collection of strings and a list of queries. For every query there is a string given. We need to print the number of times the given string occurs in the collection of strings. Examples: Input : arr[] = {wer, wer, tyu, oio, tyu} q[] = {wer, tyu, uio} Output : 2 2 0 Explanation : q[0] appears two times in arr[], q1[] appears The idea is simple, for every query string we compare it with all strings given in array. If the query string is matches, we increment count. C++ Java Python3 C# PHP Javascript // C++ program to find number of times a// string appears in an array.#include<bits/stdc++.h>using namespace std; // Returns count of occurrences of s in arr[]int search(string arr[], string s, int n){ int counter = 0; for(int j = 0; j < n; j++) // Checking if string given in query // is present in the given string. // If present, increase times if (s == arr[j]) counter++; return counter;} void answerQueries(string arr[], string q[], int n, int m){ for(int i = 0; i < m; i++) cout << search(arr, q[i], n) << " ";} // Driver Codeint main(){ string arr[] = { "aba", "baba", "aba", "xzxb" }; string q[] = { "aba", "xzxb", "ab" }; int n = sizeof(arr) / sizeof(arr[0]); int m = sizeof(q) / sizeof(q[0]); answerQueries(arr, q, n, m);} // This code is contributed by rutvik_56 // Java program to find number of times a string// appears in an array.class SubString{ /* Returns count of occurrences of s in arr[] */ static int search(String[]arr, String s) { int counter = 0; for (int j = 0; j < arr.length; j++) /* checking if string given in query is present in the given string. If present, increase times*/ if (s.equals(arr[j])) counter++; return counter; } static void answerQueries(String[] arr, String q[]) { for (int i=0;i<q.length; i++) System.out.print(search(arr, q[i]) + " "); } /* driver code*/ public static void main(String[] args) { String[] arr = {"aba","baba","aba","xzxb"}; String[] q = {"aba","xzxb","ab"}; answerQueries(arr, q); }} # Python3 program to find number of# times a string appears in an array. # Returns count of occurrences of s in arr[]def search(arr, s): counter = 0 for j in range(len(arr)): # checking if string given in query # is present in the given string. # If present, increase times if (s == (arr[j])): counter += 1 return counter def answerQueries(arr, q): for i in range(len(q)): print(search(arr, q[i]), end = " ") # Driver codeif __name__ == '__main__': arr = ["aba", "baba", "aba", "xzxb"] q = ["aba", "xzxb", "ab"] answerQueries(arr, q) # This code is contributed# by PrinciRaj19992 // C# program to find number of// times a string appears in an array.using System; class SubString{ /* Returns count of occurrences of s in arr[] */ static int search(String[]arr, String s) { int counter = 0; for (int j = 0; j < arr.Length; j++) /* checking if string given in query is present in the given string. If present, increase times*/ if (s.Equals(arr[j])) counter++; return counter; } static void answerQueries(String []arr, String []q) { for (int i = 0; i < q.Length; i++) Console.Write(search(arr, q[i]) + " "); } // Driver code public static void Main() { String []arr = {"aba","baba","aba","xzxb"}; String []q = {"aba","xzxb","ab"}; answerQueries(arr, q); }} //This code is contributed by nitin mittal <?php# Php program to find number of# times a string appears in an array. # Returns count of occurrences of s in arr[]function search($arr, $s){ $counter = 0; for ($j=0; $j<count($arr); $j++) { # checking if string given in query # is present in the given string. # If present, increase times if ($s == ($arr[$j])) $counter += 1; } return $counter;}function answerQueries($arr, $q){ for ($i=0; $i<count($q); $i++) { echo(search($arr, $q[$i])); echo (" "); }} # Driver code $arr = array("aba", "baba", "aba", "xzxb");$q = array("aba", "xzxb", "ab");answerQueries($arr, $q); # This code is contributed# by Shivi_Aggarwal?> <script>// javascript program to find number of times a string// appears in an array. /* Returns count of occurrences of s in arr */ function search( arr, s) { var counter = 0; for (j = 0; j < arr.length; j++) /* * checking if string given in query is present in the given string. If present, * increase times */ if (s === (arr[j])) counter++; return counter; } function answerQueries( arr, q) { for (i = 0; i < q.length; i++) document.write(search(arr, q[i]) + " "); } /* driver code */ var arr = [ "aba", "baba", "aba", "xzxb" ]; var q = [ "aba", "xzxb", "ab" ]; answerQueries(arr, q); // This code is contributed by gauravrajput1</script> Output: 2 1 0 Trie an efficient data structure used for strong and retrieval of data like strings. The searching complexity is optimal as key length. In this solution we insert the collection of strings in the Trie data structure so they get stored in it. One important thing is, we keep count of occurrences in leaf nodes. Then we search the Trie for the given query string and check if it is present in the Trie. CPP Java Python3 Javascript // C++ program to count number of times// a string appears in an array of strings#include<iostream>using namespace std; const int MAX_CHAR = 26; struct Trie{ // To store number of times // a string is present. It is // 0 is string is not present int cnt; Trie *node[MAX_CHAR]; Trie() { for(int i=0; i<MAX_CHAR; i++) node[i] = NULL; cnt = 0; }}; /* function to insert a string into the Trie*/Trie *insert(Trie *root,string s){ Trie *temp = root; int n = s.size(); for(int i=0; i<n; i++) { /*calculation ascii value*/ int index = s[i]-'a'; /* If the given node is not already present in the Trie than create the new node*/ if (!root->node[index]) root->node[index] = new Trie(); root = root->node[index]; } root->cnt++; return temp;} /* Returns count of occurrences of s in Trie*/int search(Trie *root, string s){ int n = s.size(); for (int i=0; i<n; i++) { int index = s[i]-'a'; if (!root->node[index]) return 0; root = root->node[index]; } return root->cnt;} void answerQueries(string arr[], int n, string q[], int m){ Trie *root = new Trie(); /* inserting in Trie */ for (int i=0; i<n; i++) root = insert(root,arr[i]); /* searching the strings in Trie */ for (int i=0; i<m; i++) cout << search(root, q[i]) << " "; } /* Driver code */int main(){ string arr[] = {"aba","baba","aba","xzxb"}; int n = sizeof(arr)/sizeof(arr[0]); string q[] = {"aba","xzxb","ab"}; int m = sizeof(q)/sizeof(q[0]); answerQueries(arr, n, q, m); return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG{ // Java program to count number of times// a string appears in an array of string static int MAX_CHAR = 26; static class Trie{ // To store number of times // a string is present. It is // 0 is string is not present public int cnt; public Trie node[] = new Trie[MAX_CHAR]; public Trie() { for(int i=0; i<MAX_CHAR; i++) node[i] = null; cnt = 0; }} /* function to insert a string into the Trie*/static Trie insert(Trie root,String s){ Trie temp = root; int n = s.length(); for(int i=0; i<n; i++) { /*calculation ascii value*/ int index = (int)s.charAt(i) - (int)'a'; /* If the given node is not already present in the Trie than create the new node*/ if (root.node[index] == null) root.node[index] = new Trie(); root = root.node[index]; } root.cnt++; return temp;} /* Returns count of occurrences of s in Trie*/static int search(Trie root, String s){ int n = s.length(); for (int i=0; i<n; i++) { int index = (int)s.charAt(i) - (int)'a'; if (root.node[index] == null) return 0; root = root.node[index]; } return root.cnt;} static void answerQueries(String arr[], int n, String q[], int m){ Trie root = new Trie(); /* inserting in Trie */ for (int i=0; i<n; i++) root = insert(root,arr[i]); /* searching the Strings in Trie */ for (int i=0; i<m; i++) System.out.print(search(root, q[i]) + " "); } // Driver Codepublic static void main(String args[]){ String arr[] = {"aba","baba","aba","xzxb"}; int n = arr.length; String q[] = {"aba","xzxb","ab"}; int m = q.length; answerQueries(arr, n, q, m);}} // This code is contributed by shinjanpatra # Python3 program to count number of times# a string appears in an array of stringsMAX_CHAR = 26 class Trie: # To store number of times # a string is present. It is # 0 is string is not present def __init__(self): self.cnt = 0 self.node = [None for i in range(MAX_CHAR)] # function to insert a string into the Triedef insert(root, s): temp = root n = len(s) for i in range(n): # calculation ascii value index = ord(s[i]) - ord('a') ''' If the given node is not already present in the Trie than create the new node ''' if (not root.node[index]): root.node[index] = Trie() root = root.node[index] root.cnt += 1 return temp # Returns count of occurrences of s in Triedef search( root, s): n = len(s) for i in range(n): index = ord(s[i]) - ord('a') if (not root.node[index]): return 0 root = root.node[index] return root.cnt def answerQueries(arr, n, q, m): root = Trie() # inserting in Trie for i in range(n): root = insert(root, arr[i]) # searching the strings in Trie for i in range(m): print(search(root, q[i])) # Driver codeif __name__=='__main__': arr = ["aba", "baba", "aba", "xzxb"] n = len(arr) q = ["aba", "xzxb", "ab"] m = len(q) answerQueries(arr, n, q, m) # This code is contributed by pratham76 <script> // JavaScript program to count number of times// a string appears in an array of stringsconst MAX_CHAR = 26 class Trie{ // To store number of times // a string is present. It is // 0 is string is not present constructor(){ this.cnt = 0 this.node = new Array(MAX_CHAR).fill(null) }} // function to insert a string into the Triefunction insert(root, s){ let temp = root let n = s.length for(let i=0;i<n;i++){ // calculation ascii value let index = s.charCodeAt(i) - 'a'.charCodeAt(0) // If the given node is not already // present in the Trie than create // the new node if (!root.node[index]){ root.node[index] = new Trie() } root = root.node[index] } root.cnt += 1 return temp} // Returns count of occurrences of s in Triefunction search(root,s){ let n = s.length for(let i=0;i<n;i++){ let index = s.charCodeAt(i) - 'a'.charCodeAt(0) if (!root.node[index]) return 0 root = root.node[index] } return root.cnt} function answerQueries(arr, n, q, m){ let root = new Trie() // inserting in Trie for(let i = 0; i < n; i++){ root = insert(root, arr[i]) } // searching the strings in Trie for(let i = 0; i < m; i++){ document.write(search(root, q[i]),"</br>") }} // Driver code let arr = ["aba", "baba", "aba", "xzxb"]let n = arr.length let q = ["aba", "xzxb", "ab"]let m = q.length answerQueries(arr, n, q, m) // This code is contributed by shinjanpatra </script> Output: 2 1 0 We can use a hash map and insert all given strings into it. For every query string, we simply do a look-up in the hash map.Please refer Data Structure for Dictionary for comparison of hashing and Trie based solutions.This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal princiraj1992 Shivi_Aggarwal rutvik_56 pratham76 GauravRajput1 shinjanpatra Trie Hash Strings Hash Strings Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hash Functions and list/types of Hash functions Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorting a Map by value in C++ STL Sort string of characters File Organization in DBMS | Set 2 Reverse a string in Java Write a program to reverse an array or string C++ Data Types KMP Algorithm for Pattern Searching Write a program to print all permutations of a given string
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 258, "s": 54, "text": "You are given a collection of strings and a list of queries. For every query there is a string given. We need to print the number of times the given string occurs in the collection of strings. Examples: " }, { "code": null, "e": 408, "s": 258, "text": "Input : arr[] = {wer, wer, tyu, oio, tyu}\n q[] = {wer, tyu, uio}\nOutput : 2 2 0\nExplanation : \nq[0] appears two times in arr[], q1[] appears" }, { "code": null, "e": 552, "s": 408, "text": "The idea is simple, for every query string we compare it with all strings given in array. If the query string is matches, we increment count. " }, { "code": null, "e": 556, "s": 552, "text": "C++" }, { "code": null, "e": 561, "s": 556, "text": "Java" }, { "code": null, "e": 569, "s": 561, "text": "Python3" }, { "code": null, "e": 572, "s": 569, "text": "C#" }, { "code": null, "e": 576, "s": 572, "text": "PHP" }, { "code": null, "e": 587, "s": 576, "text": "Javascript" }, { "code": "// C++ program to find number of times a// string appears in an array.#include<bits/stdc++.h>using namespace std; // Returns count of occurrences of s in arr[]int search(string arr[], string s, int n){ int counter = 0; for(int j = 0; j < n; j++) // Checking if string given in query // is present in the given string. // If present, increase times if (s == arr[j]) counter++; return counter;} void answerQueries(string arr[], string q[], int n, int m){ for(int i = 0; i < m; i++) cout << search(arr, q[i], n) << \" \";} // Driver Codeint main(){ string arr[] = { \"aba\", \"baba\", \"aba\", \"xzxb\" }; string q[] = { \"aba\", \"xzxb\", \"ab\" }; int n = sizeof(arr) / sizeof(arr[0]); int m = sizeof(q) / sizeof(q[0]); answerQueries(arr, q, n, m);} // This code is contributed by rutvik_56", "e": 1494, "s": 587, "text": null }, { "code": "// Java program to find number of times a string// appears in an array.class SubString{ /* Returns count of occurrences of s in arr[] */ static int search(String[]arr, String s) { int counter = 0; for (int j = 0; j < arr.length; j++) /* checking if string given in query is present in the given string. If present, increase times*/ if (s.equals(arr[j])) counter++; return counter; } static void answerQueries(String[] arr, String q[]) { for (int i=0;i<q.length; i++) System.out.print(search(arr, q[i]) + \" \"); } /* driver code*/ public static void main(String[] args) { String[] arr = {\"aba\",\"baba\",\"aba\",\"xzxb\"}; String[] q = {\"aba\",\"xzxb\",\"ab\"}; answerQueries(arr, q); }}", "e": 2359, "s": 1494, "text": null }, { "code": "# Python3 program to find number of# times a string appears in an array. # Returns count of occurrences of s in arr[]def search(arr, s): counter = 0 for j in range(len(arr)): # checking if string given in query # is present in the given string. # If present, increase times if (s == (arr[j])): counter += 1 return counter def answerQueries(arr, q): for i in range(len(q)): print(search(arr, q[i]), end = \" \") # Driver codeif __name__ == '__main__': arr = [\"aba\", \"baba\", \"aba\", \"xzxb\"] q = [\"aba\", \"xzxb\", \"ab\"] answerQueries(arr, q) # This code is contributed# by PrinciRaj19992", "e": 3037, "s": 2359, "text": null }, { "code": "// C# program to find number of// times a string appears in an array.using System; class SubString{ /* Returns count of occurrences of s in arr[] */ static int search(String[]arr, String s) { int counter = 0; for (int j = 0; j < arr.Length; j++) /* checking if string given in query is present in the given string. If present, increase times*/ if (s.Equals(arr[j])) counter++; return counter; } static void answerQueries(String []arr, String []q) { for (int i = 0; i < q.Length; i++) Console.Write(search(arr, q[i]) + \" \"); } // Driver code public static void Main() { String []arr = {\"aba\",\"baba\",\"aba\",\"xzxb\"}; String []q = {\"aba\",\"xzxb\",\"ab\"}; answerQueries(arr, q); }} //This code is contributed by nitin mittal", "e": 3937, "s": 3037, "text": null }, { "code": "<?php# Php program to find number of# times a string appears in an array. # Returns count of occurrences of s in arr[]function search($arr, $s){ $counter = 0; for ($j=0; $j<count($arr); $j++) { # checking if string given in query # is present in the given string. # If present, increase times if ($s == ($arr[$j])) $counter += 1; } return $counter;}function answerQueries($arr, $q){ for ($i=0; $i<count($q); $i++) { echo(search($arr, $q[$i])); echo (\" \"); }} # Driver code $arr = array(\"aba\", \"baba\", \"aba\", \"xzxb\");$q = array(\"aba\", \"xzxb\", \"ab\");answerQueries($arr, $q); # This code is contributed# by Shivi_Aggarwal?>", "e": 4635, "s": 3937, "text": null }, { "code": "<script>// javascript program to find number of times a string// appears in an array. /* Returns count of occurrences of s in arr */ function search( arr, s) { var counter = 0; for (j = 0; j < arr.length; j++) /* * checking if string given in query is present in the given string. If present, * increase times */ if (s === (arr[j])) counter++; return counter; } function answerQueries( arr, q) { for (i = 0; i < q.length; i++) document.write(search(arr, q[i]) + \" \"); } /* driver code */ var arr = [ \"aba\", \"baba\", \"aba\", \"xzxb\" ]; var q = [ \"aba\", \"xzxb\", \"ab\" ]; answerQueries(arr, q); // This code is contributed by gauravrajput1</script>", "e": 5434, "s": 4635, "text": null }, { "code": null, "e": 5443, "s": 5434, "text": "Output: " }, { "code": null, "e": 5449, "s": 5443, "text": "2 1 0" }, { "code": null, "e": 5852, "s": 5449, "text": "Trie an efficient data structure used for strong and retrieval of data like strings. The searching complexity is optimal as key length. In this solution we insert the collection of strings in the Trie data structure so they get stored in it. One important thing is, we keep count of occurrences in leaf nodes. Then we search the Trie for the given query string and check if it is present in the Trie. " }, { "code": null, "e": 5856, "s": 5852, "text": "CPP" }, { "code": null, "e": 5861, "s": 5856, "text": "Java" }, { "code": null, "e": 5869, "s": 5861, "text": "Python3" }, { "code": null, "e": 5880, "s": 5869, "text": "Javascript" }, { "code": "// C++ program to count number of times// a string appears in an array of strings#include<iostream>using namespace std; const int MAX_CHAR = 26; struct Trie{ // To store number of times // a string is present. It is // 0 is string is not present int cnt; Trie *node[MAX_CHAR]; Trie() { for(int i=0; i<MAX_CHAR; i++) node[i] = NULL; cnt = 0; }}; /* function to insert a string into the Trie*/Trie *insert(Trie *root,string s){ Trie *temp = root; int n = s.size(); for(int i=0; i<n; i++) { /*calculation ascii value*/ int index = s[i]-'a'; /* If the given node is not already present in the Trie than create the new node*/ if (!root->node[index]) root->node[index] = new Trie(); root = root->node[index]; } root->cnt++; return temp;} /* Returns count of occurrences of s in Trie*/int search(Trie *root, string s){ int n = s.size(); for (int i=0; i<n; i++) { int index = s[i]-'a'; if (!root->node[index]) return 0; root = root->node[index]; } return root->cnt;} void answerQueries(string arr[], int n, string q[], int m){ Trie *root = new Trie(); /* inserting in Trie */ for (int i=0; i<n; i++) root = insert(root,arr[i]); /* searching the strings in Trie */ for (int i=0; i<m; i++) cout << search(root, q[i]) << \" \"; } /* Driver code */int main(){ string arr[] = {\"aba\",\"baba\",\"aba\",\"xzxb\"}; int n = sizeof(arr)/sizeof(arr[0]); string q[] = {\"aba\",\"xzxb\",\"ab\"}; int m = sizeof(q)/sizeof(q[0]); answerQueries(arr, n, q, m); return 0;}", "e": 7590, "s": 5880, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG{ // Java program to count number of times// a string appears in an array of string static int MAX_CHAR = 26; static class Trie{ // To store number of times // a string is present. It is // 0 is string is not present public int cnt; public Trie node[] = new Trie[MAX_CHAR]; public Trie() { for(int i=0; i<MAX_CHAR; i++) node[i] = null; cnt = 0; }} /* function to insert a string into the Trie*/static Trie insert(Trie root,String s){ Trie temp = root; int n = s.length(); for(int i=0; i<n; i++) { /*calculation ascii value*/ int index = (int)s.charAt(i) - (int)'a'; /* If the given node is not already present in the Trie than create the new node*/ if (root.node[index] == null) root.node[index] = new Trie(); root = root.node[index]; } root.cnt++; return temp;} /* Returns count of occurrences of s in Trie*/static int search(Trie root, String s){ int n = s.length(); for (int i=0; i<n; i++) { int index = (int)s.charAt(i) - (int)'a'; if (root.node[index] == null) return 0; root = root.node[index]; } return root.cnt;} static void answerQueries(String arr[], int n, String q[], int m){ Trie root = new Trie(); /* inserting in Trie */ for (int i=0; i<n; i++) root = insert(root,arr[i]); /* searching the Strings in Trie */ for (int i=0; i<m; i++) System.out.print(search(root, q[i]) + \" \"); } // Driver Codepublic static void main(String args[]){ String arr[] = {\"aba\",\"baba\",\"aba\",\"xzxb\"}; int n = arr.length; String q[] = {\"aba\",\"xzxb\",\"ab\"}; int m = q.length; answerQueries(arr, n, q, m);}} // This code is contributed by shinjanpatra", "e": 9506, "s": 7590, "text": null }, { "code": "# Python3 program to count number of times# a string appears in an array of stringsMAX_CHAR = 26 class Trie: # To store number of times # a string is present. It is # 0 is string is not present def __init__(self): self.cnt = 0 self.node = [None for i in range(MAX_CHAR)] # function to insert a string into the Triedef insert(root, s): temp = root n = len(s) for i in range(n): # calculation ascii value index = ord(s[i]) - ord('a') ''' If the given node is not already present in the Trie than create the new node ''' if (not root.node[index]): root.node[index] = Trie() root = root.node[index] root.cnt += 1 return temp # Returns count of occurrences of s in Triedef search( root, s): n = len(s) for i in range(n): index = ord(s[i]) - ord('a') if (not root.node[index]): return 0 root = root.node[index] return root.cnt def answerQueries(arr, n, q, m): root = Trie() # inserting in Trie for i in range(n): root = insert(root, arr[i]) # searching the strings in Trie for i in range(m): print(search(root, q[i])) # Driver codeif __name__=='__main__': arr = [\"aba\", \"baba\", \"aba\", \"xzxb\"] n = len(arr) q = [\"aba\", \"xzxb\", \"ab\"] m = len(q) answerQueries(arr, n, q, m) # This code is contributed by pratham76", "e": 10932, "s": 9506, "text": null }, { "code": "<script> // JavaScript program to count number of times// a string appears in an array of stringsconst MAX_CHAR = 26 class Trie{ // To store number of times // a string is present. It is // 0 is string is not present constructor(){ this.cnt = 0 this.node = new Array(MAX_CHAR).fill(null) }} // function to insert a string into the Triefunction insert(root, s){ let temp = root let n = s.length for(let i=0;i<n;i++){ // calculation ascii value let index = s.charCodeAt(i) - 'a'.charCodeAt(0) // If the given node is not already // present in the Trie than create // the new node if (!root.node[index]){ root.node[index] = new Trie() } root = root.node[index] } root.cnt += 1 return temp} // Returns count of occurrences of s in Triefunction search(root,s){ let n = s.length for(let i=0;i<n;i++){ let index = s.charCodeAt(i) - 'a'.charCodeAt(0) if (!root.node[index]) return 0 root = root.node[index] } return root.cnt} function answerQueries(arr, n, q, m){ let root = new Trie() // inserting in Trie for(let i = 0; i < n; i++){ root = insert(root, arr[i]) } // searching the strings in Trie for(let i = 0; i < m; i++){ document.write(search(root, q[i]),\"</br>\") }} // Driver code let arr = [\"aba\", \"baba\", \"aba\", \"xzxb\"]let n = arr.length let q = [\"aba\", \"xzxb\", \"ab\"]let m = q.length answerQueries(arr, n, q, m) // This code is contributed by shinjanpatra </script>", "e": 12508, "s": 10932, "text": null }, { "code": null, "e": 12517, "s": 12508, "text": "Output: " }, { "code": null, "e": 12523, "s": 12517, "text": "2\n1\n0" }, { "code": null, "e": 13155, "s": 12523, "text": "We can use a hash map and insert all given strings into it. For every query string, we simply do a look-up in the hash map.Please refer Data Structure for Dictionary for comparison of hashing and Trie based solutions.This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13168, "s": 13155, "text": "nitin mittal" }, { "code": null, "e": 13182, "s": 13168, "text": "princiraj1992" }, { "code": null, "e": 13197, "s": 13182, "text": "Shivi_Aggarwal" }, { "code": null, "e": 13207, "s": 13197, "text": "rutvik_56" }, { "code": null, "e": 13217, "s": 13207, "text": "pratham76" }, { "code": null, "e": 13231, "s": 13217, "text": "GauravRajput1" }, { "code": null, "e": 13244, "s": 13231, "text": "shinjanpatra" }, { "code": null, "e": 13249, "s": 13244, "text": "Trie" }, { "code": null, "e": 13254, "s": 13249, "text": "Hash" }, { "code": null, "e": 13262, "s": 13254, "text": "Strings" }, { "code": null, "e": 13267, "s": 13262, "text": "Hash" }, { "code": null, "e": 13275, "s": 13267, "text": "Strings" }, { "code": null, "e": 13280, "s": 13275, "text": "Trie" }, { "code": null, "e": 13378, "s": 13280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13426, "s": 13378, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 13496, "s": 13426, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 13530, "s": 13496, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 13556, "s": 13530, "text": "Sort string of characters" }, { "code": null, "e": 13590, "s": 13556, "text": "File Organization in DBMS | Set 2" }, { "code": null, "e": 13615, "s": 13590, "text": "Reverse a string in Java" }, { "code": null, "e": 13661, "s": 13615, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 13676, "s": 13661, "text": "C++ Data Types" }, { "code": null, "e": 13712, "s": 13676, "text": "KMP Algorithm for Pattern Searching" } ]
Fruitful Functions and Void Functions in Julia
25 Aug, 2020 Functions are one of the most useful tools when writing a program. Every programming language including Julia uses functions, it can be for keeping the code simple and readable or to keep the program secure from outside interference. In almost every programming language there are two types of functions: Fruitful Functions Void Functions These are the functions that return a value after their completion. A fruitful function must always return a value to where it is called from. A fruitful function can return any type of value may it be string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one variable, the value to be returned can be an array or a vector. A fruitful function can also return multiple values. Example 1: # Creation of Functionfunction add_f(a, b); c = a + b; # Returning the value return c;end # Function calld = add_f(3, 4);print(d) Output: Example 2: # Creation of Functionfunction mul_f(a, b, c); d = a * b * c; # Returning the result # to caller function return d;end # Function callx = mul_f(2, 4, 6);print(x) Output: Void functions are those that do not return any value after their calculation is complete. These types of functions are used when the calculations of the functions are not needed in the actual program. These types of functions perform tasks that are crucial to successfully run the program but do not give a specific value to be used in the program. Example 1: # Creation of Functionfunction add_v(a, b); c = a + b; print(c);end # Function Calladd_v(3, 4) Output: Example 2: # Creation of Functionfunction mul_v(a, b, c) print(a * b * c);end # Function Callmul_v(2, 4, 6) Output: Julia-functions Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) NamedTuple in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Getting the maximum value from a list in Julia - max() Method Join an array of strings into a single string in Julia - join() Method Difference Between MATLAB and Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2020" }, { "code": null, "e": 333, "s": 28, "text": "Functions are one of the most useful tools when writing a program. Every programming language including Julia uses functions, it can be for keeping the code simple and readable or to keep the program secure from outside interference. In almost every programming language there are two types of functions:" }, { "code": null, "e": 352, "s": 333, "text": "Fruitful Functions" }, { "code": null, "e": 367, "s": 352, "text": "Void Functions" }, { "code": null, "e": 788, "s": 367, "text": "These are the functions that return a value after their completion. A fruitful function must always return a value to where it is called from. A fruitful function can return any type of value may it be string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one variable, the value to be returned can be an array or a vector. A fruitful function can also return multiple values." }, { "code": null, "e": 799, "s": 788, "text": "Example 1:" }, { "code": "# Creation of Functionfunction add_f(a, b); c = a + b; # Returning the value return c;end # Function calld = add_f(3, 4);print(d)", "e": 945, "s": 799, "text": null }, { "code": null, "e": 953, "s": 945, "text": "Output:" }, { "code": null, "e": 964, "s": 953, "text": "Example 2:" }, { "code": "# Creation of Functionfunction mul_f(a, b, c); d = a * b * c; # Returning the result # to caller function return d;end # Function callx = mul_f(2, 4, 6);print(x)", "e": 1146, "s": 964, "text": null }, { "code": null, "e": 1154, "s": 1146, "text": "Output:" }, { "code": null, "e": 1504, "s": 1154, "text": "Void functions are those that do not return any value after their calculation is complete. These types of functions are used when the calculations of the functions are not needed in the actual program. These types of functions perform tasks that are crucial to successfully run the program but do not give a specific value to be used in the program." }, { "code": null, "e": 1515, "s": 1504, "text": "Example 1:" }, { "code": "# Creation of Functionfunction add_v(a, b); c = a + b; print(c);end # Function Calladd_v(3, 4)", "e": 1617, "s": 1515, "text": null }, { "code": null, "e": 1625, "s": 1617, "text": "Output:" }, { "code": null, "e": 1636, "s": 1625, "text": "Example 2:" }, { "code": "# Creation of Functionfunction mul_v(a, b, c) print(a * b * c);end # Function Callmul_v(2, 4, 6)", "e": 1737, "s": 1636, "text": null }, { "code": null, "e": 1745, "s": 1737, "text": "Output:" }, { "code": null, "e": 1761, "s": 1745, "text": "Julia-functions" }, { "code": null, "e": 1768, "s": 1761, "text": "Picked" }, { "code": null, "e": 1774, "s": 1768, "text": "Julia" }, { "code": null, "e": 1872, "s": 1774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1900, "s": 1872, "text": "Exception handling in Julia" }, { "code": null, "e": 1970, "s": 1900, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 2029, "s": 1970, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 2102, "s": 2029, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 2122, "s": 2102, "text": "NamedTuple in Julia" }, { "code": null, "e": 2170, "s": 2122, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 2240, "s": 2170, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 2302, "s": 2240, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 2373, "s": 2302, "text": "Join an array of strings into a single string in Julia - join() Method" } ]
C++ program to append content of one text file to another
16 Jun, 2022 Given source and destination text files. Append the content from the source file to the destination file and then display the content of the destination file.Example : Input : file.txt : "geeks", file2.txt : "geeks for" Output: file2.txt : "geeks for geeks" Method 1:Approach: Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted.Check if there’s an error in opening or locating a file. If yes, then throw an error message.If both files are found, then write content from the source file to the destination file.Display the content of the destination file. Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted. Check if there’s an error in opening or locating a file. If yes, then throw an error message. If both files are found, then write content from the source file to the destination file. Display the content of the destination file. Below is the implementation of the above approach: CPP // C++ implementation to append// content from source file to// destination file#include <bits/stdc++.h>using namespace std; // driver codeint main(){ fstream file; // Input stream class to // operate on files. ifstream ifile("file.txt", ios::in); // Output stream class to // operate on files. ofstream ofile("file2.txt", ios::out | ios::app); // check if file exists if (!ifile.is_open()) { // file not found (i.e, not opened). // Print an error message. cout << "file not found"; } else { // then add more lines to // the file if need be ofile << ifile.rdbuf(); } string word; // opening file file.open("file2.txt"); // extracting words form the file while (file >> word) { // displaying content of // destination file cout << word << " "; } return 0;} file not found Method 2: We can do the same using different functions mentioned below: fopen(): Returns a pointer to the object that controls the opened file stream fprintf(): Writes the string pointed by format to the stream fclose(): Closes the file associated with the stream and disassociates it. fgetc(): Returns the character currently pointed by the internal file position indicator of the specified stream Approach: Open source file in read mode and destination file in append mode using fopen()check if they existIterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loopClose both files using fclose()Open destination file in read modeprint itclose it Open source file in read mode and destination file in append mode using fopen() check if they exist Iterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loop Close both files using fclose() Open destination file in read mode print it close it Below is the implementation of the above approach: C++ // C++ program to Append and Read text of text files#include <bits/stdc++.h> using namespace std;int main(){ // open file in read mode to read it's content FILE* file = fopen("file.txt", "r"); // open file in append mode to append readed content FILE* file2 = fopen("file2.txt", "a"); if (file2 == NULL) { cout << "file not found"; return 1; } else if (file == NULL) { cout << "file not found"; return 1; } // Read contents from file char ch = fgetc(file); while (ch != EOF) { // print readed content from file in file2 fprintf(file2, "%c", ch); ch = fgetc(file); } fclose(file); fclose(file2); // open file 2 again in read mode to read the content FILE* file3 = fopen("file2.txt", "r"); // Read contents from file char ch2 = fgetc(file3); while (ch2 != EOF) { // print readed content from file printf("%c", ch2); ch2 = fgetc(file3); } fclose(file3);} // This code is contributed by Shivesh Kumar Dwivedi file not found cpdwivedi916 cpp-file-handling C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2022" }, { "code": null, "e": 221, "s": 53, "text": "Given source and destination text files. Append the content from the source file to the destination file and then display the content of the destination file.Example :" }, { "code": null, "e": 311, "s": 221, "text": "Input : file.txt : \"geeks\", file2.txt : \"geeks for\"\nOutput: file2.txt : \"geeks for geeks\"" }, { "code": null, "e": 330, "s": 311, "text": "Method 1:Approach:" }, { "code": null, "e": 697, "s": 330, "text": "Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted.Check if there’s an error in opening or locating a file. If yes, then throw an error message.If both files are found, then write content from the source file to the destination file.Display the content of the destination file." }, { "code": null, "e": 838, "s": 697, "text": "Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted." }, { "code": null, "e": 932, "s": 838, "text": "Check if there’s an error in opening or locating a file. If yes, then throw an error message." }, { "code": null, "e": 1022, "s": 932, "text": "If both files are found, then write content from the source file to the destination file." }, { "code": null, "e": 1067, "s": 1022, "text": "Display the content of the destination file." }, { "code": null, "e": 1118, "s": 1067, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1122, "s": 1118, "text": "CPP" }, { "code": "// C++ implementation to append// content from source file to// destination file#include <bits/stdc++.h>using namespace std; // driver codeint main(){ fstream file; // Input stream class to // operate on files. ifstream ifile(\"file.txt\", ios::in); // Output stream class to // operate on files. ofstream ofile(\"file2.txt\", ios::out | ios::app); // check if file exists if (!ifile.is_open()) { // file not found (i.e, not opened). // Print an error message. cout << \"file not found\"; } else { // then add more lines to // the file if need be ofile << ifile.rdbuf(); } string word; // opening file file.open(\"file2.txt\"); // extracting words form the file while (file >> word) { // displaying content of // destination file cout << word << \" \"; } return 0;}", "e": 2006, "s": 1122, "text": null }, { "code": null, "e": 2021, "s": 2006, "text": "file not found" }, { "code": null, "e": 2093, "s": 2021, "text": "Method 2: We can do the same using different functions mentioned below:" }, { "code": null, "e": 2171, "s": 2093, "text": "fopen(): Returns a pointer to the object that controls the opened file stream" }, { "code": null, "e": 2232, "s": 2171, "text": "fprintf(): Writes the string pointed by format to the stream" }, { "code": null, "e": 2307, "s": 2232, "text": "fclose(): Closes the file associated with the stream and disassociates it." }, { "code": null, "e": 2420, "s": 2307, "text": "fgetc(): Returns the character currently pointed by the internal file position indicator of the specified stream" }, { "code": null, "e": 2430, "s": 2420, "text": "Approach:" }, { "code": null, "e": 2735, "s": 2430, "text": "Open source file in read mode and destination file in append mode using fopen()check if they existIterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loopClose both files using fclose()Open destination file in read modeprint itclose it" }, { "code": null, "e": 2815, "s": 2735, "text": "Open source file in read mode and destination file in append mode using fopen()" }, { "code": null, "e": 2835, "s": 2815, "text": "check if they exist" }, { "code": null, "e": 2961, "s": 2835, "text": "Iterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loop" }, { "code": null, "e": 2993, "s": 2961, "text": "Close both files using fclose()" }, { "code": null, "e": 3028, "s": 2993, "text": "Open destination file in read mode" }, { "code": null, "e": 3037, "s": 3028, "text": "print it" }, { "code": null, "e": 3046, "s": 3037, "text": "close it" }, { "code": null, "e": 3097, "s": 3046, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3101, "s": 3097, "text": "C++" }, { "code": "// C++ program to Append and Read text of text files#include <bits/stdc++.h> using namespace std;int main(){ // open file in read mode to read it's content FILE* file = fopen(\"file.txt\", \"r\"); // open file in append mode to append readed content FILE* file2 = fopen(\"file2.txt\", \"a\"); if (file2 == NULL) { cout << \"file not found\"; return 1; } else if (file == NULL) { cout << \"file not found\"; return 1; } // Read contents from file char ch = fgetc(file); while (ch != EOF) { // print readed content from file in file2 fprintf(file2, \"%c\", ch); ch = fgetc(file); } fclose(file); fclose(file2); // open file 2 again in read mode to read the content FILE* file3 = fopen(\"file2.txt\", \"r\"); // Read contents from file char ch2 = fgetc(file3); while (ch2 != EOF) { // print readed content from file printf(\"%c\", ch2); ch2 = fgetc(file3); } fclose(file3);} // This code is contributed by Shivesh Kumar Dwivedi", "e": 4165, "s": 3101, "text": null }, { "code": null, "e": 4180, "s": 4165, "text": "file not found" }, { "code": null, "e": 4193, "s": 4180, "text": "cpdwivedi916" }, { "code": null, "e": 4211, "s": 4193, "text": "cpp-file-handling" }, { "code": null, "e": 4215, "s": 4211, "text": "C++" }, { "code": null, "e": 4228, "s": 4215, "text": "C++ Programs" }, { "code": null, "e": 4232, "s": 4228, "text": "CPP" }, { "code": null, "e": 4330, "s": 4232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4354, "s": 4330, "text": "Sorting a vector in C++" }, { "code": null, "e": 4374, "s": 4354, "text": "Polymorphism in C++" }, { "code": null, "e": 4407, "s": 4374, "text": "Friend class and function in C++" }, { "code": null, "e": 4432, "s": 4407, "text": "std::string class in C++" }, { "code": null, "e": 4476, "s": 4432, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4511, "s": 4476, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 4545, "s": 4511, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 4589, "s": 4545, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 4648, "s": 4589, "text": "How to return multiple values from a function in C or C++?" } ]
jQuery UI Sortable update Event
09 Dec, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using the jQuery JavaScript Library. jQuery UI is great for building UI interfaces for the webpages. It can be used to build highly interactive web applications or can be used to add widgets easily. The jQuery UI Sortable update event is used to trigger when the user stopped sorting and the DOM position has changed. Syntax: Initialize the sortable widget with the update callback function. $(".selector").selectable({ update: function( event, ui ) {} }); Bind an event listener to the sortable update event. $( ".selector" ).on( "sortupdate", function( event, ui ) {} ); Parameters: event: This event is triggered when the user stopped the sorting with a position change of DOM. ui: This is of type object with below-given options.helper: The jQuery object representing the sorted helper.item: The jQuery object representing the current dragged item.offset: The current absolute position of the helper object which is represented as { top, left }.position: The current position of the helper object which is represented as { top, left }.originalPosition: The original position of the helper object which is represented as { top, left }.sender: The sortable itemof type jQuery object coming from moving from one sortable to another.placeholder: The element which is used as a placeholder. This is of type jQuery object. helper: The jQuery object representing the sorted helper. item: The jQuery object representing the current dragged item. offset: The current absolute position of the helper object which is represented as { top, left }. position: The current position of the helper object which is represented as { top, left }. originalPosition: The original position of the helper object which is represented as { top, left }. sender: The sortable itemof type jQuery object coming from moving from one sortable to another. placeholder: The element which is used as a placeholder. This is of type jQuery object. CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”https://code.jquery.com/jquery-1.12.4.js”></script><script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"> </script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"> </script> <style> #sortable { list-style-type: none; width: 50%; } #sortable li { margin: 10px 0; padding: 0.5em; font-size: 25px; height: 20px; } </style> <script> $(function () { $("#sortable").sortable({ update: function( event, ui ) { alert("Sortable Event Updated!") } }); }); </script></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h4>jQuery UI Sortable update Event</h4> <ul id="sortable"> <li class="ui-state-default">BCD</li> <li class="ui-state-default">CAB</li> <li class="ui-state-default">BAC</li> <li class="ui-state-default">BCA</li> <li class="ui-state-default">ABC</li> </ul> </center></body></html> Output: Reference: https://api.jqueryui.com/sortable/#event-update jQuery-UI Picked JQuery 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": "\n09 Dec, 2021" }, { "code": null, "e": 301, "s": 28, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using the jQuery JavaScript Library. jQuery UI is great for building UI interfaces for the webpages. It can be used to build highly interactive web applications or can be used to add widgets easily." }, { "code": null, "e": 420, "s": 301, "text": "The jQuery UI Sortable update event is used to trigger when the user stopped sorting and the DOM position has changed." }, { "code": null, "e": 428, "s": 420, "text": "Syntax:" }, { "code": null, "e": 494, "s": 428, "text": "Initialize the sortable widget with the update callback function." }, { "code": null, "e": 562, "s": 494, "text": "$(\".selector\").selectable({\n update: function( event, ui ) {}\n});" }, { "code": null, "e": 615, "s": 562, "text": "Bind an event listener to the sortable update event." }, { "code": null, "e": 678, "s": 615, "text": "$( \".selector\" ).on( \"sortupdate\", function( event, ui ) {} );" }, { "code": null, "e": 690, "s": 678, "text": "Parameters:" }, { "code": null, "e": 786, "s": 690, "text": "event: This event is triggered when the user stopped the sorting with a position change of DOM." }, { "code": null, "e": 1426, "s": 786, "text": "ui: This is of type object with below-given options.helper: The jQuery object representing the sorted helper.item: The jQuery object representing the current dragged item.offset: The current absolute position of the helper object which is represented as { top, left }.position: The current position of the helper object which is represented as { top, left }.originalPosition: The original position of the helper object which is represented as { top, left }.sender: The sortable itemof type jQuery object coming from moving from one sortable to another.placeholder: The element which is used as a placeholder. This is of type jQuery object." }, { "code": null, "e": 1484, "s": 1426, "text": "helper: The jQuery object representing the sorted helper." }, { "code": null, "e": 1547, "s": 1484, "text": "item: The jQuery object representing the current dragged item." }, { "code": null, "e": 1645, "s": 1547, "text": "offset: The current absolute position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1736, "s": 1645, "text": "position: The current position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1836, "s": 1736, "text": "originalPosition: The original position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1932, "s": 1836, "text": "sender: The sortable itemof type jQuery object coming from moving from one sortable to another." }, { "code": null, "e": 2020, "s": 1932, "text": "placeholder: The element which is used as a placeholder. This is of type jQuery object." }, { "code": null, "e": 2084, "s": 2020, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 2315, "s": 2084, "text": "<link rel=”stylesheet” href=”https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”https://code.jquery.com/jquery-1.12.4.js”></script><script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 2324, "s": 2315, "text": "Example:" }, { "code": null, "e": 2329, "s": 2324, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\"> <script src=\"https://code.jquery.com/jquery-1.12.4.js\"> </script> <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script> <style> #sortable { list-style-type: none; width: 50%; } #sortable li { margin: 10px 0; padding: 0.5em; font-size: 25px; height: 20px; } </style> <script> $(function () { $(\"#sortable\").sortable({ update: function( event, ui ) { alert(\"Sortable Event Updated!\") } }); }); </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4>jQuery UI Sortable update Event</h4> <ul id=\"sortable\"> <li class=\"ui-state-default\">BCD</li> <li class=\"ui-state-default\">CAB</li> <li class=\"ui-state-default\">BAC</li> <li class=\"ui-state-default\">BCA</li> <li class=\"ui-state-default\">ABC</li> </ul> </center></body></html>", "e": 3589, "s": 2329, "text": null }, { "code": null, "e": 3597, "s": 3589, "text": "Output:" }, { "code": null, "e": 3656, "s": 3597, "text": "Reference: https://api.jqueryui.com/sortable/#event-update" }, { "code": null, "e": 3666, "s": 3656, "text": "jQuery-UI" }, { "code": null, "e": 3673, "s": 3666, "text": "Picked" }, { "code": null, "e": 3680, "s": 3673, "text": "JQuery" }, { "code": null, "e": 3697, "s": 3680, "text": "Web Technologies" } ]
Python – turtle.exitonclick()
17 Aug, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to Go into mainloop until the mouse is clicked. It doesn’t require any argument. Bind bye() method to mouseclick on TurtleScreen. If using_IDLE – value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE’s mainloop is active also for the client script. This is a method of the Screen-class and not available for TurtleScreen instances. Syntax : turtle.exitoncick()Parameters : NoneReturns : Nothing Below is the implementation of above method with an example : Example : # import packageimport turtle # loop for motionfor i in range(3): turtle.circle(40) turtle.right(120) # exit from the screen # if and only if# mouse is clickedturtle.exitonclick() Output : Here we can see that : Turtle screen is loaded Turtle draw some stuff Turtle window remain as it is When user click (yellow colored sign) on turtle window it closes i.e; exit on click. Python-turtle 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": "\n17 Aug, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 652, "s": 245, "text": "This function is used to Go into mainloop until the mouse is clicked. It doesn’t require any argument. Bind bye() method to mouseclick on TurtleScreen. If using_IDLE – value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE’s mainloop is active also for the client script." }, { "code": null, "e": 735, "s": 652, "text": "This is a method of the Screen-class and not available for TurtleScreen instances." }, { "code": null, "e": 798, "s": 735, "text": "Syntax : turtle.exitoncick()Parameters : NoneReturns : Nothing" }, { "code": null, "e": 860, "s": 798, "text": "Below is the implementation of above method with an example :" }, { "code": null, "e": 870, "s": 860, "text": "Example :" }, { "code": "# import packageimport turtle # loop for motionfor i in range(3): turtle.circle(40) turtle.right(120) # exit from the screen # if and only if# mouse is clickedturtle.exitonclick()", "e": 1054, "s": 870, "text": null }, { "code": null, "e": 1063, "s": 1054, "text": "Output :" }, { "code": null, "e": 1086, "s": 1063, "text": "Here we can see that :" }, { "code": null, "e": 1110, "s": 1086, "text": "Turtle screen is loaded" }, { "code": null, "e": 1133, "s": 1110, "text": "Turtle draw some stuff" }, { "code": null, "e": 1163, "s": 1133, "text": "Turtle window remain as it is" }, { "code": null, "e": 1248, "s": 1163, "text": "When user click (yellow colored sign) on turtle window it closes i.e; exit on click." }, { "code": null, "e": 1262, "s": 1248, "text": "Python-turtle" }, { "code": null, "e": 1269, "s": 1262, "text": "Python" }, { "code": null, "e": 1367, "s": 1269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1399, "s": 1367, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1426, "s": 1399, "text": "Python Classes and Objects" }, { "code": null, "e": 1457, "s": 1426, "text": "Python | os.path.join() method" }, { "code": null, "e": 1480, "s": 1457, "text": "Introduction To PYTHON" }, { "code": null, "e": 1501, "s": 1480, "text": "Python OOPs Concepts" }, { "code": null, "e": 1557, "s": 1501, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1599, "s": 1557, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1641, "s": 1599, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1680, "s": 1641, "text": "Python | Get unique values from a list" } ]
DROP SCHEMA in SQL Server
04 Sep, 2020 The DROP SCHEMA statement could be used to delete a schema from a database. SQL Server have some built-in schema, for example : dbo, guest, sys, and INFORMATION_SCHEMA which cannot be deleted. Syntax : DROP SCHEMA [IF EXISTS] schema_name; Note : Delete all objects from the schema before dropping the schema. If the schema have any object in it, the output will be an error. Example :Let us create a new schema named geeksh (https://www.geeksforgeeks.org/create-schema-in-sql-server/); CREATE SCHEMA geeksh; GO Now create a table named geektab inside the geeksh schema : CREATE TABLE geeksh.geektab (id INT PRIMARY KEY, date DATE NOT NULL, city varchar(200) NOT NULL); Drop the schema geeksh : DROP SCHEMA geeksh;SQL Server will throw similar error as the schema is not empty. Msg 3729, Level 16, State 1, Line 1 Cannot drop schema 'geeksh' because it is being referenced by object 'geektab'. Let us drop the table geeksh.geektab : DROP TABLE geeksh.geektab; Again run the DROP SCHEMA again to drop the geeksh schema : DROP SCHEMA IF EXISTS geeksh; Now, the geeksh schema has been deleted from the database. SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? Difference between Where and Having Clause in SQL SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2020" }, { "code": null, "e": 221, "s": 28, "text": "The DROP SCHEMA statement could be used to delete a schema from a database. SQL Server have some built-in schema, for example : dbo, guest, sys, and INFORMATION_SCHEMA which cannot be deleted." }, { "code": null, "e": 230, "s": 221, "text": "Syntax :" }, { "code": null, "e": 268, "s": 230, "text": "DROP SCHEMA [IF EXISTS] schema_name;\n" }, { "code": null, "e": 404, "s": 268, "text": "Note : Delete all objects from the schema before dropping the schema. If the schema have any object in it, the output will be an error." }, { "code": null, "e": 515, "s": 404, "text": "Example :Let us create a new schema named geeksh (https://www.geeksforgeeks.org/create-schema-in-sql-server/);" }, { "code": null, "e": 541, "s": 515, "text": "CREATE SCHEMA geeksh;\nGO\n" }, { "code": null, "e": 601, "s": 541, "text": "Now create a table named geektab inside the geeksh schema :" }, { "code": null, "e": 700, "s": 601, "text": "CREATE TABLE geeksh.geektab\n(id INT PRIMARY KEY,\ndate DATE NOT NULL,\ncity varchar(200) NOT NULL);\n" }, { "code": null, "e": 725, "s": 700, "text": "Drop the schema geeksh :" }, { "code": null, "e": 808, "s": 725, "text": "DROP SCHEMA geeksh;SQL Server will throw similar error as the schema is not empty." }, { "code": null, "e": 925, "s": 808, "text": "Msg 3729, Level 16, State 1, Line 1\nCannot drop schema 'geeksh' because it is being referenced by object 'geektab'.\n" }, { "code": null, "e": 964, "s": 925, "text": "Let us drop the table geeksh.geektab :" }, { "code": null, "e": 992, "s": 964, "text": "DROP TABLE geeksh.geektab;\n" }, { "code": null, "e": 1052, "s": 992, "text": "Again run the DROP SCHEMA again to drop the geeksh schema :" }, { "code": null, "e": 1083, "s": 1052, "text": "DROP SCHEMA IF EXISTS geeksh;\n" }, { "code": null, "e": 1142, "s": 1083, "text": "Now, the geeksh schema has been deleted from the database." }, { "code": null, "e": 1153, "s": 1142, "text": "SQL-Server" }, { "code": null, "e": 1158, "s": 1153, "text": "DBMS" }, { "code": null, "e": 1162, "s": 1158, "text": "SQL" }, { "code": null, "e": 1167, "s": 1162, "text": "DBMS" }, { "code": null, "e": 1171, "s": 1167, "text": "SQL" }, { "code": null, "e": 1269, "s": 1171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1310, "s": 1269, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 1347, "s": 1310, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 1388, "s": 1347, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 1420, "s": 1388, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1470, "s": 1420, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 1512, "s": 1470, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 1556, "s": 1512, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 1577, "s": 1556, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 1643, "s": 1577, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Using Else Conditional Statement With For loop in Python
13 Jul, 2022 Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement. Else block is executed in below Python 3.x program: Python for i in range(1, 4): print(i)else: # Executed because no break in for print("No Break") Output : 1 2 3 No Break Else block is NOT executed in Python 3.x or below: Python for i in range(1, 4): print(i) breakelse: # Not executed as there is a break print("No Break") Output : 1 Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in the third iteration of the loop and hence the else present after the for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed. Python # Python 3.x program to check if an array consists # of even numberdef contains_even_number(l): for ele in l: if ele % 2 == 0: print ("list contains an even number") break # This else executes only if break is NEVER # reached and loop terminated after all iterations. else: print ("list does not contain an even number") # Driver codeprint ("For List 1:")contains_even_number([1, 9, 8])print (" \nFor List 2:")contains_even_number([1, 3, 5]) Output: For List 1: list contains an even number For List 2: list does not contain an even number As an exercise, predict the output of the following program. Python count = 0while (count < 1): count = count+1 print(count) breakelse: print("No Break") tarun2207 ddeevviissaavviittaa tyunsworth Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 109, "s": 52, "text": "Using else conditional statement with for loop in python" }, { "code": null, "e": 317, "s": 109, "text": "In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. " }, { "code": null, "e": 424, "s": 317, "text": "The else block just after for/while is executed only when the loop is NOT terminated by a break statement." }, { "code": null, "e": 477, "s": 424, "text": "Else block is executed in below Python 3.x program: " }, { "code": null, "e": 484, "s": 477, "text": "Python" }, { "code": "for i in range(1, 4): print(i)else: # Executed because no break in for print(\"No Break\")", "e": 580, "s": 484, "text": null }, { "code": null, "e": 590, "s": 580, "text": "Output : " }, { "code": null, "e": 605, "s": 590, "text": "1\n2\n3\nNo Break" }, { "code": null, "e": 657, "s": 605, "text": "Else block is NOT executed in Python 3.x or below: " }, { "code": null, "e": 664, "s": 657, "text": "Python" }, { "code": "for i in range(1, 4): print(i) breakelse: # Not executed as there is a break print(\"No Break\")", "e": 768, "s": 664, "text": null }, { "code": null, "e": 778, "s": 768, "text": "Output : " }, { "code": null, "e": 780, "s": 778, "text": "1" }, { "code": null, "e": 1335, "s": 780, "text": "Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in the third iteration of the loop and hence the else present after the for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed." }, { "code": null, "e": 1342, "s": 1335, "text": "Python" }, { "code": "# Python 3.x program to check if an array consists # of even numberdef contains_even_number(l): for ele in l: if ele % 2 == 0: print (\"list contains an even number\") break # This else executes only if break is NEVER # reached and loop terminated after all iterations. else: print (\"list does not contain an even number\") # Driver codeprint (\"For List 1:\")contains_even_number([1, 9, 8])print (\" \\nFor List 2:\")contains_even_number([1, 3, 5])", "e": 1840, "s": 1342, "text": null }, { "code": null, "e": 1849, "s": 1840, "text": "Output: " }, { "code": null, "e": 1940, "s": 1849, "text": "For List 1:\nlist contains an even number\n\nFor List 2:\nlist does not contain an even number" }, { "code": null, "e": 2002, "s": 1940, "text": "As an exercise, predict the output of the following program. " }, { "code": null, "e": 2009, "s": 2002, "text": "Python" }, { "code": "count = 0while (count < 1): count = count+1 print(count) breakelse: print(\"No Break\")", "e": 2111, "s": 2009, "text": null }, { "code": null, "e": 2121, "s": 2111, "text": "tarun2207" }, { "code": null, "e": 2142, "s": 2121, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 2153, "s": 2142, "text": "tyunsworth" }, { "code": null, "e": 2160, "s": 2153, "text": "Python" } ]
Nested Classes in C#
16 Sep, 2021 A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods (member function which defines actions) into a single unit. In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code. Syntax: class Outer_class { // Code.. class Inner_class { // Code.. } } Example: C# // C# program to illustrate the// concept of nested classusing System; // Outer classpublic class Outer_class { // Method of outer class public void method1() { Console.WriteLine("Outer class method"); } // Inner class public class Inner_class { // Method of inner class public void method2() { Console.WriteLine("Inner class Method"); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create the instance of outer class Outer_class obj1 = new Outer_class(); obj1.method1(); // This statement gives an error because // you are not allowed to access inner // class methods with outer class objects // obj1. method2(); // Creating an instance of inner class Outer_class.Inner_class obj2 = new Outer_class.Inner_class(); // Accessing the method of inner class obj2.method2(); }} Output: Outer class method Inner class Method Important points: A nested class can be declared as a private, public, protected, internal, protected internal, or private protected. Outer class is not allowed to access inner class members directly as shown in above example. You are allowed to create objects of inner class in outer class. Inner class can access static member declared in outer class as shown in the below example:Example: C# // C# program to illustrate the// concept of nested class accessing// static members of the outer classusing System; // Outer classpublic class Outer_class { // Static data member of the outer class public static string str = "Geeksforgeeks"; // Inner class public class Inner_class { // Static method of Inner class public static void method1() { // Displaying the value of a // static member of the outer class Console.WriteLine(Outer_class.str); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Accessing static method1 // of the inner class Outer_class.Inner_class.method1(); }} Output : Geeksforgeeks Inner class can access non-static member declared in outer class as shown in the below example:Example: C# // C# program to illustrate the// concept of nested class// accessing non-static member// of the outer classusing System; // Outer classpublic class Outer_class { // Non-static data // member of outer class public int number = 1000000; // Inner class public class Inner_class { // Static method of Inner class public static void method1() { // Creating the object of the outer class Outer_class obj = new Outer_class(); // Displaying the value of a // static member of the outer class // with the help of obj Console.WriteLine(obj.number); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Accessing static method1 // of inner class Outer_class.Inner_class.method1(); }} Output : 1000000 Instance Inner class can access non-static member declared in Outer class as shown in the below example:Example: C# // C# program to illustrate the// concept of nested class// accessing non-static member// of the outer classusing System; // Outer classpublic class Outer_class { // Non-static data // member of outer class public int number = 2000000; // Non-static reference to Inner_class // instance. public Inner_class Inner { get; set; } // Constructor to establish link between // instance of Outer_class to its // instance of the Inner_class public Outer_class() { this.Inner = new Inner_class(this); } // Inner class public class Inner_class { // private field to hold // reference to an instance // of the Outer_class private Outer_class obj; // constructor that establishes // a reference to the Outer_class // to use within an Inner_cass instance public Inner_class(Outer_class outer) { obj = outer; } // Method of Inner class public void method1() { // Displaying the value of a // member of the outer class // with the help of obj Console.WriteLine(obj.number); } }} // Driver Classpublic class GFG { // Main method public static void Main() { // Create instance of Outer_class Outer_class Outer = new Outer_class(); // Accessing static method1 // of inner class Outer.Inner.method1(); }} Output : 2000000 The scope of a nested class is bounded by the scope of its enclosing class. By default, the nested class is private. In C#, a user is allowed to inherit a class (including nested class) into another class. Example: C# // C# program to illustrate the// concept inheritanceusing System; // Outer classpublic class Outer_class { // Method of outer class public void method1() { Console.WriteLine("Outer class method"); } // Inner class public class Inner_class { }} // Derived classpublic class Exclass : Outer_class { // Method of derived class public void func() { Console.WriteLine("Method of derived class"); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Creating object of // the derived class Exclass obj = new Exclass(); obj.func(); obj.method1(); }} Output : Method of derived class Outer class method In C#, the user is allowed to inherit a nested class from the outer class. corykoski hoan84286 CSharp-OOP 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": 53, "s": 25, "text": "\n16 Sep, 2021" }, { "code": null, "e": 543, "s": 53, "text": "A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods (member function which defines actions) into a single unit. In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code." }, { "code": null, "e": 551, "s": 543, "text": "Syntax:" }, { "code": null, "e": 650, "s": 551, "text": "class Outer_class {\n\n // Code..\n\n class Inner_class {\n\n // Code.. \n }\n}" }, { "code": null, "e": 659, "s": 650, "text": "Example:" }, { "code": null, "e": 662, "s": 659, "text": "C#" }, { "code": "// C# program to illustrate the// concept of nested classusing System; // Outer classpublic class Outer_class { // Method of outer class public void method1() { Console.WriteLine(\"Outer class method\"); } // Inner class public class Inner_class { // Method of inner class public void method2() { Console.WriteLine(\"Inner class Method\"); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create the instance of outer class Outer_class obj1 = new Outer_class(); obj1.method1(); // This statement gives an error because // you are not allowed to access inner // class methods with outer class objects // obj1. method2(); // Creating an instance of inner class Outer_class.Inner_class obj2 = new Outer_class.Inner_class(); // Accessing the method of inner class obj2.method2(); }}", "e": 1656, "s": 662, "text": null }, { "code": null, "e": 1665, "s": 1656, "text": "Output: " }, { "code": null, "e": 1703, "s": 1665, "text": "Outer class method\nInner class Method" }, { "code": null, "e": 1722, "s": 1703, "text": "Important points: " }, { "code": null, "e": 1838, "s": 1722, "text": "A nested class can be declared as a private, public, protected, internal, protected internal, or private protected." }, { "code": null, "e": 1931, "s": 1838, "text": "Outer class is not allowed to access inner class members directly as shown in above example." }, { "code": null, "e": 1996, "s": 1931, "text": "You are allowed to create objects of inner class in outer class." }, { "code": null, "e": 2096, "s": 1996, "text": "Inner class can access static member declared in outer class as shown in the below example:Example:" }, { "code": null, "e": 2099, "s": 2096, "text": "C#" }, { "code": "// C# program to illustrate the// concept of nested class accessing// static members of the outer classusing System; // Outer classpublic class Outer_class { // Static data member of the outer class public static string str = \"Geeksforgeeks\"; // Inner class public class Inner_class { // Static method of Inner class public static void method1() { // Displaying the value of a // static member of the outer class Console.WriteLine(Outer_class.str); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Accessing static method1 // of the inner class Outer_class.Inner_class.method1(); }}", "e": 2833, "s": 2099, "text": null }, { "code": null, "e": 2842, "s": 2833, "text": "Output :" }, { "code": null, "e": 2856, "s": 2842, "text": "Geeksforgeeks" }, { "code": null, "e": 2960, "s": 2856, "text": "Inner class can access non-static member declared in outer class as shown in the below example:Example:" }, { "code": null, "e": 2963, "s": 2960, "text": "C#" }, { "code": "// C# program to illustrate the// concept of nested class// accessing non-static member// of the outer classusing System; // Outer classpublic class Outer_class { // Non-static data // member of outer class public int number = 1000000; // Inner class public class Inner_class { // Static method of Inner class public static void method1() { // Creating the object of the outer class Outer_class obj = new Outer_class(); // Displaying the value of a // static member of the outer class // with the help of obj Console.WriteLine(obj.number); } }} // Driver Classpublic class GFG { // Main method static public void Main() { // Accessing static method1 // of inner class Outer_class.Inner_class.method1(); }}", "e": 3820, "s": 2963, "text": null }, { "code": null, "e": 3830, "s": 3820, "text": "Output : " }, { "code": null, "e": 3838, "s": 3830, "text": "1000000" }, { "code": null, "e": 3951, "s": 3838, "text": "Instance Inner class can access non-static member declared in Outer class as shown in the below example:Example:" }, { "code": null, "e": 3954, "s": 3951, "text": "C#" }, { "code": "// C# program to illustrate the// concept of nested class// accessing non-static member// of the outer classusing System; // Outer classpublic class Outer_class { // Non-static data // member of outer class public int number = 2000000; // Non-static reference to Inner_class // instance. public Inner_class Inner { get; set; } // Constructor to establish link between // instance of Outer_class to its // instance of the Inner_class public Outer_class() { this.Inner = new Inner_class(this); } // Inner class public class Inner_class { // private field to hold // reference to an instance // of the Outer_class private Outer_class obj; // constructor that establishes // a reference to the Outer_class // to use within an Inner_cass instance public Inner_class(Outer_class outer) { obj = outer; } // Method of Inner class public void method1() { // Displaying the value of a // member of the outer class // with the help of obj Console.WriteLine(obj.number); } }} // Driver Classpublic class GFG { // Main method public static void Main() { // Create instance of Outer_class Outer_class Outer = new Outer_class(); // Accessing static method1 // of inner class Outer.Inner.method1(); }}", "e": 5398, "s": 3954, "text": null }, { "code": null, "e": 5408, "s": 5398, "text": "Output : " }, { "code": null, "e": 5416, "s": 5408, "text": "2000000" }, { "code": null, "e": 5492, "s": 5416, "text": "The scope of a nested class is bounded by the scope of its enclosing class." }, { "code": null, "e": 5533, "s": 5492, "text": "By default, the nested class is private." }, { "code": null, "e": 5631, "s": 5533, "text": "In C#, a user is allowed to inherit a class (including nested class) into another class. Example:" }, { "code": null, "e": 5634, "s": 5631, "text": "C#" }, { "code": "// C# program to illustrate the// concept inheritanceusing System; // Outer classpublic class Outer_class { // Method of outer class public void method1() { Console.WriteLine(\"Outer class method\"); } // Inner class public class Inner_class { }} // Derived classpublic class Exclass : Outer_class { // Method of derived class public void func() { Console.WriteLine(\"Method of derived class\"); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Creating object of // the derived class Exclass obj = new Exclass(); obj.func(); obj.method1(); }}", "e": 6307, "s": 5634, "text": null }, { "code": null, "e": 6317, "s": 6307, "text": "Output : " }, { "code": null, "e": 6360, "s": 6317, "text": "Method of derived class\nOuter class method" }, { "code": null, "e": 6435, "s": 6360, "text": "In C#, the user is allowed to inherit a nested class from the outer class." }, { "code": null, "e": 6447, "s": 6437, "text": "corykoski" }, { "code": null, "e": 6457, "s": 6447, "text": "hoan84286" }, { "code": null, "e": 6468, "s": 6457, "text": "CSharp-OOP" }, { "code": null, "e": 6471, "s": 6468, "text": "C#" }, { "code": null, "e": 6569, "s": 6471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6612, "s": 6569, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6661, "s": 6612, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6684, "s": 6661, "text": "Extension Method in C#" }, { "code": null, "e": 6700, "s": 6684, "text": "C# | List Class" }, { "code": null, "e": 6728, "s": 6700, "text": "HashSet in C# with Examples" }, { "code": null, "e": 6789, "s": 6728, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 6812, "s": 6789, "text": "Switch Statement in C#" }, { "code": null, "e": 6834, "s": 6812, "text": "Partial Classes in C#" }, { "code": null, "e": 6859, "s": 6834, "text": "Lambda Expressions in C#" } ]
How to create a Box Layout in Java?
To create a Box Layout in Java Swing, use the BoxLayout class. Here, we have also set that the components should be laid our left to right or top to bottom − Box box = new Box(BoxLayout.X_AXIS); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(Box.createGlue()); box.add(button5); box.add(button6); box.add(button7); box.add(button8); Above, we have 8 buttons in our Box Layout. We have separated 4 buttons each using the createGlue() method. The following is an example to create a BoxLayout in Java − package my; import java.awt.BorderLayout; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Groups"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button1 = new JButton("CSK"); JButton button2 = new JButton("DC"); JButton button3 = new JButton("MI"); JButton button4 = new JButton("SRH"); JButton button5 = new JButton("RR"); JButton button6 = new JButton("KKR"); JButton button7 = new JButton("KXIP"); JButton button8 = new JButton("RCB"); Box box = new Box(BoxLayout.X_AXIS); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(Box.createGlue()); box.add(button5); box.add(button6); box.add(button7); box.add(button8); JScrollPane jScrollPane = new JScrollPane(); jScrollPane.setViewportView(box); frame.add(jScrollPane, BorderLayout.CENTER); frame.setSize(550, 250); frame.setVisible(true); } }
[ { "code": null, "e": 1345, "s": 1187, "text": "To create a Box Layout in Java Swing, use the BoxLayout class. Here, we have also set that the components should be laid our left to right or top to bottom −" }, { "code": null, "e": 1553, "s": 1345, "text": "Box box = new Box(BoxLayout.X_AXIS);\nbox.add(button1);\nbox.add(button2);\nbox.add(button3);\nbox.add(button4);\nbox.add(Box.createGlue());\nbox.add(button5);\nbox.add(button6);\nbox.add(button7);\nbox.add(button8);" }, { "code": null, "e": 1661, "s": 1553, "text": "Above, we have 8 buttons in our Box Layout. We have separated 4 buttons each using the createGlue() method." }, { "code": null, "e": 1721, "s": 1661, "text": "The following is an example to create a BoxLayout in Java −" }, { "code": null, "e": 2904, "s": 1721, "text": "package my;\nimport java.awt.BorderLayout;\nimport javax.swing.Box;\nimport javax.swing.BoxLayout;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Groups\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JButton button1 = new JButton(\"CSK\");\n JButton button2 = new JButton(\"DC\");\n JButton button3 = new JButton(\"MI\");\n JButton button4 = new JButton(\"SRH\");\n JButton button5 = new JButton(\"RR\");\n JButton button6 = new JButton(\"KKR\");\n JButton button7 = new JButton(\"KXIP\");\n JButton button8 = new JButton(\"RCB\");\n Box box = new Box(BoxLayout.X_AXIS);\n box.add(button1);\n box.add(button2);\n box.add(button3);\n box.add(button4);\n box.add(Box.createGlue());\n box.add(button5);\n box.add(button6);\n box.add(button7);\n box.add(button8);\n JScrollPane jScrollPane = new JScrollPane();\n jScrollPane.setViewportView(box);\n frame.add(jScrollPane, BorderLayout.CENTER);\n frame.setSize(550, 250);\n frame.setVisible(true);\n }\n}" } ]
Get or Set names of Elements of an Object in R Programming – names() Function
05 Jun, 2020 names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named. Syntax: names(x) <- value Parameters:x: Object i.e. vector, matrix, data frame, etc.value: Names to be assigned to x Example 1: # R program to assign name to an object # Creating a vectorx <- c(1, 2, 3, 4, 5) # Assigning names using names() functionnames(x) <- c("gfg1", "gfg2", "gfg3", "gfg4", "gfg5") # Printing name vector that is assigned names(x) # Printing updated vectorprint(x) Output: [1] "gfg1" "gfg2" "gfg3" "gfg4" "gfg5" gfg1 gfg2 gfg3 gfg4 gfg5 1 2 3 4 5 Example 2: # R program to get names of an Object # Importing Library library(datasets) # Importing dataset head(airquality) # Calling names() function to get namesnames(airquality) Output: Ozone Solar.R Wind Temp Month Day 1 41 190 7.4 67 5 1 2 36 118 8.0 72 5 2 3 12 149 12.6 74 5 3 4 18 313 11.5 62 5 4 5 NA NA 14.3 56 5 5 6 28 NA 14.9 66 5 6 [1] "Ozone" "Solar.R" "Wind" "Temp" "Month" "Day" R DataFrame-Function R List-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jun, 2020" }, { "code": null, "e": 371, "s": 54, "text": "names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named." }, { "code": null, "e": 397, "s": 371, "text": "Syntax: names(x) <- value" }, { "code": null, "e": 488, "s": 397, "text": "Parameters:x: Object i.e. vector, matrix, data frame, etc.value: Names to be assigned to x" }, { "code": null, "e": 499, "s": 488, "text": "Example 1:" }, { "code": "# R program to assign name to an object # Creating a vectorx <- c(1, 2, 3, 4, 5) # Assigning names using names() functionnames(x) <- c(\"gfg1\", \"gfg2\", \"gfg3\", \"gfg4\", \"gfg5\") # Printing name vector that is assigned names(x) # Printing updated vectorprint(x)", "e": 761, "s": 499, "text": null }, { "code": null, "e": 769, "s": 761, "text": "Output:" }, { "code": null, "e": 861, "s": 769, "text": "[1] \"gfg1\" \"gfg2\" \"gfg3\" \"gfg4\" \"gfg5\"\ngfg1 gfg2 gfg3 gfg4 gfg5 \n 1 2 3 4 5 \n" }, { "code": null, "e": 872, "s": 861, "text": "Example 2:" }, { "code": "# R program to get names of an Object # Importing Library library(datasets) # Importing dataset head(airquality) # Calling names() function to get namesnames(airquality)", "e": 1049, "s": 872, "text": null }, { "code": null, "e": 1057, "s": 1049, "text": "Output:" }, { "code": null, "e": 1374, "s": 1057, "text": " Ozone Solar.R Wind Temp Month Day\n1 41 190 7.4 67 5 1\n2 36 118 8.0 72 5 2\n3 12 149 12.6 74 5 3\n4 18 313 11.5 62 5 4\n5 NA NA 14.3 56 5 5\n6 28 NA 14.9 66 5 6\n[1] \"Ozone\" \"Solar.R\" \"Wind\" \"Temp\" \"Month\" \"Day\" \n" }, { "code": null, "e": 1395, "s": 1374, "text": "R DataFrame-Function" }, { "code": null, "e": 1411, "s": 1395, "text": "R List-Function" }, { "code": null, "e": 1429, "s": 1411, "text": "R Matrix-Function" }, { "code": null, "e": 1447, "s": 1429, "text": "R Object-Function" }, { "code": null, "e": 1465, "s": 1447, "text": "R Vector-Function" }, { "code": null, "e": 1476, "s": 1465, "text": "R Language" } ]
Is an array a primitive type or an object in Java?
11 Dec, 2018 An array in Java is an object. Now the question how is this possible? What is the reason behind that? In Java, we can create arrays by using new operator and we know that every object is created using new operator. Hence we can say that array is also an object. Now the question also arises, every time we create an object for a class then what is the class of array? In Java, there is a class for every array type, so there’s a class for int[] and similarly for float, double etc. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable. In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array. For every array type corresponding classes are available and these classes are the part of java language and not available to the programmer level. To know the class of any array, we can go with the following approach: // Here x is the name of the array. System.out.println(x.getClass().getName()); // Java program to display class of // int array typepublic class Test{ public static void main(String[] args) { int[] x = new int[3]; System.out.println(x.getClass().getName()); }} Output: [I NOTE:[I this is the class for this array, one [ (square bracket) because it is one dimensional and I for integer data type.Here is the table specifying the corresponding class name for some array types:- Array type Corresponding class Name int[] [I int[][] [[I double[] [D double[][] [[D short[] [S byte[] [B boolean[] [Z In Java programming language, arrays are objects which are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. // Java program to check the class of // int array typepublic class Test { public static void main(String[] args) { // Object is the parent class of all classes // of Java. Here args is the object of String // class. System.out.println(args instanceof Object); int[] arr = new int[2]; // Here arr is also an object of int class. System.out.println(arr instanceof Object); }} Output: true true Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Array-Programs Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2018" }, { "code": null, "e": 422, "s": 54, "text": "An array in Java is an object. Now the question how is this possible? What is the reason behind that? In Java, we can create arrays by using new operator and we know that every object is created using new operator. Hence we can say that array is also an object. Now the question also arises, every time we create an object for a class then what is the class of array?" }, { "code": null, "e": 536, "s": 422, "text": "In Java, there is a class for every array type, so there’s a class for int[] and similarly for float, double etc." }, { "code": null, "e": 665, "s": 536, "text": "The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable." }, { "code": null, "e": 867, "s": 665, "text": "In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array." }, { "code": null, "e": 1086, "s": 867, "text": "For every array type corresponding classes are available and these classes are the part of java language and not available to the programmer level. To know the class of any array, we can go with the following approach:" }, { "code": null, "e": 1167, "s": 1086, "text": "// Here x is the name of the array.\nSystem.out.println(x.getClass().getName()); " }, { "code": "// Java program to display class of // int array typepublic class Test{ public static void main(String[] args) { int[] x = new int[3]; System.out.println(x.getClass().getName()); }}", "e": 1372, "s": 1167, "text": null }, { "code": null, "e": 1380, "s": 1372, "text": "Output:" }, { "code": null, "e": 1385, "s": 1380, "text": "[I \n" }, { "code": null, "e": 1589, "s": 1385, "text": "NOTE:[I this is the class for this array, one [ (square bracket) because it is one dimensional and I for integer data type.Here is the table specifying the corresponding class name for some array types:-" }, { "code": null, "e": 1843, "s": 1589, "text": "Array type Corresponding class Name\nint[] [I\nint[][] [[I\ndouble[] [D\ndouble[][] [[D\nshort[] [S\nbyte[] [B\nboolean[] [Z\n" }, { "code": null, "e": 2028, "s": 1843, "text": "In Java programming language, arrays are objects which are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array." }, { "code": "// Java program to check the class of // int array typepublic class Test { public static void main(String[] args) { // Object is the parent class of all classes // of Java. Here args is the object of String // class. System.out.println(args instanceof Object); int[] arr = new int[2]; // Here arr is also an object of int class. System.out.println(arr instanceof Object); }}", "e": 2466, "s": 2028, "text": null }, { "code": null, "e": 2474, "s": 2466, "text": "Output:" }, { "code": null, "e": 2485, "s": 2474, "text": "true\ntrue\n" }, { "code": null, "e": 2559, "s": 2485, "text": "Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html" }, { "code": null, "e": 2865, "s": 2559, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2990, "s": 2865, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3010, "s": 2990, "text": "Java-Array-Programs" }, { "code": null, "e": 3022, "s": 3010, "text": "Java-Arrays" }, { "code": null, "e": 3027, "s": 3022, "text": "Java" }, { "code": null, "e": 3032, "s": 3027, "text": "Java" } ]
Rust – HashMaps
15 Nov, 2021 The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated. To insert a value in a HashMap in Rust follow the below steps: Import HashMap Create HashMap named gfg Insert the records using gfg.insert(key, value) Syntax : // import HashMap use std::collections::HashMap; // initialize the HashMap let mut gfg=HashMap::new(); //insert the values In HashMap gfg.insert("Data Structures","90"); Rust // Inserting in HashMap Rustuse std::collections::HashMap; fn main() { // initialize the HashMap// mut means we can reassign to something elselet mut gfg=HashMap::new(); // inserting records gfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99"); // for printing all the records "{:?}" this is mustprintln!("{:?}",gfg );} Output : {"CP": "99", "Algorithms": "99", "Data Structures": "90", "FAANG": "97", "Interview Preparations": "100"} To iterate over a HashMap in Rust follow the below steps: Import HashMap Insert records in HashMap Iterate using iter() method with for loop Syntax : // here gfg is HashMap for (key, val) in gfg.iter() { println!("{} {}", key, val); } Rust // Rust Program to Iterating over HashMap // import HashMapuse std::collections::HashMap;fn main() { // create HashMap let mut gfg=HashMap::new(); // inserting overgfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99"); // iterating using iter() method on gfgfor (key, val) in gfg.iter() { println!("{} {}", key, val); }} Output : Algorithms 99 FAANG 97 CP 99 Interview Preparations 100 Data Structures 90 To check whether a key is present in a HashMap follow the below steps: Import HashMap Insert records in HashMap Use contains_key(& key) to check the key present or not Syntax : if gfg.contains_key( & "FAANG") { println!("yes it contains the given key well done gfg"); } Rust // Rust program for contains Key // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99"); // contains_key() method to check// if key present or not if gfg.contains_key( & "FAANG") { println!("yes it contains the given key well done gfg"); }} Output : yes it contains the given key well done gfg To check for the length of HashMap in Rust follow the below steps: Import HashMap Insert records in HashMap Use len() method on HashMap for the length of HashMap Syntax : //for length of HashMap gfg.len(); Rust // Rust program for length of HashMap // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99"); // length of HashMap using len()println!("len of gfg HashMap={}",gfg.len()); } Output : len of gfg HashMap=5 To remove elements from a Hashmap: Import HashMap. Insert records in HashMap. Use the remove(key) method to remove from HashMap. Syntax : // length of HashMap // here gfg is HashMap gfg.remove(& "key") Rust // Rust program for removing from HashMap // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99"); // remove using remove() methodgfg.remove( & "CP");println!("len of gfg HashMap={}",gfg.len());} Output : len of gfg HashMap=4 To access values from HashMap using keys: Import HashMap. Insert records in HashMap. Use get( & key) for getting the value. Syntax : // for getting through key gfg.get( & key) Rust // Rust program for getting value by key // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert("Data Structures","90");gfg.insert("Algorithms","99");gfg.insert("Interview Preparations","100");gfg.insert("FAANG","97");gfg.insert("CP","99");let value= gfg.get(&"Algorithms");println!("value={:?}",value)} Output : value=Some("99") clintra saurabh1990aror Picked Rust custom-types Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Nov, 2021" }, { "code": null, "e": 274, "s": 28, "text": "The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated." }, { "code": null, "e": 337, "s": 274, "text": "To insert a value in a HashMap in Rust follow the below steps:" }, { "code": null, "e": 352, "s": 337, "text": "Import HashMap" }, { "code": null, "e": 377, "s": 352, "text": "Create HashMap named gfg" }, { "code": null, "e": 425, "s": 377, "text": "Insert the records using gfg.insert(key, value)" }, { "code": null, "e": 434, "s": 425, "text": "Syntax :" }, { "code": null, "e": 604, "s": 434, "text": "// import HashMap\nuse std::collections::HashMap;\n// initialize the HashMap\nlet mut gfg=HashMap::new();\n//insert the values In HashMap\ngfg.insert(\"Data Structures\",\"90\");" }, { "code": null, "e": 609, "s": 604, "text": "Rust" }, { "code": "// Inserting in HashMap Rustuse std::collections::HashMap; fn main() { // initialize the HashMap// mut means we can reassign to something elselet mut gfg=HashMap::new(); // inserting records gfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\"); // for printing all the records \"{:?}\" this is mustprintln!(\"{:?}\",gfg );}", "e": 1035, "s": 609, "text": null }, { "code": null, "e": 1044, "s": 1035, "text": "Output :" }, { "code": null, "e": 1150, "s": 1044, "text": "{\"CP\": \"99\", \"Algorithms\": \"99\",\n\"Data Structures\": \"90\",\n\"FAANG\": \"97\",\n\"Interview Preparations\": \"100\"}" }, { "code": null, "e": 1208, "s": 1150, "text": "To iterate over a HashMap in Rust follow the below steps:" }, { "code": null, "e": 1223, "s": 1208, "text": "Import HashMap" }, { "code": null, "e": 1249, "s": 1223, "text": "Insert records in HashMap" }, { "code": null, "e": 1292, "s": 1249, "text": "Iterate using iter() method with for loop " }, { "code": null, "e": 1301, "s": 1292, "text": "Syntax :" }, { "code": null, "e": 1392, "s": 1301, "text": "// here gfg is HashMap \nfor (key, val) in gfg.iter() {\n println!(\"{} {}\", key, val);\n }" }, { "code": null, "e": 1397, "s": 1392, "text": "Rust" }, { "code": "// Rust Program to Iterating over HashMap // import HashMapuse std::collections::HashMap;fn main() { // create HashMap let mut gfg=HashMap::new(); // inserting overgfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\"); // iterating using iter() method on gfgfor (key, val) in gfg.iter() { println!(\"{} {}\", key, val); }}", "e": 1823, "s": 1397, "text": null }, { "code": null, "e": 1832, "s": 1823, "text": "Output :" }, { "code": null, "e": 1907, "s": 1832, "text": "Algorithms 99\nFAANG 97\nCP 99\nInterview Preparations 100\nData Structures 90" }, { "code": null, "e": 1978, "s": 1907, "text": "To check whether a key is present in a HashMap follow the below steps:" }, { "code": null, "e": 1993, "s": 1978, "text": "Import HashMap" }, { "code": null, "e": 2019, "s": 1993, "text": "Insert records in HashMap" }, { "code": null, "e": 2076, "s": 2019, "text": "Use contains_key(& key) to check the key present or not " }, { "code": null, "e": 2086, "s": 2076, "text": "Syntax : " }, { "code": null, "e": 2186, "s": 2086, "text": " if gfg.contains_key( & \"FAANG\")\n {\n println!(\"yes it contains the given key well done gfg\");\n }" }, { "code": null, "e": 2191, "s": 2186, "text": "Rust" }, { "code": "// Rust program for contains Key // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\"); // contains_key() method to check// if key present or not if gfg.contains_key( & \"FAANG\") { println!(\"yes it contains the given key well done gfg\"); }}", "e": 2676, "s": 2191, "text": null }, { "code": null, "e": 2685, "s": 2676, "text": "Output :" }, { "code": null, "e": 2729, "s": 2685, "text": "yes it contains the given key well done gfg" }, { "code": null, "e": 2796, "s": 2729, "text": "To check for the length of HashMap in Rust follow the below steps:" }, { "code": null, "e": 2811, "s": 2796, "text": "Import HashMap" }, { "code": null, "e": 2837, "s": 2811, "text": "Insert records in HashMap" }, { "code": null, "e": 2891, "s": 2837, "text": "Use len() method on HashMap for the length of HashMap" }, { "code": null, "e": 2900, "s": 2891, "text": "Syntax :" }, { "code": null, "e": 2935, "s": 2900, "text": "//for length of HashMap\ngfg.len();" }, { "code": null, "e": 2940, "s": 2935, "text": "Rust" }, { "code": "// Rust program for length of HashMap // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\"); // length of HashMap using len()println!(\"len of gfg HashMap={}\",gfg.len()); }", "e": 3353, "s": 2940, "text": null }, { "code": null, "e": 3362, "s": 3353, "text": "Output :" }, { "code": null, "e": 3383, "s": 3362, "text": "len of gfg HashMap=5" }, { "code": null, "e": 3418, "s": 3383, "text": "To remove elements from a Hashmap:" }, { "code": null, "e": 3434, "s": 3418, "text": "Import HashMap." }, { "code": null, "e": 3461, "s": 3434, "text": "Insert records in HashMap." }, { "code": null, "e": 3512, "s": 3461, "text": "Use the remove(key) method to remove from HashMap." }, { "code": null, "e": 3521, "s": 3512, "text": "Syntax :" }, { "code": null, "e": 3585, "s": 3521, "text": "// length of HashMap\n// here gfg is HashMap\ngfg.remove(& \"key\")" }, { "code": null, "e": 3590, "s": 3585, "text": "Rust" }, { "code": "// Rust program for removing from HashMap // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\"); // remove using remove() methodgfg.remove( & \"CP\");println!(\"len of gfg HashMap={}\",gfg.len());}", "e": 4025, "s": 3590, "text": null }, { "code": null, "e": 4034, "s": 4025, "text": "Output :" }, { "code": null, "e": 4055, "s": 4034, "text": "len of gfg HashMap=4" }, { "code": null, "e": 4097, "s": 4055, "text": "To access values from HashMap using keys:" }, { "code": null, "e": 4113, "s": 4097, "text": "Import HashMap." }, { "code": null, "e": 4140, "s": 4113, "text": "Insert records in HashMap." }, { "code": null, "e": 4179, "s": 4140, "text": "Use get( & key) for getting the value." }, { "code": null, "e": 4188, "s": 4179, "text": "Syntax :" }, { "code": null, "e": 4231, "s": 4188, "text": "// for getting through key\ngfg.get( & key)" }, { "code": null, "e": 4236, "s": 4231, "text": "Rust" }, { "code": "// Rust program for getting value by key // importing hashmapuse std::collections::HashMap;fn main() { // creating hashMap// mut means we can reassign gfglet mut gfg=HashMap::new();gfg.insert(\"Data Structures\",\"90\");gfg.insert(\"Algorithms\",\"99\");gfg.insert(\"Interview Preparations\",\"100\");gfg.insert(\"FAANG\",\"97\");gfg.insert(\"CP\",\"99\");let value= gfg.get(&\"Algorithms\");println!(\"value={:?}\",value)}", "e": 4636, "s": 4236, "text": null }, { "code": null, "e": 4645, "s": 4636, "text": "Output :" }, { "code": null, "e": 4662, "s": 4645, "text": "value=Some(\"99\")" }, { "code": null, "e": 4670, "s": 4662, "text": "clintra" }, { "code": null, "e": 4686, "s": 4670, "text": "saurabh1990aror" }, { "code": null, "e": 4693, "s": 4686, "text": "Picked" }, { "code": null, "e": 4711, "s": 4693, "text": "Rust custom-types" }, { "code": null, "e": 4716, "s": 4711, "text": "Rust" } ]
sizeof() for Floating Constant in C
02 Jun, 2017 In C language, we have three floating data types i.e. float, double and long double. And the exact size of each of these 3 types depends on the C compiler implementation/platform. The following program can be used to find out the size of each floating data type on your machine. #include "stdio.h"int main(){ printf("%d %d %d",sizeof(float), sizeof(double), sizeof(long double)); return 0;} But what about the size of a floating point constant (e.g. 31.4 or 2.718)? For example if we have PI macro defined as follows, what would be the sizeof(3.14). #define PI 3.14 Now if we do sizeof(PI), what will be its size? Is is equal to sizeof(float) ? Or is it also compiler implementation dependent. Well, for floating constants, C standard (C11 i.e. ISO/IEC 9899:2011) has given guideline. As per C11 clause 6.4.4.2, “An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.“ It means the type of a floating constant is same as that of double data type. So if size of a double on a machine is 8 bytes, the size of floating constant would be 8 bytes. One can find out this using the below program #include "stdio.h"#define PI 3.14int main(){ printf("%d",sizeof(PI)); return 0;} As per the above mentioned C standard clause, a floating constant can be converted to float type by using f or F. Similarly, a floating constant can be converted to long double by using l or L. So it shouldn’t take much thought on guessing the output of the following: #include "stdio.h"int main(){ printf("%d %d",sizeof(3.14F), sizeof(3.14L)); return 0;} Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn C-Data Types Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2017" }, { "code": null, "e": 331, "s": 52, "text": "In C language, we have three floating data types i.e. float, double and long double. And the exact size of each of these 3 types depends on the C compiler implementation/platform. The following program can be used to find out the size of each floating data type on your machine." }, { "code": "#include \"stdio.h\"int main(){ printf(\"%d %d %d\",sizeof(float), sizeof(double), sizeof(long double)); return 0;}", "e": 443, "s": 331, "text": null }, { "code": null, "e": 602, "s": 443, "text": "But what about the size of a floating point constant (e.g. 31.4 or 2.718)? For example if we have PI macro defined as follows, what would be the sizeof(3.14)." }, { "code": null, "e": 618, "s": 602, "text": "#define PI 3.14" }, { "code": null, "e": 1027, "s": 618, "text": "Now if we do sizeof(PI), what will be its size? Is is equal to sizeof(float) ? Or is it also compiler implementation dependent. Well, for floating constants, C standard (C11 i.e. ISO/IEC 9899:2011) has given guideline. As per C11 clause 6.4.4.2, “An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.“" }, { "code": null, "e": 1247, "s": 1027, "text": "It means the type of a floating constant is same as that of double data type. So if size of a double on a machine is 8 bytes, the size of floating constant would be 8 bytes. One can find out this using the below program" }, { "code": "#include \"stdio.h\"#define PI 3.14int main(){ printf(\"%d\",sizeof(PI)); return 0;}", "e": 1328, "s": 1247, "text": null }, { "code": null, "e": 1597, "s": 1328, "text": "As per the above mentioned C standard clause, a floating constant can be converted to float type by using f or F. Similarly, a floating constant can be converted to long double by using l or L. So it shouldn’t take much thought on guessing the output of the following:" }, { "code": "#include \"stdio.h\"int main(){ printf(\"%d %d\",sizeof(3.14F), sizeof(3.14L)); return 0;}", "e": 1684, "s": 1597, "text": null }, { "code": null, "e": 1840, "s": 1684, "text": "Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn " }, { "code": null, "e": 1853, "s": 1840, "text": "C-Data Types" }, { "code": null, "e": 1862, "s": 1853, "text": "Articles" }, { "code": null, "e": 1873, "s": 1862, "text": "C Language" } ]
TreeMap remove() Method in Java
08 Jun, 2022 The java.util.TreeMap.remove() is an inbuilt method of TreeMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Tree_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map. Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL. Below programs illustrates the working of java.util.TreeMap.remove() method: Program 1: When passing an existing key. Java // Java code to illustrate the remove() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Removing the existing key mapping String returned_value = (String)tree_map.remove(20); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new map System.out.println("New map is: " + tree_map); }} Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Returned value is: Geeks New map is: {10=Geeks, 15=4, 25=Welcomes, 30=You} Program 2: When passing a new key. Java // Java code to illustrate the remove() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Removing the new key mapping // Note : 50 is not present and so null // should be returned (nothing to remove) String returned_value = (String)tree_map.remove(50); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new map System.out.println("New map is: " + tree_map); }} Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Returned value is: null New map is: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. vaibhav2992 simmytarika5 Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java Introduction to Java Constructors in Java Initializing a List in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 235, "s": 28, "text": "The java.util.TreeMap.remove() is an inbuilt method of TreeMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. " }, { "code": null, "e": 243, "s": 235, "text": "Syntax:" }, { "code": null, "e": 271, "s": 243, "text": "Tree_Map.remove(Object key)" }, { "code": null, "e": 364, "s": 271, "text": "Parameters: The method takes one parameter key whose mapping is to be removed from the Map. " }, { "code": null, "e": 504, "s": 364, "text": "Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL. " }, { "code": null, "e": 582, "s": 504, "text": "Below programs illustrates the working of java.util.TreeMap.remove() method: " }, { "code": null, "e": 624, "s": 582, "text": "Program 1: When passing an existing key. " }, { "code": null, "e": 629, "s": 624, "text": "Java" }, { "code": "// Java code to illustrate the remove() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Removing the existing key mapping String returned_value = (String)tree_map.remove(20); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displaying the new map System.out.println(\"New map is: \" + tree_map); }}", "e": 1596, "s": 629, "text": null }, { "code": null, "e": 1741, "s": 1596, "text": "Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nReturned value is: Geeks\nNew map is: {10=Geeks, 15=4, 25=Welcomes, 30=You}" }, { "code": null, "e": 1777, "s": 1741, "text": "Program 2: When passing a new key. " }, { "code": null, "e": 1782, "s": 1777, "text": "Java" }, { "code": "// Java code to illustrate the remove() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Removing the new key mapping // Note : 50 is not present and so null // should be returned (nothing to remove) String returned_value = (String)tree_map.remove(50); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displaying the new map System.out.println(\"New map is: \" + tree_map); }}", "e": 2837, "s": 1782, "text": null }, { "code": null, "e": 2991, "s": 2837, "text": "Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nReturned value is: null\nNew map is: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}" }, { "code": null, "e": 3115, "s": 2991, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 3127, "s": 3115, "text": "vaibhav2992" }, { "code": null, "e": 3140, "s": 3127, "text": "simmytarika5" }, { "code": null, "e": 3157, "s": 3140, "text": "Java-Collections" }, { "code": null, "e": 3170, "s": 3157, "text": "java-TreeMap" }, { "code": null, "e": 3175, "s": 3170, "text": "Java" }, { "code": null, "e": 3180, "s": 3175, "text": "Java" }, { "code": null, "e": 3197, "s": 3180, "text": "Java-Collections" }, { "code": null, "e": 3295, "s": 3197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3314, "s": 3295, "text": "Interfaces in Java" }, { "code": null, "e": 3329, "s": 3314, "text": "Stream In Java" }, { "code": null, "e": 3347, "s": 3329, "text": "ArrayList in Java" }, { "code": null, "e": 3367, "s": 3347, "text": "Collections in Java" }, { "code": null, "e": 3391, "s": 3367, "text": "Singleton Class in Java" }, { "code": null, "e": 3423, "s": 3391, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3443, "s": 3423, "text": "Stack Class in Java" }, { "code": null, "e": 3464, "s": 3443, "text": "Introduction to Java" }, { "code": null, "e": 3485, "s": 3464, "text": "Constructors in Java" } ]
Program for Volume and Surface area of Frustum of Cone
23 Apr, 2018 Given slant height, height and radius of a frustum of a cone, we have to calculate the volume and surface area of the frustum of a cone. Frustum of coneIn geometry, a frustum is the portion of a solid (normally a cone or pyramid) that lies between one or two parallel planes cutting it.If we cut a right circular cone by a plane parallel to its base, the portion of the solid between this plane and the base is known as the frustum of a cone. Given below is a right circular cone. The right circular cone after being cut by a plane parallel to its base results in a frustum as follows: which has a circular base at bottom of radius Rcircular upper portion with radius rheight hand slant height l Volume of frustum of cone: Volume (V) = 1/3 * pi * h(r2 + R2 + r*R) where r = radius of smaller circle R = radius of bigger circle (or radius of base of the cone) h = height of the frustum Curved Surface Area of frustum of cone: Curved Surface Area (CSA) = pi * l(R + r) where r = radius of smaller circle R = radius of bigger circle l = slant height of the frustum TotalSurface Area of frustum of cone: Total Surface Area (TSA) = pi * l(R + r) + pi(R2 + r2) where r = radius of smaller circle R = radius of bigger circle l = slant height of frustum Examples: Input : Radius of smaller circle = 3 Radius of bigger circle = 8 Height of frustum = 12 Slant height of frustum = 13 Output : Volume Of Frustum of Cone : 1218.937 Curved Surface Area Of Frustum of Cone : 449.24738 Total Surface Area Of Frustum of Cone : 678.58344 Input : Radius of smaller circle = 7 Radius of bigger circle = 10 Height of frustum = 4 Slant height of frustum = 5 Output : Volume Of Frustum of Cone : 917.34436 Curved Surface Area Of Frustum of Cone : 267.03516 Total Surface Area Of Frustum of Cone : 735.1321 C++ Java Python3 C# PHP // CPP program to calculate Volume and// Surface area of frustum of cone#include <iostream>using namespace std; float pi = 3.14159; // Function to calculate Volume of frustum of conefloat volume(float r, float R, float h){ return (float(1) / float(3)) * pi * h * (r * r + R * R + r * R);} // Function to calculate Curved Surface area of// frustum of conefloat curved_surface_area(float r, float R, float l){ return pi * l * (R + r);} // Function to calculate Total Surface area of // frustum of conefloat total_surface_area(float r, float R, float l, float h){ return pi * l * (R + r) + pi * (r * r + R * R);} // Driver functionint main(){ float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume and surface area cout << "Volume Of Frustum of Cone : " << volume(small_radius, big_radius, height) << endl; cout << "Curved Surface Area Of Frustum of Cone : " << curved_surface_area(small_radius, big_radius, slant_height) << endl; cout << "Total Surface Area Of Frustum of Cone : " << total_surface_area(small_radius, big_radius, slant_height, height); return 0;} // Java program to calculate Volume and Surface area// of frustum of cone public class demo { static float pi = 3.14159f; // Function to calculate Volume of frustum of cone public static float volume(float r, float R, float h) { return (float)1 / 3 * pi * h * (r * r + R * R + r * R); } // Function to calculate Curved Surface area of // frustum of cone public static float curved_surface_area(float r, float R, float l) { return pi * l * (R + r); } // Function to calculate Total Surface area of // frustum of cone public static float total_surface_area(float r, float R, float l, float h) { return pi * l * (R + r) + pi * (r * r + R * R); } // Driver function public static void main(String args[]) { float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume and surface area System.out.print("Volume Of Frustum of Cone : "); System.out.println(volume(small_radius, big_radius, height)); System.out.print("Curved Surface Area Of" + " Frustum of Cone : "); System.out.println(curved_surface_area(small_radius, big_radius, slant_height)); System.out.print("Total Surface Area Of" + " Frustum of Cone : "); System.out.println(total_surface_area(small_radius, big_radius, slant_height, height)); }} # Python3 code to calculate # Volume and Surface area of# frustum of coneimport math pi = math.pi # Function to calculate Volume# of frustum of conedef volume( r , R , h ): return 1 /3 * pi * h * (r * r + R * R + r * R) # Function to calculate Curved # Surface area of frustum of conedef curved_surface_area( r , R , l ): return pi * l * (R + r) # Function to calculate Total # Surface area of frustum of conedef total_surface_area( r , R , l , h ): return pi * l * (R + r) + pi * (r * r + R * R) # Driver Codesmall_radius = 3big_radius = 8slant_height = 13height = 12 # Printing value of volume # and surface areaprint("Volume Of Frustum of Cone : " ,end='')print(volume(small_radius, big_radius, height)) print("Curved Surface Area Of Frustum"+ " of Cone : ",end='')print(curved_surface_area(small_radius, big_radius,slant_height)) print("Total Surface Area Of Frustum"+ " of Cone : ",end='')print(total_surface_area(small_radius, big_radius,slant_height, height)) # This code is contributed by "Sharad_Bhardwaj". // C# program to calculate Volume and // Surface area of frustum of coneusing System; public class demo { static float pi = 3.14159f; // Function to calculate // Volume of frustum of cone public static float volume(float r, float R, float h) { return (float)1 / 3 * pi * h * (r * r + R * R + r * R); } // Function to calculate Curved // Surface area of frustum of cone public static float curved_surface_area(float r, float R, float l) { return pi * l * (R + r); } // Function to calculate Total // Surface area of frustum of cone public static float total_surface_area(float r, float R, float l, float h) { return pi * l * (R + r) + pi * (r * r + R * R); } // Driver function public static void Main() { float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume // and surface area Console.Write("Volume Of Frustum of Cone : "); Console.WriteLine(volume(small_radius, big_radius, height)); Console.Write("Curved Surface Area Of" + " Frustum of Cone : "); Console.WriteLine(curved_surface_area(small_radius, big_radius, slant_height)); Console.Write("Total Surface Area Of" + " Frustum of Cone : "); Console.WriteLine(total_surface_area(small_radius, big_radius, slant_height, height)); }} // This article is contributed by vt_m <?php// PHP program to calculate Volume and// Surface area of frustum of cone // Function to calculate // Volume of frustum of conefunction volume($r, $R, $h){ $pi = 3.14159; return (1 / (3)) * $pi * $h * ($r * $r + $R * $R + $r * $R);} // Function to calculate Curved // Surface area of frustum of conefunction curved_surface_area($r, $R, $l){ $pi = 3.14159; return $pi * $l * ($R + $r);} // Function to calculate Total Surface // area of frustum of conefunction total_surface_area( $r, $R, $l, $h){ $pi = 3.14159; return ($pi * $l * ($R + $r) + $pi * ($r * $r + $R * $R));} // Driver Code $small_radius = 3; $big_radius = 8; $slant_height = 13; $height = 12; // Printing value of volume // and surface area echo("Volume Of Frustum of Cone : "); echo(volume($small_radius, $big_radius, $height)); echo("\n"); echo("Curved Surface Area Of Frustum of Cone : "); echo (curved_surface_area($small_radius, $big_radius , $slant_height)); echo("\n"); echo("Total Surface Area Of Frustum of Cone : "); echo(total_surface_area($small_radius, $big_radius, $slant_height, $height)); // This code is contributed by vt_m?> Output: Volume Of Frustum of Cone : 1218.937 Curved Surface Area Of Frustum of Cone : 449.24738 Total Surface Area Of Frustum of Cone : 678.58344 vt_m area-volume-programs Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Check whether a given point lies inside a triangle or not Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2018" }, { "code": null, "e": 165, "s": 28, "text": "Given slant height, height and radius of a frustum of a cone, we have to calculate the volume and surface area of the frustum of a cone." }, { "code": null, "e": 471, "s": 165, "text": "Frustum of coneIn geometry, a frustum is the portion of a solid (normally a cone or pyramid) that lies between one or two parallel planes cutting it.If we cut a right circular cone by a plane parallel to its base, the portion of the solid between this plane and the base is known as the frustum of a cone." }, { "code": null, "e": 509, "s": 471, "text": "Given below is a right circular cone." }, { "code": null, "e": 614, "s": 509, "text": "The right circular cone after being cut by a plane parallel to its base results in a frustum as follows:" }, { "code": null, "e": 724, "s": 614, "text": "which has a circular base at bottom of radius Rcircular upper portion with radius rheight hand slant height l" }, { "code": null, "e": 751, "s": 724, "text": "Volume of frustum of cone:" }, { "code": null, "e": 915, "s": 751, "text": "Volume (V) = 1/3 * pi * h(r2 + R2 + r*R)\n\nwhere\nr = radius of smaller circle\nR = radius of bigger circle (or radius of base of the cone)\nh = height of the frustum\n" }, { "code": null, "e": 955, "s": 915, "text": "Curved Surface Area of frustum of cone:" }, { "code": null, "e": 1094, "s": 955, "text": "Curved Surface Area (CSA) = pi * l(R + r)\n\nwhere\nr = radius of smaller circle\nR = radius of bigger circle\nl = slant height of the frustum\n" }, { "code": null, "e": 1132, "s": 1094, "text": "TotalSurface Area of frustum of cone:" }, { "code": null, "e": 1280, "s": 1132, "text": "Total Surface Area (TSA) = pi * l(R + r) + pi(R2 + r2)\n\nwhere\nr = radius of smaller circle\nR = radius of bigger circle\nl = slant height of frustum\n" }, { "code": null, "e": 1290, "s": 1280, "text": "Examples:" }, { "code": null, "e": 1869, "s": 1290, "text": "Input : Radius of smaller circle = 3\n Radius of bigger circle = 8\n Height of frustum = 12\n Slant height of frustum = 13\nOutput :\nVolume Of Frustum of Cone : 1218.937\nCurved Surface Area Of Frustum of Cone : 449.24738\nTotal Surface Area Of Frustum of Cone : 678.58344\n\n\nInput : Radius of smaller circle = 7\n Radius of bigger circle = 10\n Height of frustum = 4\n Slant height of frustum = 5\n\nOutput :\nVolume Of Frustum of Cone : 917.34436\nCurved Surface Area Of Frustum of Cone : 267.03516\nTotal Surface Area Of Frustum of Cone : 735.1321\n" }, { "code": null, "e": 1873, "s": 1869, "text": "C++" }, { "code": null, "e": 1878, "s": 1873, "text": "Java" }, { "code": null, "e": 1886, "s": 1878, "text": "Python3" }, { "code": null, "e": 1889, "s": 1886, "text": "C#" }, { "code": null, "e": 1893, "s": 1889, "text": "PHP" }, { "code": "// CPP program to calculate Volume and// Surface area of frustum of cone#include <iostream>using namespace std; float pi = 3.14159; // Function to calculate Volume of frustum of conefloat volume(float r, float R, float h){ return (float(1) / float(3)) * pi * h * (r * r + R * R + r * R);} // Function to calculate Curved Surface area of// frustum of conefloat curved_surface_area(float r, float R, float l){ return pi * l * (R + r);} // Function to calculate Total Surface area of // frustum of conefloat total_surface_area(float r, float R, float l, float h){ return pi * l * (R + r) + pi * (r * r + R * R);} // Driver functionint main(){ float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume and surface area cout << \"Volume Of Frustum of Cone : \" << volume(small_radius, big_radius, height) << endl; cout << \"Curved Surface Area Of Frustum of Cone : \" << curved_surface_area(small_radius, big_radius, slant_height) << endl; cout << \"Total Surface Area Of Frustum of Cone : \" << total_surface_area(small_radius, big_radius, slant_height, height); return 0;}", "e": 3225, "s": 1893, "text": null }, { "code": "// Java program to calculate Volume and Surface area// of frustum of cone public class demo { static float pi = 3.14159f; // Function to calculate Volume of frustum of cone public static float volume(float r, float R, float h) { return (float)1 / 3 * pi * h * (r * r + R * R + r * R); } // Function to calculate Curved Surface area of // frustum of cone public static float curved_surface_area(float r, float R, float l) { return pi * l * (R + r); } // Function to calculate Total Surface area of // frustum of cone public static float total_surface_area(float r, float R, float l, float h) { return pi * l * (R + r) + pi * (r * r + R * R); } // Driver function public static void main(String args[]) { float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume and surface area System.out.print(\"Volume Of Frustum of Cone : \"); System.out.println(volume(small_radius, big_radius, height)); System.out.print(\"Curved Surface Area Of\" + \" Frustum of Cone : \"); System.out.println(curved_surface_area(small_radius, big_radius, slant_height)); System.out.print(\"Total Surface Area Of\" + \" Frustum of Cone : \"); System.out.println(total_surface_area(small_radius, big_radius, slant_height, height)); }}", "e": 4887, "s": 3225, "text": null }, { "code": "# Python3 code to calculate # Volume and Surface area of# frustum of coneimport math pi = math.pi # Function to calculate Volume# of frustum of conedef volume( r , R , h ): return 1 /3 * pi * h * (r * r + R * R + r * R) # Function to calculate Curved # Surface area of frustum of conedef curved_surface_area( r , R , l ): return pi * l * (R + r) # Function to calculate Total # Surface area of frustum of conedef total_surface_area( r , R , l , h ): return pi * l * (R + r) + pi * (r * r + R * R) # Driver Codesmall_radius = 3big_radius = 8slant_height = 13height = 12 # Printing value of volume # and surface areaprint(\"Volume Of Frustum of Cone : \" ,end='')print(volume(small_radius, big_radius, height)) print(\"Curved Surface Area Of Frustum\"+ \" of Cone : \",end='')print(curved_surface_area(small_radius, big_radius,slant_height)) print(\"Total Surface Area Of Frustum\"+ \" of Cone : \",end='')print(total_surface_area(small_radius, big_radius,slant_height, height)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 6088, "s": 4887, "text": null }, { "code": "// C# program to calculate Volume and // Surface area of frustum of coneusing System; public class demo { static float pi = 3.14159f; // Function to calculate // Volume of frustum of cone public static float volume(float r, float R, float h) { return (float)1 / 3 * pi * h * (r * r + R * R + r * R); } // Function to calculate Curved // Surface area of frustum of cone public static float curved_surface_area(float r, float R, float l) { return pi * l * (R + r); } // Function to calculate Total // Surface area of frustum of cone public static float total_surface_area(float r, float R, float l, float h) { return pi * l * (R + r) + pi * (r * r + R * R); } // Driver function public static void Main() { float small_radius = 3; float big_radius = 8; float slant_height = 13; float height = 12; // Printing value of volume // and surface area Console.Write(\"Volume Of Frustum of Cone : \"); Console.WriteLine(volume(small_radius, big_radius, height)); Console.Write(\"Curved Surface Area Of\" + \" Frustum of Cone : \"); Console.WriteLine(curved_surface_area(small_radius, big_radius, slant_height)); Console.Write(\"Total Surface Area Of\" + \" Frustum of Cone : \"); Console.WriteLine(total_surface_area(small_radius, big_radius, slant_height, height)); }} // This article is contributed by vt_m", "e": 7831, "s": 6088, "text": null }, { "code": "<?php// PHP program to calculate Volume and// Surface area of frustum of cone // Function to calculate // Volume of frustum of conefunction volume($r, $R, $h){ $pi = 3.14159; return (1 / (3)) * $pi * $h * ($r * $r + $R * $R + $r * $R);} // Function to calculate Curved // Surface area of frustum of conefunction curved_surface_area($r, $R, $l){ $pi = 3.14159; return $pi * $l * ($R + $r);} // Function to calculate Total Surface // area of frustum of conefunction total_surface_area( $r, $R, $l, $h){ $pi = 3.14159; return ($pi * $l * ($R + $r) + $pi * ($r * $r + $R * $R));} // Driver Code $small_radius = 3; $big_radius = 8; $slant_height = 13; $height = 12; // Printing value of volume // and surface area echo(\"Volume Of Frustum of Cone : \"); echo(volume($small_radius, $big_radius, $height)); echo(\"\\n\"); echo(\"Curved Surface Area Of Frustum of Cone : \"); echo (curved_surface_area($small_radius, $big_radius , $slant_height)); echo(\"\\n\"); echo(\"Total Surface Area Of Frustum of Cone : \"); echo(total_surface_area($small_radius, $big_radius, $slant_height, $height)); // This code is contributed by vt_m?>", "e": 9221, "s": 7831, "text": null }, { "code": null, "e": 9229, "s": 9221, "text": "Output:" }, { "code": null, "e": 9368, "s": 9229, "text": "Volume Of Frustum of Cone : 1218.937\nCurved Surface Area Of Frustum of Cone : 449.24738\nTotal Surface Area Of Frustum of Cone : 678.58344\n" }, { "code": null, "e": 9373, "s": 9368, "text": "vt_m" }, { "code": null, "e": 9394, "s": 9373, "text": "area-volume-programs" }, { "code": null, "e": 9404, "s": 9394, "text": "Geometric" }, { "code": null, "e": 9423, "s": 9404, "text": "School Programming" }, { "code": null, "e": 9433, "s": 9423, "text": "Geometric" }, { "code": null, "e": 9531, "s": 9433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9580, "s": 9531, "text": "Program for distance between two points on earth" }, { "code": null, "e": 9633, "s": 9580, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 9684, "s": 9633, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 9737, "s": 9684, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 9795, "s": 9737, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 9813, "s": 9795, "text": "Python Dictionary" }, { "code": null, "e": 9838, "s": 9813, "text": "Reverse a string in Java" }, { "code": null, "e": 9854, "s": 9838, "text": "Arrays in C/C++" }, { "code": null, "e": 9877, "s": 9854, "text": "Introduction To PYTHON" } ]
Nagarro Archives - GeeksforGeeks
Check whether two strings are anagram of each other Find the middle of a given linked list Print a given matrix in spiral form GCD of more than two (or array) numbers Nagarro Interview Experience Nagarro Interview Experience | On-Campus 2021 Nagarro Interview Experience Nagarro Interview Experience for Trainee-Software Engineer Nagarro Interview Experience for Associate Engineer Trainee | On-Campus 2022 Nagarro Interview Experience | Set 1 (On-Campus)
[ { "code": null, "e": 24182, "s": 24130, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 24221, "s": 24182, "text": "Find the middle of a given linked list" }, { "code": null, "e": 24257, "s": 24221, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 24297, "s": 24257, "text": "GCD of more than two (or array) numbers" }, { "code": null, "e": 24326, "s": 24297, "text": "Nagarro Interview Experience" }, { "code": null, "e": 24372, "s": 24326, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 24401, "s": 24372, "text": "Nagarro Interview Experience" }, { "code": null, "e": 24460, "s": 24401, "text": "Nagarro Interview Experience for Trainee-Software Engineer" }, { "code": null, "e": 24537, "s": 24460, "text": "Nagarro Interview Experience for Associate Engineer Trainee | On-Campus 2022" } ]
Increment a number by one by manipulating the bits
15 Jun, 2022 Given a non-negative integer n. The problem is to increment n by 1 by manipulating the bits of n.Examples : Input : 6 Output : 7 Input : 15 Output : 16 Approach: Following are the steps: Get the position of rightmost unset bit of n. Let this position be k.Set the k-th bit of n.Toggle the last k-1 bits of n.Finally, return n. Get the position of rightmost unset bit of n. Let this position be k. Set the k-th bit of n. Toggle the last k-1 bits of n. Finally, return n. C++ Java Python 3 C# PHP Javascript // C++ implementation to increment a number// by one by manipulating the bits#include <bits/stdc++.h>using namespace std; // function to find the position// of rightmost set bitint getPosOfRightmostSetBit(int n){ return log2(n & -n);} // function to toggle the last m bitsunsigned int toggleLastKBits(unsigned int n, unsigned int k){ // calculating a number 'num' having 'm' bits // and all are set unsigned int num = (1 << k) - 1; // toggle the last m bits and return the number return (n ^ num);} // function to increment a number by one// by manipulating the bitsunsigned int incrementByOne(unsigned int n){ // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set by this operation n = ((1 << k) | n); // from the right toggle all the bits before the // k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n;} // Driver program to test aboveint main(){ unsigned int n = 15; cout << incrementByOne(n); return 0;} // Java implementation to increment a number// by one by manipulating the bitsimport java.io.*;import java.util.*; class GFG { // function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)(Math.log(n & -n) / Math.log(2)); } // function to toggle the last m bits static int toggleLastKBits( int n, int k) { // calculating a number 'num' having // 'm' bits and all are set int num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits static int incrementByOne( int n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver Program public static void main (String[] args) { int n = 15; System.out.println(incrementByOne(n)); }} // This code is contributed by Gitanjali. # python 3 implementation# to increment a number# by one by manipulating# the bitsimport math # function to find the# position of rightmost# set bitdef getPosOfRightmostSetBit(n) : return math.log2(n & -n) # function to toggle the last m bitsdef toggleLastKBits(n, k) : # calculating a number # 'num' having 'm' bits # and all are set num = (1 << (int)(k)) - 1 # toggle the last m bits and # return the number return (n ^ num) # function to increment# a number by one by# manipulating the bitsdef incrementByOne(n) : # get position of rightmost # unset bit if all bits of # 'n' are set, then the bit # left to the MSB is the # rightmost unset bit k = getPosOfRightmostSetBit(~n) # kth bit of n is being # set by this operation n = ((1 << (int)(k)) | n) # from the right toggle # all the bits before the # k-th bit if (k != 0) : n = toggleLastKBits(n, k) # required number return n # Driver programn = 15print(incrementByOne(n)) # This code is contributed# by Nikita Tiwari. // C# implementation to increment a number// by one by manipulating the bitsusing System; class GFG { // function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)(Math.Log(n & -n) / Math.Log(2)); } // function to toggle the last m bits static int toggleLastKBits( int n, int k) { // calculating a number 'num' having // 'm' bits and all are set int num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits static int incrementByOne( int n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver Program public static void Main () { int n = 15; Console.WriteLine(incrementByOne(n)); }} // This code is contributed by Sam007. <?php// PHP implementation to increment a number// by one by manipulating the bits // function to find the position// of rightmost set bitfunction getPosOfRightmostSetBit($n){ $t = $n & -$n; return log($t, 2);} // function to toggle the last m bitsfunction toggleLastKBits($n, $k){ // calculating a number 'num' // having 'm' bits and all are set $num = (1 << $k) - 1; // toggle the last m bits and // return the number return ($n ^ $num);} // function to increment a number by one// by manipulating the bitsfunction incrementByOne($n){ // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit $k = getPosOfRightmostSetBit(~$n); // kth bit of n is being set // by this operation $n = ((1 << $k) | $n); // from the right toggle all the // bits before the k-th if ($k != 0) $n = toggleLastKBits($n, $k); // required number return $n;} // Driver code$n = 15;echo incrementByOne($n); // This code is contributed by Mithun Kumar?> <script> // JavaScript program to increment a number// by one by manipulating the bits // function to find the position // of rightmost set bit function getPosOfRightmostSetBit(n) { return (Math.log(n & -n) / Math.log(2)); } // function to toggle the last m bits function toggleLastKBits(n, k) { // calculating a number 'num' having // 'm' bits and all are set let num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits function incrementByOne(n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit let k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver code let n = 15; document.write(incrementByOne(n)); </script> Output : 16 Time Complexity: O(1)Space Complexity: O(1) Mithun Kumar souravghosh0416 ranjanrohit840 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find whether a given number is power of 2 Bits manipulation (Important tactics) Little and Big Endian Mystery Binary representation of a given number Divide two integers without using multiplication, division and mod operator Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once C++ bitset and its application Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given a non-negative integer n. The problem is to increment n by 1 by manipulating the bits of n.Examples : " }, { "code": null, "e": 209, "s": 164, "text": "Input : 6\nOutput : 7\n\nInput : 15\nOutput : 16" }, { "code": null, "e": 247, "s": 211, "text": "Approach: Following are the steps: " }, { "code": null, "e": 388, "s": 247, "text": "Get the position of rightmost unset bit of n. Let this position be k.Set the k-th bit of n.Toggle the last k-1 bits of n.Finally, return n. " }, { "code": null, "e": 458, "s": 388, "text": "Get the position of rightmost unset bit of n. Let this position be k." }, { "code": null, "e": 481, "s": 458, "text": "Set the k-th bit of n." }, { "code": null, "e": 512, "s": 481, "text": "Toggle the last k-1 bits of n." }, { "code": null, "e": 532, "s": 512, "text": "Finally, return n. " }, { "code": null, "e": 538, "s": 534, "text": "C++" }, { "code": null, "e": 543, "s": 538, "text": "Java" }, { "code": null, "e": 552, "s": 543, "text": "Python 3" }, { "code": null, "e": 555, "s": 552, "text": "C#" }, { "code": null, "e": 559, "s": 555, "text": "PHP" }, { "code": null, "e": 570, "s": 559, "text": "Javascript" }, { "code": "// C++ implementation to increment a number// by one by manipulating the bits#include <bits/stdc++.h>using namespace std; // function to find the position// of rightmost set bitint getPosOfRightmostSetBit(int n){ return log2(n & -n);} // function to toggle the last m bitsunsigned int toggleLastKBits(unsigned int n, unsigned int k){ // calculating a number 'num' having 'm' bits // and all are set unsigned int num = (1 << k) - 1; // toggle the last m bits and return the number return (n ^ num);} // function to increment a number by one// by manipulating the bitsunsigned int incrementByOne(unsigned int n){ // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set by this operation n = ((1 << k) | n); // from the right toggle all the bits before the // k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n;} // Driver program to test aboveint main(){ unsigned int n = 15; cout << incrementByOne(n); return 0;}", "e": 1751, "s": 570, "text": null }, { "code": "// Java implementation to increment a number// by one by manipulating the bitsimport java.io.*;import java.util.*; class GFG { // function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)(Math.log(n & -n) / Math.log(2)); } // function to toggle the last m bits static int toggleLastKBits( int n, int k) { // calculating a number 'num' having // 'm' bits and all are set int num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits static int incrementByOne( int n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver Program public static void main (String[] args) { int n = 15; System.out.println(incrementByOne(n)); }} // This code is contributed by Gitanjali.", "e": 3176, "s": 1751, "text": null }, { "code": "# python 3 implementation# to increment a number# by one by manipulating# the bitsimport math # function to find the# position of rightmost# set bitdef getPosOfRightmostSetBit(n) : return math.log2(n & -n) # function to toggle the last m bitsdef toggleLastKBits(n, k) : # calculating a number # 'num' having 'm' bits # and all are set num = (1 << (int)(k)) - 1 # toggle the last m bits and # return the number return (n ^ num) # function to increment# a number by one by# manipulating the bitsdef incrementByOne(n) : # get position of rightmost # unset bit if all bits of # 'n' are set, then the bit # left to the MSB is the # rightmost unset bit k = getPosOfRightmostSetBit(~n) # kth bit of n is being # set by this operation n = ((1 << (int)(k)) | n) # from the right toggle # all the bits before the # k-th bit if (k != 0) : n = toggleLastKBits(n, k) # required number return n # Driver programn = 15print(incrementByOne(n)) # This code is contributed# by Nikita Tiwari.", "e": 4245, "s": 3176, "text": null }, { "code": "// C# implementation to increment a number// by one by manipulating the bitsusing System; class GFG { // function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)(Math.Log(n & -n) / Math.Log(2)); } // function to toggle the last m bits static int toggleLastKBits( int n, int k) { // calculating a number 'num' having // 'm' bits and all are set int num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits static int incrementByOne( int n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit int k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver Program public static void Main () { int n = 15; Console.WriteLine(incrementByOne(n)); }} // This code is contributed by Sam007.", "e": 5652, "s": 4245, "text": null }, { "code": "<?php// PHP implementation to increment a number// by one by manipulating the bits // function to find the position// of rightmost set bitfunction getPosOfRightmostSetBit($n){ $t = $n & -$n; return log($t, 2);} // function to toggle the last m bitsfunction toggleLastKBits($n, $k){ // calculating a number 'num' // having 'm' bits and all are set $num = (1 << $k) - 1; // toggle the last m bits and // return the number return ($n ^ $num);} // function to increment a number by one// by manipulating the bitsfunction incrementByOne($n){ // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit $k = getPosOfRightmostSetBit(~$n); // kth bit of n is being set // by this operation $n = ((1 << $k) | $n); // from the right toggle all the // bits before the k-th if ($k != 0) $n = toggleLastKBits($n, $k); // required number return $n;} // Driver code$n = 15;echo incrementByOne($n); // This code is contributed by Mithun Kumar?>", "e": 6727, "s": 5652, "text": null }, { "code": "<script> // JavaScript program to increment a number// by one by manipulating the bits // function to find the position // of rightmost set bit function getPosOfRightmostSetBit(n) { return (Math.log(n & -n) / Math.log(2)); } // function to toggle the last m bits function toggleLastKBits(n, k) { // calculating a number 'num' having // 'm' bits and all are set let num = (1 << k) - 1; // toggle the last m bits and return // the number return (n ^ num); } // function to increment a number by one // by manipulating the bits function incrementByOne(n) { // get position of rightmost unset bit // if all bits of 'n' are set, then the // bit left to the MSB is the rightmost // unset bit let k = getPosOfRightmostSetBit(~n); // kth bit of n is being set // by this operation n = ((1 << k) | n); // from the right toggle all // the bits before the k-th bit if (k != 0) n = toggleLastKBits(n, k); // required number return n; } // Driver code let n = 15; document.write(incrementByOne(n)); </script>", "e": 7999, "s": 6727, "text": null }, { "code": null, "e": 8009, "s": 7999, "text": "Output : " }, { "code": null, "e": 8012, "s": 8009, "text": "16" }, { "code": null, "e": 8057, "s": 8012, "text": "Time Complexity: O(1)Space Complexity: O(1) " }, { "code": null, "e": 8070, "s": 8057, "text": "Mithun Kumar" }, { "code": null, "e": 8086, "s": 8070, "text": "souravghosh0416" }, { "code": null, "e": 8101, "s": 8086, "text": "ranjanrohit840" }, { "code": null, "e": 8111, "s": 8101, "text": "Bit Magic" }, { "code": null, "e": 8121, "s": 8111, "text": "Bit Magic" }, { "code": null, "e": 8219, "s": 8121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8272, "s": 8219, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 8310, "s": 8272, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 8340, "s": 8310, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 8380, "s": 8340, "text": "Binary representation of a given number" }, { "code": null, "e": 8456, "s": 8380, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 8499, "s": 8456, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 8515, "s": 8499, "text": "Bit Fields in C" }, { "code": null, "e": 8550, "s": 8515, "text": "Find the element that appears once" }, { "code": null, "e": 8581, "s": 8550, "text": "C++ bitset and its application" } ]
JavaFX - 2D Shapes
In the previous chapter, we have seen the basic application of JavaFX, where we learnt how to create an empty window and how to draw a line on an XY plane of JavaFX. In addition to the line, we can also draw several other 2D shapes. In general, a 2D shape is a geometrical figure that can be drawn on the XY plane, these include Line, Rectangle, Circle, etc. Using the JavaFX library, you can draw − Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc. Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc. Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc. Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc. In addition to these, you can also draw a 2D shape by parsing SVG path. In addition to these, you can also draw a 2D shape by parsing SVG path. Each of the above mentioned 2D shape is represented by a class and all these classes belongs to the package javafx.scene.shape. The class named Shape is the base class of all the 2-Dimensional shapes in JavaFX. To create a chart, you need to − Instantiate the respective class of the required shape. Set the properties of the shape. Add the shape object to the group. To create a 2 Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a line you need to instantiate the class named Line as follows − Line line = new Line(); After instantiating the class, you need to set the properties for the shape using the setter methods. For example, to draw a line you need to pass its x and y coordinates of the start point and end point of the line. You can specify these values using their respective setter methods as follows − //Setting the Properties of the Line line.setStartX(150.0f); line.setStartY(140.0f); line.setEndX(450.0f); line.setEndY(140.0f); Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below. //Creating a Group object Group root = new Group(line); The following table gives you the list of various shapes (classes) provided by JavaFX. A line is a geometrical structure joining two point. The Line class of the package javafx.scene.shape represents a line in the XY plane. In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles. In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape. In JavaFX, you can draw a rectangle either with sharp edges or with arched edges and The one with arched edges is known as a rounded rectangle. A circle is a line forming a closed loop, every point on which is a fixed distance from a centre point. In JavaFX, a circle is represented by a class named Circle. This class belongs to the package javafx.scene.shape. An ellipse is defined by two points, each called a focus. If any point on the ellipse is taken, the sum of the distances to the focus points is constant. The size of the ellipse is determined by the sum of these two distances. In JavaFX, an ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape. A closed shape formed by a number of coplanar line segments connected end to end. In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. A polyline is same a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments. In JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. A cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape. A quadratic curve is a Bezier parametric curve in the XY plane is a curve of degree 2. In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape. An arc is part of a curve. In JavaFX, an arc is represented by a class named Arc. This class belongs to the package − javafx.scene.shape. In addition to this we can draw three types of arc's Open, Chord, Round. In JavaFX, we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape. This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.. In the previous section, we have seen how to draw some simple predefined shapes by instantiating classes and setting respective parameters. But, just these predefined shapes are not sufficient to build complexer shapes other than the primitives provided by the javafx.shape package. For example, if you want to draw a graphical element as shown in the following diagram, you cannot rely on those simple shapes. To draw such complex structures JavaFX provides a class named Path. This class represents the geometrical outline of a shape. It is attached to an observable list which holds various Path Elements such as moveTo, LineTo, HlineTo, VlineTo, ArcTo, QuadCurveTo, CubicCurveTo. On instantiating, this class constructs a path based on the given path elements. You can pass the path elements to this class while instantiating it as follows− Path myshape = new Path(pathElement1, pathElement2, pathElement3); Or, you can get the observable list and add all the path elements using addAll() method as follows − Path myshape = new Path(); myshape.getElements().addAll(pathElement1, pathElement2, pathElement3); You can also add elements individually using the add() method as − Path myshape = new Path(); myshape.getElements().add(pathElement1); The Path Element MoveTo is used to move the current position of the path to a specified point. It is generally used to set the starting point of a shape drawn using the path elements. It is represented by a class named LineTo of the package javafx.scene.shape. It has 2 properties of the double datatype namely − X − The x coordinate of the point to which a line is to be drawn from the current position. X − The x coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. You can create a move to path element by instantiating the MoveTo class and passing the x, y coordinates of the new point as follows − MoveTo moveTo = new MoveTo(x, y); If you don’t pass any values to the constructor, then the new point will be set to (0,0). You can also set values to the x, y coordinate, using their respective setter methods as follows − setX(value); setY(value); In this example, we will show how to draw the following shape using the Path, MoveTo and Line classes. Save this code in a file with the name ComplexShape.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class ComplexShape extends Application { @Override public void start(Stage stage) { //Creating a Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(108, 71); //Creating 1st line LineTo line1 = new LineTo(321, 161); //Creating 2nd line LineTo line2 = new LineTo(126,232); //Creating 3rd line LineTo line3 = new LineTo(232,52); //Creating 4th line LineTo line4 = new LineTo(269, 250); //Creating 4th line LineTo line5 = new LineTo(108, 71); //Adding all the elements to the path path.getElements().add(moveTo); path.getElements().addAll(line1, line2, line3, line4, line5); //Creating a Group object Group root = new Group(path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing an arc through a path"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac ComplexShape.java java ComplexShape On executing, the above program generates a JavaFX window displaying an arc, which is drawn from the current position to the specified point as shown below. Following are the various path elements (classes) provided by JavaFX. These classes exist in the package javafx.shape. All these classes inherit the class PathElement. The path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape. The path element HLineTo is used to draw a horizontal line to a point in the specified coordinates from the current position. It is represented by a class named HLineTo. This class belongs to the package javafx.scene.shape. The path element vertical line is used to draw a vertical line to a point in the specified coordinates from the current position. It is represented by a class named VLineTo. This class belongs to the package javafx.scene.shape. The path element quadratic curve is used to draw a quadratic curve to a point in the specified coordinates from the current position. It is represented by a class named QuadraticCurveTo. This class belongs to the package javafx.scene.shape. The path element cubic curve is used to draw a cubic curve to a point in the specified coordinates from the current position. It is represented by a class named CubicCurveTo. This class belongs to the package javafx.scene.shape. The path element Arc is used to draw an arc to a point in the specified coordinates from the current position. It is represented by a class named ArcTo. This class belongs to the package javafx.scene.shape. For all the 2-Dimensional objects, you can set various properties like fill, stroke, StrokeType, etc. The following section discusses various properties of 2D objects. Stroke Type Stroke Width Stroke Fill Stroke Stroke Line Stroke Miter Limit Stroke Line Cap Smooth If we add more than one shape to a group, the first shape is overlapped by the second one as shown below. In addition to the transformations (rotate, scale, translate, etc.), transitions (animations), you can also perform three operations on 2D objects namely – Union, Subtraction and Intersection. This operation takes two or more shapes as inputs and returns the area occupied by them. This operation takes two or more shapes as inputs and returns the intersection area between them. This operation takes two or more shapes as an input. Then, it returns the area of the first shape excluding the area overlapped by the second one.
[ { "code": null, "e": 2267, "s": 2034, "text": "In the previous chapter, we have seen the basic application of JavaFX, where we learnt how to create an empty window and how to draw a line on an XY plane of JavaFX. In addition to the line, we can also draw several other 2D shapes." }, { "code": null, "e": 2393, "s": 2267, "text": "In general, a 2D shape is a geometrical figure that can be drawn on the XY plane, these include Line, Rectangle, Circle, etc." }, { "code": null, "e": 2434, "s": 2393, "text": "Using the JavaFX library, you can draw −" }, { "code": null, "e": 2543, "s": 2434, "text": "Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc." }, { "code": null, "e": 2652, "s": 2543, "text": "Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc." }, { "code": null, "e": 2768, "s": 2652, "text": "Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc." }, { "code": null, "e": 2884, "s": 2768, "text": "Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc." }, { "code": null, "e": 2956, "s": 2884, "text": "In addition to these, you can also draw a 2D shape by parsing SVG path." }, { "code": null, "e": 3028, "s": 2956, "text": "In addition to these, you can also draw a 2D shape by parsing SVG path." }, { "code": null, "e": 3239, "s": 3028, "text": "Each of the above mentioned 2D shape is represented by a class and all these classes belongs to the package javafx.scene.shape. The class named Shape is the base class of all the 2-Dimensional shapes in JavaFX." }, { "code": null, "e": 3272, "s": 3239, "text": "To create a chart, you need to −" }, { "code": null, "e": 3328, "s": 3272, "text": "Instantiate the respective class of the required shape." }, { "code": null, "e": 3361, "s": 3328, "text": "Set the properties of the shape." }, { "code": null, "e": 3396, "s": 3361, "text": "Add the shape object to the group." }, { "code": null, "e": 3488, "s": 3396, "text": "To create a 2 Dimensional shape, first of all you need to instantiate its respective class." }, { "code": null, "e": 3588, "s": 3488, "text": "For example, if you want to create a line you need to instantiate the class named Line as follows −" }, { "code": null, "e": 3613, "s": 3588, "text": "Line line = new Line();\n" }, { "code": null, "e": 3715, "s": 3613, "text": "After instantiating the class, you need to set the properties for the shape using the setter methods." }, { "code": null, "e": 3910, "s": 3715, "text": "For example, to draw a line you need to pass its x and y coordinates of the start point and end point of the line. You can specify these values using their respective setter methods as follows −" }, { "code": null, "e": 4052, "s": 3910, "text": "//Setting the Properties of the Line \nline.setStartX(150.0f); \nline.setStartY(140.0f); \nline.setEndX(450.0f); \nline.setEndY(140.0f);\n" }, { "code": null, "e": 4178, "s": 4052, "text": "Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below." }, { "code": null, "e": 4237, "s": 4178, "text": "//Creating a Group object \nGroup root = new Group(line);\n" }, { "code": null, "e": 4324, "s": 4237, "text": "The following table gives you the list of various shapes (classes) provided by JavaFX." }, { "code": null, "e": 4461, "s": 4324, "text": "A line is a geometrical structure joining two point. The Line class of the package javafx.scene.shape represents a line in the XY plane." }, { "code": null, "e": 4723, "s": 4461, "text": "In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles. In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 4867, "s": 4723, "text": "In JavaFX, you can draw a rectangle either with sharp edges or with arched edges and The one with arched edges is known as a rounded rectangle." }, { "code": null, "e": 5085, "s": 4867, "text": "A circle is a line forming a closed loop, every point on which is a fixed distance from a centre point. In JavaFX, a circle is represented by a class named Circle. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 5312, "s": 5085, "text": "An ellipse is defined by two points, each called a focus. If any point on the ellipse is taken, the sum of the distances to the focus points is constant. The size of the ellipse is determined by the sum of these two distances." }, { "code": null, "e": 5429, "s": 5312, "text": "In JavaFX, an ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 5627, "s": 5429, "text": "A closed shape formed by a number of coplanar line segments connected end to end. In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 5881, "s": 5627, "text": "A polyline is same a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments. In JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 6087, "s": 5881, "text": "A cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 6294, "s": 6087, "text": "A quadratic curve is a Bezier parametric curve in the XY plane is a curve of degree 2. In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 6432, "s": 6294, "text": "An arc is part of a curve. In JavaFX, an arc is represented by a class named Arc. This class belongs to the package − javafx.scene.shape." }, { "code": null, "e": 6505, "s": 6432, "text": "In addition to this we can draw three types of arc's Open, Chord, Round." }, { "code": null, "e": 6816, "s": 6505, "text": "In JavaFX, we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape. This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.." }, { "code": null, "e": 6956, "s": 6816, "text": "In the previous section, we have seen how to draw some simple predefined shapes by instantiating classes and setting respective parameters." }, { "code": null, "e": 7099, "s": 6956, "text": "But, just these predefined shapes are not sufficient to build complexer shapes other than the primitives provided by the javafx.shape package." }, { "code": null, "e": 7227, "s": 7099, "text": "For example, if you want to draw a graphical element as shown in the following diagram, you cannot rely on those simple shapes." }, { "code": null, "e": 7353, "s": 7227, "text": "To draw such complex structures JavaFX provides a class named Path. This class represents the geometrical outline of a shape." }, { "code": null, "e": 7500, "s": 7353, "text": "It is attached to an observable list which holds various Path Elements such as moveTo, LineTo, HlineTo, VlineTo, ArcTo, QuadCurveTo, CubicCurveTo." }, { "code": null, "e": 7581, "s": 7500, "text": "On instantiating, this class constructs a path based on the given path elements." }, { "code": null, "e": 7662, "s": 7581, "text": "You can pass the path elements to this class while instantiating it as follows− " }, { "code": null, "e": 7730, "s": 7662, "text": "Path myshape = new Path(pathElement1, pathElement2, pathElement3);\n" }, { "code": null, "e": 7831, "s": 7730, "text": "Or, you can get the observable list and add all the path elements using addAll() method as follows −" }, { "code": null, "e": 7933, "s": 7831, "text": "Path myshape = new Path(); \nmyshape.getElements().addAll(pathElement1, pathElement2, pathElement3); \n" }, { "code": null, "e": 8000, "s": 7933, "text": "You can also add elements individually using the add() method as −" }, { "code": null, "e": 8070, "s": 8000, "text": "Path myshape = new Path(); \nmyshape.getElements().add(pathElement1);\n" }, { "code": null, "e": 8254, "s": 8070, "text": "The Path Element MoveTo is used to move the current position of the path to a specified point. It is generally used to set the starting point of a shape drawn using the path elements." }, { "code": null, "e": 8383, "s": 8254, "text": "It is represented by a class named LineTo of the package javafx.scene.shape. It has 2 properties of the double datatype namely −" }, { "code": null, "e": 8475, "s": 8383, "text": "X − The x coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 8567, "s": 8475, "text": "X − The x coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 8659, "s": 8567, "text": "Y − The y coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 8751, "s": 8659, "text": "Y − The y coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 8886, "s": 8751, "text": "You can create a move to path element by instantiating the MoveTo class and passing the x, y coordinates of the new point as follows −" }, { "code": null, "e": 8921, "s": 8886, "text": "MoveTo moveTo = new MoveTo(x, y);\n" }, { "code": null, "e": 9011, "s": 8921, "text": "If you don’t pass any values to the constructor, then the new point will be set to (0,0)." }, { "code": null, "e": 9110, "s": 9011, "text": "You can also set values to the x, y coordinate, using their respective setter methods as follows −" }, { "code": null, "e": 9139, "s": 9110, "text": "setX(value); \nsetY(value); \n" }, { "code": null, "e": 9242, "s": 9139, "text": "In this example, we will show how to draw the following shape using the Path, MoveTo and Line classes." }, { "code": null, "e": 9300, "s": 9242, "text": "Save this code in a file with the name ComplexShape.java." }, { "code": null, "e": 10864, "s": 9300, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.LineTo; \nimport javafx.scene.shape.MoveTo; \nimport javafx.scene.shape.Path; \n \npublic class ComplexShape extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Path \n Path path = new Path(); \n \n //Moving to the starting point \n MoveTo moveTo = new MoveTo(108, 71); \n \n //Creating 1st line \n LineTo line1 = new LineTo(321, 161); \n \n //Creating 2nd line \n LineTo line2 = new LineTo(126,232); \n \n //Creating 3rd line \n LineTo line3 = new LineTo(232,52); \n \n //Creating 4th line \n LineTo line4 = new LineTo(269, 250); \n \n //Creating 4th line \n LineTo line5 = new LineTo(108, 71); \n \n //Adding all the elements to the path \n path.getElements().add(moveTo); \n path.getElements().addAll(line1, line2, line3, line4, line5); \n \n //Creating a Group object \n Group root = new Group(path); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing an arc through a path\");\n \n //Adding scene to the stage \n stage.setScene(scene);\n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 10958, "s": 10864, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 11002, "s": 10958, "text": "javac ComplexShape.java \njava ComplexShape\n" }, { "code": null, "e": 11159, "s": 11002, "text": "On executing, the above program generates a JavaFX window displaying an arc, which is drawn from the current position to the specified point as shown below." }, { "code": null, "e": 11327, "s": 11159, "text": "Following are the various path elements (classes) provided by JavaFX. These classes exist in the package javafx.shape. All these classes inherit the class PathElement." }, { "code": null, "e": 11545, "s": 11327, "text": "The path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 11769, "s": 11545, "text": "The path element HLineTo is used to draw a horizontal line to a point in the specified coordinates from the current position. It is represented by a class named HLineTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 11997, "s": 11769, "text": "The path element vertical line is used to draw a vertical line to a point in the specified coordinates from the current position. It is represented by a class named VLineTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 12238, "s": 11997, "text": "The path element quadratic curve is used to draw a quadratic curve to a point in the specified coordinates from the current position. It is represented by a class named QuadraticCurveTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 12467, "s": 12238, "text": "The path element cubic curve is used to draw a cubic curve to a point in the specified coordinates from the current position. It is represented by a class named CubicCurveTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 12674, "s": 12467, "text": "The path element Arc is used to draw an arc to a point in the specified coordinates from the current position. It is represented by a class named ArcTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 12842, "s": 12674, "text": "For all the 2-Dimensional objects, you can set various properties like fill, stroke, StrokeType, etc. The following section discusses various properties of 2D objects." }, { "code": null, "e": 12854, "s": 12842, "text": "Stroke Type" }, { "code": null, "e": 12867, "s": 12854, "text": "Stroke Width" }, { "code": null, "e": 12879, "s": 12867, "text": "Stroke Fill" }, { "code": null, "e": 12886, "s": 12879, "text": "Stroke" }, { "code": null, "e": 12898, "s": 12886, "text": "Stroke Line" }, { "code": null, "e": 12917, "s": 12898, "text": "Stroke Miter Limit" }, { "code": null, "e": 12933, "s": 12917, "text": "Stroke Line Cap" }, { "code": null, "e": 12940, "s": 12933, "text": "Smooth" }, { "code": null, "e": 13046, "s": 12940, "text": "If we add more than one shape to a group, the first shape is overlapped by the second one as shown below." }, { "code": null, "e": 13239, "s": 13046, "text": "In addition to the transformations (rotate, scale, translate, etc.), transitions (animations), you can also perform three operations on 2D objects namely – Union, Subtraction and Intersection." }, { "code": null, "e": 13328, "s": 13239, "text": "This operation takes two or more shapes as inputs and returns the area occupied by them." }, { "code": null, "e": 13426, "s": 13328, "text": "This operation takes two or more shapes as inputs and returns the intersection area between them." } ]
JavaScript String toLowerCase() Method
07 Oct, 2021 Below is the example of the String toLowerCase() Method. Example: JavaScript <script>function func() { var str = 'GEEKSFORGEEKS'; var string = str.toLowerCase(); document.write(string);}func();</script> Output: geeksforgeeks str.toLowerCase() method converts the entire string to lower case. This method does not affect any of the special characters, digits, and the alphabets that are already in the lower case. Syntax: str.toLowerCase() Return value: This method returns a new string in which all the upper case letters are converted to lower case.Examples for the above method are provided below:Example 1: var str = 'It iS a Great Day.'; var string = str.toLowerCase(); print(string); Output: it is a great day. In this example, the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits, and all those characters that are already in the lower case.Example 2: var str = 'It iS a 5r&e@@t Day.'; var string = str.toLowerCase(); print(string); Output: it is a 5r&e@@t day. In this example the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits and all those characters that are already in lower case.Codes for the above method are provided below:Program 1: JavaScript <script>// JavaScript Program to illustrate// toLowerCase() method function func() { // Original string var str = 'It iS a Great Day.'; // Converting to lower case var string = str.toLowerCase(); document.write(string);} func();</script> Output: it is a great day. Program 2: JavaScript <script>// JavaScript Program to illustrate// toLowerCase() method function func() { //Original string var str = 'It iS a 5r&e@@t Day.'; //Converting to lower case var string = str.toLowerCase(); document.write(string);} func();</script> Output: it is a 5r&e@@t day. Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Opera 3 and above Safari 1 and above ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 87, "s": 28, "text": "Below is the example of the String toLowerCase() Method. " }, { "code": null, "e": 98, "s": 87, "text": "Example: " }, { "code": null, "e": 109, "s": 98, "text": "JavaScript" }, { "code": "<script>function func() { var str = 'GEEKSFORGEEKS'; var string = str.toLowerCase(); document.write(string);}func();</script>", "e": 244, "s": 109, "text": null }, { "code": null, "e": 254, "s": 244, "text": "Output: " }, { "code": null, "e": 268, "s": 254, "text": "geeksforgeeks" }, { "code": null, "e": 466, "s": 268, "text": "str.toLowerCase() method converts the entire string to lower case. This method does not affect any of the special characters, digits, and the alphabets that are already in the lower case. Syntax: " }, { "code": null, "e": 484, "s": 466, "text": "str.toLowerCase()" }, { "code": null, "e": 657, "s": 484, "text": "Return value: This method returns a new string in which all the upper case letters are converted to lower case.Examples for the above method are provided below:Example 1: " }, { "code": null, "e": 736, "s": 657, "text": "var str = 'It iS a Great Day.';\nvar string = str.toLowerCase();\nprint(string);" }, { "code": null, "e": 746, "s": 736, "text": "Output: " }, { "code": null, "e": 765, "s": 746, "text": "it is a great day." }, { "code": null, "e": 994, "s": 765, "text": "In this example, the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits, and all those characters that are already in the lower case.Example 2: " }, { "code": null, "e": 1075, "s": 994, "text": "var str = 'It iS a 5r&e@@t Day.';\nvar string = str.toLowerCase();\nprint(string);" }, { "code": null, "e": 1085, "s": 1075, "text": "Output: " }, { "code": null, "e": 1106, "s": 1085, "text": "it is a 5r&e@@t day." }, { "code": null, "e": 1375, "s": 1106, "text": "In this example the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits and all those characters that are already in lower case.Codes for the above method are provided below:Program 1: " }, { "code": null, "e": 1386, "s": 1375, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate// toLowerCase() method function func() { // Original string var str = 'It iS a Great Day.'; // Converting to lower case var string = str.toLowerCase(); document.write(string);} func();</script>", "e": 1648, "s": 1386, "text": null }, { "code": null, "e": 1658, "s": 1648, "text": "Output: " }, { "code": null, "e": 1677, "s": 1658, "text": "it is a great day." }, { "code": null, "e": 1690, "s": 1677, "text": "Program 2: " }, { "code": null, "e": 1701, "s": 1690, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate// toLowerCase() method function func() { //Original string var str = 'It iS a 5r&e@@t Day.'; //Converting to lower case var string = str.toLowerCase(); document.write(string);} func();</script>", "e": 1963, "s": 1701, "text": null }, { "code": null, "e": 1973, "s": 1963, "text": "Output: " }, { "code": null, "e": 1994, "s": 1973, "text": "it is a 5r&e@@t day." }, { "code": null, "e": 2015, "s": 1996, "text": "Supported Browser:" }, { "code": null, "e": 2034, "s": 2015, "text": "Chrome 1 and above" }, { "code": null, "e": 2052, "s": 2034, "text": "Edge 12 and above" }, { "code": null, "e": 2072, "s": 2052, "text": "Firefox 1 and above" }, { "code": null, "e": 2102, "s": 2072, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 2120, "s": 2102, "text": "Opera 3 and above" }, { "code": null, "e": 2139, "s": 2120, "text": "Safari 1 and above" }, { "code": null, "e": 2151, "s": 2139, "text": "ysachin2314" }, { "code": null, "e": 2170, "s": 2151, "text": "JavaScript-Methods" }, { "code": null, "e": 2188, "s": 2170, "text": "javascript-string" }, { "code": null, "e": 2199, "s": 2188, "text": "JavaScript" }, { "code": null, "e": 2216, "s": 2199, "text": "Web Technologies" }, { "code": null, "e": 2314, "s": 2216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2375, "s": 2314, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2447, "s": 2375, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2487, "s": 2447, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2528, "s": 2487, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2580, "s": 2528, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2613, "s": 2580, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2675, "s": 2613, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2736, "s": 2675, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2786, "s": 2736, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Coefficient of Determination-R2 score
16 Jul, 2020 Coefficient of determination also called as R2 score is used to evaluate the performance of a linear regression model. It is the amount of the variation in the output dependent attribute which is predictable from the input independent variable(s). It is used to check how well-observed results are reproduced by the model, depending on the ratio of total deviation of results described by the model. Mathematical Formula: R2= 1- SSres / SStot Where,SSres is the sum of squares of the residual errors.SStot is the total sum of the errors. Interpretation of R2 score:Assume R2 = 0.68It can be referred that 68% of the changeability of the dependent output attribute can be explained by the model while the remaining 32 % of the variability is still unaccounted for.R2 indicates the proportion of data points which lie within the line created by the regression equation. A higher value of R2 is desirable as it indicates better results. ExamplesCase 1 Model gives accurate results R2 = 1- 0/200 = 1 Case 2 Model gives same results always R2 = 1- 200/200 = 0 Case 3 Model gives ambiguous results R2 = 1- 600/200 = -2 We can import r2_score from sklearn.metrics in Python to compute R2 score. Python Implementation:Code 1: Import r2_score from sklearn.metrics from sklearn.metrics import r2_score Code 2: Calculate R2 score for all the above cases. ### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[10, 20, 30]r2 = r2_score(y, f)print('r2 score for perfect model is', r2) Output: r2 score for perfect model is 1.0 ### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[20, 20, 20]r2 = r2_score(y, f)print('r2 score for a model which predicts mean value always is', r2) Output: r2 score for a model which predicts mean value always is 0.0 Code 3: ### Assume y is the actual value and f is the predicted valuesy = [10, 20, 30]f = [30, 10, 20]r2 = r2_score(y, f)print('r2 score for a worse model is', r2) Output: r2 score for a worse model is -2.0 Conclusion: The best possible score is 1 which is obtained when the predicted values are the same as the actual values. R2 score of baseline model is 0. During the worse cases, R2 score can even be negative. Python numpy-Statistics Functions Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI Getting started with Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jul, 2020" }, { "code": null, "e": 453, "s": 53, "text": "Coefficient of determination also called as R2 score is used to evaluate the performance of a linear regression model. It is the amount of the variation in the output dependent attribute which is predictable from the input independent variable(s). It is used to check how well-observed results are reproduced by the model, depending on the ratio of total deviation of results described by the model." }, { "code": null, "e": 475, "s": 453, "text": "Mathematical Formula:" }, { "code": null, "e": 496, "s": 475, "text": "R2= 1- SSres / SStot" }, { "code": null, "e": 591, "s": 496, "text": "Where,SSres is the sum of squares of the residual errors.SStot is the total sum of the errors." }, { "code": null, "e": 987, "s": 591, "text": "Interpretation of R2 score:Assume R2 = 0.68It can be referred that 68% of the changeability of the dependent output attribute can be explained by the model while the remaining 32 % of the variability is still unaccounted for.R2 indicates the proportion of data points which lie within the line created by the regression equation. A higher value of R2 is desirable as it indicates better results." }, { "code": null, "e": 1031, "s": 987, "text": "ExamplesCase 1 Model gives accurate results" }, { "code": null, "e": 1051, "s": 1031, "text": " R2 = 1- 0/200 = 1" }, { "code": null, "e": 1090, "s": 1051, "text": "Case 2 Model gives same results always" }, { "code": null, "e": 1111, "s": 1090, "text": " R2 = 1- 200/200 = 0" }, { "code": null, "e": 1148, "s": 1111, "text": "Case 3 Model gives ambiguous results" }, { "code": null, "e": 1170, "s": 1148, "text": " R2 = 1- 600/200 = -2" }, { "code": null, "e": 1245, "s": 1170, "text": "We can import r2_score from sklearn.metrics in Python to compute R2 score." }, { "code": null, "e": 1312, "s": 1245, "text": "Python Implementation:Code 1: Import r2_score from sklearn.metrics" }, { "code": "from sklearn.metrics import r2_score", "e": 1349, "s": 1312, "text": null }, { "code": null, "e": 1401, "s": 1349, "text": "Code 2: Calculate R2 score for all the above cases." }, { "code": "### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[10, 20, 30]r2 = r2_score(y, f)print('r2 score for perfect model is', r2)", "e": 1555, "s": 1401, "text": null }, { "code": null, "e": 1563, "s": 1555, "text": "Output:" }, { "code": null, "e": 1597, "s": 1563, "text": "r2 score for perfect model is 1.0" }, { "code": "### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[20, 20, 20]r2 = r2_score(y, f)print('r2 score for a model which predicts mean value always is', r2) ", "e": 1780, "s": 1597, "text": null }, { "code": null, "e": 1788, "s": 1780, "text": "Output:" }, { "code": null, "e": 1849, "s": 1788, "text": "r2 score for a model which predicts mean value always is 0.0" }, { "code": null, "e": 1857, "s": 1849, "text": "Code 3:" }, { "code": "### Assume y is the actual value and f is the predicted valuesy = [10, 20, 30]f = [30, 10, 20]r2 = r2_score(y, f)print('r2 score for a worse model is', r2)", "e": 2013, "s": 1857, "text": null }, { "code": null, "e": 2021, "s": 2013, "text": "Output:" }, { "code": null, "e": 2056, "s": 2021, "text": "r2 score for a worse model is -2.0" }, { "code": null, "e": 2068, "s": 2056, "text": "Conclusion:" }, { "code": null, "e": 2176, "s": 2068, "text": "The best possible score is 1 which is obtained when the predicted values are the same as the actual values." }, { "code": null, "e": 2209, "s": 2176, "text": "R2 score of baseline model is 0." }, { "code": null, "e": 2264, "s": 2209, "text": "During the worse cases, R2 score can even be negative." }, { "code": null, "e": 2298, "s": 2264, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 2315, "s": 2298, "text": "Machine Learning" }, { "code": null, "e": 2322, "s": 2315, "text": "Python" }, { "code": null, "e": 2339, "s": 2322, "text": "Machine Learning" }, { "code": null, "e": 2437, "s": 2339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2460, "s": 2437, "text": "Reinforcement learning" }, { "code": null, "e": 2497, "s": 2460, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 2537, "s": 2497, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2561, "s": 2537, "text": "Search Algorithms in AI" }, { "code": null, "e": 2599, "s": 2561, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2627, "s": 2599, "text": "Read JSON file using Python" }, { "code": null, "e": 2677, "s": 2627, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2699, "s": 2677, "text": "Python map() function" }, { "code": null, "e": 2717, "s": 2699, "text": "Python Dictionary" } ]
How to convert functional component to class component in ReactJS ?
24 May, 2021 If we want to convert a function component to a class component then we need to make the following major changes. Change the function to a classAdd the render methodConvert all function to a methodAdd ConstructorReplace hooks with lifecycle methods Change the function to a class Add the render method Convert all function to a method Add Constructor Replace hooks with lifecycle methods Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername 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 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Example: Functional Component Write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React, { useState } from 'react'; function App(props) { const [counter, setCounter] = useState(0); const myFunction = (e) => { alert("The value of counter is " + counter) setCounter(counter + 1); } return ( <div> <p>Hello, {props.name}</p> <button onClick={myFunction}>Click me!</button> </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: Example: Class Component Using the above steps to convert a function component to a class component, we have written the following code in the App.js file. App.js import React, { useState } from 'react'; class App extends React.Component { constructor(props) { super(props) this.state = { counter: 0 } this.myFunction = this.myFunction.bind(this); } myFunction(e) { alert("The value of counter is " + this.state.counter) this.setState({ counter: this.state.counter + 1 }) } render() { return ( <div > <p>Hello From GFG</p> <button onClick={this.myFunction}> Click me! </button> </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: Picked React-Questions ReactJS-Advanced ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2021" }, { "code": null, "e": 142, "s": 28, "text": "If we want to convert a function component to a class component then we need to make the following major changes." }, { "code": null, "e": 277, "s": 142, "text": "Change the function to a classAdd the render methodConvert all function to a methodAdd ConstructorReplace hooks with lifecycle methods" }, { "code": null, "e": 308, "s": 277, "text": "Change the function to a class" }, { "code": null, "e": 330, "s": 308, "text": "Add the render method" }, { "code": null, "e": 363, "s": 330, "text": "Convert all function to a method" }, { "code": null, "e": 379, "s": 363, "text": "Add Constructor" }, { "code": null, "e": 416, "s": 379, "text": "Replace hooks with lifecycle methods" }, { "code": null, "e": 444, "s": 416, "text": "Creating React Application:" }, { "code": null, "e": 539, "s": 444, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 603, "s": 539, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 635, "s": 603, "text": "npx create-react-app foldername" }, { "code": null, "e": 748, "s": 635, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 848, "s": 748, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 862, "s": 848, "text": "cd foldername" }, { "code": null, "e": 914, "s": 862, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 945, "s": 914, "text": "Example: Functional Component " }, { "code": null, "e": 1062, "s": 945, "text": "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": 1069, "s": 1062, "text": "App.js" }, { "code": "import React, { useState } from 'react'; function App(props) { const [counter, setCounter] = useState(0); const myFunction = (e) => { alert(\"The value of counter is \" + counter) setCounter(counter + 1); } return ( <div> <p>Hello, {props.name}</p> <button onClick={myFunction}>Click me!</button> </div> );} export default App;", "e": 1432, "s": 1069, "text": null }, { "code": null, "e": 1545, "s": 1432, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1555, "s": 1545, "text": "npm start" }, { "code": null, "e": 1654, "s": 1555, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 1680, "s": 1654, "text": "Example: Class Component " }, { "code": null, "e": 1812, "s": 1680, "text": "Using the above steps to convert a function component to a class component, we have written the following code in the App.js file. " }, { "code": null, "e": 1819, "s": 1812, "text": "App.js" }, { "code": "import React, { useState } from 'react'; class App extends React.Component { constructor(props) { super(props) this.state = { counter: 0 } this.myFunction = this.myFunction.bind(this); } myFunction(e) { alert(\"The value of counter is \" + this.state.counter) this.setState({ counter: this.state.counter + 1 }) } render() { return ( <div > <p>Hello From GFG</p> <button onClick={this.myFunction}> Click me! </button> </div> ); }} export default App;", "e": 2353, "s": 1819, "text": null }, { "code": null, "e": 2466, "s": 2353, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2476, "s": 2466, "text": "npm start" }, { "code": null, "e": 2575, "s": 2476, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2582, "s": 2575, "text": "Picked" }, { "code": null, "e": 2598, "s": 2582, "text": "React-Questions" }, { "code": null, "e": 2615, "s": 2598, "text": "ReactJS-Advanced" }, { "code": null, "e": 2623, "s": 2615, "text": "ReactJS" }, { "code": null, "e": 2640, "s": 2623, "text": "Web Technologies" }, { "code": null, "e": 2738, "s": 2640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2776, "s": 2738, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2795, "s": 2776, "text": "ReactJS setState()" }, { "code": null, "e": 2863, "s": 2795, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 2898, "s": 2863, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 2919, "s": 2898, "text": "ReactJS defaultProps" }, { "code": null, "e": 2952, "s": 2919, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3014, "s": 2952, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3075, "s": 3014, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3125, "s": 3075, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Remove and print every third from list until it becomes empty
21 Nov, 2018 Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty.Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90]Output : 30 60 90 40 80 50 20 70 10Explanation:The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 60, after that 90 is encountered. Then again the count starts from 10 for the next third element which is 40. Proceeding in the same manner as we did before we get next third element after 40 is 80. This process is repeated until the list becomes empty. Input : [1, 2, 3, 4]Output : 3 2 4 1Explanation:The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed. Approach The index of the list starts from 0 and the first third element will be at position 2. Traverse till the list becomes empty and each time find the index of the next third element and print its corresponding value. After printing reduce the length of the list. # Python program to remove to every third# element until list becomes emptydef removeThirdNumber(int_list): # list starts with # 0 index pos = 3 - 1 index = 0 len_list = (len(int_list)) # breaks out once the # list becomes empty while len_list > 0: index = (pos + index) % len_list # removes and prints the required # element print(int_list.pop(index)) len_list -= 1 # Driver codenums = [1, 2, 3, 4] removeThirdNumber(nums) Output: 3 2 4 1 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Nov, 2018" }, { "code": null, "e": 191, "s": 52, "text": "Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty.Examples:" }, { "code": null, "e": 651, "s": 191, "text": "Input : [10, 20, 30, 40, 50, 60, 70, 80, 90]Output : 30 60 90 40 80 50 20 70 10Explanation:The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 60, after that 90 is encountered. Then again the count starts from 10 for the next third element which is 40. Proceeding in the same manner as we did before we get next third element after 40 is 80. This process is repeated until the list becomes empty." }, { "code": null, "e": 937, "s": 651, "text": "Input : [1, 2, 3, 4]Output : 3 2 4 1Explanation:The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed." }, { "code": null, "e": 1206, "s": 937, "text": "Approach The index of the list starts from 0 and the first third element will be at position 2. Traverse till the list becomes empty and each time find the index of the next third element and print its corresponding value. After printing reduce the length of the list." }, { "code": "# Python program to remove to every third# element until list becomes emptydef removeThirdNumber(int_list): # list starts with # 0 index pos = 3 - 1 index = 0 len_list = (len(int_list)) # breaks out once the # list becomes empty while len_list > 0: index = (pos + index) % len_list # removes and prints the required # element print(int_list.pop(index)) len_list -= 1 # Driver codenums = [1, 2, 3, 4] removeThirdNumber(nums)", "e": 1720, "s": 1206, "text": null }, { "code": null, "e": 1728, "s": 1720, "text": "Output:" }, { "code": null, "e": 1737, "s": 1728, "text": "3\n2\n4\n1\n" }, { "code": null, "e": 1758, "s": 1737, "text": "Python list-programs" }, { "code": null, "e": 1770, "s": 1758, "text": "python-list" }, { "code": null, "e": 1777, "s": 1770, "text": "Python" }, { "code": null, "e": 1789, "s": 1777, "text": "python-list" } ]
XQuery - Quick Guide
XQuery is a functional language that is used to retrieve information stored in XML format. XQuery can be used on XML documents, relational databases containing data in XML formats, or XML Databases. XQuery 3.0 is a W3C recommendation from April 8, 2014. The definition of XQuery as given by its official documentation is as follows − Functional Language − XQuery is a language to retrieve/querying XML based data. Functional Language − XQuery is a language to retrieve/querying XML based data. Analogous to SQL − XQuery is to XML what SQL is to databases. Analogous to SQL − XQuery is to XML what SQL is to databases. XPath based − XQuery uses XPath expressions to navigate through XML documents. XPath based − XQuery uses XPath expressions to navigate through XML documents. Universally accepted − XQuery is supported by all major databases. Universally accepted − XQuery is supported by all major databases. W3C Standard − XQuery is a W3C standard. W3C Standard − XQuery is a W3C standard. Using XQuery, both hierarchical and tabular data can be retrieved. Using XQuery, both hierarchical and tabular data can be retrieved. XQuery can be used to query tree and graphical structures. XQuery can be used to query tree and graphical structures. XQuery can be directly used to query webpages. XQuery can be directly used to query webpages. XQuery can be directly used to build webpages. XQuery can be directly used to build webpages. XQuery can be used to transform xml documents. XQuery can be used to transform xml documents. XQuery is ideal for XML-based databases and object-based databases. Object databases are much more flexible and powerful than purely tabular databases. XQuery is ideal for XML-based databases and object-based databases. Object databases are much more flexible and powerful than purely tabular databases. This chapter elaborates how to set up XQuery library in a local development environment. We are using an open source standalone XQuery processor Saxon Home Edition (Saxon-HE) which is widely used. This processor supports XSLT 2.0, XQuery 3.0, and XPath 3.0 and is highly optimized for performance. Saxon XQuery processor can be used without having any XML database. We'll use a simple XML document as our database in our examples. In order to use Saxon XQuery processor, you should have saxon9he.jar, saxon9-test.jar, saxon9-unpack, saxon9-xqj.jar in your application's classpath. These jar files are available in the download file SaxonHE9-6-0-1J.zip Download SaxonHE9-6-0-1J.zip. We'll use the Java-based Saxon XQuery processor to test books.xqy, a file containing XQuery expression against our sample XML document, i.e., books.xml. In this example, we'll see how to write and process a query to get the title elements of the books whose price is greater than 30. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>40.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> for $x in doc("books.xml")/books/book where $x/price>30 return $x/title package com.tutorialspoint.xquery; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javax.xml.xquery.XQConnection; import javax.xml.xquery.XQDataSource; import javax.xml.xquery.XQException; import javax.xml.xquery.XQPreparedExpression; import javax.xml.xquery.XQResultSequence; import com.saxonica.xqj.SaxonXQDataSource; public class XQueryTester { public static void main(String[] args){ try { execute(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XQException e) { e.printStackTrace(); } } private static void execute() throws FileNotFoundException, XQException{ InputStream inputStream = new FileInputStream(new File("books.xqy")); XQDataSource ds = new SaxonXQDataSource(); XQConnection conn = ds.getConnection(); XQPreparedExpression exp = conn.prepareExpression(inputStream); XQResultSequence result = exp.executeQuery(); while (result.next()) { System.out.println(result.getItemAsString(null)); } } } Step 1 − Copy XQueryTester.java to any location, say, E: > java Step 1 − Copy XQueryTester.java to any location, say, E: > java Step 2 − Copy books.xml to the same location, E: > java Step 2 − Copy books.xml to the same location, E: > java Step 3 − Copy books.xqy to the same location, E: > java Step 3 − Copy books.xqy to the same location, E: > java Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial E:\java\javac XQueryTester.java Step 5 − Execute XQueryTester Step 5 − Execute XQueryTester E:\java\java XQueryTester You'll get the following result − <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> books.xml represents the sample data. books.xml represents the sample data. books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter. books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter. XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed. XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed. Following is a sample XML document containing the records of a bookstore of various books. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>70.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> Following is a sample Xquery document containing the query expression to be executed on the above XML document. The purpose is to get the title elements of those XML nodes where the price is greater than 30. for $x in doc("books.xml")/books/book where $x/price>30 return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. Let us understand each piece of the above XQuery expression. doc("books.xml") doc() is one of the XQuery functions that is used to locate the XML source. Here we've passed "books.xml". Considering the relative path, books.xml should lie in the same path where books.xqy is present. doc("books.xml")/books/book XQuery uses XPath expressions heavily to locate the required portion of XML on which search is to be made. Here we've chosen all the book nodes available under books node. for $x in doc("books.xml")/books/book XQuery treats xml data as objects. In the above example, $x represents the selected node, while the for loop iterates over the collection of nodes. where $x/price>30 As $x represents the selected node, "/" is used to get the value of the required element; "where" clause is used to put a condition on the search results. return $x/title As $x represents the selected node, "/" is used to get the value of the required element, price, title; "return" clause is used to return the elements from the search results. FLWOR is an acronym that stands for "For, Let, Where, Order by, Return". The following list shows what they account for in a FLWOR expression − F - For - Selects a collection of all nodes. F - For - Selects a collection of all nodes. L - Let - Puts the result in an XQuery variable. L - Let - Puts the result in an XQuery variable. W - Where - Selects the nodes specified by the condition. W - Where - Selects the nodes specified by the condition. O - Order by - Orders the nodes specified as per criteria. O - Order by - Orders the nodes specified as per criteria. R - Return - Returns the final result. R - Return - Returns the final result. Following is a sample XML document that contains information on a collection of books. We will use a FLWOR expression to retrieve the titles of those books with a price greater than 30. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>70.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> The following Xquery document contains the query expression to be executed on the above XML document. let $books := (doc("books.xml")/books/book) return <results> { for $x in $books where $x/price>30 order by $x/price return $x/title } </results> <title lang="en">Learn XQuery in 24 hours</title> <title lang="en">Learn .Net in 24 hours</title> To verify the result, replace the contents of books.xqy (given in theEnvironment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. XQuery can also be easily used to transform an XML document into an HTML page. Take a look at the following example to understand how XQuery does it. We will use the same books.xml file. The following example uses XQuery extract data from books.xml and create an HTML table containing the titles of all the books along with their respective prices. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>70.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> Given below is the Xquery expression that is to be executed on the above XML document. let $books := (doc("books.xml")/books/book) return <table><tr><th>Title</th><th>Price</th></tr> { for $x in $books order by $x/price return <tr><td>{data($x/title)}</td><td>{data($x/price)}</td></tr> } </table> </results> <table> <tr> <th>Title</th> <th>Price</th> </tr> <tr> <td>Learn XPath in 24 hours</td> <td>16.50</td> </tr> <tr> <td>Learn Java in 24 Hours</td> <td>30.00</td> </tr> <tr> <td>Learn XQuery in 24 hours</td> <td>50.00</td> </tr> <tr> <td>Learn .Net in 24 hours</td> <td>70.50</td> </tr> </table> To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. Here we've used the following XQuery expressions − data() function to evaluate the value of the title element, and data() function to evaluate the value of the title element, and {} operator to tell the XQuery processor to consider data() as a function. If {} operator is not used, then data() will be treated as normal text. {} operator to tell the XQuery processor to consider data() as a function. If {} operator is not used, then data() will be treated as normal text. XQuery is XPath compliant. It uses XPath expressions to restrict the search results on XML collections. For more details on how to use XPath, see our XPath Tutorial. Recall the following XPath expression which we have used earlier to get the list of books. doc("books.xml")/books/book We will use the books.xml file and apply XQuery to it. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>40.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> We have given here three versions of an XQuery statement that fulfil the same objective of displaying the book titles having a price value greater than 30. (: read the entire xml document :) let $books := doc("books.xml") for $x in $books/books/book where $x/price > 30 return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> (: read all books :) let $books := doc("books.xml")/books/book for $x in $books where $x/price > 30 return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> (: read books with price > 30 :) let $books := doc("books.xml")/books/book[price > 30] for $x in $books return $x/title <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. Sequences represent an ordered collection of items where items can be of similar or of different types. Sequences are created using parenthesis with strings inside quotes or double quotes and numbers as such. XML elements can also be used as the items of a sequence. let $items := ('orange', <apple/>, <fruit type="juicy"/>, <vehicle type="car">sentro</vehicle>, 1,2,3,'a','b',"abc") let $count := count($items) return <result> <count>{$count}</count> <items> { for $item in $items return <item>{$item}</item> } </items> </result> <result> <count>10</count> <items> <item>orange</item> <item> <apple/> </item> <item> <fruit type="juicy"/> </item> <item> <vehicle type="car">Sentro</vehicle> </item> <item>1</item> <item>2</item> <item>3</item> <item>a</item> <item>b</item> <item>abc</item> </items> </result> Items of a sequence can be iterated one by one, using index or by value. The above example iterated the items of a sequence one by one. Let's see the other two ways in action. let $items := (1,2,3,4,5,6) let $count := count($items) return <result> <count>{$count}</count> <items> { for $item in $items[2] return <item>{$item}</item> } </items> </result> <result> <count>6</count> <items> <item>2</item> </items> </result> let $items := (1,2,3,4,5,6) let $count := count($items) return <result> <count>{$count}</count> <items> { for $item in $items[. = (1,2,3)] return <item>{$item}</item> } </items> </result> <result> <count>6</count> <items> <item>1</item> <item>2</item> <item>3</item> </items> </result> The following table lists the commonly used sequence functions provided by XQuery. count($seq as item()*) Counts the items in a sequence. sum($seq as item()*) Returns the sum of the items in a sequence. avg($seq as item()*) Returns the average of the items in a sequence. min($seq as item()*) Returns the minimum valued item in a sequence. max($seq as item()*) Returns the maximum valued item in a sequence. distinct-values($seq as item()*) Returns select distinct items from a sequence. subsequence($seq as item()*, $startingLoc as xs:double, $length as xs:double) Returns a subset of provided sequence. insert-before($seq as item()*, $position as xs:integer, $inserts as item()*) Inserts an item in a sequence. remove($seq as item()*, $position as xs:integer) Removes an item from a sequence. reverse($seq as item()*) Returns the reversed sequence. index-of($seq as anyAtomicType()*, $target as anyAtomicType()) Returns indexes as integers to indicate availability of an item within a sequence. last() Returns the last element of a sequence when used in predicate expression. position() Used in FLOWR expressions to get the position of an item in a sequence. The following table lists the commonly used string manipulation functions provided by XQuery. string-length($string as xs:string) as xs:integer Returns the length of the string. concat($input as xs:anyAtomicType?) as xs:string Returns the concatenated string as output. string-join($sequence as xs:string*, $delimiter as xs:string) as xs:string Returns the combination of items in a sequence separated by a delimiter. The following table lists the commonly used date functions provided by XQuery. current-date() Returns the current date. current-time() Returns the current time. current-dateTime() Returns both the current date and the current time. Following is the list of commonly used regular expression functions provided by XQuery matches($input, $regex) Returns true if the input matches with the provided regular expression. replace($input, $regex, $string) Replaces the matched input string with given string. tokenize($input, $regex) Returns a sequence of items matching the regular expression. XQuery provides a very useful if-then-else construct to check the validity of the input values passed. Given below is the syntax of the if-then-else construct. if (condition) then ... else ... We will use the following books.xml file and apply to it XQuery expression containing an if-then-else construct to retrieve the titles of those books with a price value that is greater than 30. <?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java in 24 Hours</title> <author>Robert</author> <year>2005</year> <price>30.00</price> </book> <book category="DOTNET"> <title lang="en">Learn .Net in 24 hours</title> <author>Peter</author> <year>2011</year> <price>40.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 24 hours</title> <author>Robert</author> <author>Peter</author> <year>2013</year> <price>50.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 24 hours</title> <author>Jay Ban</author> <year>2010</year> <price>16.50</price> </book> </books> The following XQuery expression is to be applied on the above XML document. <result> { if(not(doc("books.xml"))) then ( <error> <message>books.xml does not exist</message> </error> ) else ( for $x in doc("books.xml")/books/book where $x/price>30 return $x/title ) } </result> <result> <title lang="en">Learn .Net in 24 hours</title> <title lang="en">Learn XQuery in 24 hours</title> </result> To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program. XQuery provides the capability to write custom functions. Listed below are the guidelines to create a custom function. Use the keyword declare function to define a function. Use the keyword declare function to define a function. Use the data types defined in the current XML Schema Use the data types defined in the current XML Schema Enclose the body of function inside curly braces. Enclose the body of function inside curly braces. Prefix the name of the function with an XML namespace. Prefix the name of the function with an XML namespace. The following syntax is used while creating a custom function. declare function prefix:function_name($parameter as datatype?...) as returnDatatype? { function body... }; The following example shows how to create a user-defined function in XQuery. declare function local:discount($price as xs:decimal?,$percentDiscount as xs:decimal?) as xs:decimal? { let $discount := $price - ($price * $percentDiscount div 100) return $discount }; let $originalPrice := 100 let $discountAvailed := 10 return ( local:discount($originalPrice, $discountAvailed)) 90 To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program.
[ { "code": null, "e": 2260, "s": 2006, "text": "XQuery is a functional language that is used to retrieve information stored in XML format. XQuery can be used on XML documents, relational databases containing data in XML formats, or XML Databases. XQuery 3.0 is a W3C recommendation from April 8, 2014." }, { "code": null, "e": 2340, "s": 2260, "text": "The definition of XQuery as given by its official documentation is as follows −" }, { "code": null, "e": 2420, "s": 2340, "text": "Functional Language − XQuery is a language to retrieve/querying XML based data." }, { "code": null, "e": 2500, "s": 2420, "text": "Functional Language − XQuery is a language to retrieve/querying XML based data." }, { "code": null, "e": 2562, "s": 2500, "text": "Analogous to SQL − XQuery is to XML what SQL is to databases." }, { "code": null, "e": 2624, "s": 2562, "text": "Analogous to SQL − XQuery is to XML what SQL is to databases." }, { "code": null, "e": 2703, "s": 2624, "text": "XPath based − XQuery uses XPath expressions to navigate through XML documents." }, { "code": null, "e": 2782, "s": 2703, "text": "XPath based − XQuery uses XPath expressions to navigate through XML documents." }, { "code": null, "e": 2849, "s": 2782, "text": "Universally accepted − XQuery is supported by all major databases." }, { "code": null, "e": 2916, "s": 2849, "text": "Universally accepted − XQuery is supported by all major databases." }, { "code": null, "e": 2957, "s": 2916, "text": "W3C Standard − XQuery is a W3C standard." }, { "code": null, "e": 2998, "s": 2957, "text": "W3C Standard − XQuery is a W3C standard." }, { "code": null, "e": 3065, "s": 2998, "text": "Using XQuery, both hierarchical and tabular data can be retrieved." }, { "code": null, "e": 3132, "s": 3065, "text": "Using XQuery, both hierarchical and tabular data can be retrieved." }, { "code": null, "e": 3191, "s": 3132, "text": "XQuery can be used to query tree and graphical structures." }, { "code": null, "e": 3250, "s": 3191, "text": "XQuery can be used to query tree and graphical structures." }, { "code": null, "e": 3297, "s": 3250, "text": "XQuery can be directly used to query webpages." }, { "code": null, "e": 3344, "s": 3297, "text": "XQuery can be directly used to query webpages." }, { "code": null, "e": 3391, "s": 3344, "text": "XQuery can be directly used to build webpages." }, { "code": null, "e": 3438, "s": 3391, "text": "XQuery can be directly used to build webpages." }, { "code": null, "e": 3485, "s": 3438, "text": "XQuery can be used to transform xml documents." }, { "code": null, "e": 3532, "s": 3485, "text": "XQuery can be used to transform xml documents." }, { "code": null, "e": 3684, "s": 3532, "text": "XQuery is ideal for XML-based databases and object-based databases. Object databases are much more flexible and powerful than purely tabular databases." }, { "code": null, "e": 3836, "s": 3684, "text": "XQuery is ideal for XML-based databases and object-based databases. Object databases are much more flexible and powerful than purely tabular databases." }, { "code": null, "e": 3925, "s": 3836, "text": "This chapter elaborates how to set up XQuery library in a local development environment." }, { "code": null, "e": 4267, "s": 3925, "text": "We are using an open source standalone XQuery processor Saxon Home Edition (Saxon-HE) which is widely used. This processor supports XSLT 2.0, XQuery 3.0, and XPath 3.0 and is highly optimized for performance. Saxon XQuery processor can be used without having any XML database. We'll use a simple XML document as our database in our examples." }, { "code": null, "e": 4518, "s": 4267, "text": "In order to use Saxon XQuery processor, you should have saxon9he.jar, saxon9-test.jar, saxon9-unpack, saxon9-xqj.jar in your application's classpath. These jar files are available in the download file SaxonHE9-6-0-1J.zip Download SaxonHE9-6-0-1J.zip." }, { "code": null, "e": 4671, "s": 4518, "text": "We'll use the Java-based Saxon XQuery processor to test books.xqy, a file containing XQuery expression against our sample XML document, i.e., books.xml." }, { "code": null, "e": 4802, "s": 4671, "text": "In this example, we'll see how to write and process a query to get the title elements of the books whose price is greater than 30." }, { "code": null, "e": 5599, "s": 4802, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>40.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 5671, "s": 5599, "text": "for $x in doc(\"books.xml\")/books/book\nwhere $x/price>30\nreturn $x/title" }, { "code": null, "e": 6831, "s": 5671, "text": "package com.tutorialspoint.xquery;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\n\nimport javax.xml.xquery.XQConnection;\nimport javax.xml.xquery.XQDataSource;\nimport javax.xml.xquery.XQException;\nimport javax.xml.xquery.XQPreparedExpression;\nimport javax.xml.xquery.XQResultSequence;\n\nimport com.saxonica.xqj.SaxonXQDataSource;\n\npublic class XQueryTester {\n public static void main(String[] args){\n try {\n execute();\n }\n \n catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n \n catch (XQException e) {\n e.printStackTrace();\n }\n }\n\n private static void execute() throws FileNotFoundException, XQException{\n InputStream inputStream = new FileInputStream(new File(\"books.xqy\"));\n XQDataSource ds = new SaxonXQDataSource();\n XQConnection conn = ds.getConnection();\n XQPreparedExpression exp = conn.prepareExpression(inputStream);\n XQResultSequence result = exp.executeQuery();\n \n while (result.next()) {\n System.out.println(result.getItemAsString(null));\n }\n }\t\n}" }, { "code": null, "e": 6897, "s": 6831, "text": "Step 1 − Copy XQueryTester.java to any location, say, E: > java " }, { "code": null, "e": 6963, "s": 6897, "text": "Step 1 − Copy XQueryTester.java to any location, say, E: > java " }, { "code": null, "e": 7021, "s": 6963, "text": "Step 2 − Copy books.xml to the same location, E: > java " }, { "code": null, "e": 7079, "s": 7021, "text": "Step 2 − Copy books.xml to the same location, E: > java " }, { "code": null, "e": 7137, "s": 7079, "text": "Step 3 − Copy books.xqy to the same location, E: > java " }, { "code": null, "e": 7195, "s": 7137, "text": "Step 3 − Copy books.xqy to the same location, E: > java " }, { "code": null, "e": 7393, "s": 7195, "text": "Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial\n" }, { "code": null, "e": 7590, "s": 7393, "text": "Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial" }, { "code": null, "e": 7623, "s": 7590, "text": "E:\\java\\javac XQueryTester.java\n" }, { "code": null, "e": 7654, "s": 7623, "text": "Step 5 − Execute XQueryTester\n" }, { "code": null, "e": 7684, "s": 7654, "text": "Step 5 − Execute XQueryTester" }, { "code": null, "e": 7711, "s": 7684, "text": "E:\\java\\java XQueryTester\n" }, { "code": null, "e": 7745, "s": 7711, "text": "You'll get the following result −" }, { "code": null, "e": 7844, "s": 7745, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 7882, "s": 7844, "text": "books.xml represents the sample data." }, { "code": null, "e": 7920, "s": 7882, "text": "books.xml represents the sample data." }, { "code": null, "e": 8061, "s": 7920, "text": "books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter." }, { "code": null, "e": 8202, "s": 8061, "text": "books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter." }, { "code": null, "e": 8378, "s": 8202, "text": "XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed." }, { "code": null, "e": 8554, "s": 8378, "text": "XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed." }, { "code": null, "e": 8645, "s": 8554, "text": "Following is a sample XML document containing the records of a bookstore of various books." }, { "code": null, "e": 9442, "s": 8645, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>70.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 9650, "s": 9442, "text": "Following is a sample Xquery document containing the query expression to be executed on the above XML document. The purpose is to get the title elements of those XML nodes where the price is greater than 30." }, { "code": null, "e": 9722, "s": 9650, "text": "for $x in doc(\"books.xml\")/books/book\nwhere $x/price>30\nreturn $x/title" }, { "code": null, "e": 9821, "s": 9722, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 9994, "s": 9821, "text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 10055, "s": 9994, "text": "Let us understand each piece of the above XQuery expression." }, { "code": null, "e": 10072, "s": 10055, "text": "doc(\"books.xml\")" }, { "code": null, "e": 10276, "s": 10072, "text": "doc() is one of the XQuery functions that is used to locate the XML source. Here we've passed \"books.xml\". Considering the relative path, books.xml should lie in the same path where books.xqy is present." }, { "code": null, "e": 10304, "s": 10276, "text": "doc(\"books.xml\")/books/book" }, { "code": null, "e": 10476, "s": 10304, "text": "XQuery uses XPath expressions heavily to locate the required portion of XML on which search is to be made. Here we've chosen all the book nodes available under books node." }, { "code": null, "e": 10514, "s": 10476, "text": "for $x in doc(\"books.xml\")/books/book" }, { "code": null, "e": 10662, "s": 10514, "text": "XQuery treats xml data as objects. In the above example, $x represents the selected node, while the for loop iterates over the collection of nodes." }, { "code": null, "e": 10680, "s": 10662, "text": "where $x/price>30" }, { "code": null, "e": 10835, "s": 10680, "text": "As $x represents the selected node, \"/\" is used to get the value of the required element; \"where\" clause is used to put a condition on the search results." }, { "code": null, "e": 10852, "s": 10835, "text": "return $x/title\n" }, { "code": null, "e": 11028, "s": 10852, "text": "As $x represents the selected node, \"/\" is used to get the value of the required element, price, title; \"return\" clause is used to return the elements from the search results." }, { "code": null, "e": 11172, "s": 11028, "text": "FLWOR is an acronym that stands for \"For, Let, Where, Order by, Return\". The following list shows what they account for in a FLWOR expression −" }, { "code": null, "e": 11217, "s": 11172, "text": "F - For - Selects a collection of all nodes." }, { "code": null, "e": 11262, "s": 11217, "text": "F - For - Selects a collection of all nodes." }, { "code": null, "e": 11311, "s": 11262, "text": "L - Let - Puts the result in an XQuery variable." }, { "code": null, "e": 11360, "s": 11311, "text": "L - Let - Puts the result in an XQuery variable." }, { "code": null, "e": 11418, "s": 11360, "text": "W - Where - Selects the nodes specified by the condition." }, { "code": null, "e": 11476, "s": 11418, "text": "W - Where - Selects the nodes specified by the condition." }, { "code": null, "e": 11535, "s": 11476, "text": "O - Order by - Orders the nodes specified as per criteria." }, { "code": null, "e": 11594, "s": 11535, "text": "O - Order by - Orders the nodes specified as per criteria." }, { "code": null, "e": 11633, "s": 11594, "text": "R - Return - Returns the final result." }, { "code": null, "e": 11672, "s": 11633, "text": "R - Return - Returns the final result." }, { "code": null, "e": 11858, "s": 11672, "text": "Following is a sample XML document that contains information on a collection of books. We will use a FLWOR expression to retrieve the titles of those books with a price greater than 30." }, { "code": null, "e": 12655, "s": 11858, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>70.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 12757, "s": 12655, "text": "The following Xquery document contains the query expression to be executed on the above XML document." }, { "code": null, "e": 12914, "s": 12757, "text": "let $books := (doc(\"books.xml\")/books/book)\nreturn <results>\n{\n for $x in $books\n where $x/price>30\n order by $x/price\n return $x/title\n}\n</results>" }, { "code": null, "e": 13013, "s": 12914, "text": "<title lang=\"en\">Learn XQuery in 24 hours</title>\n<title lang=\"en\">Learn .Net in 24 hours</title>\n" }, { "code": null, "e": 13185, "s": 13013, "text": "To verify the result, replace the contents of books.xqy (given in theEnvironment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 13335, "s": 13185, "text": "XQuery can also be easily used to transform an XML document into an HTML page. Take a look at the following example to understand how XQuery does it." }, { "code": null, "e": 13534, "s": 13335, "text": "We will use the same books.xml file. The following example uses XQuery extract data from books.xml and create an HTML table containing the titles of all the books along with their respective prices." }, { "code": null, "e": 14331, "s": 13534, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>70.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 14418, "s": 14331, "text": "Given below is the Xquery expression that is to be executed on the above XML document." }, { "code": null, "e": 14652, "s": 14418, "text": "let $books := (doc(\"books.xml\")/books/book)\nreturn <table><tr><th>Title</th><th>Price</th></tr>\n{\n for $x in $books \n order by $x/price\n return <tr><td>{data($x/title)}</td><td>{data($x/price)}</td></tr>\n}\n</table>\n</results>" }, { "code": null, "e": 15042, "s": 14652, "text": "<table>\n <tr>\n <th>Title</th>\n <th>Price</th>\n </tr>\n <tr>\n <td>Learn XPath in 24 hours</td>\n <td>16.50</td>\n </tr> \n <tr>\n <td>Learn Java in 24 Hours</td>\n <td>30.00</td>\n </tr>\n <tr>\n <td>Learn XQuery in 24 hours</td>\n <td>50.00</td>\n </tr> \n <tr>\n <td>Learn .Net in 24 hours</td>\n <td>70.50</td>\n </tr>\n</table>\n" }, { "code": null, "e": 15215, "s": 15042, "text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 15266, "s": 15215, "text": "Here we've used the following XQuery expressions −" }, { "code": null, "e": 15330, "s": 15266, "text": "data() function to evaluate the value of the title element, and" }, { "code": null, "e": 15394, "s": 15330, "text": "data() function to evaluate the value of the title element, and" }, { "code": null, "e": 15541, "s": 15394, "text": "{} operator to tell the XQuery processor to consider data() as a function. If {} operator is not used, then data() will be treated as normal text." }, { "code": null, "e": 15688, "s": 15541, "text": "{} operator to tell the XQuery processor to consider data() as a function. If {} operator is not used, then data() will be treated as normal text." }, { "code": null, "e": 15854, "s": 15688, "text": "XQuery is XPath compliant. It uses XPath expressions to restrict the search results on XML collections. For more details on how to use XPath, see our XPath Tutorial." }, { "code": null, "e": 15945, "s": 15854, "text": "Recall the following XPath expression which we have used earlier to get the list of books." }, { "code": null, "e": 15973, "s": 15945, "text": "doc(\"books.xml\")/books/book" }, { "code": null, "e": 16028, "s": 15973, "text": "We will use the books.xml file and apply XQuery to it." }, { "code": null, "e": 16825, "s": 16028, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>40.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>" }, { "code": null, "e": 16981, "s": 16825, "text": "We have given here three versions of an XQuery statement that fulfil the same objective of displaying the book titles having a price value greater than 30." }, { "code": null, "e": 17112, "s": 16981, "text": "(: read the entire xml document :)\nlet $books := doc(\"books.xml\")\n\nfor $x in $books/books/book\nwhere $x/price > 30\nreturn $x/title" }, { "code": null, "e": 17210, "s": 17112, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>" }, { "code": null, "e": 17327, "s": 17210, "text": "(: read all books :)\nlet $books := doc(\"books.xml\")/books/book\n\nfor $x in $books\nwhere $x/price > 30\nreturn $x/title" }, { "code": null, "e": 17426, "s": 17327, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 17547, "s": 17426, "text": "(: read books with price > 30 :)\nlet $books := doc(\"books.xml\")/books/book[price > 30]\n\nfor $x in $books\nreturn $x/title" }, { "code": null, "e": 17646, "s": 17547, "text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n" }, { "code": null, "e": 17819, "s": 17646, "text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 17923, "s": 17819, "text": "Sequences represent an ordered collection of items where items can be of similar or of different types." }, { "code": null, "e": 18086, "s": 17923, "text": "Sequences are created using parenthesis with strings inside quotes or double quotes and numbers as such. XML elements can also be used as the items of a sequence." }, { "code": null, "e": 18394, "s": 18086, "text": "let $items := ('orange', <apple/>, <fruit type=\"juicy\"/>, <vehicle type=\"car\">sentro</vehicle>, 1,2,3,'a','b',\"abc\")\nlet $count := count($items)\nreturn\n<result>\n <count>{$count}</count>\n \n <items>\n {\n\t for $item in $items\n return <item>{$item}</item>\n }\n </items>\n \n</result>" }, { "code": null, "e": 18788, "s": 18394, "text": "<result>\n <count>10</count>\n <items>\n <item>orange</item>\n <item>\n <apple/>\n </item>\n <item>\n <fruit type=\"juicy\"/>\n </item>\n <item>\n <vehicle type=\"car\">Sentro</vehicle>\n </item>\n <item>1</item>\n <item>2</item>\n <item>3</item>\n <item>a</item>\n <item>b</item>\n <item>abc</item>\n </items>\n</result>\n" }, { "code": null, "e": 18964, "s": 18788, "text": "Items of a sequence can be iterated one by one, using index or by value. The above example iterated the items of a sequence one by one. Let's see the other two ways in action." }, { "code": null, "e": 19210, "s": 18964, "text": "let $items := (1,2,3,4,5,6)\nlet $count := count($items)\nreturn\n <result>\n <count>{$count}</count>\n \n <items>\n {\n for $item in $items[2]\n return <item>{$item}</item>\n }\n </items>\n \n </result>" }, { "code": null, "e": 19294, "s": 19210, "text": "<result>\n <count>6</count>\n <items>\n <item>2</item>\n </items>\n</result>\n" }, { "code": null, "e": 19550, "s": 19294, "text": "let $items := (1,2,3,4,5,6)\nlet $count := count($items)\nreturn\n <result>\n <count>{$count}</count>\n \n <items>\n {\n for $item in $items[. = (1,2,3)]\n return <item>{$item}</item>\n }\n </items>\n \n </result>" }, { "code": null, "e": 19676, "s": 19550, "text": "<result>\n <count>6</count>\n <items>\n <item>1</item>\n <item>2</item>\n <item>3</item>\n </items>\n</result>\n" }, { "code": null, "e": 19759, "s": 19676, "text": "The following table lists the commonly used sequence functions provided by XQuery." }, { "code": null, "e": 19782, "s": 19759, "text": "count($seq as item()*)" }, { "code": null, "e": 19814, "s": 19782, "text": "Counts the items in a sequence." }, { "code": null, "e": 19835, "s": 19814, "text": "sum($seq as item()*)" }, { "code": null, "e": 19879, "s": 19835, "text": "Returns the sum of the items in a sequence." }, { "code": null, "e": 19900, "s": 19879, "text": "avg($seq as item()*)" }, { "code": null, "e": 19948, "s": 19900, "text": "Returns the average of the items in a sequence." }, { "code": null, "e": 19969, "s": 19948, "text": "min($seq as item()*)" }, { "code": null, "e": 20016, "s": 19969, "text": "Returns the minimum valued item in a sequence." }, { "code": null, "e": 20037, "s": 20016, "text": "max($seq as item()*)" }, { "code": null, "e": 20084, "s": 20037, "text": "Returns the maximum valued item in a sequence." }, { "code": null, "e": 20117, "s": 20084, "text": "distinct-values($seq as item()*)" }, { "code": null, "e": 20164, "s": 20117, "text": "Returns select distinct items from a sequence." }, { "code": null, "e": 20242, "s": 20164, "text": "subsequence($seq as item()*, $startingLoc as xs:double, $length as xs:double)" }, { "code": null, "e": 20281, "s": 20242, "text": "Returns a subset of provided sequence." }, { "code": null, "e": 20358, "s": 20281, "text": "insert-before($seq as item()*, $position as xs:integer, $inserts as item()*)" }, { "code": null, "e": 20389, "s": 20358, "text": "Inserts an item in a sequence." }, { "code": null, "e": 20438, "s": 20389, "text": "remove($seq as item()*, $position as xs:integer)" }, { "code": null, "e": 20471, "s": 20438, "text": "Removes an item from a sequence." }, { "code": null, "e": 20496, "s": 20471, "text": "reverse($seq as item()*)" }, { "code": null, "e": 20527, "s": 20496, "text": "Returns the reversed sequence." }, { "code": null, "e": 20590, "s": 20527, "text": "index-of($seq as anyAtomicType()*, $target as anyAtomicType())" }, { "code": null, "e": 20673, "s": 20590, "text": "Returns indexes as integers to indicate availability of an item within a sequence." }, { "code": null, "e": 20680, "s": 20673, "text": "last()" }, { "code": null, "e": 20754, "s": 20680, "text": "Returns the last element of a sequence when used in predicate expression." }, { "code": null, "e": 20765, "s": 20754, "text": "position()" }, { "code": null, "e": 20837, "s": 20765, "text": "Used in FLOWR expressions to get the position of an item in a sequence." }, { "code": null, "e": 20931, "s": 20837, "text": "The following table lists the commonly used string manipulation functions provided by XQuery." }, { "code": null, "e": 20981, "s": 20931, "text": "string-length($string as xs:string) as xs:integer" }, { "code": null, "e": 21015, "s": 20981, "text": "Returns the length of the string." }, { "code": null, "e": 21064, "s": 21015, "text": "concat($input as xs:anyAtomicType?) as xs:string" }, { "code": null, "e": 21107, "s": 21064, "text": "Returns the concatenated string as output." }, { "code": null, "e": 21182, "s": 21107, "text": "string-join($sequence as xs:string*, $delimiter as xs:string) as xs:string" }, { "code": null, "e": 21255, "s": 21182, "text": "Returns the combination of items in a sequence separated by a delimiter." }, { "code": null, "e": 21334, "s": 21255, "text": "The following table lists the commonly used date functions provided by XQuery." }, { "code": null, "e": 21349, "s": 21334, "text": "current-date()" }, { "code": null, "e": 21375, "s": 21349, "text": "Returns the current date." }, { "code": null, "e": 21390, "s": 21375, "text": "current-time()" }, { "code": null, "e": 21416, "s": 21390, "text": "Returns the current time." }, { "code": null, "e": 21435, "s": 21416, "text": "current-dateTime()" }, { "code": null, "e": 21487, "s": 21435, "text": "Returns both the current date and the current time." }, { "code": null, "e": 21574, "s": 21487, "text": "Following is the list of commonly used regular expression functions provided by XQuery" }, { "code": null, "e": 21598, "s": 21574, "text": "matches($input, $regex)" }, { "code": null, "e": 21670, "s": 21598, "text": "Returns true if the input matches with the provided regular expression." }, { "code": null, "e": 21703, "s": 21670, "text": "replace($input, $regex, $string)" }, { "code": null, "e": 21756, "s": 21703, "text": "Replaces the matched input string with given string." }, { "code": null, "e": 21781, "s": 21756, "text": "tokenize($input, $regex)" }, { "code": null, "e": 21842, "s": 21781, "text": "Returns a sequence of items matching the regular expression." }, { "code": null, "e": 22002, "s": 21842, "text": "XQuery provides a very useful if-then-else construct to check the validity of the input values passed. Given below is the syntax of the if-then-else construct." }, { "code": null, "e": 22039, "s": 22002, "text": "if (condition) then\n ... \nelse\n ... " }, { "code": null, "e": 22233, "s": 22039, "text": "We will use the following books.xml file and apply to it XQuery expression containing an if-then-else construct to retrieve the titles of those books with a price value that is greater than 30." }, { "code": null, "e": 23021, "s": 22233, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>40.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author>\n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n</books>" }, { "code": null, "e": 23097, "s": 23021, "text": "The following XQuery expression is to be applied on the above XML document." }, { "code": null, "e": 23350, "s": 23097, "text": "<result>\n{\n if(not(doc(\"books.xml\"))) then (\n <error>\n <message>books.xml does not exist</message>\n </error>\n )\n else ( \n for $x in doc(\"books.xml\")/books/book\t\n where $x/price>30\n return $x/title\n )\n}\n</result>" }, { "code": null, "e": 23474, "s": 23350, "text": "<result>\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n</result>\n" }, { "code": null, "e": 23647, "s": 23474, "text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program." }, { "code": null, "e": 23766, "s": 23647, "text": "XQuery provides the capability to write custom functions. Listed below are the guidelines to create a custom function." }, { "code": null, "e": 23821, "s": 23766, "text": "Use the keyword declare function to define a function." }, { "code": null, "e": 23876, "s": 23821, "text": "Use the keyword declare function to define a function." }, { "code": null, "e": 23929, "s": 23876, "text": "Use the data types defined in the current XML Schema" }, { "code": null, "e": 23982, "s": 23929, "text": "Use the data types defined in the current XML Schema" }, { "code": null, "e": 24032, "s": 23982, "text": "Enclose the body of function inside curly braces." }, { "code": null, "e": 24082, "s": 24032, "text": "Enclose the body of function inside curly braces." }, { "code": null, "e": 24137, "s": 24082, "text": "Prefix the name of the function with an XML namespace." }, { "code": null, "e": 24192, "s": 24137, "text": "Prefix the name of the function with an XML namespace." }, { "code": null, "e": 24255, "s": 24192, "text": "The following syntax is used while creating a custom function." }, { "code": null, "e": 24365, "s": 24255, "text": "declare function prefix:function_name($parameter as datatype?...)\nas returnDatatype?\n{\n function body...\n};" }, { "code": null, "e": 24442, "s": 24365, "text": "The following example shows how to create a user-defined function in XQuery." }, { "code": null, "e": 24751, "s": 24442, "text": "declare function local:discount($price as xs:decimal?,$percentDiscount as xs:decimal?)\nas xs:decimal? {\n let $discount := $price - ($price * $percentDiscount div 100) \n return $discount\n};\n\nlet $originalPrice := 100\n\nlet $discountAvailed := 10\n\nreturn ( local:discount($originalPrice, $discountAvailed)) " }, { "code": null, "e": 24755, "s": 24751, "text": "90\n" } ]
Gray to Binary and Binary to Gray conversion
12 Jun, 2022 Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states with minimal effort and is used in K-maps, error correction, communication, etc. How to generate n bit Gray Codes? Following is 2-bit sequence (n = 2) 00 01 11 10 Following is 3-bit sequence (n = 3) 000 001 011 010 110 111 101 100 And Following is 4-bit sequence (n = 4) 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 n-bit Gray Codes can be generated from a list of (n-1)-bit Gray codes using the following steps. Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is the reverse of L1.Modify the list L1 by prefixing a ‘0’ in all codes of L1.Modify the list L2 by prefixing a ‘1’ in all codes of L2.Concatenate L1 and L2. The concatenated list is the required list of n-bit Gray codes. Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is the reverse of L1. Modify the list L1 by prefixing a ‘0’ in all codes of L1. Modify the list L2 by prefixing a ‘1’ in all codes of L2. Concatenate L1 and L2. The concatenated list is the required list of n-bit Gray codes. Please refer Generate n-bit Gray Codes for a detailed program. How to Convert Binary To Gray and Vice Versa? Binary : 0011 Gray : 0010 Binary : 01001 Gray : 01101 In computer science many a time we need to convert binary code to gray code and vice versa. This conversion can be done by applying the following rules : Binary to Gray conversion : The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the given binary code.Other bits of the output gray code can be obtained by XORing binary code bit at that index and previous index. The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the given binary code. Other bits of the output gray code can be obtained by XORing binary code bit at that index and previous index. Binary code to gray code conversion Gray to binary conversion : The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the given gray code.Other bits of the output binary code can be obtained by checking the gray code bit at that index. If the current gray code bit is 0, then copy the previous binary code bit, else copy the invert of the previous binary code bit. The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the given gray code. Other bits of the output binary code can be obtained by checking the gray code bit at that index. If the current gray code bit is 0, then copy the previous binary code bit, else copy the invert of the previous binary code bit. Gray code to binary code conversion Below is the implementation of the above steps. C++ Java Python3 C# PHP Javascript // C++ program for Binary To Gray// and Gray to Binary conversion#include <iostream>using namespace std; // Helper function to xor two characterschar xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bitchar flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary string// to gray stringstring binarytoGray(string binary){ string gray = ""; // MSB of gray code is same as binary code gray += binary[0]; // Compute remaining bits, next bit is computed by // doing XOR of previous and current in Binary for (int i = 1; i < binary.length(); i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray;} // function to convert gray code string// to binary stringstring graytoBinary(string gray){ string binary = ""; // MSB of binary code is same as gray code binary += gray[0]; // Compute remaining bits for (int i = 1; i < gray.length(); i++) { // If current bit is 0, concatenate // previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary;} // Driver program to test above functionsint main(){ string binary = "01001"; cout << "Gray code of " << binary << " is " << binarytoGray(binary) << endl; string gray = "01101"; cout << "Binary code of " << gray << " is " << graytoBinary(gray) << endl; return 0;} // Java program for Binary To Gray// and Gray to Binary conversionimport java.io.*;class code_conversion{ // Helper function to xor // two characters char xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bit char flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary // string to gray string String binarytoGray(String binary) { String gray = ""; // MSB of gray code is same // as binary code gray += binary.charAt(0); // Compute remaining bits, next bit is // computed by doing XOR of previous // and current in Binary for (int i = 1; i < binary.length(); i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary.charAt(i - 1), binary.charAt(i)); } return gray; } // function to convert gray code // string to binary string String graytoBinary(String gray) { String binary = ""; // MSB of binary code is same // as gray code binary += gray.charAt(0); // Compute remaining bits for (int i = 1; i < gray.length(); i++) { // If current bit is 0, // concatenate previous bit if (gray.charAt(i) == '0') binary += binary.charAt(i - 1); // Else, concatenate invert of // previous bit else binary += flip(binary.charAt(i - 1)); } return binary; } // Driver program to test above functions public static void main(String args[]) throws IOException { code_conversion ob = new code_conversion(); String binary = "01001"; System.out.println("Gray code of " + binary + " is " + ob.binarytoGray(binary)); String gray = "01101"; System.out.println("Binary code of " + gray + " is " + ob.graytoBinary(gray)); } } // This code is contributed by Anshika Goyal. # Python3 program for Binary To Gray# and Gray to Binary conversion # Helper function to xor two charactersdef xor_c(a, b): return '0' if(a == b) else '1'; # Helper function to flip the bitdef flip(c): return '1' if(c == '0') else '0'; # function to convert binary string# to gray stringdef binarytoGray(binary): gray = ""; # MSB of gray code is same as # binary code gray += binary[0]; # Compute remaining bits, next bit # is computed by doing XOR of previous # and current in Binary for i in range(1, len(binary)): # Concatenate XOR of previous # bit with current bit gray += xor_c(binary[i - 1], binary[i]); return gray; # function to convert gray code# string to binary stringdef graytoBinary(gray): binary = ""; # MSB of binary code is same # as gray code binary += gray[0]; # Compute remaining bits for i in range(1, len(gray)): # If current bit is 0, # concatenate previous bit if (gray[i] == '0'): binary += binary[i - 1]; # Else, concatenate invert # of previous bit else: binary += flip(binary[i - 1]); return binary; # Driver Codebinary = "01001";print("Gray code of", binary, "is", binarytoGray(binary)); gray = "01101";print("Binary code of", gray, "is", graytoBinary(gray)); # This code is contributed by mits // C# program for Binary To Gray// and Gray to Binary conversion.using System; class GFG { // Helper function to xor // two characters static char xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bit static char flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary // string to gray string static String binarytoGray(String binary) { String gray = ""; // MSB of gray code is same // as binary code gray += binary[0]; // Compute remaining bits, next // bit is computed by doing XOR // of previous and current in // Binary for (int i = 1; i < binary.Length; i++) { // Concatenate XOR of previous // bit with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray; } // function to convert gray code // string to binary string static String graytoBinary(String gray) { String binary = ""; // MSB of binary code is same // as gray code binary += gray[0]; // Compute remaining bits for (int i = 1; i < gray.Length; i++) { // If current bit is 0, // concatenate previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary; } // Driver program to test above // functions public static void Main() { String binary = "01001"; Console.WriteLine("Gray code of " + binary + " is " + binarytoGray(binary)); String gray = "01101"; Console.Write("Binary code of " + gray + " is " + graytoBinary(gray)); }} // This code is contributed by nitin mittal. <?php// PHP program for Binary To Gray// and Gray to Binary conversion // Helper function to xor two charactersfunction xor_c($a, $b){ return ($a == $b) ? '0' : '1';} // Helper function to flip the bitfunction flip($c){ return ($c == '0') ? '1' : '0';} // function to convert binary string// to gray stringfunction binarytoGray($binary){ $gray = ""; // MSB of gray code is same as // binary code $gray .= $binary[0]; // Compute remaining bits, next bit is // computed by doing XOR of previous // and current in Binary for ($i = 1; $i < strlen($binary); $i++) { // Concatenate XOR of previous bit // with current bit $gray .= xor_c($binary[$i - 1], $binary[$i]); } return $gray;} // function to convert gray code string// to binary stringfunction graytoBinary($gray){ $binary = ""; // MSB of binary code is same as gray code $binary .= $gray[0]; // Compute remaining bits for ($i = 1; $i < strlen($gray); $i++) { // If current bit is 0, concatenate // previous bit if ($gray[$i] == '0') $binary .= $binary[$i - 1]; // Else, concatenate invert of // previous bit else $binary .= flip($binary[$i - 1]); } return $binary;} // Driver Code$binary = "01001";print("Gray code of " . $binary . " is " . binarytoGray($binary) . "\n"); $gray = "01101";print("Binary code of " . $gray . " is " . graytoBinary($gray)); // This code is contributed by mits?> <script> // Javascript program for Binary To Gray// and Gray to Binary conversion // Helper function to xor two charactersfunction xor_c(a, b){ return (a == b) ? '0' : '1'; } // Helper function to flip the bitfunction flip(c){ return (c == '0') ? '1' : '0'; } // Function to convert binary string// to gray stringfunction binarytoGray(binary){ let gray = ""; // MSB of gray code is same // as binary code gray += binary[0]; // Compute remaining bits, next bit // is computed by doing XOR of previous // and current in Binary for(let i = 1; i < binary.length; i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray;} // Function to convert gray code string// to binary stringfunction graytoBinary(gray){ let binary = ""; // MSB of binary code is same // as gray code binary += gray[0]; // Compute remaining bits for(let i = 1; i < gray.length; i++) { // If current bit is 0, concatenate // previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary;} // Driver codelet binary = "01001";document.write("Gray code of " + binary + " is " + binarytoGray(binary) + "</br>"); let gray = "01101";document.write("Binary code of " + gray + " is " + graytoBinary(gray)); // This code is contributed by vaibhavrabadiya3 </script> Gray code of 01001 is 01101 Binary code of 01101 is 01001 Time Complexity: O(n) Auxiliary Space: O(n) Here, n is length of the binary string. Binary to Gray using Bitwise Operators C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; int greyConverter(int n) { return n ^ (n >> 1); } int main(){ int n = 3; cout << greyConverter(n) << endl; n = 9; cout << greyConverter(n) << endl; return 0;} // Java Program for above approachpublic class Main { public static int greyConverter(int n) { return n ^ (n >> 1); } // Driver code public static void main(String[] args) { int n = 3; System.out.println(greyConverter(n)); n = 9; System.out.println(greyConverter(n)); }} // This code is contributed by divyesh072019 # Python3 code for above approachdef greyConverter(n): return n ^ (n >> 1) n = 3print(greyConverter(n)) n = 9print(greyConverter(n)) # This code is contributed by divyeshrabadiya07 // C# program for above approachusing System; class GFG { static int greyConverter(int n) { return n ^ (n >> 1); } // Driver Code public static void Main(string[] args) { int n = 3; Console.WriteLine(greyConverter(n)); n = 9; Console.WriteLine(greyConverter(n)); }} // This code is contributed by rutvik_56 <script> // Javascript program for above approachfunction greyConverter(n){ return n ^ (n >> 1);} // Driver codelet n = 3;document.write(greyConverter(n) + "</br>"); n = 9;document.write(greyConverter(n)); // This code is contributed by suresh07 </script> 2 13 Time Complexity: O(1) Auxiliary Space: O(1) Gray to Binary using Bitwise Operators C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; int binaryConverter(int n){ int res = n; while (n > 0) { n >>= 1; res ^= n; } return res;} // Driver Codeint main(){ int n = 4; // Function call cout << binaryConverter(n) << endl; return 0;} // This code is contributed by sshrey47 // Java Program for above approachpublic class Main { public static int binaryConverter(int n) { int res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } // Driver code public static void main(String[] args) { int n = 4; System.out.println(binaryConverter(n)); }} // This code is contributed by sshrey47 # Python3 code for above approachdef binaryConverter(n): res = n while n > 0: n >>= 1 res ^= n return res n = 4print(binaryConverter(n)) # This code is contributed by sshrey47 using System; public class GFG { static int binaryConverter(int n) { int res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } static public void Main() { int n = 4; Console.WriteLine(binaryConverter(n)); }} // This code is contributed by sshrey47 <script> // Javascript program for above approach function binaryConverter(n) { let res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } let n = 4; // Function call document.write(binaryConverter(n)); // This code is contributed by mukesh07.</script> 7 Time Complexity: O(1) Auxiliary Space: O(1) This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal Mithun Kumar gp6 ramswarup_kulhary divyeshrabadiya07 divyesh072019 rutvik_56 sshrey47 suresh07 mukesh07 vaibhavrabadiya3 sumitgumber28 geeky01adarsh ranjanrohit840 binary-representation Bitwise-XOR gray-code Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Left Shift and Right Shift Operators in C/C++ Count set bits in an integer Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) How to swap two numbers without using a temporary variable? Program to find whether a given number is power of 2 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jun, 2022" }, { "code": null, "e": 253, "s": 54, "text": "Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. " }, { "code": null, "e": 485, "s": 253, "text": "Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states with minimal effort and is used in K-maps, error correction, communication, etc." }, { "code": null, "e": 520, "s": 485, "text": "How to generate n bit Gray Codes? " }, { "code": null, "e": 765, "s": 520, "text": "Following is 2-bit sequence (n = 2)\n 00 01 11 10\nFollowing is 3-bit sequence (n = 3)\n 000 001 011 010 110 111 101 100\nAnd Following is 4-bit sequence (n = 4)\n 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 \n 1110 1010 1011 1001 1000" }, { "code": null, "e": 863, "s": 765, "text": "n-bit Gray Codes can be generated from a list of (n-1)-bit Gray codes using the following steps. " }, { "code": null, "e": 1158, "s": 863, "text": "Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is the reverse of L1.Modify the list L1 by prefixing a ‘0’ in all codes of L1.Modify the list L2 by prefixing a ‘1’ in all codes of L2.Concatenate L1 and L2. The concatenated list is the required list of n-bit Gray codes." }, { "code": null, "e": 1253, "s": 1158, "text": "Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is the reverse of L1." }, { "code": null, "e": 1311, "s": 1253, "text": "Modify the list L1 by prefixing a ‘0’ in all codes of L1." }, { "code": null, "e": 1369, "s": 1311, "text": "Modify the list L2 by prefixing a ‘1’ in all codes of L2." }, { "code": null, "e": 1456, "s": 1369, "text": "Concatenate L1 and L2. The concatenated list is the required list of n-bit Gray codes." }, { "code": null, "e": 1519, "s": 1456, "text": "Please refer Generate n-bit Gray Codes for a detailed program." }, { "code": null, "e": 1566, "s": 1519, "text": "How to Convert Binary To Gray and Vice Versa? " }, { "code": null, "e": 1625, "s": 1566, "text": "Binary : 0011\nGray : 0010\n\nBinary : 01001\nGray : 01101" }, { "code": null, "e": 1779, "s": 1625, "text": "In computer science many a time we need to convert binary code to gray code and vice versa. This conversion can be done by applying the following rules :" }, { "code": null, "e": 1808, "s": 1779, "text": "Binary to Gray conversion : " }, { "code": null, "e": 2019, "s": 1808, "text": "The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the given binary code.Other bits of the output gray code can be obtained by XORing binary code bit at that index and previous index." }, { "code": null, "e": 2120, "s": 2019, "text": "The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the given binary code." }, { "code": null, "e": 2231, "s": 2120, "text": "Other bits of the output gray code can be obtained by XORing binary code bit at that index and previous index." }, { "code": null, "e": 2267, "s": 2231, "text": "Binary code to gray code conversion" }, { "code": null, "e": 2295, "s": 2267, "text": "Gray to binary conversion :" }, { "code": null, "e": 2622, "s": 2295, "text": "The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the given gray code.Other bits of the output binary code can be obtained by checking the gray code bit at that index. If the current gray code bit is 0, then copy the previous binary code bit, else copy the invert of the previous binary code bit." }, { "code": null, "e": 2723, "s": 2622, "text": "The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the given gray code." }, { "code": null, "e": 2950, "s": 2723, "text": "Other bits of the output binary code can be obtained by checking the gray code bit at that index. If the current gray code bit is 0, then copy the previous binary code bit, else copy the invert of the previous binary code bit." }, { "code": null, "e": 2986, "s": 2950, "text": "Gray code to binary code conversion" }, { "code": null, "e": 3034, "s": 2986, "text": "Below is the implementation of the above steps." }, { "code": null, "e": 3038, "s": 3034, "text": "C++" }, { "code": null, "e": 3043, "s": 3038, "text": "Java" }, { "code": null, "e": 3051, "s": 3043, "text": "Python3" }, { "code": null, "e": 3054, "s": 3051, "text": "C#" }, { "code": null, "e": 3058, "s": 3054, "text": "PHP" }, { "code": null, "e": 3069, "s": 3058, "text": "Javascript" }, { "code": "// C++ program for Binary To Gray// and Gray to Binary conversion#include <iostream>using namespace std; // Helper function to xor two characterschar xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bitchar flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary string// to gray stringstring binarytoGray(string binary){ string gray = \"\"; // MSB of gray code is same as binary code gray += binary[0]; // Compute remaining bits, next bit is computed by // doing XOR of previous and current in Binary for (int i = 1; i < binary.length(); i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray;} // function to convert gray code string// to binary stringstring graytoBinary(string gray){ string binary = \"\"; // MSB of binary code is same as gray code binary += gray[0]; // Compute remaining bits for (int i = 1; i < gray.length(); i++) { // If current bit is 0, concatenate // previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary;} // Driver program to test above functionsint main(){ string binary = \"01001\"; cout << \"Gray code of \" << binary << \" is \" << binarytoGray(binary) << endl; string gray = \"01101\"; cout << \"Binary code of \" << gray << \" is \" << graytoBinary(gray) << endl; return 0;}", "e": 4657, "s": 3069, "text": null }, { "code": "// Java program for Binary To Gray// and Gray to Binary conversionimport java.io.*;class code_conversion{ // Helper function to xor // two characters char xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bit char flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary // string to gray string String binarytoGray(String binary) { String gray = \"\"; // MSB of gray code is same // as binary code gray += binary.charAt(0); // Compute remaining bits, next bit is // computed by doing XOR of previous // and current in Binary for (int i = 1; i < binary.length(); i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary.charAt(i - 1), binary.charAt(i)); } return gray; } // function to convert gray code // string to binary string String graytoBinary(String gray) { String binary = \"\"; // MSB of binary code is same // as gray code binary += gray.charAt(0); // Compute remaining bits for (int i = 1; i < gray.length(); i++) { // If current bit is 0, // concatenate previous bit if (gray.charAt(i) == '0') binary += binary.charAt(i - 1); // Else, concatenate invert of // previous bit else binary += flip(binary.charAt(i - 1)); } return binary; } // Driver program to test above functions public static void main(String args[]) throws IOException { code_conversion ob = new code_conversion(); String binary = \"01001\"; System.out.println(\"Gray code of \" + binary + \" is \" + ob.binarytoGray(binary)); String gray = \"01101\"; System.out.println(\"Binary code of \" + gray + \" is \" + ob.graytoBinary(gray)); } } // This code is contributed by Anshika Goyal.", "e": 6845, "s": 4657, "text": null }, { "code": "# Python3 program for Binary To Gray# and Gray to Binary conversion # Helper function to xor two charactersdef xor_c(a, b): return '0' if(a == b) else '1'; # Helper function to flip the bitdef flip(c): return '1' if(c == '0') else '0'; # function to convert binary string# to gray stringdef binarytoGray(binary): gray = \"\"; # MSB of gray code is same as # binary code gray += binary[0]; # Compute remaining bits, next bit # is computed by doing XOR of previous # and current in Binary for i in range(1, len(binary)): # Concatenate XOR of previous # bit with current bit gray += xor_c(binary[i - 1], binary[i]); return gray; # function to convert gray code# string to binary stringdef graytoBinary(gray): binary = \"\"; # MSB of binary code is same # as gray code binary += gray[0]; # Compute remaining bits for i in range(1, len(gray)): # If current bit is 0, # concatenate previous bit if (gray[i] == '0'): binary += binary[i - 1]; # Else, concatenate invert # of previous bit else: binary += flip(binary[i - 1]); return binary; # Driver Codebinary = \"01001\";print(\"Gray code of\", binary, \"is\", binarytoGray(binary)); gray = \"01101\";print(\"Binary code of\", gray, \"is\", graytoBinary(gray)); # This code is contributed by mits", "e": 8285, "s": 6845, "text": null }, { "code": "// C# program for Binary To Gray// and Gray to Binary conversion.using System; class GFG { // Helper function to xor // two characters static char xor_c(char a, char b) { return (a == b) ? '0' : '1'; } // Helper function to flip the bit static char flip(char c) { return (c == '0') ? '1' : '0'; } // function to convert binary // string to gray string static String binarytoGray(String binary) { String gray = \"\"; // MSB of gray code is same // as binary code gray += binary[0]; // Compute remaining bits, next // bit is computed by doing XOR // of previous and current in // Binary for (int i = 1; i < binary.Length; i++) { // Concatenate XOR of previous // bit with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray; } // function to convert gray code // string to binary string static String graytoBinary(String gray) { String binary = \"\"; // MSB of binary code is same // as gray code binary += gray[0]; // Compute remaining bits for (int i = 1; i < gray.Length; i++) { // If current bit is 0, // concatenate previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary; } // Driver program to test above // functions public static void Main() { String binary = \"01001\"; Console.WriteLine(\"Gray code of \" + binary + \" is \" + binarytoGray(binary)); String gray = \"01101\"; Console.Write(\"Binary code of \" + gray + \" is \" + graytoBinary(gray)); }} // This code is contributed by nitin mittal.", "e": 10302, "s": 8285, "text": null }, { "code": "<?php// PHP program for Binary To Gray// and Gray to Binary conversion // Helper function to xor two charactersfunction xor_c($a, $b){ return ($a == $b) ? '0' : '1';} // Helper function to flip the bitfunction flip($c){ return ($c == '0') ? '1' : '0';} // function to convert binary string// to gray stringfunction binarytoGray($binary){ $gray = \"\"; // MSB of gray code is same as // binary code $gray .= $binary[0]; // Compute remaining bits, next bit is // computed by doing XOR of previous // and current in Binary for ($i = 1; $i < strlen($binary); $i++) { // Concatenate XOR of previous bit // with current bit $gray .= xor_c($binary[$i - 1], $binary[$i]); } return $gray;} // function to convert gray code string// to binary stringfunction graytoBinary($gray){ $binary = \"\"; // MSB of binary code is same as gray code $binary .= $gray[0]; // Compute remaining bits for ($i = 1; $i < strlen($gray); $i++) { // If current bit is 0, concatenate // previous bit if ($gray[$i] == '0') $binary .= $binary[$i - 1]; // Else, concatenate invert of // previous bit else $binary .= flip($binary[$i - 1]); } return $binary;} // Driver Code$binary = \"01001\";print(\"Gray code of \" . $binary . \" is \" . binarytoGray($binary) . \"\\n\"); $gray = \"01101\";print(\"Binary code of \" . $gray . \" is \" . graytoBinary($gray)); // This code is contributed by mits?>", "e": 11836, "s": 10302, "text": null }, { "code": "<script> // Javascript program for Binary To Gray// and Gray to Binary conversion // Helper function to xor two charactersfunction xor_c(a, b){ return (a == b) ? '0' : '1'; } // Helper function to flip the bitfunction flip(c){ return (c == '0') ? '1' : '0'; } // Function to convert binary string// to gray stringfunction binarytoGray(binary){ let gray = \"\"; // MSB of gray code is same // as binary code gray += binary[0]; // Compute remaining bits, next bit // is computed by doing XOR of previous // and current in Binary for(let i = 1; i < binary.length; i++) { // Concatenate XOR of previous bit // with current bit gray += xor_c(binary[i - 1], binary[i]); } return gray;} // Function to convert gray code string// to binary stringfunction graytoBinary(gray){ let binary = \"\"; // MSB of binary code is same // as gray code binary += gray[0]; // Compute remaining bits for(let i = 1; i < gray.length; i++) { // If current bit is 0, concatenate // previous bit if (gray[i] == '0') binary += binary[i - 1]; // Else, concatenate invert of // previous bit else binary += flip(binary[i - 1]); } return binary;} // Driver codelet binary = \"01001\";document.write(\"Gray code of \" + binary + \" is \" + binarytoGray(binary) + \"</br>\"); let gray = \"01101\";document.write(\"Binary code of \" + gray + \" is \" + graytoBinary(gray)); // This code is contributed by vaibhavrabadiya3 </script>", "e": 13416, "s": 11836, "text": null }, { "code": null, "e": 13474, "s": 13416, "text": "Gray code of 01001 is 01101\nBinary code of 01101 is 01001" }, { "code": null, "e": 13496, "s": 13474, "text": "Time Complexity: O(n)" }, { "code": null, "e": 13518, "s": 13496, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 13559, "s": 13518, "text": "Here, n is length of the binary string. " }, { "code": null, "e": 13598, "s": 13559, "text": "Binary to Gray using Bitwise Operators" }, { "code": null, "e": 13602, "s": 13598, "text": "C++" }, { "code": null, "e": 13607, "s": 13602, "text": "Java" }, { "code": null, "e": 13615, "s": 13607, "text": "Python3" }, { "code": null, "e": 13618, "s": 13615, "text": "C#" }, { "code": null, "e": 13629, "s": 13618, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; int greyConverter(int n) { return n ^ (n >> 1); } int main(){ int n = 3; cout << greyConverter(n) << endl; n = 9; cout << greyConverter(n) << endl; return 0;}", "e": 13883, "s": 13629, "text": null }, { "code": "// Java Program for above approachpublic class Main { public static int greyConverter(int n) { return n ^ (n >> 1); } // Driver code public static void main(String[] args) { int n = 3; System.out.println(greyConverter(n)); n = 9; System.out.println(greyConverter(n)); }} // This code is contributed by divyesh072019", "e": 14257, "s": 13883, "text": null }, { "code": "# Python3 code for above approachdef greyConverter(n): return n ^ (n >> 1) n = 3print(greyConverter(n)) n = 9print(greyConverter(n)) # This code is contributed by divyeshrabadiya07", "e": 14443, "s": 14257, "text": null }, { "code": "// C# program for above approachusing System; class GFG { static int greyConverter(int n) { return n ^ (n >> 1); } // Driver Code public static void Main(string[] args) { int n = 3; Console.WriteLine(greyConverter(n)); n = 9; Console.WriteLine(greyConverter(n)); }} // This code is contributed by rutvik_56", "e": 14796, "s": 14443, "text": null }, { "code": "<script> // Javascript program for above approachfunction greyConverter(n){ return n ^ (n >> 1);} // Driver codelet n = 3;document.write(greyConverter(n) + \"</br>\"); n = 9;document.write(greyConverter(n)); // This code is contributed by suresh07 </script>", "e": 15055, "s": 14796, "text": null }, { "code": null, "e": 15060, "s": 15055, "text": "2\n13" }, { "code": null, "e": 15082, "s": 15060, "text": "Time Complexity: O(1)" }, { "code": null, "e": 15104, "s": 15082, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 15143, "s": 15104, "text": "Gray to Binary using Bitwise Operators" }, { "code": null, "e": 15147, "s": 15143, "text": "C++" }, { "code": null, "e": 15152, "s": 15147, "text": "Java" }, { "code": null, "e": 15160, "s": 15152, "text": "Python3" }, { "code": null, "e": 15163, "s": 15160, "text": "C#" }, { "code": null, "e": 15174, "s": 15163, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; int binaryConverter(int n){ int res = n; while (n > 0) { n >>= 1; res ^= n; } return res;} // Driver Codeint main(){ int n = 4; // Function call cout << binaryConverter(n) << endl; return 0;} // This code is contributed by sshrey47", "e": 15529, "s": 15174, "text": null }, { "code": "// Java Program for above approachpublic class Main { public static int binaryConverter(int n) { int res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } // Driver code public static void main(String[] args) { int n = 4; System.out.println(binaryConverter(n)); }} // This code is contributed by sshrey47", "e": 15928, "s": 15529, "text": null }, { "code": "# Python3 code for above approachdef binaryConverter(n): res = n while n > 0: n >>= 1 res ^= n return res n = 4print(binaryConverter(n)) # This code is contributed by sshrey47", "e": 16130, "s": 15928, "text": null }, { "code": "using System; public class GFG { static int binaryConverter(int n) { int res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } static public void Main() { int n = 4; Console.WriteLine(binaryConverter(n)); }} // This code is contributed by sshrey47", "e": 16470, "s": 16130, "text": null }, { "code": "<script> // Javascript program for above approach function binaryConverter(n) { let res = n; while (n > 0) { n >>= 1; res ^= n; } return res; } let n = 4; // Function call document.write(binaryConverter(n)); // This code is contributed by mukesh07.</script>", "e": 16827, "s": 16470, "text": null }, { "code": null, "e": 16829, "s": 16827, "text": "7" }, { "code": null, "e": 16851, "s": 16829, "text": "Time Complexity: O(1)" }, { "code": null, "e": 16873, "s": 16851, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 17046, "s": 16873, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 17059, "s": 17046, "text": "nitin mittal" }, { "code": null, "e": 17072, "s": 17059, "text": "Mithun Kumar" }, { "code": null, "e": 17076, "s": 17072, "text": "gp6" }, { "code": null, "e": 17094, "s": 17076, "text": "ramswarup_kulhary" }, { "code": null, "e": 17112, "s": 17094, "text": "divyeshrabadiya07" }, { "code": null, "e": 17126, "s": 17112, "text": "divyesh072019" }, { "code": null, "e": 17136, "s": 17126, "text": "rutvik_56" }, { "code": null, "e": 17145, "s": 17136, "text": "sshrey47" }, { "code": null, "e": 17154, "s": 17145, "text": "suresh07" }, { "code": null, "e": 17163, "s": 17154, "text": "mukesh07" }, { "code": null, "e": 17180, "s": 17163, "text": "vaibhavrabadiya3" }, { "code": null, "e": 17194, "s": 17180, "text": "sumitgumber28" }, { "code": null, "e": 17208, "s": 17194, "text": "geeky01adarsh" }, { "code": null, "e": 17223, "s": 17208, "text": "ranjanrohit840" }, { "code": null, "e": 17245, "s": 17223, "text": "binary-representation" }, { "code": null, "e": 17257, "s": 17245, "text": "Bitwise-XOR" }, { "code": null, "e": 17267, "s": 17257, "text": "gray-code" }, { "code": null, "e": 17277, "s": 17267, "text": "Bit Magic" }, { "code": null, "e": 17290, "s": 17277, "text": "Mathematical" }, { "code": null, "e": 17303, "s": 17290, "text": "Mathematical" }, { "code": null, "e": 17313, "s": 17303, "text": "Bit Magic" }, { "code": null, "e": 17411, "s": 17313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17457, "s": 17411, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 17486, "s": 17457, "text": "Count set bits in an integer" }, { "code": null, "e": 17554, "s": 17486, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 17614, "s": 17554, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 17667, "s": 17614, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 17697, "s": 17667, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 17740, "s": 17697, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 17800, "s": 17740, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 17815, "s": 17800, "text": "C++ Data Types" } ]
How to pass a parameter to an event handler or callback ?
30 Aug, 2021 React js is one of the most popular JavaScript frameworks today. There are a lot of companies whose websites are built on React due to the framework’s unique features. React UI comprises several components. There are a lot of tasks that users can perform on a React user interface. Each component has different HTML elements where the user can click, hover or trigger any form of event. Event Handlers: Events are the signals sent when there is a change in the UI. Users may click hover drag the mouse or press any key to perform these events. To respond to these changes users can write event handler code. You need to keep these 2 points in mind while working with React events. React events are named in the format of camelCase (onChange instead of onchange). React event handlers are placed inside curly braces (onChange={handleSubmit} instead of onChange=”handleSubmit”). Approach: Let us create a React project and then we will create a event handler. Users can interact and trigger an event through this. After seeing the response in UI we will create our own parameters. This will help you to understand the underlying logic of event handlers and passing parameters through it. Creating React Project: Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.npx create-react-app project_name Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once. npx create-react-app project_name Step 2: After creating your react project move into the folder to perform different operations.cd project_name Step 2: After creating your react project move into the folder to perform different operations. cd project_name Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new components user makes or the code changes we will be performing will be done in the source folder. Example 1: In this example, we will create an event handler that sends a Welcome message i.e. Alert whenever you click the button. App.js import React from "react";class App extends React.Component { call() { alert("Welcome to Geeks for Geeeks!"); } render() { return ( <button onClick={this.call}>Click the button!</button> ); }} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message. Example 2: In this example, we will use the arrow function to create a new function that calls the function call with the right parameter. Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button. App.js import React from "react";class App extends React.Component { call(message,event) { alert(message); } render() { return ( //Creating a arrow function <button onClick={(event)=> this.call("Your message",event)}> Click the button! </button> ); }}export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message. Example 3: In this example, we will use Bind Method that is also used to pass the parameters in functions of class-based components. App.js import React from "react";class App extends React.Component { call(message) { alert(message); } render() { return ( <button onClick= {this.call.bind(this,"Your message")}> Click the button! </button> ); }}export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to do crud operations in ReactJS ? How to create a multi-page website using React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2021" }, { "code": null, "e": 417, "s": 28, "text": "React js is one of the most popular JavaScript frameworks today. There are a lot of companies whose websites are built on React due to the framework’s unique features. React UI comprises several components. There are a lot of tasks that users can perform on a React user interface. Each component has different HTML elements where the user can click, hover or trigger any form of event. " }, { "code": null, "e": 711, "s": 417, "text": "Event Handlers: Events are the signals sent when there is a change in the UI. Users may click hover drag the mouse or press any key to perform these events. To respond to these changes users can write event handler code. You need to keep these 2 points in mind while working with React events." }, { "code": null, "e": 793, "s": 711, "text": "React events are named in the format of camelCase (onChange instead of onchange)." }, { "code": null, "e": 907, "s": 793, "text": "React event handlers are placed inside curly braces (onChange={handleSubmit} instead of onChange=”handleSubmit”)." }, { "code": null, "e": 1216, "s": 907, "text": "Approach: Let us create a React project and then we will create a event handler. Users can interact and trigger an event through this. After seeing the response in UI we will create our own parameters. This will help you to understand the underlying logic of event handlers and passing parameters through it." }, { "code": null, "e": 1240, "s": 1216, "text": "Creating React Project:" }, { "code": null, "e": 1465, "s": 1240, "text": "Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.npx create-react-app project_name" }, { "code": null, "e": 1657, "s": 1465, "text": "Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once." }, { "code": null, "e": 1691, "s": 1657, "text": "npx create-react-app project_name" }, { "code": null, "e": 1802, "s": 1691, "text": "Step 2: After creating your react project move into the folder to perform different operations.cd project_name" }, { "code": null, "e": 1898, "s": 1802, "text": "Step 2: After creating your react project move into the folder to perform different operations." }, { "code": null, "e": 1914, "s": 1898, "text": "cd project_name" }, { "code": null, "e": 2191, "s": 1914, "text": "Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new components user makes or the code changes we will be performing will be done in the source folder. " }, { "code": null, "e": 2324, "s": 2191, "text": "Example 1: In this example, we will create an event handler that sends a Welcome message i.e. Alert whenever you click the button. " }, { "code": null, "e": 2331, "s": 2324, "text": "App.js" }, { "code": "import React from \"react\";class App extends React.Component { call() { alert(\"Welcome to Geeks for Geeeks!\"); } render() { return ( <button onClick={this.call}>Click the button!</button> ); }} export default App;", "e": 2563, "s": 2331, "text": null }, { "code": null, "e": 2643, "s": 2563, "text": "Step to run the application: Open the terminal and type the following command. " }, { "code": null, "e": 2653, "s": 2643, "text": "npm start" }, { "code": null, "e": 2853, "s": 2653, "text": "Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message." }, { "code": null, "e": 3292, "s": 2853, "text": "Example 2: In this example, we will use the arrow function to create a new function that calls the function call with the right parameter. Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button." }, { "code": null, "e": 3299, "s": 3292, "text": "App.js" }, { "code": "import React from \"react\";class App extends React.Component { call(message,event) { alert(message); } render() { return ( //Creating a arrow function <button onClick={(event)=> this.call(\"Your message\",event)}> Click the button! </button> ); }}export default App;", "e": 3602, "s": 3299, "text": null }, { "code": null, "e": 3682, "s": 3602, "text": "Step to run the application: Open the terminal and type the following command. " }, { "code": null, "e": 3692, "s": 3682, "text": "npm start" }, { "code": null, "e": 3892, "s": 3692, "text": "Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message." }, { "code": null, "e": 4025, "s": 3892, "text": "Example 3: In this example, we will use Bind Method that is also used to pass the parameters in functions of class-based components." }, { "code": null, "e": 4032, "s": 4025, "text": "App.js" }, { "code": "import React from \"react\";class App extends React.Component { call(message) { alert(message); } render() { return ( <button onClick= {this.call.bind(this,\"Your message\")}> Click the button! </button> ); }}export default App;", "e": 4287, "s": 4032, "text": null }, { "code": null, "e": 4367, "s": 4287, "text": "Step to run the application: Open the terminal and type the following command. " }, { "code": null, "e": 4377, "s": 4367, "text": "npm start" }, { "code": null, "e": 4577, "s": 4377, "text": "Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Click on the button to see the welcome message." }, { "code": null, "e": 4584, "s": 4577, "text": "Picked" }, { "code": null, "e": 4600, "s": 4584, "text": "React-Questions" }, { "code": null, "e": 4608, "s": 4600, "text": "ReactJS" }, { "code": null, "e": 4625, "s": 4608, "text": "Web Technologies" }, { "code": null, "e": 4723, "s": 4625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4761, "s": 4723, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 4788, "s": 4761, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 4827, "s": 4788, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 4866, "s": 4827, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 4918, "s": 4866, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 4951, "s": 4918, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5013, "s": 4951, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5074, "s": 5013, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5124, "s": 5074, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the maximum elements in the first and the second halves of the Array
28 May, 2022 , Given an array arr[] of N integers. The task is to find the largest elements in the first half and the second half of the array. Note that if the size of the array is odd then the middle element will be included in both halves.Examples: Input: arr[] = {1, 12, 14, 5} Output: 12, 14 First half is {1, 12} and the second half is {14, 5}.Input: arr[] = {1, 2, 3, 4, 5} Output: 3, 5 Approach: Calculate the middle index of the array as mid = N / 2. Now the first halve elements will be present in the subarray arr[0...mid-1] and arr[mid...N-1] if N is even. If N is odd then the halves are arr[0...mid] and arr[mid...N-1]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 print largest element in// first half and second half of an arrayvoid findMax(int arr[], int n){ // To store the maximum element // in the first half int maxFirst = INT_MIN; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) maxFirst = max(maxFirst, arr[i]); // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) maxFirst = max(maxFirst, arr[mid]); // To store the maximum element // in the second half int maxSecond = INT_MIN; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) maxSecond = max(maxSecond, arr[i]); // Print the found maximums cout << maxFirst << ", " << maxSecond;} // Driver codeint main(){ int arr[] = { 1, 12, 14, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findMax(arr, n); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ static void findMax(int []arr, int n) { // To store the maximum element // in the first half int maxFirst = Integer.MIN_VALUE; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) { maxFirst = Math.max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.max(maxFirst, arr[mid]); } // To store the maximum element // in the second half int maxSecond = Integer.MIN_VALUE; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) { maxSecond = Math.max(maxSecond, arr[i]); } // Print the found maximums System.out.print(maxFirst + ", " + maxSecond); // cout << maxFirst << ", " << maxSecond; } // Driver Code public static void main(String[] args) { int []arr = { 1, 12, 14, 5 }; int n = arr.length; findMax(arr, n); }} // This code is contributed by anuj_67.. # Python3 implementation of the approachimport sys # Function to print largest element in# first half and second half of an arraydef findMax(arr, n) : # To store the maximum element # in the first half maxFirst = -sys.maxsize - 1 # Middle index of the array mid = n // 2; # Calculate the maximum element # in the first half for i in range(0, mid): maxFirst = max(maxFirst, arr[i]) # If the size of array is odd then # the middle element will be included # in both the halves if (n % 2 == 1): maxFirst = max(maxFirst, arr[mid]) # To store the maximum element # in the second half maxSecond = -sys.maxsize - 1 # Calculate the maximum element # int the second half for i in range(mid, n): maxSecond = max(maxSecond, arr[i]) # Print the found maximums print(maxFirst, ",", maxSecond) # Driver codearr = [1, 12, 14, 5 ]n = len(arr) findMax(arr, n) # This code is contributed by ihritik // C# implementation of the approachusing System; class GFG{ static void findMax(int []arr, int n) { // To store the maximum element // in the first half int maxFirst = int.MinValue; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) { maxFirst = Math.Max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.Max(maxFirst, arr[mid]); } // To store the maximum element // in the second half int maxSecond = int.MinValue; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) { maxSecond = Math.Max(maxSecond, arr[i]); } // Print the found maximums Console.WriteLine(maxFirst + ", " + maxSecond); // cout << maxFirst << ", " << maxSecond; } // Driver Code public static void Main() { int []arr = { 1, 12, 14, 5 }; int n = arr.Length; findMax(arr, n); }} // This code is contributed by nidhiva // javascript implementation of the approach function findMax(arr, n) { // To store the maximum element // in the first half var maxFirst = Number.MIN_VALUE // Middle index of the array var mid = n / 2; // Calculate the maximum element // in the first half for (var i = 0; i < mid; i++) { maxFirst = Math.max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.max(maxFirst, arr[mid]); } // To store the maximum element // in the second half var maxSecond = Number.MIN_VALUE // Calculate the maximum element // int the second half for (var i = mid; i < n; i++) { maxSecond = Math.max(maxSecond, arr[i]); } // Print the found maximums document.write(maxFirst + ", " + maxSecond); } // Driver Code var arr = [ 1, 12, 14, 5 ]; var n = arr.length; findMax(arr, n); // This code is contributed by bunnyram19. 12, 14 Time Complexity: O(n), since the loop runs from 0 to (mid – 1), and then from mid to (n – 1). Auxiliary Space: O(1), since no extra space has been taken. nidhiva vt_m ihritik subhammahato348 bunnyram19 Constructive Algorithms Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2022" }, { "code": null, "e": 268, "s": 28, "text": ", Given an array arr[] of N integers. The task is to find the largest elements in the first half and the second half of the array. Note that if the size of the array is odd then the middle element will be included in both halves.Examples: " }, { "code": null, "e": 411, "s": 268, "text": "Input: arr[] = {1, 12, 14, 5} Output: 12, 14 First half is {1, 12} and the second half is {14, 5}.Input: arr[] = {1, 2, 3, 4, 5} Output: 3, 5 " }, { "code": null, "e": 701, "s": 411, "text": "Approach: Calculate the middle index of the array as mid = N / 2. Now the first halve elements will be present in the subarray arr[0...mid-1] and arr[mid...N-1] if N is even. If N is odd then the halves are arr[0...mid] and arr[mid...N-1]Below is the implementation of the above approach: " }, { "code": null, "e": 705, "s": 701, "text": "C++" }, { "code": null, "e": 710, "s": 705, "text": "Java" }, { "code": null, "e": 718, "s": 710, "text": "Python3" }, { "code": null, "e": 721, "s": 718, "text": "C#" }, { "code": null, "e": 732, "s": 721, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print largest element in// first half and second half of an arrayvoid findMax(int arr[], int n){ // To store the maximum element // in the first half int maxFirst = INT_MIN; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) maxFirst = max(maxFirst, arr[i]); // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) maxFirst = max(maxFirst, arr[mid]); // To store the maximum element // in the second half int maxSecond = INT_MIN; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) maxSecond = max(maxSecond, arr[i]); // Print the found maximums cout << maxFirst << \", \" << maxSecond;} // Driver codeint main(){ int arr[] = { 1, 12, 14, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findMax(arr, n); return 0;}", "e": 1809, "s": 732, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ static void findMax(int []arr, int n) { // To store the maximum element // in the first half int maxFirst = Integer.MIN_VALUE; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) { maxFirst = Math.max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.max(maxFirst, arr[mid]); } // To store the maximum element // in the second half int maxSecond = Integer.MIN_VALUE; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) { maxSecond = Math.max(maxSecond, arr[i]); } // Print the found maximums System.out.print(maxFirst + \", \" + maxSecond); // cout << maxFirst << \", \" << maxSecond; } // Driver Code public static void main(String[] args) { int []arr = { 1, 12, 14, 5 }; int n = arr.length; findMax(arr, n); }} // This code is contributed by anuj_67..", "e": 3157, "s": 1809, "text": null }, { "code": "# Python3 implementation of the approachimport sys # Function to print largest element in# first half and second half of an arraydef findMax(arr, n) : # To store the maximum element # in the first half maxFirst = -sys.maxsize - 1 # Middle index of the array mid = n // 2; # Calculate the maximum element # in the first half for i in range(0, mid): maxFirst = max(maxFirst, arr[i]) # If the size of array is odd then # the middle element will be included # in both the halves if (n % 2 == 1): maxFirst = max(maxFirst, arr[mid]) # To store the maximum element # in the second half maxSecond = -sys.maxsize - 1 # Calculate the maximum element # int the second half for i in range(mid, n): maxSecond = max(maxSecond, arr[i]) # Print the found maximums print(maxFirst, \",\", maxSecond) # Driver codearr = [1, 12, 14, 5 ]n = len(arr) findMax(arr, n) # This code is contributed by ihritik", "e": 4126, "s": 3157, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static void findMax(int []arr, int n) { // To store the maximum element // in the first half int maxFirst = int.MinValue; // Middle index of the array int mid = n / 2; // Calculate the maximum element // in the first half for (int i = 0; i < mid; i++) { maxFirst = Math.Max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.Max(maxFirst, arr[mid]); } // To store the maximum element // in the second half int maxSecond = int.MinValue; // Calculate the maximum element // int the second half for (int i = mid; i < n; i++) { maxSecond = Math.Max(maxSecond, arr[i]); } // Print the found maximums Console.WriteLine(maxFirst + \", \" + maxSecond); // cout << maxFirst << \", \" << maxSecond; } // Driver Code public static void Main() { int []arr = { 1, 12, 14, 5 }; int n = arr.Length; findMax(arr, n); }} // This code is contributed by nidhiva", "e": 5444, "s": 4126, "text": null }, { "code": "// javascript implementation of the approach function findMax(arr, n) { // To store the maximum element // in the first half var maxFirst = Number.MIN_VALUE // Middle index of the array var mid = n / 2; // Calculate the maximum element // in the first half for (var i = 0; i < mid; i++) { maxFirst = Math.max(maxFirst, arr[i]); } // If the size of array is odd then // the middle element will be included // in both the halves if (n % 2 == 1) { maxFirst = Math.max(maxFirst, arr[mid]); } // To store the maximum element // in the second half var maxSecond = Number.MIN_VALUE // Calculate the maximum element // int the second half for (var i = mid; i < n; i++) { maxSecond = Math.max(maxSecond, arr[i]); } // Print the found maximums document.write(maxFirst + \", \" + maxSecond); } // Driver Code var arr = [ 1, 12, 14, 5 ]; var n = arr.length; findMax(arr, n); // This code is contributed by bunnyram19.", "e": 6668, "s": 5444, "text": null }, { "code": null, "e": 6675, "s": 6668, "text": "12, 14" }, { "code": null, "e": 6771, "s": 6677, "text": "Time Complexity: O(n), since the loop runs from 0 to (mid – 1), and then from mid to (n – 1)." }, { "code": null, "e": 6831, "s": 6771, "text": "Auxiliary Space: O(1), since no extra space has been taken." }, { "code": null, "e": 6839, "s": 6831, "text": "nidhiva" }, { "code": null, "e": 6844, "s": 6839, "text": "vt_m" }, { "code": null, "e": 6852, "s": 6844, "text": "ihritik" }, { "code": null, "e": 6868, "s": 6852, "text": "subhammahato348" }, { "code": null, "e": 6879, "s": 6868, "text": "bunnyram19" }, { "code": null, "e": 6903, "s": 6879, "text": "Constructive Algorithms" }, { "code": null, "e": 6910, "s": 6903, "text": "Arrays" }, { "code": null, "e": 6923, "s": 6910, "text": "Mathematical" }, { "code": null, "e": 6930, "s": 6923, "text": "Arrays" }, { "code": null, "e": 6943, "s": 6930, "text": "Mathematical" }, { "code": null, "e": 7041, "s": 6943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7073, "s": 7041, "text": "Introduction to Data Structures" }, { "code": null, "e": 7098, "s": 7073, "text": "Window Sliding Technique" }, { "code": null, "e": 7145, "s": 7098, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7209, "s": 7145, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7240, "s": 7209, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7270, "s": 7240, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7313, "s": 7270, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7373, "s": 7313, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7388, "s": 7373, "text": "C++ Data Types" } ]
Python | os.path.commonprefix() method
22 May, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used for common path name manipulation. os.path.commonprefix() method in Python is used to get longest common path prefix in a list of paths. This method returns only common prefix value in the specified list, returned value may or may not be a valid path as it check for common prefix by comparing character by character in the list.For example consider the following list of paths: list of paths common prefix ['/home/User/Photos', /home/User/Videos'] /home/User/ A valid path ['/usr/local/bin', '/usr/lib'] /usr/l Not a valid path Syntax: os.path.commonprefix(list) Parameter:path: A list of path-like object. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a string value which represents the longest common path prefix in specified list. Code #1: Use of os.path.commonprefix() method # Python program to explain os.path.commonprefix() method # importing os module import os # List of Pathspaths = ['/home/User/Desktop', '/home/User/Documents', '/home/User/Downloads'] # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths) # Print the # longest common path prefix# in the specified list print("Longest common path prefix:", prefix) # List of Pathspaths = ['/usr/local/bin', '/usr/bin'] # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths) # Print the # longest common path prefix# in the specified list print("Longest common path prefix:", prefix) Longest common path prefix: /home/User/D Longest common path prefix: /usr/ Note: If the specified list is empty, os.path.commonprefix() method will return a empty string. Reference: https://docs.python.org/3/library/os.path.html python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2019" }, { "code": null, "e": 338, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used for common path name manipulation." }, { "code": null, "e": 682, "s": 338, "text": "os.path.commonprefix() method in Python is used to get longest common path prefix in a list of paths. This method returns only common prefix value in the specified list, returned value may or may not be a valid path as it check for common prefix by comparing character by character in the list.For example consider the following list of paths:" }, { "code": null, "e": 901, "s": 682, "text": " list of paths common prefix\n['/home/User/Photos', /home/User/Videos'] /home/User/ A valid path\n['/usr/local/bin', '/usr/lib'] /usr/l Not a valid path\n" }, { "code": null, "e": 936, "s": 901, "text": "Syntax: os.path.commonprefix(list)" }, { "code": null, "e": 1055, "s": 936, "text": "Parameter:path: A list of path-like object. A path-like object is either a string or bytes object representing a path." }, { "code": null, "e": 1170, "s": 1055, "text": "Return Type: This method returns a string value which represents the longest common path prefix in specified list." }, { "code": null, "e": 1216, "s": 1170, "text": "Code #1: Use of os.path.commonprefix() method" }, { "code": "# Python program to explain os.path.commonprefix() method # importing os module import os # List of Pathspaths = ['/home/User/Desktop', '/home/User/Documents', '/home/User/Downloads'] # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths) # Print the # longest common path prefix# in the specified list print(\"Longest common path prefix:\", prefix) # List of Pathspaths = ['/usr/local/bin', '/usr/bin'] # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths) # Print the # longest common path prefix# in the specified list print(\"Longest common path prefix:\", prefix)", "e": 1895, "s": 1216, "text": null }, { "code": null, "e": 1971, "s": 1895, "text": "Longest common path prefix: /home/User/D\nLongest common path prefix: /usr/\n" }, { "code": null, "e": 2067, "s": 1971, "text": "Note: If the specified list is empty, os.path.commonprefix() method will return a empty string." }, { "code": null, "e": 2125, "s": 2067, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 2142, "s": 2125, "text": "python-os-module" }, { "code": null, "e": 2149, "s": 2142, "text": "Python" } ]
Equilibrium index of an array
11 Jun, 2022 Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A: Example : Input: A[] = {-7, 1, 5, 2, -4, 3, 0} Output: 3 3 is an equilibrium index, because: A[0] + A[1] + A[2] = A[4] + A[5] + A[6] Input: A[] = {1, 2, 3} Output: -1 Write a function int equilibrium(int[] arr, int n); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist. 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. Method 1 (Simple but inefficient) Use two loops. Outer loop iterates through all the element and inner loop finds out whether the current index picked by the outer loop is equilibrium index or not. Time complexity of this solution is O(n^2). C++ C Java Python3 C# PHP Javascript // C++ program to find equilibrium// index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int arr[], int n){ int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << equilibrium(arr, arr_size); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku) // C program to find equilibrium// index of an array #include <stdio.h> int equilibrium(int arr[], int n){ int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf("%d", equilibrium(arr, arr_size)); getchar(); return 0;} // Java program to find equilibrium// index of an array class EquilibriumIndex { int equilibrium(int arr[], int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // Driver code public static void main(String[] args) { EquilibriumIndex equi = new EquilibriumIndex(); int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println(equi.equilibrium(arr, arr_size)); }} // This code has been contributed by Mayank Jaiswal # Python program to find equilibrium# index of an array # function to find the equilibrium indexdef equilibrium(arr): leftsum = 0 rightsum = 0 n = len(arr) # Check for indexes one by one # until an equilibrium index is found for i in range(n): leftsum = 0 rightsum = 0 # get left sum for j in range(i): leftsum += arr[j] # get right sum for j in range(i + 1, n): rightsum += arr[j] # if leftsum and rightsum are same, # then we are done if leftsum == rightsum: return i # return -1 if no equilibrium index is found return -1 # driver codearr = [-7, 1, 5, 2, -4, 3, 0]print (equilibrium(arr)) # This code is contributed by Abhishek Sharama // C# program to find equilibrium// index of an array using System; class GFG { static int equilibrium(int[] arr, int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { // initialize left sum // for current index i leftsum = 0; // initialize right sum // for current index i rightsum = 0; /* get left sum */ for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // driver code public static void Main() { int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.Write(equilibrium(arr, arr_size)); }} // This code is contributed by Sam007 <?php// PHP program to find equilibrium// index of an array function equilibrium($arr, $n){ $i; $j; $leftsum; $rightsum; /* Check for indexes one by one until an equilibrium index is found */ for ($i = 0; $i < $n; ++$i) { /* get left sum */ $leftsum = 0; for ($j = 0; $j < $i; $j++) $leftsum += $arr[$j]; /* get right sum */ $rightsum = 0; for ($j = $i + 1; $j < $n; $j++) $rightsum += $arr[$j]; /* if leftsum and rightsum are same, then we are done */ if ($leftsum == $rightsum) return $i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver code$arr = array( -7, 1, 5, 2, -4, 3, 0 );$arr_size = sizeof($arr);echo equilibrium($arr, $arr_size); // This code is contributed// by akt_mit?> <script>// JavaScript Program to find equilibrium// index of an arrayfunction equilibrium(arr, n){ var i, j; var leftsum, rightsum; /*Check for indexes one by one until an equilibrium index is found*/ for(i = 0; i < n; ++i) { /*get left sum*/ leftsum = 0; for(let j = 0; j < i; j++) leftsum += arr[j]; /*get right sum*/ rightsum = 0; for(let j = i + 1; j < n; j++) rightsum += arr[j]; /*if leftsum and rightsum are same, then we are done*/ if(leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found*/ return -1;} // Driver code var arr = new Array(-7,1,5,2,-4,3,0); n = arr.length; document.write(equilibrium(arr,n)); // This code is contributed by simranarora5sos </script> 3 Time Complexity: O(n^2) Auxiliary Space: O(1) Method 2 (Tricky and Efficient) The idea is to get the total sum of the array first. Then Iterate through the array and keep updating the left sum which is initialized as zero. In the loop, we can get the right sum by subtracting the elements one by one. Thanks to Sambasiva for suggesting this solution and providing code for this. 1) Initialize leftsum as 0 2) Get the total sum of the array as sum 3) Iterate through the array and for each index i, do following. a) Update sum to get the right sum. sum = sum - arr[i] // sum is now right sum b) If leftsum is equal to sum, then return current index. // update leftsum for next iteration. c) leftsum = leftsum + arr[i] 4) return -1 // If we come out of loop without returning then // there is no equilibrium index The image below shows the dry run of the above approach: Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ program to find equilibrium// index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int arr[], int n){ int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << "First equilibrium index is " << equilibrium(arr, arr_size); return 0;} // This is code is contributed by rathbhupendra // C program to find equilibrium// index of an array #include <stdio.h> int equilibrium(int arr[], int n){ int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf("First equilibrium index is %d", equilibrium(arr, arr_size)); getchar(); return 0;} // Java program to find equilibrium// index of an array class EquilibriumIndex { int equilibrium(int arr[], int n) { int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code public static void main(String[] args) { EquilibriumIndex equi = new EquilibriumIndex(); int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println("First equilibrium index is " + equi.equilibrium(arr, arr_size)); }} // This code has been contributed by Mayank Jaiswal # Python program to find the equilibrium# index of an array # function to find the equilibrium indexdef equilibrium(arr): # finding the sum of whole array total_sum = sum(arr) leftsum = 0 for i, num in enumerate(arr): # total_sum is now right sum # for index i total_sum -= num if leftsum == total_sum: return i leftsum += num # If no equilibrium index found, # then return -1 return -1 # Driver codearr = [-7, 1, 5, 2, -4, 3, 0]print ('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Abhishek Sharma // C# program to find the equilibrium// index of an array using System; class GFG { static int equilibrium(int[] arr, int n) { // initialize sum of whole array int sum = 0; // initialize leftsum int leftsum = 0; /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { // sum is now right sum // for index i sum -= arr[i]; if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code public static void Main() { int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.Write("First equilibrium index is " + equilibrium(arr, arr_size)); }}// This code is contributed by Sam007 <?php// PHP program to find equilibrium// index of an array function equilibrium($arr, $n){ $sum = 0; // initialize sum of // whole array $leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for ($i = 0; $i < $n; ++$i) $sum += $arr[$i]; for ($i = 0; $i < $n; ++$i) { // sum is now right sum // for index i $sum -= $arr[$i]; if ($leftsum == $sum) return $i; $leftsum += $arr[$i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver code$arr = array( -7, 1, 5, 2, -4, 3, 0 );$arr_size = sizeof($arr);echo "First equilibrium index is ", equilibrium($arr, $arr_size); // This code is contributed by ajit?> <script>// program to find equilibrium// index of an array function equilibrium(arr, n){ sum = 0; // initialize sum of whole array leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (let i = 0; i < n; ++i) sum += arr[i]; for (let i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver code arr =new Array(-7, 1, 5, 2, -4, 3, 0);n=arr.length;document.write("First equilibrium index is " + equilibrium(arr, n)); // This code is contributed by simranarora5sos</script> First equilibrium index is 3 Time Complexity: O(n) Auxiliary Space: O(1) Method 3 : This is a quite simple and straightforward method. The idea is to take the prefix sum of the array twice. Once from the front end of array and another from the back end of array. After taking both prefix sums run a loop and check for some i if both the prefix sum from one array is equal to prefix sum from the second array then that point can be considered as the Equilibrium point. C++ Java Python3 C# Javascript // C++ program to find equilibrium index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int a[], int n){ if (n == 1) return (0); int forward[n] = { 0 }; int rev[n] = { 0 }; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (int i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "First Point of equilibrium is at index " << equilibrium(arr, n) << "\n"; return 0;} // Java program to find equilibrium// index of an arrayclass GFG{ static int equilibrium(int a[], int n){ if (n == 1) return (0); int[] front = new int[n]; int[] back = new int[n]; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i != 0) { front[i] = front[i - 1] + a[i]; } else { front[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { back[i] = back[i + 1] + a[i]; } else { back[i] = a[i]; } } // Checking for equilibrium index by //comparing front and back sums for(int i = 0; i < n; i++) { if (front[i] == back[i]) { return i; } } // If no equilibrium index found,then return -1 return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println("First Point of equilibrium " + "is at index " + equilibrium(arr, arr_size));}} // This code is contributed by Lovish Aggarwal # Python program to find the equilibrium# index of an array # Function to find the equilibrium indexdef equilibrium(arr): left_sum = [] right_sum = [] # Iterate from 0 to len(arr) for i in range(len(arr)): # If i is not 0 if(i): left_sum.append(left_sum[i-1]+arr[i]) right_sum.append(right_sum[i-1]+arr[len(arr)-1-i]) else: left_sum.append(arr[i]) right_sum.append(arr[len(arr)-1]) # Iterate from 0 to len(arr) for i in range(len(arr)): if(left_sum[i] == right_sum[len(arr) - 1 - i ]): return(i) # If no equilibrium index found,then return -1 return -1 # Driver codearr = [-7, 1, 5, 2, -4, 3, 0]print('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Lokesh Sharma // C# program to find equilibrium// index of an arrayusing System; class GFG{ static int equilibrium(int[] a, int n){ if (n == 1) return (0); int[] front = new int[n]; int[] back = new int[n]; // Taking the prefixsum from front end array for(int i = 0; i < n; i++) { if (i != 0) { front[i] = front[i - 1] + a[i]; } else { front[i] = a[i]; } } // Taking the prefixsum from back end of array for(int i = n - 1; i > 0; i--) { if (i <= n - 2) { back[i] = back[i + 1] + a[i]; } else { back[i] = a[i]; } } // Checking for equilibrium index by // comparing front and back sums for(int i = 0; i < n; i++) { if (front[i] == back[i]) { return i; } } // If no equilibrium index found,then return -1 return -1;} // Driver codepublic static void Main(string[] args){ int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.WriteLine("First Point of equilibrium " + "is at index " + equilibrium(arr, arr_size));}} // This code is contributed by ukasp <script>// Program to find equilibrium index of an array function equilibrium(a, n){ if (n == 1) return (0); var forward = new Array(0); var rev = new Array(0); // Taking the prefixsum from front end array for (let i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (let i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (let i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector} // Driver code arr = new Array(-7, 1, 5, 2, -4, 3, 0); n = arr.length; document.write("First Point of equilibrium is at index " + equilibrium(arr, n) + "\n"); // This code is contributed by simranarora5sos</script> First Point of equilibrium is at index 3 Time Complexity: O(n) Auxiliary Space : O(n) Method 4:– Using binary search To handle all the testcase, we can use binary search algorithm. 1.calculate the mid and then create left sum and right sum around mid 2.if left sum is greater than right sum, move to left until it become equal or less than right sum 3. else if right sum is greater than left, move right until it become equal or less than left sum. 4. finally we compare two sums if they are equal we got mid as index else its -1 C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; void find(int arr[], int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { cout <<"First Point of equilibrium is at index ="<< mid << endl; return; } cout <<"First Point of equilibrium is at index ="<< -1 << endl;}int main(){ int arr[] = { 1,1,1,-1,1,1,1 }; int n = sizeof(arr) / sizeof(arr[0]); find(arr, n);} // Java program for the above approachimport java.io.*;import java.util.*; class GFG{ static void find(int arr[], int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { System.out.print("First Point of equilibrium is at index ="+ mid); return; } System.out.print("First Point of equilibrium is at index =" + -1);} // Driver codepublic static void main(String args[]){ int arr[] = { 1,1,1,-1,1,1,1 }; int n = arr.length; find(arr, n);}} # Python program for the above approachdef find(arr, n): mid = n // 2; leftSum = 0; rightSum = 0; # calculation sum to left of mid for i in range(mid): leftSum += arr[i]; # calculating sum to right of mid for i in range(n - 1, mid, -1): rightSum += arr[i]; # if rightsum > leftsum if (rightSum > leftSum): # we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum and mid < n - 1): rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid += 1; else: # we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum and mid > 0): rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid -= 1; # check if both sum become equal if (rightSum == leftSum): print("First Point of equilibrium is at index =" , mid); return; print("First Point of equilibrium is at index =" , -1); # Driver codeif __name__ == '__main__': arr = [ 1, 1, 1, -1, 1, 1, 1 ]; n = len(arr); find(arr, n); # This code is contributed by gauravrajput1 // C# program for the above approachusing System;using System.Collections.Generic;using System.Linq; public class GFG { static void find(int[] arr, int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { Console.Write("First Point of equilibrium is at index ="+ mid); return; } Console.Write("First Point of equilibrium is at index =" + -1);} // Driver Codepublic static void Main (string[] args) { int[] arr = { 1,1,1,-1,1,1,1 }; int n = arr.Length; find(arr, n);}} // This code is contributed by code_hunt. <script>// javascript program for the above approach function find(arr , n) { var mid = parseInt(n / 2); var leftSum = 0, rightSum = 0; // calculation sum to left of mid for (i = 0; i < mid; i++) { leftSum += arr[i]; } // calculating sum to right of mid for (i = n - 1; i > mid; i--) { rightSum += arr[i]; } // if rightsum > leftsum if (rightSum > leftSum) { // we keep moving right until rightSum // become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { // we keep moving right until leftSum // become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } // check if both sum become equal if (rightSum == leftSum) { document.write("First Point of equilibrium is at index =" + mid); return; } document.write("First Point of equilibrium is at index =" + -1); } // Driver code var arr = [ 1, 1, 1, -1, 1, 1, 1 ]; var n = arr.length; find(arr, n); // This code is contributed by gauravrajput1</script> First Point of equilibrium is at index =3 Time Complexity: O(n) Auxiliary Space: O(1) As pointed out by Sameer, we can remove the return statement and add a print statement to print all equilibrium indexes instead of returning only one. YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=W-t1rjLxvQw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem. onlycodes jit_t Akanksha_Rai rathbhupendra nidhi_biet believer411 luckysharmazm lovishagg simranarora5sos ukasp 100rahulsingh100 sweetyty CoderSaty splevel62 code_hunt GauravRajput1 as5853535 adnanirshad158 sachinvinod1904 Adobe Amazon Hike prefix-sum Arrays Amazon Hike Adobe prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jun, 2022" }, { "code": null, "e": 221, "s": 52, "text": "Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A: " }, { "code": null, "e": 232, "s": 221, "text": "Example : " }, { "code": null, "e": 355, "s": 232, "text": "Input: A[] = {-7, 1, 5, 2, -4, 3, 0} Output: 3 3 is an equilibrium index, because: A[0] + A[1] + A[2] = A[4] + A[5] + A[6]" }, { "code": null, "e": 390, "s": 355, "text": "Input: A[] = {1, 2, 3} Output: -1 " }, { "code": null, "e": 559, "s": 390, "text": "Write a function int equilibrium(int[] arr, int n); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist. " }, { "code": null, "e": 568, "s": 559, "text": "Chapters" }, { "code": null, "e": 595, "s": 568, "text": "descriptions off, selected" }, { "code": null, "e": 645, "s": 595, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 668, "s": 645, "text": "captions off, selected" }, { "code": null, "e": 676, "s": 668, "text": "English" }, { "code": null, "e": 700, "s": 676, "text": "This is a modal window." }, { "code": null, "e": 769, "s": 700, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 791, "s": 769, "text": "End of dialog window." }, { "code": null, "e": 1034, "s": 791, "text": "Method 1 (Simple but inefficient) Use two loops. Outer loop iterates through all the element and inner loop finds out whether the current index picked by the outer loop is equilibrium index or not. Time complexity of this solution is O(n^2). " }, { "code": null, "e": 1038, "s": 1034, "text": "C++" }, { "code": null, "e": 1040, "s": 1038, "text": "C" }, { "code": null, "e": 1045, "s": 1040, "text": "Java" }, { "code": null, "e": 1053, "s": 1045, "text": "Python3" }, { "code": null, "e": 1056, "s": 1053, "text": "C#" }, { "code": null, "e": 1060, "s": 1056, "text": "PHP" }, { "code": null, "e": 1071, "s": 1060, "text": "Javascript" }, { "code": "// C++ program to find equilibrium// index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int arr[], int n){ int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << equilibrium(arr, arr_size); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 2009, "s": 1071, "text": null }, { "code": "// C program to find equilibrium// index of an array #include <stdio.h> int equilibrium(int arr[], int n){ int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", equilibrium(arr, arr_size)); getchar(); return 0;}", "e": 2884, "s": 2009, "text": null }, { "code": "// Java program to find equilibrium// index of an array class EquilibriumIndex { int equilibrium(int arr[], int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // Driver code public static void main(String[] args) { EquilibriumIndex equi = new EquilibriumIndex(); int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println(equi.equilibrium(arr, arr_size)); }} // This code has been contributed by Mayank Jaiswal", "e": 3983, "s": 2884, "text": null }, { "code": "# Python program to find equilibrium# index of an array # function to find the equilibrium indexdef equilibrium(arr): leftsum = 0 rightsum = 0 n = len(arr) # Check for indexes one by one # until an equilibrium index is found for i in range(n): leftsum = 0 rightsum = 0 # get left sum for j in range(i): leftsum += arr[j] # get right sum for j in range(i + 1, n): rightsum += arr[j] # if leftsum and rightsum are same, # then we are done if leftsum == rightsum: return i # return -1 if no equilibrium index is found return -1 # driver codearr = [-7, 1, 5, 2, -4, 3, 0]print (equilibrium(arr)) # This code is contributed by Abhishek Sharama", "e": 4783, "s": 3983, "text": null }, { "code": "// C# program to find equilibrium// index of an array using System; class GFG { static int equilibrium(int[] arr, int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { // initialize left sum // for current index i leftsum = 0; // initialize right sum // for current index i rightsum = 0; /* get left sum */ for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // driver code public static void Main() { int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.Write(equilibrium(arr, arr_size)); }} // This code is contributed by Sam007", "e": 5947, "s": 4783, "text": null }, { "code": "<?php// PHP program to find equilibrium// index of an array function equilibrium($arr, $n){ $i; $j; $leftsum; $rightsum; /* Check for indexes one by one until an equilibrium index is found */ for ($i = 0; $i < $n; ++$i) { /* get left sum */ $leftsum = 0; for ($j = 0; $j < $i; $j++) $leftsum += $arr[$j]; /* get right sum */ $rightsum = 0; for ($j = $i + 1; $j < $n; $j++) $rightsum += $arr[$j]; /* if leftsum and rightsum are same, then we are done */ if ($leftsum == $rightsum) return $i; } /* return -1 if no equilibrium index is found */ return -1;} // Driver code$arr = array( -7, 1, 5, 2, -4, 3, 0 );$arr_size = sizeof($arr);echo equilibrium($arr, $arr_size); // This code is contributed// by akt_mit?>", "e": 6797, "s": 5947, "text": null }, { "code": "<script>// JavaScript Program to find equilibrium// index of an arrayfunction equilibrium(arr, n){ var i, j; var leftsum, rightsum; /*Check for indexes one by one until an equilibrium index is found*/ for(i = 0; i < n; ++i) { /*get left sum*/ leftsum = 0; for(let j = 0; j < i; j++) leftsum += arr[j]; /*get right sum*/ rightsum = 0; for(let j = i + 1; j < n; j++) rightsum += arr[j]; /*if leftsum and rightsum are same, then we are done*/ if(leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found*/ return -1;} // Driver code var arr = new Array(-7,1,5,2,-4,3,0); n = arr.length; document.write(equilibrium(arr,n)); // This code is contributed by simranarora5sos </script>", "e": 7816, "s": 6797, "text": null }, { "code": null, "e": 7818, "s": 7816, "text": "3" }, { "code": null, "e": 7842, "s": 7818, "text": "Time Complexity: O(n^2)" }, { "code": null, "e": 7864, "s": 7842, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 8197, "s": 7864, "text": "Method 2 (Tricky and Efficient) The idea is to get the total sum of the array first. Then Iterate through the array and keep updating the left sum which is initialized as zero. In the loop, we can get the right sum by subtracting the elements one by one. Thanks to Sambasiva for suggesting this solution and providing code for this." }, { "code": null, "e": 8674, "s": 8197, "text": "1) Initialize leftsum as 0\n2) Get the total sum of the array as sum\n3) Iterate through the array and for each index i, do following.\n a) Update sum to get the right sum. \n sum = sum - arr[i] \n // sum is now right sum\n b) If leftsum is equal to sum, then return current index. \n // update leftsum for next iteration.\n c) leftsum = leftsum + arr[i]\n4) return -1 \n// If we come out of loop without returning then\n// there is no equilibrium index" }, { "code": null, "e": 8732, "s": 8674, "text": "The image below shows the dry run of the above approach: " }, { "code": null, "e": 8784, "s": 8732, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 8788, "s": 8784, "text": "C++" }, { "code": null, "e": 8790, "s": 8788, "text": "C" }, { "code": null, "e": 8795, "s": 8790, "text": "Java" }, { "code": null, "e": 8803, "s": 8795, "text": "Python3" }, { "code": null, "e": 8806, "s": 8803, "text": "C#" }, { "code": null, "e": 8810, "s": 8806, "text": "PHP" }, { "code": null, "e": 8821, "s": 8810, "text": "Javascript" }, { "code": "// C++ program to find equilibrium// index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int arr[], int n){ int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); cout << \"First equilibrium index is \" << equilibrium(arr, arr_size); return 0;} // This is code is contributed by rathbhupendra", "e": 9633, "s": 8821, "text": null }, { "code": "// C program to find equilibrium// index of an array #include <stdio.h> int equilibrium(int arr[], int n){ int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf(\"First equilibrium index is %d\", equilibrium(arr, arr_size)); getchar(); return 0;}", "e": 10398, "s": 9633, "text": null }, { "code": "// Java program to find equilibrium// index of an array class EquilibriumIndex { int equilibrium(int arr[], int n) { int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code public static void main(String[] args) { EquilibriumIndex equi = new EquilibriumIndex(); int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println(\"First equilibrium index is \" + equi.equilibrium(arr, arr_size)); }} // This code has been contributed by Mayank Jaiswal", "e": 11377, "s": 10398, "text": null }, { "code": "# Python program to find the equilibrium# index of an array # function to find the equilibrium indexdef equilibrium(arr): # finding the sum of whole array total_sum = sum(arr) leftsum = 0 for i, num in enumerate(arr): # total_sum is now right sum # for index i total_sum -= num if leftsum == total_sum: return i leftsum += num # If no equilibrium index found, # then return -1 return -1 # Driver codearr = [-7, 1, 5, 2, -4, 3, 0]print ('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Abhishek Sharma", "e": 12014, "s": 11377, "text": null }, { "code": "// C# program to find the equilibrium// index of an array using System; class GFG { static int equilibrium(int[] arr, int n) { // initialize sum of whole array int sum = 0; // initialize leftsum int leftsum = 0; /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { // sum is now right sum // for index i sum -= arr[i]; if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code public static void Main() { int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.Write(\"First equilibrium index is \" + equilibrium(arr, arr_size)); }}// This code is contributed by Sam007", "e": 12958, "s": 12014, "text": null }, { "code": "<?php// PHP program to find equilibrium// index of an array function equilibrium($arr, $n){ $sum = 0; // initialize sum of // whole array $leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for ($i = 0; $i < $n; ++$i) $sum += $arr[$i]; for ($i = 0; $i < $n; ++$i) { // sum is now right sum // for index i $sum -= $arr[$i]; if ($leftsum == $sum) return $i; $leftsum += $arr[$i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver code$arr = array( -7, 1, 5, 2, -4, 3, 0 );$arr_size = sizeof($arr);echo \"First equilibrium index is \", equilibrium($arr, $arr_size); // This code is contributed by ajit?>", "e": 13706, "s": 12958, "text": null }, { "code": "<script>// program to find equilibrium// index of an array function equilibrium(arr, n){ sum = 0; // initialize sum of whole array leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (let i = 0; i < n; ++i) sum += arr[i]; for (let i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1;} // Driver code arr =new Array(-7, 1, 5, 2, -4, 3, 0);n=arr.length;document.write(\"First equilibrium index is \" + equilibrium(arr, n)); // This code is contributed by simranarora5sos</script>", "e": 14412, "s": 13706, "text": null }, { "code": null, "e": 14441, "s": 14412, "text": "First equilibrium index is 3" }, { "code": null, "e": 14464, "s": 14441, "text": " Time Complexity: O(n)" }, { "code": null, "e": 14486, "s": 14464, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 14497, "s": 14486, "text": "Method 3 :" }, { "code": null, "e": 14676, "s": 14497, "text": "This is a quite simple and straightforward method. The idea is to take the prefix sum of the array twice. Once from the front end of array and another from the back end of array." }, { "code": null, "e": 14881, "s": 14676, "text": "After taking both prefix sums run a loop and check for some i if both the prefix sum from one array is equal to prefix sum from the second array then that point can be considered as the Equilibrium point." }, { "code": null, "e": 14885, "s": 14881, "text": "C++" }, { "code": null, "e": 14890, "s": 14885, "text": "Java" }, { "code": null, "e": 14898, "s": 14890, "text": "Python3" }, { "code": null, "e": 14901, "s": 14898, "text": "C#" }, { "code": null, "e": 14912, "s": 14901, "text": "Javascript" }, { "code": "// C++ program to find equilibrium index of an array#include <bits/stdc++.h>using namespace std; int equilibrium(int a[], int n){ if (n == 1) return (0); int forward[n] = { 0 }; int rev[n] = { 0 }; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (int i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector} // Driver codeint main(){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"First Point of equilibrium is at index \" << equilibrium(arr, n) << \"\\n\"; return 0;}", "e": 16111, "s": 14912, "text": null }, { "code": "// Java program to find equilibrium// index of an arrayclass GFG{ static int equilibrium(int a[], int n){ if (n == 1) return (0); int[] front = new int[n]; int[] back = new int[n]; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i != 0) { front[i] = front[i - 1] + a[i]; } else { front[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { back[i] = back[i + 1] + a[i]; } else { back[i] = a[i]; } } // Checking for equilibrium index by //comparing front and back sums for(int i = 0; i < n; i++) { if (front[i] == back[i]) { return i; } } // If no equilibrium index found,then return -1 return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println(\"First Point of equilibrium \" + \"is at index \" + equilibrium(arr, arr_size));}} // This code is contributed by Lovish Aggarwal", "e": 17364, "s": 16111, "text": null }, { "code": "# Python program to find the equilibrium# index of an array # Function to find the equilibrium indexdef equilibrium(arr): left_sum = [] right_sum = [] # Iterate from 0 to len(arr) for i in range(len(arr)): # If i is not 0 if(i): left_sum.append(left_sum[i-1]+arr[i]) right_sum.append(right_sum[i-1]+arr[len(arr)-1-i]) else: left_sum.append(arr[i]) right_sum.append(arr[len(arr)-1]) # Iterate from 0 to len(arr) for i in range(len(arr)): if(left_sum[i] == right_sum[len(arr) - 1 - i ]): return(i) # If no equilibrium index found,then return -1 return -1 # Driver codearr = [-7, 1, 5, 2, -4, 3, 0]print('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Lokesh Sharma", "e": 18188, "s": 17364, "text": null }, { "code": "// C# program to find equilibrium// index of an arrayusing System; class GFG{ static int equilibrium(int[] a, int n){ if (n == 1) return (0); int[] front = new int[n]; int[] back = new int[n]; // Taking the prefixsum from front end array for(int i = 0; i < n; i++) { if (i != 0) { front[i] = front[i - 1] + a[i]; } else { front[i] = a[i]; } } // Taking the prefixsum from back end of array for(int i = n - 1; i > 0; i--) { if (i <= n - 2) { back[i] = back[i + 1] + a[i]; } else { back[i] = a[i]; } } // Checking for equilibrium index by // comparing front and back sums for(int i = 0; i < n; i++) { if (front[i] == back[i]) { return i; } } // If no equilibrium index found,then return -1 return -1;} // Driver codepublic static void Main(string[] args){ int[] arr = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.Length; Console.WriteLine(\"First Point of equilibrium \" + \"is at index \" + equilibrium(arr, arr_size));}} // This code is contributed by ukasp", "e": 19421, "s": 18188, "text": null }, { "code": "<script>// Program to find equilibrium index of an array function equilibrium(a, n){ if (n == 1) return (0); var forward = new Array(0); var rev = new Array(0); // Taking the prefixsum from front end array for (let i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (let i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (let i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector} // Driver code arr = new Array(-7, 1, 5, 2, -4, 3, 0); n = arr.length; document.write(\"First Point of equilibrium is at index \" + equilibrium(arr, n) + \"\\n\"); // This code is contributed by simranarora5sos</script>", "e": 20613, "s": 19421, "text": null }, { "code": null, "e": 20654, "s": 20613, "text": "First Point of equilibrium is at index 3" }, { "code": null, "e": 20676, "s": 20654, "text": "Time Complexity: O(n)" }, { "code": null, "e": 20699, "s": 20676, "text": "Auxiliary Space : O(n)" }, { "code": null, "e": 20730, "s": 20699, "text": "Method 4:– Using binary search" }, { "code": null, "e": 20794, "s": 20730, "text": "To handle all the testcase, we can use binary search algorithm." }, { "code": null, "e": 20864, "s": 20794, "text": "1.calculate the mid and then create left sum and right sum around mid" }, { "code": null, "e": 20963, "s": 20864, "text": "2.if left sum is greater than right sum, move to left until it become equal or less than right sum" }, { "code": null, "e": 21062, "s": 20963, "text": "3. else if right sum is greater than left, move right until it become equal or less than left sum." }, { "code": null, "e": 21143, "s": 21062, "text": "4. finally we compare two sums if they are equal we got mid as index else its -1" }, { "code": null, "e": 21147, "s": 21143, "text": "C++" }, { "code": null, "e": 21152, "s": 21147, "text": "Java" }, { "code": null, "e": 21160, "s": 21152, "text": "Python3" }, { "code": null, "e": 21163, "s": 21160, "text": "C#" }, { "code": null, "e": 21174, "s": 21163, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; void find(int arr[], int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { cout <<\"First Point of equilibrium is at index =\"<< mid << endl; return; } cout <<\"First Point of equilibrium is at index =\"<< -1 << endl;}int main(){ int arr[] = { 1,1,1,-1,1,1,1 }; int n = sizeof(arr) / sizeof(arr[0]); find(arr, n);}", "e": 22401, "s": 21174, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ static void find(int arr[], int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { System.out.print(\"First Point of equilibrium is at index =\"+ mid); return; } System.out.print(\"First Point of equilibrium is at index =\" + -1);} // Driver codepublic static void main(String args[]){ int arr[] = { 1,1,1,-1,1,1,1 }; int n = arr.length; find(arr, n);}}", "e": 23707, "s": 22401, "text": null }, { "code": "# Python program for the above approachdef find(arr, n): mid = n // 2; leftSum = 0; rightSum = 0; # calculation sum to left of mid for i in range(mid): leftSum += arr[i]; # calculating sum to right of mid for i in range(n - 1, mid, -1): rightSum += arr[i]; # if rightsum > leftsum if (rightSum > leftSum): # we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum and mid < n - 1): rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid += 1; else: # we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum and mid > 0): rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid -= 1; # check if both sum become equal if (rightSum == leftSum): print(\"First Point of equilibrium is at index =\" , mid); return; print(\"First Point of equilibrium is at index =\" , -1); # Driver codeif __name__ == '__main__': arr = [ 1, 1, 1, -1, 1, 1, 1 ]; n = len(arr); find(arr, n); # This code is contributed by gauravrajput1", "e": 24892, "s": 23707, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq; public class GFG { static void find(int[] arr, int n){ int mid = n / 2; int leftSum = 0, rightSum = 0; //calculation sum to left of mid for (int i = 0; i < mid; i++) { leftSum += arr[i]; } //calculating sum to right of mid for (int i = n - 1; i > mid; i--) { rightSum += arr[i]; } //if rightsum > leftsum if (rightSum > leftSum) { //we keep moving right until rightSum become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { //we keep moving right until leftSum become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } //check if both sum become equal if (rightSum == leftSum) { Console.Write(\"First Point of equilibrium is at index =\"+ mid); return; } Console.Write(\"First Point of equilibrium is at index =\" + -1);} // Driver Codepublic static void Main (string[] args) { int[] arr = { 1,1,1,-1,1,1,1 }; int n = arr.Length; find(arr, n);}} // This code is contributed by code_hunt.", "e": 26280, "s": 24892, "text": null }, { "code": "<script>// javascript program for the above approach function find(arr , n) { var mid = parseInt(n / 2); var leftSum = 0, rightSum = 0; // calculation sum to left of mid for (i = 0; i < mid; i++) { leftSum += arr[i]; } // calculating sum to right of mid for (i = n - 1; i > mid; i--) { rightSum += arr[i]; } // if rightsum > leftsum if (rightSum > leftSum) { // we keep moving right until rightSum // become equal or less than leftSum while (rightSum > leftSum && mid < n - 1) { rightSum -= arr[mid + 1]; leftSum += arr[mid]; mid++; } } else { // we keep moving right until leftSum // become equal or less than RightSum while (leftSum > rightSum && mid > 0) { rightSum += arr[mid]; leftSum -= arr[mid - 1]; mid--; } } // check if both sum become equal if (rightSum == leftSum) { document.write(\"First Point of equilibrium is at index =\" + mid); return; } document.write(\"First Point of equilibrium is at index =\" + -1); } // Driver code var arr = [ 1, 1, 1, -1, 1, 1, 1 ]; var n = arr.length; find(arr, n); // This code is contributed by gauravrajput1</script>", "e": 27748, "s": 26280, "text": null }, { "code": null, "e": 27790, "s": 27748, "text": "First Point of equilibrium is at index =3" }, { "code": null, "e": 27812, "s": 27790, "text": "Time Complexity: O(n)" }, { "code": null, "e": 27835, "s": 27812, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 27987, "s": 27835, "text": "As pointed out by Sameer, we can remove the return statement and add a print statement to print all equilibrium indexes instead of returning only one. " }, { "code": null, "e": 28281, "s": 27989, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=W-t1rjLxvQw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 28402, "s": 28283, "text": "Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 28414, "s": 28404, "text": "onlycodes" }, { "code": null, "e": 28420, "s": 28414, "text": "jit_t" }, { "code": null, "e": 28433, "s": 28420, "text": "Akanksha_Rai" }, { "code": null, "e": 28447, "s": 28433, "text": "rathbhupendra" }, { "code": null, "e": 28458, "s": 28447, "text": "nidhi_biet" }, { "code": null, "e": 28470, "s": 28458, "text": "believer411" }, { "code": null, "e": 28484, "s": 28470, "text": "luckysharmazm" }, { "code": null, "e": 28494, "s": 28484, "text": "lovishagg" }, { "code": null, "e": 28510, "s": 28494, "text": "simranarora5sos" }, { "code": null, "e": 28516, "s": 28510, "text": "ukasp" }, { "code": null, "e": 28533, "s": 28516, "text": "100rahulsingh100" }, { "code": null, "e": 28542, "s": 28533, "text": "sweetyty" }, { "code": null, "e": 28552, "s": 28542, "text": "CoderSaty" }, { "code": null, "e": 28562, "s": 28552, "text": "splevel62" }, { "code": null, "e": 28572, "s": 28562, "text": "code_hunt" }, { "code": null, "e": 28586, "s": 28572, "text": "GauravRajput1" }, { "code": null, "e": 28596, "s": 28586, "text": "as5853535" }, { "code": null, "e": 28611, "s": 28596, "text": "adnanirshad158" }, { "code": null, "e": 28627, "s": 28611, "text": "sachinvinod1904" }, { "code": null, "e": 28633, "s": 28627, "text": "Adobe" }, { "code": null, "e": 28640, "s": 28633, "text": "Amazon" }, { "code": null, "e": 28645, "s": 28640, "text": "Hike" }, { "code": null, "e": 28656, "s": 28645, "text": "prefix-sum" }, { "code": null, "e": 28663, "s": 28656, "text": "Arrays" }, { "code": null, "e": 28670, "s": 28663, "text": "Amazon" }, { "code": null, "e": 28675, "s": 28670, "text": "Hike" }, { "code": null, "e": 28681, "s": 28675, "text": "Adobe" }, { "code": null, "e": 28692, "s": 28681, "text": "prefix-sum" }, { "code": null, "e": 28699, "s": 28692, "text": "Arrays" }, { "code": null, "e": 28797, "s": 28699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28812, "s": 28797, "text": "Arrays in Java" }, { "code": null, "e": 28858, "s": 28812, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 28926, "s": 28858, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 28970, "s": 28926, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 29002, "s": 28970, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 29018, "s": 29002, "text": "Arrays in C/C++" }, { "code": null, "e": 29050, "s": 29018, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29098, "s": 29050, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 29112, "s": 29098, "text": "Linear Search" } ]
Count smaller elements on right side using Set in C++ STL
28 Jun, 2021 Write a function to count the number of smaller elements on the right of each element in an array. Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains the count of smaller elements on right side of each element arr[i] in the array. Examples: Input : arr[] = {12, 1, 2, 3, 0, 11, 4} Output :countSmaller[] = {6, 1, 1, 1, 0, 1, 0} Input :arr[]={5, 4, 3, 2, 1} Output :countSmaller[]={4, 3, 2, 1, 0} In this post an easy implementation of https://www.geeksforgeeks.org/count-smaller-elements-on-right-side/ is discussed.Create an empty Set in C++ STL (Note that Set in C++ STL is implemented Self Balancing Binary Search Tree). Traverse the array element from i=len-1 to 0 and insert every element in a set.Find the first element that is lower than A[i] using lower_bound function.Find the distance between above found element and the beginning of the set using distance function.Store the distance in another array Lets say CountSmaller.Print that array . Traverse the array element from i=len-1 to 0 and insert every element in a set. Find the first element that is lower than A[i] using lower_bound function. Find the distance between above found element and the beginning of the set using distance function. Store the distance in another array Lets say CountSmaller. Print that array . CPP // CPP program to find count of smaller// elements on right side using set in C++// STL.#include <bits/stdc++.h>using namespace std;void countSmallerRight(int A[], int len){ set<int> s; int countSmaller[len]; for (int i = len - 1; i >= 0; i--) { s.insert(A[i]); auto it = s.lower_bound(A[i]); countSmaller[i] = distance(s.begin(), it); } for (int i = 0; i < len; i++) cout << countSmaller[i] << " ";} // Driver codeint main(){ int A[] = {12, 1, 2, 3, 0, 11, 4}; int len = sizeof(A) / sizeof(int); countSmallerRight(A, len); return 0;} 6 1 1 1 0 1 0 Note that the above implementation takes worst-case time complexity O(n^2) as the worst case time complexity of distance function is O(n) but the above implementation is very simple and works better than the naive algorithm in the average case.Above approach works for unique elements but for duplicate elements just replace Set with Multiset. Efficient Approach: Using policy based data structures in C++ STL. Maintain a policy-based data structure of pairs just to resolve duplicate issues. We will travel the array from the end and every time we find the order_of_key of the current element to find the number of smaller elements to the right of it. Then we will insert the current element into our policy-based data structure. Below is the implementation of the above approach: C++ // C++ implementation of the above approach#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>#define pbds \ tree<pair<int, int>, null_type, less<pair<int, int> >, \ rb_tree_tag, tree_order_statistics_node_update>using namespace __gnu_pbds;using namespace std; // Function to find number of smaller elements// to the right of every elementvoid countSmallerRight(int arr[], int n){ pbds s; // stores the answer vector<int> ans; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) { // for the last element answer is // zero ans.push_back(0); } else { // insert number of the smaller elements // to the right of current element into the ans ans.push_back(s.order_of_key({ arr[i], i })); } // insert current element s.insert({ arr[i], i }); } reverse(ans.begin(), ans.end()); for (auto x : ans) cout << x << " ";} // Driver Codeint main(){ int n = 7; int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; countSmallerRight(arr, n); return 0;} 6 1 1 1 0 1 0 Time Complexity: O(N*LogN) yc98 pawanharwani11 cpp-set STL Arrays Arrays STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 370, "s": 52, "text": "Write a function to count the number of smaller elements on the right of each element in an array. Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains the count of smaller elements on right side of each element arr[i] in the array. Examples: " }, { "code": null, "e": 530, "s": 370, "text": "Input : arr[] = {12, 1, 2, 3, 0, 11, 4}\nOutput :countSmaller[] = {6, 1, 1, 1, 0, 1, 0} \n\nInput :arr[]={5, 4, 3, 2, 1}\nOutput :countSmaller[]={4, 3, 2, 1, 0}" }, { "code": null, "e": 762, "s": 532, "text": "In this post an easy implementation of https://www.geeksforgeeks.org/count-smaller-elements-on-right-side/ is discussed.Create an empty Set in C++ STL (Note that Set in C++ STL is implemented Self Balancing Binary Search Tree). " }, { "code": null, "e": 1091, "s": 762, "text": "Traverse the array element from i=len-1 to 0 and insert every element in a set.Find the first element that is lower than A[i] using lower_bound function.Find the distance between above found element and the beginning of the set using distance function.Store the distance in another array Lets say CountSmaller.Print that array ." }, { "code": null, "e": 1171, "s": 1091, "text": "Traverse the array element from i=len-1 to 0 and insert every element in a set." }, { "code": null, "e": 1246, "s": 1171, "text": "Find the first element that is lower than A[i] using lower_bound function." }, { "code": null, "e": 1346, "s": 1246, "text": "Find the distance between above found element and the beginning of the set using distance function." }, { "code": null, "e": 1405, "s": 1346, "text": "Store the distance in another array Lets say CountSmaller." }, { "code": null, "e": 1424, "s": 1405, "text": "Print that array ." }, { "code": null, "e": 1428, "s": 1424, "text": "CPP" }, { "code": "// CPP program to find count of smaller// elements on right side using set in C++// STL.#include <bits/stdc++.h>using namespace std;void countSmallerRight(int A[], int len){ set<int> s; int countSmaller[len]; for (int i = len - 1; i >= 0; i--) { s.insert(A[i]); auto it = s.lower_bound(A[i]); countSmaller[i] = distance(s.begin(), it); } for (int i = 0; i < len; i++) cout << countSmaller[i] << \" \";} // Driver codeint main(){ int A[] = {12, 1, 2, 3, 0, 11, 4}; int len = sizeof(A) / sizeof(int); countSmallerRight(A, len); return 0;}", "e": 2019, "s": 1428, "text": null }, { "code": null, "e": 2034, "s": 2019, "text": "6 1 1 1 0 1 0 " }, { "code": null, "e": 2378, "s": 2034, "text": "Note that the above implementation takes worst-case time complexity O(n^2) as the worst case time complexity of distance function is O(n) but the above implementation is very simple and works better than the naive algorithm in the average case.Above approach works for unique elements but for duplicate elements just replace Set with Multiset." }, { "code": null, "e": 2445, "s": 2378, "text": "Efficient Approach: Using policy based data structures in C++ STL." }, { "code": null, "e": 2527, "s": 2445, "text": "Maintain a policy-based data structure of pairs just to resolve duplicate issues." }, { "code": null, "e": 2687, "s": 2527, "text": "We will travel the array from the end and every time we find the order_of_key of the current element to find the number of smaller elements to the right of it." }, { "code": null, "e": 2767, "s": 2687, "text": "Then we will insert the current element into our policy-based data structure. " }, { "code": null, "e": 2818, "s": 2767, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2822, "s": 2818, "text": "C++" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>#define pbds \\ tree<pair<int, int>, null_type, less<pair<int, int> >, \\ rb_tree_tag, tree_order_statistics_node_update>using namespace __gnu_pbds;using namespace std; // Function to find number of smaller elements// to the right of every elementvoid countSmallerRight(int arr[], int n){ pbds s; // stores the answer vector<int> ans; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) { // for the last element answer is // zero ans.push_back(0); } else { // insert number of the smaller elements // to the right of current element into the ans ans.push_back(s.order_of_key({ arr[i], i })); } // insert current element s.insert({ arr[i], i }); } reverse(ans.begin(), ans.end()); for (auto x : ans) cout << x << \" \";} // Driver Codeint main(){ int n = 7; int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; countSmallerRight(arr, n); return 0;}", "e": 3993, "s": 2822, "text": null }, { "code": null, "e": 4008, "s": 3993, "text": "6 1 1 1 0 1 0 " }, { "code": null, "e": 4035, "s": 4008, "text": "Time Complexity: O(N*LogN)" }, { "code": null, "e": 4040, "s": 4035, "text": "yc98" }, { "code": null, "e": 4055, "s": 4040, "text": "pawanharwani11" }, { "code": null, "e": 4063, "s": 4055, "text": "cpp-set" }, { "code": null, "e": 4067, "s": 4063, "text": "STL" }, { "code": null, "e": 4074, "s": 4067, "text": "Arrays" }, { "code": null, "e": 4081, "s": 4074, "text": "Arrays" }, { "code": null, "e": 4085, "s": 4081, "text": "STL" } ]
Introduction to Pafy Module in Python
06 Aug, 2021 In this article we will learn about the pafy module. Pafy is a Python library to download YouTube content and retrieve metadata. Below are the list of features Pafy offers1. Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords 2. Download video or audio at requested resolution / bitrate / format / filesize 2. Command line tool (ytdl) for downloading directly from the command line 3. Retrieve the URL to stream the video in a player such as vlc or mplayer 4. Works with age-restricted videos and non-embeddable videos 5. Small, standalone, single importable module file 6. Select highest quality stream for download or streaming 7. Download video only (no audio) in m4v or webm format 8. Download audio only (no video) in ogg or m4a format 9. Retrieve playlists and playlist metadata 10. Works with Python 2.6+ and 3.3+ Installation In order to install pafy we use the command given below pip install pafy Note : Pafy is optionally depends on youtube-dl so therefore for more stable usage it is recommended to install youtube-dl before installing pafy. Below is the command to install youtube-dl pip install youtube_dl Example 1: Program to get the number of views on a video Python3 # importing pafyimport pafy # url of videourl = "https://www.youtube.com / watch?v = mmjDZGSr7EA" # instant createdvideo = pafy.new(url) # getting number of likescount = video.viewcount # showing likesprint("View Count : " + str(count)) Output : View Count : 287205 Example 2: Program to get the thumb image of a video Python3 # importing pafyimport pafy # url of videourl = "https://www.youtube.com / watch?v = mmjDZGSr7EA" # instant createdvideo = pafy.new(url) # getting thumb imagecount = video.thumb # showing likesprint("Thumb Image : " + str(count)) Output : Thumb Image : http://i.ytimg.com/vi/vG2PNdI8axo/default.jpg Example 3: Program to get the title of a video Python3 # importing pafyimport pafy # url of videourl = "https://www.youtube.com / watch?v = vG2PNdI8axo" # instant createdvideo = pafy.new(url) # getting titlevalue = video.title # showing likesprint("Title : " + str(value)) Output : Title : DSA Self Paced Course | GeeksforGeeks ruhelaa48 Python-Pafy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2021" }, { "code": null, "e": 158, "s": 28, "text": "In this article we will learn about the pafy module. Pafy is a Python library to download YouTube content and retrieve metadata. " }, { "code": null, "e": 882, "s": 158, "text": "Below are the list of features Pafy offers1. Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords 2. Download video or audio at requested resolution / bitrate / format / filesize 2. Command line tool (ytdl) for downloading directly from the command line 3. Retrieve the URL to stream the video in a player such as vlc or mplayer 4. Works with age-restricted videos and non-embeddable videos 5. Small, standalone, single importable module file 6. Select highest quality stream for download or streaming 7. Download video only (no audio) in m4v or webm format 8. Download audio only (no video) in ogg or m4a format 9. Retrieve playlists and playlist metadata 10. Works with Python 2.6+ and 3.3+ " }, { "code": null, "e": 952, "s": 882, "text": "Installation In order to install pafy we use the command given below " }, { "code": null, "e": 969, "s": 952, "text": "pip install pafy" }, { "code": null, "e": 1160, "s": 969, "text": "Note : Pafy is optionally depends on youtube-dl so therefore for more stable usage it is recommended to install youtube-dl before installing pafy. Below is the command to install youtube-dl " }, { "code": null, "e": 1183, "s": 1160, "text": "pip install youtube_dl" }, { "code": null, "e": 1241, "s": 1183, "text": "Example 1: Program to get the number of views on a video " }, { "code": null, "e": 1249, "s": 1241, "text": "Python3" }, { "code": "# importing pafyimport pafy # url of videourl = \"https://www.youtube.com / watch?v = mmjDZGSr7EA\" # instant createdvideo = pafy.new(url) # getting number of likescount = video.viewcount # showing likesprint(\"View Count : \" + str(count))", "e": 1490, "s": 1249, "text": null }, { "code": null, "e": 1500, "s": 1490, "text": "Output : " }, { "code": null, "e": 1520, "s": 1500, "text": "View Count : 287205" }, { "code": null, "e": 1574, "s": 1520, "text": "Example 2: Program to get the thumb image of a video " }, { "code": null, "e": 1582, "s": 1574, "text": "Python3" }, { "code": "# importing pafyimport pafy # url of videourl = \"https://www.youtube.com / watch?v = mmjDZGSr7EA\" # instant createdvideo = pafy.new(url) # getting thumb imagecount = video.thumb # showing likesprint(\"Thumb Image : \" + str(count))", "e": 1816, "s": 1582, "text": null }, { "code": null, "e": 1826, "s": 1816, "text": "Output : " }, { "code": null, "e": 1886, "s": 1826, "text": "Thumb Image : http://i.ytimg.com/vi/vG2PNdI8axo/default.jpg" }, { "code": null, "e": 1934, "s": 1886, "text": "Example 3: Program to get the title of a video " }, { "code": null, "e": 1942, "s": 1934, "text": "Python3" }, { "code": "# importing pafyimport pafy # url of videourl = \"https://www.youtube.com / watch?v = vG2PNdI8axo\" # instant createdvideo = pafy.new(url) # getting titlevalue = video.title # showing likesprint(\"Title : \" + str(value))", "e": 2164, "s": 1942, "text": null }, { "code": null, "e": 2174, "s": 2164, "text": "Output : " }, { "code": null, "e": 2220, "s": 2174, "text": "Title : DSA Self Paced Course | GeeksforGeeks" }, { "code": null, "e": 2232, "s": 2222, "text": "ruhelaa48" }, { "code": null, "e": 2244, "s": 2232, "text": "Python-Pafy" }, { "code": null, "e": 2251, "s": 2244, "text": "Python" } ]
How to call JavaScript function in HTML ?
06 Jun, 2022 In this article, we will see how to call JavaScript function in HTML with two approaches that are discussed below. Approach 1: First, take a button by the input tag. After clicking the button, you can see a dialog box that pops up on the screen that has already been declared in the JavaScript function as an alert. The clickEvent() function allows executing the alert() when this button gets clicked by using onclick() method. Example: HTML <!DOCTYPE html><html> <body> <input type="button" onclick="clickEvent();" value="button" /> <script> function clickEvent() { alert("Who!! You have discovered"); } </script></body> </html> Output: Approach 2: By using the display() method in JavaScript, you can see the output GeeksForGeeks in the h1 tag. Example: HTML <!DOCTYPE html><html> <head> <title>Call JavaScript function in HTML</title></head> <body> <script> function display() { document.write("<h1>GeeksForGeeks</h1>"); } display(); </script></body> </html> Output: h1 tag sumitgumber28 HTML-Questions JavaScript-Methods JavaScript-Questions Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2022" }, { "code": null, "e": 143, "s": 28, "text": "In this article, we will see how to call JavaScript function in HTML with two approaches that are discussed below." }, { "code": null, "e": 456, "s": 143, "text": "Approach 1: First, take a button by the input tag. After clicking the button, you can see a dialog box that pops up on the screen that has already been declared in the JavaScript function as an alert. The clickEvent() function allows executing the alert() when this button gets clicked by using onclick() method." }, { "code": null, "e": 465, "s": 456, "text": "Example:" }, { "code": null, "e": 470, "s": 465, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <input type=\"button\" onclick=\"clickEvent();\" value=\"button\" /> <script> function clickEvent() { alert(\"Who!! You have discovered\"); } </script></body> </html>", "e": 699, "s": 470, "text": null }, { "code": null, "e": 707, "s": 699, "text": "Output:" }, { "code": null, "e": 816, "s": 707, "text": "Approach 2: By using the display() method in JavaScript, you can see the output GeeksForGeeks in the h1 tag." }, { "code": null, "e": 825, "s": 816, "text": "Example:" }, { "code": null, "e": 830, "s": 825, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Call JavaScript function in HTML</title></head> <body> <script> function display() { document.write(\"<h1>GeeksForGeeks</h1>\"); } display(); </script></body> </html>", "e": 1072, "s": 830, "text": null }, { "code": null, "e": 1080, "s": 1072, "text": "Output:" }, { "code": null, "e": 1087, "s": 1080, "text": "h1 tag" }, { "code": null, "e": 1101, "s": 1087, "text": "sumitgumber28" }, { "code": null, "e": 1116, "s": 1101, "text": "HTML-Questions" }, { "code": null, "e": 1135, "s": 1116, "text": "JavaScript-Methods" }, { "code": null, "e": 1156, "s": 1135, "text": "JavaScript-Questions" }, { "code": null, "e": 1163, "s": 1156, "text": "Picked" }, { "code": null, "e": 1168, "s": 1163, "text": "HTML" }, { "code": null, "e": 1179, "s": 1168, "text": "JavaScript" }, { "code": null, "e": 1196, "s": 1179, "text": "Web Technologies" }, { "code": null, "e": 1201, "s": 1196, "text": "HTML" } ]
Scraping Reddit with Python and BeautifulSoup
30 May, 2021 In this article, we are going to see how to scrape Reddit with Python and BeautifulSoup. Here we will use Beautiful Soup and the request module to scrape the data. bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Approach: Import all the required modules. Pass the URL in the getdata function(UDF) to that will request to a URL, it returns a response. We are using the GET method to retrieve information from the given server using a given URL. Syntax: requests.get(url, args) Now Parse the HTML content using bs4. Syntax: soup = BeautifulSoup(r.content, ‘html5lib’) Parameters: r.content : It is the raw HTML content. html.parser : Specifying the HTML parser we want to use. Now filter the required data using soup.Find_all function. Let’s see the stepwise execution of the script. Step 1: Import all dependence Python3 # import moduleimport requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 # user define function# Scrape the datadef getdata(url): r = requests.get(url, headers = HEADERS) return r.text Step 3: Now take the URL and pass the URL into the getdata() function and Convert that data into HTML code. Python3 url = "https://www.reddit.com/r/learnpython/comments/78qnze/web_scraping_in_20_lines_of_code_with/" # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup) Output: Note: This is only HTML code or Raw data. Now find authors with a div tag where class_ =”NAURX0ARMmhJ5eqxQrlQW”. We can open the webpage in the browser and inspect the relevant element by pressing right-click as shown in the figure. Example: Python3 # find the Html tag# with find()# and convert into stringdata_str = ""for item in soup.find_all("div", class_="NAURX0ARMmhJ5eqxQrlQW"): data_str = data_str + item.get_text() print(data_str) Output: kashaziz Now find the article text, here we will follow the same methods as the above example. Example: Python3 # find the Html tag# with find()# and convert into stringdata_str = ""result = ""for item in soup.find_all("div", class_="_3xX726aBn29LDbsDtzr_6E _1Ap4F5maDtT1E1YuCiaO0r D3IL3FD0RFy_mkKLPwL4"): data_str = data_str + item.get_text()print(data_str) Output: Now Scape the comments, here we will follow the same methods as the above example. Python3 # find the Html tag# with find()# and convert into stringdata_str = "" for item in soup.find_all("p", class_="_1qeIAgB0cPwnLhDF9XSiJM"): data_str = data_str + item.get_text()print(data_str) Output: Picked Python BeautifulSoup Python web-scraping-exercises Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2021" }, { "code": null, "e": 216, "s": 52, "text": "In this article, we are going to see how to scrape Reddit with Python and BeautifulSoup. Here we will use Beautiful Soup and the request module to scrape the data." }, { "code": null, "e": 409, "s": 216, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 425, "s": 409, "text": "pip install bs4" }, { "code": null, "e": 607, "s": 425, "text": "requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 628, "s": 607, "text": "pip install requests" }, { "code": null, "e": 638, "s": 628, "text": "Approach:" }, { "code": null, "e": 671, "s": 638, "text": "Import all the required modules." }, { "code": null, "e": 860, "s": 671, "text": "Pass the URL in the getdata function(UDF) to that will request to a URL, it returns a response. We are using the GET method to retrieve information from the given server using a given URL." }, { "code": null, "e": 892, "s": 860, "text": "Syntax: requests.get(url, args)" }, { "code": null, "e": 930, "s": 892, "text": "Now Parse the HTML content using bs4." }, { "code": null, "e": 982, "s": 930, "text": "Syntax: soup = BeautifulSoup(r.content, ‘html5lib’)" }, { "code": null, "e": 994, "s": 982, "text": "Parameters:" }, { "code": null, "e": 1034, "s": 994, "text": "r.content : It is the raw HTML content." }, { "code": null, "e": 1091, "s": 1034, "text": "html.parser : Specifying the HTML parser we want to use." }, { "code": null, "e": 1150, "s": 1091, "text": "Now filter the required data using soup.Find_all function." }, { "code": null, "e": 1198, "s": 1150, "text": "Let’s see the stepwise execution of the script." }, { "code": null, "e": 1228, "s": 1198, "text": "Step 1: Import all dependence" }, { "code": null, "e": 1236, "s": 1228, "text": "Python3" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup", "e": 1296, "s": 1236, "text": null }, { "code": null, "e": 1330, "s": 1296, "text": "Step 2: Create a URL get function" }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": "# user define function# Scrape the datadef getdata(url): r = requests.get(url, headers = HEADERS) return r.text", "e": 1456, "s": 1338, "text": null }, { "code": null, "e": 1564, "s": 1456, "text": "Step 3: Now take the URL and pass the URL into the getdata() function and Convert that data into HTML code." }, { "code": null, "e": 1572, "s": 1564, "text": "Python3" }, { "code": "url = \"https://www.reddit.com/r/learnpython/comments/78qnze/web_scraping_in_20_lines_of_code_with/\" # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup)", "e": 1813, "s": 1572, "text": null }, { "code": null, "e": 1821, "s": 1813, "text": "Output:" }, { "code": null, "e": 1863, "s": 1821, "text": "Note: This is only HTML code or Raw data." }, { "code": null, "e": 2054, "s": 1863, "text": "Now find authors with a div tag where class_ =”NAURX0ARMmhJ5eqxQrlQW”. We can open the webpage in the browser and inspect the relevant element by pressing right-click as shown in the figure." }, { "code": null, "e": 2063, "s": 2054, "text": "Example:" }, { "code": null, "e": 2071, "s": 2063, "text": "Python3" }, { "code": "# find the Html tag# with find()# and convert into stringdata_str = \"\"for item in soup.find_all(\"div\", class_=\"NAURX0ARMmhJ5eqxQrlQW\"): data_str = data_str + item.get_text() print(data_str)", "e": 2271, "s": 2071, "text": null }, { "code": null, "e": 2279, "s": 2271, "text": "Output:" }, { "code": null, "e": 2288, "s": 2279, "text": "kashaziz" }, { "code": null, "e": 2374, "s": 2288, "text": "Now find the article text, here we will follow the same methods as the above example." }, { "code": null, "e": 2383, "s": 2374, "text": "Example:" }, { "code": null, "e": 2391, "s": 2383, "text": "Python3" }, { "code": "# find the Html tag# with find()# and convert into stringdata_str = \"\"result = \"\"for item in soup.find_all(\"div\", class_=\"_3xX726aBn29LDbsDtzr_6E _1Ap4F5maDtT1E1YuCiaO0r D3IL3FD0RFy_mkKLPwL4\"): data_str = data_str + item.get_text()print(data_str)", "e": 2641, "s": 2391, "text": null }, { "code": null, "e": 2649, "s": 2641, "text": "Output:" }, { "code": null, "e": 2732, "s": 2649, "text": "Now Scape the comments, here we will follow the same methods as the above example." }, { "code": null, "e": 2740, "s": 2732, "text": "Python3" }, { "code": "# find the Html tag# with find()# and convert into stringdata_str = \"\" for item in soup.find_all(\"p\", class_=\"_1qeIAgB0cPwnLhDF9XSiJM\"): data_str = data_str + item.get_text()print(data_str)", "e": 2934, "s": 2740, "text": null }, { "code": null, "e": 2942, "s": 2934, "text": "Output:" }, { "code": null, "e": 2949, "s": 2942, "text": "Picked" }, { "code": null, "e": 2970, "s": 2949, "text": "Python BeautifulSoup" }, { "code": null, "e": 3000, "s": 2970, "text": "Python web-scraping-exercises" }, { "code": null, "e": 3016, "s": 3000, "text": "Python-requests" }, { "code": null, "e": 3023, "s": 3016, "text": "Python" } ]
HashMap in Java with Examples
08 Jul, 2022 HashMap<K, V> is a part of Java’s collection since Java 1.2. This class is found in java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer). One object is used as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass. 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. Java // Java program to illustrate HashMap class of java.util// package // Importing HashMap classimport java.util.HashMap; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Create an empty hash map by declaring object // of string and integer type HashMap<String, Integer> map = new HashMap<>(); // Adding elements to the Map // using standard put() method map.put("vishal", 10); map.put("sachin", 30); map.put("vaibhav", 20); // Print size and content of the Map System.out.println("Size of map is:- " + map.size()); // Printing elements in object of Map System.out.println(map); // Checking if a key is present and if &nbnbsp; // present, print value by passing // random element if (map.containsKey("vishal")) { // Mapping Integer a = map.get("vishal"); // Printing value fr the corresponding key System.out.println("value for key" + " \"vishal\" is:- " + a); } }} Size of map is:- 3 {vaibhav=20, vishal=10, sachin=30} value for key "vishal" is:- 10 The Hierarchy of HashMap is as follows: Syntax: Declaration public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable Parameters: It takes two parameters namely as follows: The type of keys maintained by this map The type of mapped values HashMap implements Serializable, Cloneable, Map<K, V> interfaces. HashMap extends AbstractMap<K, V> class. The direct subclasses are LinkedHashMap, PrinterStateReasons. HashMap provides 4 constructors and the access modifier of each is public which are listed as follows: HashMap()HashMap(int initialCapacity)HashMap(int initialCapacity, float loadFactor)HashMap(Map map) HashMap() HashMap(int initialCapacity) HashMap(int initialCapacity, float loadFactor) HashMap(Map map) Now discussing above constructors one by one alongside implementing the same with help of clean java programs. Constructor 1: HashMap() It is the default constructor which creates an instance of HashMap with an initial capacity of 16 and load factor of 0.75. Syntax: HashMap<K, V> hm = new HashMap<K, V>(); Example Java // Java program to Demonstrate the HashMap() constructor // Importing basic required classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass GFG { // Main driver method public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(); // Adding elements using put method // Custom input elements hm1.put(1, "one"); hm1.put(2, "two"); hm1.put(3, "three"); hm2.put(4, "four"); hm2.put(5, "five"); hm2.put(6, "six"); // Print and display mapping of HashMap 1 System.out.println("Mappings of HashMap hm1 are : " + hm1); // Print and display mapping of HashMap 2 System.out.println("Mapping of HashMap hm2 are : " + hm2); }} Mappings of HashMap hm1 are : {1=one, 2=two, 3=three} Mapping of HashMap hm2 are : {4=four, 5=five, 6=six} Constructor 2: HashMap(int initialCapacity) It creates a HashMap instance with a specified initial capacity and load factor of 0.75. Syntax: HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity); Example Java // Java program to Demonstrate// HashMap(int initialCapacity) Constructor // Importing basic classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass AddElementsToHashMap { // Main driver method public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(10); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(2); // Adding elements to object of HashMap // using put method // HashMap 1 hm1.put(1, "one"); hm1.put(2, "two"); hm1.put(3, "three"); // HashMap 2 hm2.put(4, "four"); hm2.put(5, "five"); hm2.put(6, "six"); // Printing elements of HashMap 1 System.out.println("Mappings of HashMap hm1 are : " + hm1); // Printing elements of HashMap 2 System.out.println("Mapping of HashMap hm2 are : " + hm2); }} Mappings of HashMap hm1 are : {1=one, 2=two, 3=three} Mapping of HashMap hm2 are : {4=four, 5=five, 6=six} Constructor 3: HashMap(int initialCapacity, float loadFactor) It creates a HashMap instance with a specified initial capacity and specified load factor. Syntax: HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity, int loadFactor); Example Java // Java program to Demonstrate// HashMap(int initialCapacity,float loadFactor) Constructor // Importing basic classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass GFG { // Main driver method public static void main(String args[]) { // No need to mention the generic type twice HashMap<Integer, String> hm1 = new HashMap<>(5, 0.75f); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(3, 0.5f); // Add Elements using put() method // Custom input elements hm1.put(1, "one"); hm1.put(2, "two"); hm1.put(3, "three"); hm2.put(4, "four"); hm2.put(5, "five"); hm2.put(6, "six"); // Print and display elements in object of hashMap 1 System.out.println("Mappings of HashMap hm1 are : " + hm1); // Print and display elements in object of hashMap 2 System.out.println("Mapping of HashMap hm2 are : " + hm2); }} Mappings of HashMap hm1 are : {1=one, 2=two, 3=three} Mapping of HashMap hm2 are : {4=four, 5=five, 6=six} 4. HashMap(Map map): It creates an instance of HashMap with the same mappings as the specified map. HashMap<K, V> hm = new HashMap<K, V>(Map map); Java // Java program to demonstrate the // HashMap(Map map) Constructor import java.io.*;import java.util.*; class AddElementsToHashMap { public static void main(String args[]) { // No need to mention the // Generic type twice Map<Integer, String> hm1 = new HashMap<>(); // Add Elements using put method hm1.put(1, "one"); hm1.put(2, "two"); hm1.put(3, "three"); // Initialization of a HashMap // using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(hm1); System.out.println("Mappings of HashMap hm1 are : " + hm1); System.out.println("Mapping of HashMap hm2 are : " + hm2); }} Mappings of HashMap hm1 are : {1=one, 2=two, 3=three} Mapping of HashMap hm2 are : {1=one, 2=two, 3=three} 1. Adding Elements: In order to add an element to the map, we can use the put() method. However, the insertion order is not retained in the Hashmap. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient. Java // Java program to add elements// to the HashMap import java.io.*;import java.util.*; class AddElementsToHashMap { public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(); // Initialization of a HashMap // using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(); // Add Elements using put method hm1.put(1, "Geeks"); hm1.put(2, "For"); hm1.put(3, "Geeks"); hm2.put(1, "Geeks"); hm2.put(2, "For"); hm2.put(3, "Geeks"); System.out.println("Mappings of HashMap hm1 are : " + hm1); System.out.println("Mapping of HashMap hm2 are : " + hm2); }} Mappings of HashMap hm1 are : {1=Geeks, 2=For, 3=Geeks} Mapping of HashMap hm2 are : {1=Geeks, 2=For, 3=Geeks} 2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the map are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change. Java // Java program to change// elements of HashMap import java.io.*;import java.util.*;class ChangeElementsOfHashMap { public static void main(String args[]) { // Initialization of a HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Change Value using put method hm.put(1, "Geeks"); hm.put(2, "Geeks"); hm.put(3, "Geeks"); System.out.println("Initial Map " + hm); hm.put(2, "For"); System.out.println("Updated Map " + hm); }} Initial Map {1=Geeks, 2=Geeks, 3=Geeks} Updated Map {1=Geeks, 2=For, 3=Geeks} 3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map. Java // Java program to remove// elements from HashMap import java.io.*;import java.util.*;class RemoveElementsOfHashMap{ public static void main(String args[]) { // Initialization of a HashMap Map<Integer, String> hm = new HashMap<Integer, String>(); // Add elements using put method hm.put(1, "Geeks"); hm.put(2, "For"); hm.put(3, "Geeks"); hm.put(4, "For"); // Initial HashMap System.out.println("Mappings of HashMap are : " + hm); // remove element with a key // using remove method hm.remove(4); // Final HashMap System.out.println("Mappings after removal are : " + hm); }} Mappings of HashMap are : {1=Geeks, 2=For, 3=Geeks, 4=For} Mappings after removal are : {1=Geeks, 2=For, 3=Geeks} 4. Traversal of HashMap We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the entries of HashMap. Java // Java program to traversal a// Java.util.HashMap import java.util.HashMap;import java.util.Map; public class TraversalTheHashMap { public static void main(String[] args) { // initialize a HashMap HashMap<String, Integer> map = new HashMap<>(); // Add elements using put method map.put("vishal", 10); map.put("sachin", 30); map.put("vaibhav", 20); // Iterate the map using // for-each loop for (Map.Entry<String, Integer> e : map.entrySet()) System.out.println("Key: " + e.getKey() + " Value: " + e.getValue()); }} Key: vaibhav Value: 20 Key: vishal Value: 10 Key: sachin Value: 30 To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally.Few important features of HashMap are: HashMap is a part of java.util package. HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface. It also implements Cloneable and Serializable interface. K and V in the above definition represent Key and Value respectively. HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value. HashMap allows null key also but only once and multiple null values. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly similar to HashTable but is unsynchronized. Internally HashMap contains an array of Node and a node is represented as a class that contains 4 fields: int hashK keyV valueNode next int hash K key V value Node next It can be seen that the node is containing a reference to its own object. So it’s a linked list. HashMap: Node: Performance of HashMap depends on 2 parameters which are named as follows: Initial CapacityLoad Factor Initial Capacity Load Factor 1. Initial Capacity – It is the capacity of HashMap at the time of its creation (It is the number of buckets a HashMap can hold when the HashMap is instantiated). In java, it is 2^4=16 initially, meaning it can hold 16 key-value pairs. 2. Load Factor – It is the percent value of the capacity after which the capacity of Hashmap is to be increased (It is the percentage fill of buckets after which Rehashing takes place). In java, it is 0.75f by default, meaning the rehashing takes place after filling 75% of the capacity. 3. Threshold – It is the product of Load Factor and Initial Capacity. In java, by default, it is (16 * 0.75 = 12). That is, Rehashing takes place after inserting 12 key-value pairs into the HashMap. 4. Rehashing – It is the process of doubling the capacity of the HashMap after it reaches its Threshold. In java, HashMap continues to rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, .... so on. If the initial capacity is kept higher then rehashing will never be done. But by keeping it higher increases the time complexity of iteration. So it should be chosen very cleverly to increase performance. The expected number of values should be taken into account to set the initial capacity. The most generally preferred load factor value is 0.75 which provides a good deal between time and space costs. The load factor’s value varies between 0 and 1. Note: From Java 8 onward, Java has started using Self Balancing BST instead of a linked list for chaining. The advantage of self-balancing bst is, we get the worst case (when every key maps to the same slot) search time is O(Log n). As it is told that HashMap is unsynchronized i.e. multiple threads can access it simultaneously. If multiple threads access this class simultaneously and at least one thread manipulates it structurally then it is necessary to make it synchronized externally. It is done by synchronizing some object which encapsulates the map. If No such object exists then it can be wrapped around Collections.synchronizedMap() to make HashMap synchronized and avoid accidental unsynchronized access. As in the following example: Map m = Collections.synchronizedMap(new HashMap(...)); Now the Map m is synchronized. Iterators of this class are fail-fast if any structure modification is done after the creation of iterator, in any way except through the iterator’s remove method. In a failure of iterator, it will throw ConcurrentModificationException. Time complexity of HashMap: HashMap provides constant time complexity for basic operations, get and put if the hash function is properly written and it disperses the elements properly among the buckets. Iteration over HashMap depends on the capacity of HashMap and a number of key-value pairs. Basically, it is directly proportional to the capacity + size. Capacity is the number of buckets in HashMap. So it is not a good idea to keep a high number of buckets in HashMap initially. Applications of HashMap: HashMap is mainly the implementation of hashing. It is useful when we need efficient implementation of search, insert and delete operations. Please refer to the applications of hashing for details. K – The type of the keys in the map. V – The type of values mapped in the map. METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION forEach(BiConsumer<? super K, ? super V> action) replaceAll(BiFunction<? super K, ? super V,? extends V> function) Must Read: Hashmap vs Treemap Hashmap vs HashTable Recent articles on Java HashMap! This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Chinmoy Lenka serviopalacios arvindpurushotham Ganeshchowdharysadanala solankimayank sagartomar9927 mokkel simmytarika5 shmkmr38 Java - util package Java-Collections Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 494, "s": 54, "text": "HashMap<K, V> is a part of Java’s collection since Java 1.2. This class is found in java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer). One object is used as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key." }, { "code": null, "e": 843, "s": 494, "text": "HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass." }, { "code": null, "e": 852, "s": 843, "text": "Chapters" }, { "code": null, "e": 879, "s": 852, "text": "descriptions off, selected" }, { "code": null, "e": 929, "s": 879, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 952, "s": 929, "text": "captions off, selected" }, { "code": null, "e": 960, "s": 952, "text": "English" }, { "code": null, "e": 984, "s": 960, "text": "This is a modal window." }, { "code": null, "e": 1053, "s": 984, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1075, "s": 1053, "text": "End of dialog window." }, { "code": null, "e": 1080, "s": 1075, "text": "Java" }, { "code": "// Java program to illustrate HashMap class of java.util// package // Importing HashMap classimport java.util.HashMap; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Create an empty hash map by declaring object // of string and integer type HashMap<String, Integer> map = new HashMap<>(); // Adding elements to the Map // using standard put() method map.put(\"vishal\", 10); map.put(\"sachin\", 30); map.put(\"vaibhav\", 20); // Print size and content of the Map System.out.println(\"Size of map is:- \" + map.size()); // Printing elements in object of Map System.out.println(map); // Checking if a key is present and if &nbnbsp; // present, print value by passing // random element if (map.containsKey(\"vishal\")) { // Mapping Integer a = map.get(\"vishal\"); // Printing value fr the corresponding key System.out.println(\"value for key\" + \" \\\"vishal\\\" is:- \" + a); } }}", "e": 2236, "s": 1080, "text": null }, { "code": null, "e": 2321, "s": 2236, "text": "Size of map is:- 3\n{vaibhav=20, vishal=10, sachin=30}\nvalue for key \"vishal\" is:- 10" }, { "code": null, "e": 2363, "s": 2323, "text": "The Hierarchy of HashMap is as follows:" }, { "code": null, "e": 2384, "s": 2363, "text": " Syntax: Declaration" }, { "code": null, "e": 2506, "s": 2384, "text": "public class HashMap<K,V> extends AbstractMap<K,V>\n implements Map<K,V>, Cloneable, Serializable" }, { "code": null, "e": 2561, "s": 2506, "text": "Parameters: It takes two parameters namely as follows:" }, { "code": null, "e": 2601, "s": 2561, "text": "The type of keys maintained by this map" }, { "code": null, "e": 2627, "s": 2601, "text": "The type of mapped values" }, { "code": null, "e": 2796, "s": 2627, "text": "HashMap implements Serializable, Cloneable, Map<K, V> interfaces. HashMap extends AbstractMap<K, V> class. The direct subclasses are LinkedHashMap, PrinterStateReasons." }, { "code": null, "e": 2899, "s": 2796, "text": "HashMap provides 4 constructors and the access modifier of each is public which are listed as follows:" }, { "code": null, "e": 2999, "s": 2899, "text": "HashMap()HashMap(int initialCapacity)HashMap(int initialCapacity, float loadFactor)HashMap(Map map)" }, { "code": null, "e": 3009, "s": 2999, "text": "HashMap()" }, { "code": null, "e": 3038, "s": 3009, "text": "HashMap(int initialCapacity)" }, { "code": null, "e": 3085, "s": 3038, "text": "HashMap(int initialCapacity, float loadFactor)" }, { "code": null, "e": 3102, "s": 3085, "text": "HashMap(Map map)" }, { "code": null, "e": 3213, "s": 3102, "text": "Now discussing above constructors one by one alongside implementing the same with help of clean java programs." }, { "code": null, "e": 3238, "s": 3213, "text": "Constructor 1: HashMap()" }, { "code": null, "e": 3361, "s": 3238, "text": "It is the default constructor which creates an instance of HashMap with an initial capacity of 16 and load factor of 0.75." }, { "code": null, "e": 3369, "s": 3361, "text": "Syntax:" }, { "code": null, "e": 3409, "s": 3369, "text": "HashMap<K, V> hm = new HashMap<K, V>();" }, { "code": null, "e": 3417, "s": 3409, "text": "Example" }, { "code": null, "e": 3422, "s": 3417, "text": "Java" }, { "code": "// Java program to Demonstrate the HashMap() constructor // Importing basic required classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass GFG { // Main driver method public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(); // Adding elements using put method // Custom input elements hm1.put(1, \"one\"); hm1.put(2, \"two\"); hm1.put(3, \"three\"); hm2.put(4, \"four\"); hm2.put(5, \"five\"); hm2.put(6, \"six\"); // Print and display mapping of HashMap 1 System.out.println(\"Mappings of HashMap hm1 are : \" + hm1); // Print and display mapping of HashMap 2 System.out.println(\"Mapping of HashMap hm2 are : \" + hm2); }}", "e": 4466, "s": 3422, "text": null }, { "code": null, "e": 4573, "s": 4466, "text": "Mappings of HashMap hm1 are : {1=one, 2=two, 3=three}\nMapping of HashMap hm2 are : {4=four, 5=five, 6=six}" }, { "code": null, "e": 4617, "s": 4573, "text": "Constructor 2: HashMap(int initialCapacity)" }, { "code": null, "e": 4706, "s": 4617, "text": "It creates a HashMap instance with a specified initial capacity and load factor of 0.75." }, { "code": null, "e": 4714, "s": 4706, "text": "Syntax:" }, { "code": null, "e": 4773, "s": 4714, "text": "HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity);" }, { "code": null, "e": 4781, "s": 4773, "text": "Example" }, { "code": null, "e": 4786, "s": 4781, "text": "Java" }, { "code": "// Java program to Demonstrate// HashMap(int initialCapacity) Constructor // Importing basic classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass AddElementsToHashMap { // Main driver method public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(10); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(2); // Adding elements to object of HashMap // using put method // HashMap 1 hm1.put(1, \"one\"); hm1.put(2, \"two\"); hm1.put(3, \"three\"); // HashMap 2 hm2.put(4, \"four\"); hm2.put(5, \"five\"); hm2.put(6, \"six\"); // Printing elements of HashMap 1 System.out.println(\"Mappings of HashMap hm1 are : \" + hm1); // Printing elements of HashMap 2 System.out.println(\"Mapping of HashMap hm2 are : \" + hm2); }}", "e": 5883, "s": 4786, "text": null }, { "code": null, "e": 5990, "s": 5883, "text": "Mappings of HashMap hm1 are : {1=one, 2=two, 3=three}\nMapping of HashMap hm2 are : {4=four, 5=five, 6=six}" }, { "code": null, "e": 6052, "s": 5990, "text": "Constructor 3: HashMap(int initialCapacity, float loadFactor)" }, { "code": null, "e": 6143, "s": 6052, "text": "It creates a HashMap instance with a specified initial capacity and specified load factor." }, { "code": null, "e": 6151, "s": 6143, "text": "Syntax:" }, { "code": null, "e": 6227, "s": 6151, "text": "HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity, int loadFactor);" }, { "code": null, "e": 6235, "s": 6227, "text": "Example" }, { "code": null, "e": 6240, "s": 6235, "text": "Java" }, { "code": "// Java program to Demonstrate// HashMap(int initialCapacity,float loadFactor) Constructor // Importing basic classesimport java.io.*;import java.util.*; // Main class// To add elements to HashMapclass GFG { // Main driver method public static void main(String args[]) { // No need to mention the generic type twice HashMap<Integer, String> hm1 = new HashMap<>(5, 0.75f); // Initialization of a HashMap using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(3, 0.5f); // Add Elements using put() method // Custom input elements hm1.put(1, \"one\"); hm1.put(2, \"two\"); hm1.put(3, \"three\"); hm2.put(4, \"four\"); hm2.put(5, \"five\"); hm2.put(6, \"six\"); // Print and display elements in object of hashMap 1 System.out.println(\"Mappings of HashMap hm1 are : \" + hm1); // Print and display elements in object of hashMap 2 System.out.println(\"Mapping of HashMap hm2 are : \" + hm2); }}", "e": 7346, "s": 6240, "text": null }, { "code": null, "e": 7453, "s": 7346, "text": "Mappings of HashMap hm1 are : {1=one, 2=two, 3=three}\nMapping of HashMap hm2 are : {4=four, 5=five, 6=six}" }, { "code": null, "e": 7554, "s": 7453, "text": " 4. HashMap(Map map): It creates an instance of HashMap with the same mappings as the specified map." }, { "code": null, "e": 7601, "s": 7554, "text": "HashMap<K, V> hm = new HashMap<K, V>(Map map);" }, { "code": null, "e": 7606, "s": 7601, "text": "Java" }, { "code": "// Java program to demonstrate the // HashMap(Map map) Constructor import java.io.*;import java.util.*; class AddElementsToHashMap { public static void main(String args[]) { // No need to mention the // Generic type twice Map<Integer, String> hm1 = new HashMap<>(); // Add Elements using put method hm1.put(1, \"one\"); hm1.put(2, \"two\"); hm1.put(3, \"three\"); // Initialization of a HashMap // using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(hm1); System.out.println(\"Mappings of HashMap hm1 are : \" + hm1); System.out.println(\"Mapping of HashMap hm2 are : \" + hm2); }}", "e": 8373, "s": 7606, "text": null }, { "code": null, "e": 8480, "s": 8373, "text": "Mappings of HashMap hm1 are : {1=one, 2=two, 3=three}\nMapping of HashMap hm2 are : {1=one, 2=two, 3=three}" }, { "code": null, "e": 8766, "s": 8482, "text": "1. Adding Elements: In order to add an element to the map, we can use the put() method. However, the insertion order is not retained in the Hashmap. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient." }, { "code": null, "e": 8771, "s": 8766, "text": "Java" }, { "code": "// Java program to add elements// to the HashMap import java.io.*;import java.util.*; class AddElementsToHashMap { public static void main(String args[]) { // No need to mention the // Generic type twice HashMap<Integer, String> hm1 = new HashMap<>(); // Initialization of a HashMap // using Generics HashMap<Integer, String> hm2 = new HashMap<Integer, String>(); // Add Elements using put method hm1.put(1, \"Geeks\"); hm1.put(2, \"For\"); hm1.put(3, \"Geeks\"); hm2.put(1, \"Geeks\"); hm2.put(2, \"For\"); hm2.put(3, \"Geeks\"); System.out.println(\"Mappings of HashMap hm1 are : \" + hm1); System.out.println(\"Mapping of HashMap hm2 are : \" + hm2); }}", "e": 9599, "s": 8771, "text": null }, { "code": null, "e": 9710, "s": 9599, "text": "Mappings of HashMap hm1 are : {1=Geeks, 2=For, 3=Geeks}\nMapping of HashMap hm2 are : {1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 10031, "s": 9710, "text": "2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the map are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change." }, { "code": null, "e": 10036, "s": 10031, "text": "Java" }, { "code": "// Java program to change// elements of HashMap import java.io.*;import java.util.*;class ChangeElementsOfHashMap { public static void main(String args[]) { // Initialization of a HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Change Value using put method hm.put(1, \"Geeks\"); hm.put(2, \"Geeks\"); hm.put(3, \"Geeks\"); System.out.println(\"Initial Map \" + hm); hm.put(2, \"For\"); System.out.println(\"Updated Map \" + hm); }}", "e": 10576, "s": 10036, "text": null }, { "code": null, "e": 10654, "s": 10576, "text": "Initial Map {1=Geeks, 2=Geeks, 3=Geeks}\nUpdated Map {1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 10860, "s": 10654, "text": "3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map." }, { "code": null, "e": 10865, "s": 10860, "text": "Java" }, { "code": "// Java program to remove// elements from HashMap import java.io.*;import java.util.*;class RemoveElementsOfHashMap{ public static void main(String args[]) { // Initialization of a HashMap Map<Integer, String> hm = new HashMap<Integer, String>(); // Add elements using put method hm.put(1, \"Geeks\"); hm.put(2, \"For\"); hm.put(3, \"Geeks\"); hm.put(4, \"For\"); // Initial HashMap System.out.println(\"Mappings of HashMap are : \" + hm); // remove element with a key // using remove method hm.remove(4); // Final HashMap System.out.println(\"Mappings after removal are : \" + hm); }}", "e": 11618, "s": 10865, "text": null }, { "code": null, "e": 11735, "s": 11621, "text": "Mappings of HashMap are : {1=Geeks, 2=For, 3=Geeks, 4=For}\nMappings after removal are : {1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 11759, "s": 11735, "text": "4. Traversal of HashMap" }, { "code": null, "e": 12040, "s": 11759, "text": "We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the entries of HashMap." }, { "code": null, "e": 12045, "s": 12040, "text": "Java" }, { "code": "// Java program to traversal a// Java.util.HashMap import java.util.HashMap;import java.util.Map; public class TraversalTheHashMap { public static void main(String[] args) { // initialize a HashMap HashMap<String, Integer> map = new HashMap<>(); // Add elements using put method map.put(\"vishal\", 10); map.put(\"sachin\", 30); map.put(\"vaibhav\", 20); // Iterate the map using // for-each loop for (Map.Entry<String, Integer> e : map.entrySet()) System.out.println(\"Key: \" + e.getKey() + \" Value: \" + e.getValue()); }}", "e": 12680, "s": 12045, "text": null }, { "code": null, "e": 12750, "s": 12683, "text": "Key: vaibhav Value: 20\nKey: vishal Value: 10\nKey: sachin Value: 30" }, { "code": null, "e": 13096, "s": 12750, "text": "To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally.Few important features of HashMap are: " }, { "code": null, "e": 13136, "s": 13096, "text": "HashMap is a part of java.util package." }, { "code": null, "e": 13249, "s": 13136, "text": "HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface." }, { "code": null, "e": 13376, "s": 13249, "text": "It also implements Cloneable and Serializable interface. K and V in the above definition represent Key and Value respectively." }, { "code": null, "e": 13546, "s": 13376, "text": "HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value." }, { "code": null, "e": 13615, "s": 13546, "text": "HashMap allows null key also but only once and multiple null values." }, { "code": null, "e": 13816, "s": 13615, "text": "This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly similar to HashTable but is unsynchronized." }, { "code": null, "e": 13923, "s": 13816, "text": "Internally HashMap contains an array of Node and a node is represented as a class that contains 4 fields: " }, { "code": null, "e": 13953, "s": 13923, "text": "int hashK keyV valueNode next" }, { "code": null, "e": 13962, "s": 13953, "text": "int hash" }, { "code": null, "e": 13968, "s": 13962, "text": "K key" }, { "code": null, "e": 13976, "s": 13968, "text": "V value" }, { "code": null, "e": 13986, "s": 13976, "text": "Node next" }, { "code": null, "e": 14084, "s": 13986, "text": "It can be seen that the node is containing a reference to its own object. So it’s a linked list. " }, { "code": null, "e": 14095, "s": 14084, "text": "HashMap: " }, { "code": null, "e": 14103, "s": 14095, "text": "Node: " }, { "code": null, "e": 14180, "s": 14105, "text": "Performance of HashMap depends on 2 parameters which are named as follows:" }, { "code": null, "e": 14208, "s": 14180, "text": "Initial CapacityLoad Factor" }, { "code": null, "e": 14225, "s": 14208, "text": "Initial Capacity" }, { "code": null, "e": 14237, "s": 14225, "text": "Load Factor" }, { "code": null, "e": 14473, "s": 14237, "text": "1. Initial Capacity – It is the capacity of HashMap at the time of its creation (It is the number of buckets a HashMap can hold when the HashMap is instantiated). In java, it is 2^4=16 initially, meaning it can hold 16 key-value pairs." }, { "code": null, "e": 14761, "s": 14473, "text": "2. Load Factor – It is the percent value of the capacity after which the capacity of Hashmap is to be increased (It is the percentage fill of buckets after which Rehashing takes place). In java, it is 0.75f by default, meaning the rehashing takes place after filling 75% of the capacity." }, { "code": null, "e": 14960, "s": 14761, "text": "3. Threshold – It is the product of Load Factor and Initial Capacity. In java, by default, it is (16 * 0.75 = 12). That is, Rehashing takes place after inserting 12 key-value pairs into the HashMap." }, { "code": null, "e": 15176, "s": 14960, "text": "4. Rehashing – It is the process of doubling the capacity of the HashMap after it reaches its Threshold. In java, HashMap continues to rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, .... so on. " }, { "code": null, "e": 15630, "s": 15176, "text": "If the initial capacity is kept higher then rehashing will never be done. But by keeping it higher increases the time complexity of iteration. So it should be chosen very cleverly to increase performance. The expected number of values should be taken into account to set the initial capacity. The most generally preferred load factor value is 0.75 which provides a good deal between time and space costs. The load factor’s value varies between 0 and 1. " }, { "code": null, "e": 15865, "s": 15630, "text": "Note: From Java 8 onward, Java has started using Self Balancing BST instead of a linked list for chaining. The advantage of self-balancing bst is, we get the worst case (when every key maps to the same slot) search time is O(Log n). " }, { "code": null, "e": 16381, "s": 15865, "text": "As it is told that HashMap is unsynchronized i.e. multiple threads can access it simultaneously. If multiple threads access this class simultaneously and at least one thread manipulates it structurally then it is necessary to make it synchronized externally. It is done by synchronizing some object which encapsulates the map. If No such object exists then it can be wrapped around Collections.synchronizedMap() to make HashMap synchronized and avoid accidental unsynchronized access. As in the following example: " }, { "code": null, "e": 16436, "s": 16381, "text": "Map m = Collections.synchronizedMap(new HashMap(...));" }, { "code": null, "e": 17411, "s": 16436, "text": "Now the Map m is synchronized. Iterators of this class are fail-fast if any structure modification is done after the creation of iterator, in any way except through the iterator’s remove method. In a failure of iterator, it will throw ConcurrentModificationException. Time complexity of HashMap: HashMap provides constant time complexity for basic operations, get and put if the hash function is properly written and it disperses the elements properly among the buckets. Iteration over HashMap depends on the capacity of HashMap and a number of key-value pairs. Basically, it is directly proportional to the capacity + size. Capacity is the number of buckets in HashMap. So it is not a good idea to keep a high number of buckets in HashMap initially. Applications of HashMap: HashMap is mainly the implementation of hashing. It is useful when we need efficient implementation of search, insert and delete operations. Please refer to the applications of hashing for details." }, { "code": null, "e": 17448, "s": 17411, "text": "K – The type of the keys in the map." }, { "code": null, "e": 17490, "s": 17448, "text": "V – The type of values mapped in the map." }, { "code": null, "e": 17497, "s": 17490, "text": "METHOD" }, { "code": null, "e": 17509, "s": 17497, "text": "DESCRIPTION" }, { "code": null, "e": 17516, "s": 17509, "text": "METHOD" }, { "code": null, "e": 17528, "s": 17516, "text": "DESCRIPTION" }, { "code": null, "e": 17535, "s": 17528, "text": "METHOD" }, { "code": null, "e": 17547, "s": 17535, "text": "DESCRIPTION" }, { "code": null, "e": 17577, "s": 17547, "text": "forEach(BiConsumer<? super K," }, { "code": null, "e": 17596, "s": 17577, "text": "? super V> action)" }, { "code": null, "e": 17629, "s": 17596, "text": "replaceAll(BiFunction<? super K," }, { "code": null, "e": 17662, "s": 17629, "text": "? super V,? extends V> function)" }, { "code": null, "e": 17673, "s": 17662, "text": "Must Read:" }, { "code": null, "e": 17692, "s": 17673, "text": "Hashmap vs Treemap" }, { "code": null, "e": 17713, "s": 17692, "text": "Hashmap vs HashTable" }, { "code": null, "e": 17746, "s": 17713, "text": "Recent articles on Java HashMap!" }, { "code": null, "e": 18166, "s": 17746, "text": "This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 18180, "s": 18166, "text": "Chinmoy Lenka" }, { "code": null, "e": 18195, "s": 18180, "text": "serviopalacios" }, { "code": null, "e": 18213, "s": 18195, "text": "arvindpurushotham" }, { "code": null, "e": 18237, "s": 18213, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 18251, "s": 18237, "text": "solankimayank" }, { "code": null, "e": 18266, "s": 18251, "text": "sagartomar9927" }, { "code": null, "e": 18273, "s": 18266, "text": "mokkel" }, { "code": null, "e": 18286, "s": 18273, "text": "simmytarika5" }, { "code": null, "e": 18295, "s": 18286, "text": "shmkmr38" }, { "code": null, "e": 18315, "s": 18295, "text": "Java - util package" }, { "code": null, "e": 18332, "s": 18315, "text": "Java-Collections" }, { "code": null, "e": 18345, "s": 18332, "text": "Java-HashMap" }, { "code": null, "e": 18350, "s": 18345, "text": "Java" }, { "code": null, "e": 18355, "s": 18350, "text": "Java" }, { "code": null, "e": 18372, "s": 18355, "text": "Java-Collections" } ]
Testing Room Database in Android using JUnit
17 Mar, 2021 In this article, we are going to test the Room Database in android. Here we are using JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc. Here we will be using only @Test annotation to keep the article easy to understand. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Add Dependencies Inside build.gradle (project) add the following code under dependencies. It contains dependencies of Room Db, Coroutiene, JUnit, Truth, and others. implementation “org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1” implementation “androidx.room:room-runtime:2.2.6” implementation “androidx.legacy:legacy-support-v4:1.0.0” kapt “androidx.room:room-compiler:2.2.6” implementation “androidx.room:room-ktx:2.2.6” testImplementation “androidx.arch.core:core-testing:2.1.0” testImplementation “androidx.room:room-testing:2.2.6” testImplementation “junit:junit:4.13.2” testImplementation “com.google.truth:truth:1.1.2” testImplementation “org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.4” testImplementation ‘org.robolectric:robolectric:4.5.1’ androidTestImplementation “androidx.test.ext:junit-ktx:1.1.2” androidTestImplementation “androidx.test.espresso:espresso-core:3.3.0” androidTestImplementation “com.google.truth:truth:1.1.2” androidTestImplementation “androidx.arch.core:core-testing:2.1.0” androidTestImplementation “androidx.test:rules:1.3.0” androidTestImplementation “androidx.test:runner:1.3.0” androidTestImplementation “androidx.test:core-ktx:1.3.0” Before Writing our test lets first create Room Database Step 3: Create a new model class “Language.kt” Create a new class “Language.kt” and annotate it with @Entity and pass the table name. Kotlin import androidx.room.Entityimport androidx.room.PrimaryKey @Entity(tableName = "language")data class Language( val languageName : String="", val experience : String="") { @PrimaryKey(autoGenerate = true) var id : Long=0} Step 4: Create dao interface Create a new class “LanguageDao.kt” and annotate it with @Dao.Comments are added for a better understanding of the code. Kotlin import androidx.room.Daoimport androidx.room.Insertimport androidx.room.Query @Daointerface LanguageDao { // Write two functions one for adding language to the database // and another for retrieving all the items present in room db. @Insert suspend fun addLanguage(language: Language) @Query("SELECT * FROM language ORDER BY languageName DESC") suspend fun getAllLanguages(): List<Language>} Step 5: Create a Database class Create a new abstract class “LanguageDatabase.kt” and annotate it with @Database. Below is the code of LanguageDatabase.kt class comments are added for better understanding. Kotlin import android.content.Contextimport androidx.room.Databaseimport androidx.room.Roomimport androidx.room.RoomDatabase @Database(entities = [Language::class] , version = 1)abstract class LanguageDatabase : RoomDatabase() { // get reference of the dao interface that we just created abstract fun getLanguageDao() : LanguageDao companion object{ private const val DB_NAME = "Language-Database.db" // Get reference of the LanguageDatabase and assign it null value @Volatile private var instance : LanguageDatabase? = null private val LOCK = Any() // create an operator fun which has context as a parameter // assign value to the instance variable operator fun invoke(context: Context) = instance ?: synchronized(LOCK){ instance ?: buildDatabase(context).also{ instance = it } } // create a buildDatabase function assign the required values private fun buildDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, LanguageDatabase::class.java, DB_NAME ).fallbackToDestructiveMigration().build() }} Step 6: Create a Test class In order to create a test class of LanguageDatabase.kt right-click on LanguageDatabase then click generate and then select the test. A dialog will open, from the dialog choose Testing library as JUnit4 and keep the class name as default that is LanguageDatabaseTest, and click ok. After that, another dialog will open to choose the destination directory, choose the one which has ..app\src\AndoidTest\. because our test class requires context from the application. Below is the screenshot to guide you create the test class. Step 7: Working with LanguageDatabaseTest.kt class Go to LanguageDatabaseTest.kt file and write the following code. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.Contextimport androidx.room.Roomimport androidx.test.core.app.ApplicationProviderimport androidx.test.ext.junit.runners.AndroidJUnit4import com.google.common.truth.Truth.assertThatimport junit.framework.TestCaseimport kotlinx.coroutines.runBlockingimport org.junit.*import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) // Annotate with @RunWithclass LanguageDatabaseTest : TestCase() { // get reference to the LanguageDatabase and LanguageDao class private lateinit var db: LanguageDatabase private lateinit var dao: LanguageDao // Override function setUp() and annotate it with @Before // this function will be called at first when this test class is called @Before public override fun setUp() { // get context -- since this is an instrumental test it requires // context from the running application val context = ApplicationProvider.getApplicationContext<Context>() // initialize the db and dao variable db = Room.inMemoryDatabaseBuilder(context, LanguageDatabase::class.java).build() dao = db.getLanguageDao() } // Override function closeDb() and annotate it with @After // this function will be called at last when this test class is called @After fun closeDb() { db.close() } // create a test function and annotate it with @Test // here we are first adding an item to the db and then checking if that item // is present in the db -- if the item is present then our test cases pass @Test fun writeAndReadLanguage() = runBlocking { val language = Language("Java", "2 Years") dao.addLanguage(language) val languages = dao.getAllLanguages() assertThat(languages.contains(language)).isTrue() }} Step 8: Run Tests To run the test case click on the little run icon near the class name and then select Run LanguageDatabaseTest. If all the test cases pass you will get a green tick in the Run console. In our case, all tests have passed. Github Repo here. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Mar, 2021" }, { "code": null, "e": 535, "s": 28, "text": "In this article, we are going to test the Room Database in android. Here we are using JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc. Here we will be using only @Test annotation to keep the article easy to understand. Note that we are going to implement this project using the Kotlin language." }, { "code": null, "e": 564, "s": 535, "text": "Step 1: Create a new project" }, { "code": null, "e": 728, "s": 564, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 753, "s": 728, "text": "Step 2: Add Dependencies" }, { "code": null, "e": 901, "s": 753, "text": "Inside build.gradle (project) add the following code under dependencies. It contains dependencies of Room Db, Coroutiene, JUnit, Truth, and others." }, { "code": null, "e": 973, "s": 901, "text": "implementation “org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1”" }, { "code": null, "e": 1023, "s": 973, "text": "implementation “androidx.room:room-runtime:2.2.6”" }, { "code": null, "e": 1080, "s": 1023, "text": "implementation “androidx.legacy:legacy-support-v4:1.0.0”" }, { "code": null, "e": 1121, "s": 1080, "text": "kapt “androidx.room:room-compiler:2.2.6”" }, { "code": null, "e": 1167, "s": 1121, "text": "implementation “androidx.room:room-ktx:2.2.6”" }, { "code": null, "e": 1226, "s": 1167, "text": "testImplementation “androidx.arch.core:core-testing:2.1.0”" }, { "code": null, "e": 1280, "s": 1226, "text": "testImplementation “androidx.room:room-testing:2.2.6”" }, { "code": null, "e": 1320, "s": 1280, "text": "testImplementation “junit:junit:4.13.2”" }, { "code": null, "e": 1370, "s": 1320, "text": "testImplementation “com.google.truth:truth:1.1.2”" }, { "code": null, "e": 1443, "s": 1370, "text": "testImplementation “org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.4”" }, { "code": null, "e": 1498, "s": 1443, "text": "testImplementation ‘org.robolectric:robolectric:4.5.1’" }, { "code": null, "e": 1560, "s": 1498, "text": "androidTestImplementation “androidx.test.ext:junit-ktx:1.1.2”" }, { "code": null, "e": 1631, "s": 1560, "text": "androidTestImplementation “androidx.test.espresso:espresso-core:3.3.0”" }, { "code": null, "e": 1688, "s": 1631, "text": "androidTestImplementation “com.google.truth:truth:1.1.2”" }, { "code": null, "e": 1754, "s": 1688, "text": "androidTestImplementation “androidx.arch.core:core-testing:2.1.0”" }, { "code": null, "e": 1808, "s": 1754, "text": "androidTestImplementation “androidx.test:rules:1.3.0”" }, { "code": null, "e": 1863, "s": 1808, "text": "androidTestImplementation “androidx.test:runner:1.3.0”" }, { "code": null, "e": 1920, "s": 1863, "text": "androidTestImplementation “androidx.test:core-ktx:1.3.0”" }, { "code": null, "e": 1976, "s": 1920, "text": "Before Writing our test lets first create Room Database" }, { "code": null, "e": 2023, "s": 1976, "text": "Step 3: Create a new model class “Language.kt”" }, { "code": null, "e": 2110, "s": 2023, "text": "Create a new class “Language.kt” and annotate it with @Entity and pass the table name." }, { "code": null, "e": 2117, "s": 2110, "text": "Kotlin" }, { "code": "import androidx.room.Entityimport androidx.room.PrimaryKey @Entity(tableName = \"language\")data class Language( val languageName : String=\"\", val experience : String=\"\") { @PrimaryKey(autoGenerate = true) var id : Long=0}", "e": 2351, "s": 2117, "text": null }, { "code": null, "e": 2380, "s": 2351, "text": "Step 4: Create dao interface" }, { "code": null, "e": 2501, "s": 2380, "text": "Create a new class “LanguageDao.kt” and annotate it with @Dao.Comments are added for a better understanding of the code." }, { "code": null, "e": 2508, "s": 2501, "text": "Kotlin" }, { "code": "import androidx.room.Daoimport androidx.room.Insertimport androidx.room.Query @Daointerface LanguageDao { // Write two functions one for adding language to the database // and another for retrieving all the items present in room db. @Insert suspend fun addLanguage(language: Language) @Query(\"SELECT * FROM language ORDER BY languageName DESC\") suspend fun getAllLanguages(): List<Language>}", "e": 2922, "s": 2508, "text": null }, { "code": null, "e": 2954, "s": 2922, "text": "Step 5: Create a Database class" }, { "code": null, "e": 3128, "s": 2954, "text": "Create a new abstract class “LanguageDatabase.kt” and annotate it with @Database. Below is the code of LanguageDatabase.kt class comments are added for better understanding." }, { "code": null, "e": 3135, "s": 3128, "text": "Kotlin" }, { "code": "import android.content.Contextimport androidx.room.Databaseimport androidx.room.Roomimport androidx.room.RoomDatabase @Database(entities = [Language::class] , version = 1)abstract class LanguageDatabase : RoomDatabase() { // get reference of the dao interface that we just created abstract fun getLanguageDao() : LanguageDao companion object{ private const val DB_NAME = \"Language-Database.db\" // Get reference of the LanguageDatabase and assign it null value @Volatile private var instance : LanguageDatabase? = null private val LOCK = Any() // create an operator fun which has context as a parameter // assign value to the instance variable operator fun invoke(context: Context) = instance ?: synchronized(LOCK){ instance ?: buildDatabase(context).also{ instance = it } } // create a buildDatabase function assign the required values private fun buildDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, LanguageDatabase::class.java, DB_NAME ).fallbackToDestructiveMigration().build() }}", "e": 4334, "s": 3135, "text": null }, { "code": null, "e": 4362, "s": 4334, "text": "Step 6: Create a Test class" }, { "code": null, "e": 4887, "s": 4362, "text": "In order to create a test class of LanguageDatabase.kt right-click on LanguageDatabase then click generate and then select the test. A dialog will open, from the dialog choose Testing library as JUnit4 and keep the class name as default that is LanguageDatabaseTest, and click ok. After that, another dialog will open to choose the destination directory, choose the one which has ..app\\src\\AndoidTest\\. because our test class requires context from the application. Below is the screenshot to guide you create the test class." }, { "code": null, "e": 4938, "s": 4887, "text": "Step 7: Working with LanguageDatabaseTest.kt class" }, { "code": null, "e": 5077, "s": 4938, "text": "Go to LanguageDatabaseTest.kt file and write the following code. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5084, "s": 5077, "text": "Kotlin" }, { "code": "import android.content.Contextimport androidx.room.Roomimport androidx.test.core.app.ApplicationProviderimport androidx.test.ext.junit.runners.AndroidJUnit4import com.google.common.truth.Truth.assertThatimport junit.framework.TestCaseimport kotlinx.coroutines.runBlockingimport org.junit.*import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) // Annotate with @RunWithclass LanguageDatabaseTest : TestCase() { // get reference to the LanguageDatabase and LanguageDao class private lateinit var db: LanguageDatabase private lateinit var dao: LanguageDao // Override function setUp() and annotate it with @Before // this function will be called at first when this test class is called @Before public override fun setUp() { // get context -- since this is an instrumental test it requires // context from the running application val context = ApplicationProvider.getApplicationContext<Context>() // initialize the db and dao variable db = Room.inMemoryDatabaseBuilder(context, LanguageDatabase::class.java).build() dao = db.getLanguageDao() } // Override function closeDb() and annotate it with @After // this function will be called at last when this test class is called @After fun closeDb() { db.close() } // create a test function and annotate it with @Test // here we are first adding an item to the db and then checking if that item // is present in the db -- if the item is present then our test cases pass @Test fun writeAndReadLanguage() = runBlocking { val language = Language(\"Java\", \"2 Years\") dao.addLanguage(language) val languages = dao.getAllLanguages() assertThat(languages.contains(language)).isTrue() }}", "e": 6857, "s": 5084, "text": null }, { "code": null, "e": 6875, "s": 6857, "text": "Step 8: Run Tests" }, { "code": null, "e": 7096, "s": 6875, "text": "To run the test case click on the little run icon near the class name and then select Run LanguageDatabaseTest. If all the test cases pass you will get a green tick in the Run console. In our case, all tests have passed." }, { "code": null, "e": 7114, "s": 7096, "text": "Github Repo here." }, { "code": null, "e": 7122, "s": 7114, "text": "Android" }, { "code": null, "e": 7129, "s": 7122, "text": "Kotlin" }, { "code": null, "e": 7137, "s": 7129, "text": "Android" } ]
Single Layered Neural Networks in R Programming
22 Jul, 2020 Neural networks also known as neural nets is a type of algorithm in machine learning and artificial intelligence that works the same as the human brain operates. The artificial neurons in the neural network depict the same behavior of neurons in the human brain. Neural networks are used in risk analysis of business, forecasting the sales, and many more. Neural networks are adaptable to changing inputs so that there is no need for designing the algorithm again based on the inputs. In this article, we’ll discuss single-layered neural network with its syntax and implementation of the neuralnet() function in R programming. Following function requires neuralnet package. Neural Networks can be classified into multiple types based on their depth activation filters, Structure, Neurons used, Neuron density, data flow, and so on. The types of Neural Networks are as follows: PerceptronFeed Forward Neural NetworksConvolutional Neural NetworksRadial Basis Function Neural NetworksRecurrent Neural NetworksSequence to Sequence ModelModular Neural Network Perceptron Feed Forward Neural Networks Convolutional Neural Networks Radial Basis Function Neural Networks Recurrent Neural Networks Sequence to Sequence Model Modular Neural Network Depending upon the number of layers, there are two types of neural networks: Single Layered Neural Network: A single layer neural network contains input and output layer. The input layer receives the input signals and the output layer generates the output signals accordingly.Multilayer Neural Network: Multilayer neural network contains input, output and one or more than one hidden layer. The hidden layers perform intermediate computations before directing the input to the output layer. Single Layered Neural Network: A single layer neural network contains input and output layer. The input layer receives the input signals and the output layer generates the output signals accordingly. Multilayer Neural Network: Multilayer neural network contains input, output and one or more than one hidden layer. The hidden layers perform intermediate computations before directing the input to the output layer. A single-layered neural network often called perceptrons is a type of feed-forward neural network made up of input and output layers. Inputs provided are multi-dimensional. Perceptrons are acyclic in nature. The sum of the product of weights and the inputs is calculated in each node. The input layer transmits the signals to the output layer. The output layer performs computations. Perceptron can learn only a linear function and requires less training output. The output can be represented in one or two values(0 or 1). R language provides neuralnet() function which is available in neuralnet package to perform single layered neural network. Syntax:neuralnet(formula, data, hidden) Parameters:formula: represents formula on which model has to be fitteddata: represents dataframehidden: represents number of neurons in hidden layers To know about more optional parameters of the function, use below command in console: help(“neuralnet”) Example 1:In this example, let us create the single-layered neural network or perceptron of iris plant species of setosa and versicolor based on sepal length and sepal width.Step 1: Install the required package # Install the required packageinstall.packages("neuralnet") Step 2: Load the package # Load the packagelibrary(neuralnet) Step 3: Load the dataset # Load datasetdf <- iris[1:100, ] Step 4: Fitting neural network nn = neuralnet(Species ~ Sepal.Length + Sepal.Width, data = df, hidden = 0, linear.output = TRUE) Step 5: Plot neural network # Output to be present as PNG filepng(file = "neuralNetworkGFG.png") # Plotplot(nn) # Saving the filedev.off() Output: Example 2:In this example, let us create more reliable neural network using multi-layer neural network and make predictions based on the dataset.Step 1: Install the required package # Install the required packageinstall.packages("neuralnet") Step 2: Load the package # Load the packagelibrary(neuralnet) Step 3: Load the dataset # Load datasetdf <- mtcars Step 4: Fitting neural network nn <- neuralnet(am ~ vs + cyl + disp + hp + gear + carb + wt + drat, data = df, hidden = 3, linear.output = TRUE) Step 5: Plot neural network # Output to be present as PNG filepng(file = "neuralNetwork2GFG.png") # Plotplot(nn) # Saving the filedev.off() Step 6: Create test dataset # Create test datasetvs = c(0, 1, 1)cyl =c(6, 8, 8)disp = c(170, 250, 350)hp = c(120, 240, 300)gear = c(4, 5, 4)carb = c(4, 3, 3)wt = c(2.780, 3.210, 3.425)drat = c(3.05, 4.02, 3.95) test <- data.frame(vs, cyl, disp, hp, gear, carb, wt, drat) Step 7: Make prediction of test dataset Predict <- compute(nn, test) cat("Predicted values:\n")print(Predict$net.result) Step 8: Convert prediction into binary values probability <- Predict$net.resultpred <- ifelse(probability > 0.5, 1, 0)cat("Result in binary values:\n")print(pred) Output: Predicted values: [,1] [1,] 0.3681382 [2,] 0.9909768 [3,] 0.9909768 Result in binary values: [,1] [1,] 0 [2,] 1 [3,] 1 Explanation:In above output, “am” value for each row of test dataset is predicted using multi-layer neural network. As in neural network created by the function, predicted values greater than 0.49 makes “am” value of car to be 1. Single layer neural networks are easy to set up and train them as there is absence of hidden layers It has explicit links to statistical models It can work better only for linearly separable data. Single layer neural network has low accuracy as compared to multi-layer neural network. data-science Picked R Machine-Learning Machine Learning R Language Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2020" }, { "code": null, "e": 702, "s": 28, "text": "Neural networks also known as neural nets is a type of algorithm in machine learning and artificial intelligence that works the same as the human brain operates. The artificial neurons in the neural network depict the same behavior of neurons in the human brain. Neural networks are used in risk analysis of business, forecasting the sales, and many more. Neural networks are adaptable to changing inputs so that there is no need for designing the algorithm again based on the inputs. In this article, we’ll discuss single-layered neural network with its syntax and implementation of the neuralnet() function in R programming. Following function requires neuralnet package." }, { "code": null, "e": 905, "s": 702, "text": "Neural Networks can be classified into multiple types based on their depth activation filters, Structure, Neurons used, Neuron density, data flow, and so on. The types of Neural Networks are as follows:" }, { "code": null, "e": 1083, "s": 905, "text": "PerceptronFeed Forward Neural NetworksConvolutional Neural NetworksRadial Basis Function Neural NetworksRecurrent Neural NetworksSequence to Sequence ModelModular Neural Network" }, { "code": null, "e": 1094, "s": 1083, "text": "Perceptron" }, { "code": null, "e": 1123, "s": 1094, "text": "Feed Forward Neural Networks" }, { "code": null, "e": 1153, "s": 1123, "text": "Convolutional Neural Networks" }, { "code": null, "e": 1191, "s": 1153, "text": "Radial Basis Function Neural Networks" }, { "code": null, "e": 1217, "s": 1191, "text": "Recurrent Neural Networks" }, { "code": null, "e": 1244, "s": 1217, "text": "Sequence to Sequence Model" }, { "code": null, "e": 1267, "s": 1244, "text": "Modular Neural Network" }, { "code": null, "e": 1344, "s": 1267, "text": "Depending upon the number of layers, there are two types of neural networks:" }, { "code": null, "e": 1758, "s": 1344, "text": "Single Layered Neural Network: A single layer neural network contains input and output layer. The input layer receives the input signals and the output layer generates the output signals accordingly.Multilayer Neural Network: Multilayer neural network contains input, output and one or more than one hidden layer. The hidden layers perform intermediate computations before directing the input to the output layer." }, { "code": null, "e": 1958, "s": 1758, "text": "Single Layered Neural Network: A single layer neural network contains input and output layer. The input layer receives the input signals and the output layer generates the output signals accordingly." }, { "code": null, "e": 2173, "s": 1958, "text": "Multilayer Neural Network: Multilayer neural network contains input, output and one or more than one hidden layer. The hidden layers perform intermediate computations before directing the input to the output layer." }, { "code": null, "e": 2696, "s": 2173, "text": "A single-layered neural network often called perceptrons is a type of feed-forward neural network made up of input and output layers. Inputs provided are multi-dimensional. Perceptrons are acyclic in nature. The sum of the product of weights and the inputs is calculated in each node. The input layer transmits the signals to the output layer. The output layer performs computations. Perceptron can learn only a linear function and requires less training output. The output can be represented in one or two values(0 or 1)." }, { "code": null, "e": 2819, "s": 2696, "text": "R language provides neuralnet() function which is available in neuralnet package to perform single layered neural network." }, { "code": null, "e": 2859, "s": 2819, "text": "Syntax:neuralnet(formula, data, hidden)" }, { "code": null, "e": 3009, "s": 2859, "text": "Parameters:formula: represents formula on which model has to be fitteddata: represents dataframehidden: represents number of neurons in hidden layers" }, { "code": null, "e": 3113, "s": 3009, "text": "To know about more optional parameters of the function, use below command in console: help(“neuralnet”)" }, { "code": null, "e": 3324, "s": 3113, "text": "Example 1:In this example, let us create the single-layered neural network or perceptron of iris plant species of setosa and versicolor based on sepal length and sepal width.Step 1: Install the required package" }, { "code": "# Install the required packageinstall.packages(\"neuralnet\")", "e": 3384, "s": 3324, "text": null }, { "code": null, "e": 3409, "s": 3384, "text": "Step 2: Load the package" }, { "code": "# Load the packagelibrary(neuralnet)", "e": 3446, "s": 3409, "text": null }, { "code": null, "e": 3471, "s": 3446, "text": "Step 3: Load the dataset" }, { "code": "# Load datasetdf <- iris[1:100, ]", "e": 3505, "s": 3471, "text": null }, { "code": null, "e": 3536, "s": 3505, "text": "Step 4: Fitting neural network" }, { "code": "nn = neuralnet(Species ~ Sepal.Length + Sepal.Width, data = df, hidden = 0, linear.output = TRUE)", "e": 3661, "s": 3536, "text": null }, { "code": null, "e": 3689, "s": 3661, "text": "Step 5: Plot neural network" }, { "code": "# Output to be present as PNG filepng(file = \"neuralNetworkGFG.png\") # Plotplot(nn) # Saving the filedev.off()", "e": 3802, "s": 3689, "text": null }, { "code": null, "e": 3810, "s": 3802, "text": "Output:" }, { "code": null, "e": 3992, "s": 3810, "text": "Example 2:In this example, let us create more reliable neural network using multi-layer neural network and make predictions based on the dataset.Step 1: Install the required package" }, { "code": "# Install the required packageinstall.packages(\"neuralnet\")", "e": 4052, "s": 3992, "text": null }, { "code": null, "e": 4077, "s": 4052, "text": "Step 2: Load the package" }, { "code": "# Load the packagelibrary(neuralnet)", "e": 4114, "s": 4077, "text": null }, { "code": null, "e": 4139, "s": 4114, "text": "Step 3: Load the dataset" }, { "code": "# Load datasetdf <- mtcars", "e": 4166, "s": 4139, "text": null }, { "code": null, "e": 4197, "s": 4166, "text": "Step 4: Fitting neural network" }, { "code": "nn <- neuralnet(am ~ vs + cyl + disp + hp + gear + carb + wt + drat, data = df, hidden = 3, linear.output = TRUE)", "e": 4342, "s": 4197, "text": null }, { "code": null, "e": 4370, "s": 4342, "text": "Step 5: Plot neural network" }, { "code": "# Output to be present as PNG filepng(file = \"neuralNetwork2GFG.png\") # Plotplot(nn) # Saving the filedev.off()", "e": 4484, "s": 4370, "text": null }, { "code": null, "e": 4512, "s": 4484, "text": "Step 6: Create test dataset" }, { "code": "# Create test datasetvs = c(0, 1, 1)cyl =c(6, 8, 8)disp = c(170, 250, 350)hp = c(120, 240, 300)gear = c(4, 5, 4)carb = c(4, 3, 3)wt = c(2.780, 3.210, 3.425)drat = c(3.05, 4.02, 3.95) test <- data.frame(vs, cyl, disp, hp, gear, carb, wt, drat)", "e": 4774, "s": 4512, "text": null }, { "code": null, "e": 4814, "s": 4774, "text": "Step 7: Make prediction of test dataset" }, { "code": "Predict <- compute(nn, test) cat(\"Predicted values:\\n\")print(Predict$net.result)", "e": 4896, "s": 4814, "text": null }, { "code": null, "e": 4942, "s": 4896, "text": "Step 8: Convert prediction into binary values" }, { "code": "probability <- Predict$net.resultpred <- ifelse(probability > 0.5, 1, 0)cat(\"Result in binary values:\\n\")print(pred)", "e": 5059, "s": 4942, "text": null }, { "code": null, "e": 5067, "s": 5059, "text": "Output:" }, { "code": null, "e": 5212, "s": 5067, "text": "Predicted values:\n [,1]\n[1,] 0.3681382\n[2,] 0.9909768\n[3,] 0.9909768\n\nResult in binary values:\n [,1]\n[1,] 0\n[2,] 1\n[3,] 1\n" }, { "code": null, "e": 5442, "s": 5212, "text": "Explanation:In above output, “am” value for each row of test dataset is predicted using multi-layer neural network. As in neural network created by the function, predicted values greater than 0.49 makes “am” value of car to be 1." }, { "code": null, "e": 5542, "s": 5442, "text": "Single layer neural networks are easy to set up and train them as there is absence of hidden layers" }, { "code": null, "e": 5586, "s": 5542, "text": "It has explicit links to statistical models" }, { "code": null, "e": 5639, "s": 5586, "text": "It can work better only for linearly separable data." }, { "code": null, "e": 5727, "s": 5639, "text": "Single layer neural network has low accuracy as compared to multi-layer neural network." }, { "code": null, "e": 5740, "s": 5727, "text": "data-science" }, { "code": null, "e": 5747, "s": 5740, "text": "Picked" }, { "code": null, "e": 5766, "s": 5747, "text": "R Machine-Learning" }, { "code": null, "e": 5783, "s": 5766, "text": "Machine Learning" }, { "code": null, "e": 5794, "s": 5783, "text": "R Language" }, { "code": null, "e": 5811, "s": 5794, "text": "Machine Learning" } ]
Python | math.cos() function
20 Mar, 2019 In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.cos() function returns the cosine of value passed as argument. The value passed in this function should be in radians. Syntax: math.cos(x) Parameter:x : value to be passed to cos() Returns: Returns the cosine of value passed as argument Code #1: # Python code to demonstrate the working of cos() # importing "math" for mathematical operations import math a = math.pi / 6 # returning the value of cosine of pi / 6 print ("The value of cosine of pi / 6 is : ", end ="") print (math.cos(a)) The value of cosine of pi/6 is : 0.8660254037844387 Code #2: # Python program showing # Graphical representation of # cos() function import mathimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-(2 * np.pi), 2 * np.pi, 20) out_array = [] for i in range(len(in_array)): out_array.append(math.cos(in_array[i])) i += 1 print("in_array : ", in_array) print("\nout_array : ", out_array) # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = "o") plt.title("math.cos()") plt.xlabel("X") plt.ylabel("Y") plt.show() in_array : [-6.28318531 -5.62179738 -4.96040945 -4.29902153 -3.6376336 -2.97624567-2.31485774 -1.65346982 -0.99208189 -0.33069396 0.33069396 0.992081891.65346982 2.31485774 2.97624567 3.6376336 4.29902153 4.960409455.62179738 6.28318531] out_array : [1.0, 0.7891405093963934, 0.2454854871407988, -0.40169542465296987, -0.8794737512064891, -0.9863613034027223, -0.6772815716257412, -0.08257934547233249, 0.5469481581224268, 0.9458172417006346, 0.9458172417006346, 0.5469481581224268, -0.0825793454723316, -0.6772815716257405, -0.9863613034027223, -0.8794737512064893, -0.40169542465296987, 0.2454854871407988, 0.7891405093963934, 1.0] Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Mar, 2019" }, { "code": null, "e": 298, "s": 54, "text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.cos() function returns the cosine of value passed as argument. The value passed in this function should be in radians." }, { "code": null, "e": 318, "s": 298, "text": "Syntax: math.cos(x)" }, { "code": null, "e": 360, "s": 318, "text": "Parameter:x : value to be passed to cos()" }, { "code": null, "e": 416, "s": 360, "text": "Returns: Returns the cosine of value passed as argument" }, { "code": null, "e": 425, "s": 416, "text": "Code #1:" }, { "code": "# Python code to demonstrate the working of cos() # importing \"math\" for mathematical operations import math a = math.pi / 6 # returning the value of cosine of pi / 6 print (\"The value of cosine of pi / 6 is : \", end =\"\") print (math.cos(a)) ", "e": 680, "s": 425, "text": null }, { "code": null, "e": 733, "s": 680, "text": "The value of cosine of pi/6 is : 0.8660254037844387\n" }, { "code": null, "e": 743, "s": 733, "text": " Code #2:" }, { "code": "# Python program showing # Graphical representation of # cos() function import mathimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-(2 * np.pi), 2 * np.pi, 20) out_array = [] for i in range(len(in_array)): out_array.append(math.cos(in_array[i])) i += 1 print(\"in_array : \", in_array) print(\"\\nout_array : \", out_array) # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = \"o\") plt.title(\"math.cos()\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show() ", "e": 1252, "s": 743, "text": null }, { "code": null, "e": 1490, "s": 1252, "text": "in_array : [-6.28318531 -5.62179738 -4.96040945 -4.29902153 -3.6376336 -2.97624567-2.31485774 -1.65346982 -0.99208189 -0.33069396 0.33069396 0.992081891.65346982 2.31485774 2.97624567 3.6376336 4.29902153 4.960409455.62179738 6.28318531]" }, { "code": null, "e": 1886, "s": 1490, "text": "out_array : [1.0, 0.7891405093963934, 0.2454854871407988, -0.40169542465296987, -0.8794737512064891, -0.9863613034027223, -0.6772815716257412, -0.08257934547233249, 0.5469481581224268, 0.9458172417006346, 0.9458172417006346, 0.5469481581224268, -0.0825793454723316, -0.6772815716257405, -0.9863613034027223, -0.8794737512064893, -0.40169542465296987, 0.2454854871407988, 0.7891405093963934, 1.0]" }, { "code": null, "e": 1916, "s": 1886, "text": "Python math-library-functions" }, { "code": null, "e": 1923, "s": 1916, "text": "Python" }, { "code": null, "e": 2021, "s": 1923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2039, "s": 2021, "text": "Python Dictionary" }, { "code": null, "e": 2081, "s": 2039, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2103, "s": 2081, "text": "Enumerate() in Python" }, { "code": null, "e": 2138, "s": 2103, "text": "Read a file line by line in Python" }, { "code": null, "e": 2170, "s": 2138, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2196, "s": 2170, "text": "Python String | replace()" }, { "code": null, "e": 2225, "s": 2196, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2252, "s": 2225, "text": "Python Classes and Objects" }, { "code": null, "e": 2273, "s": 2252, "text": "Python OOPs Concepts" } ]
Introduction to Gradle
25 Aug, 2021 Gradle is an excellent open-source construction tool that is capable of the development of any kind of software. This tool was developed by a gaggle of developers named Hans Dockter, Szczepan Faber Adam Murdoch, Luke Daley, Peter Niederwieser, Daz DeBoer, and Rene Gröschkebefore 13 years before. It is an automation tool that is based on Apache Ant and Apache Maven. This tool is capable of developing applications with industry standards and supports a variety of languages including Groovy, C++, Java, Scala, and C. Gradle also is capable of controlling the development tasks with compilation and packaging to testing, deployment, and publishing. Gradle is the most stable tool when is compared to the Ant and Maven. This tool was released in late 2007 initially as an alternative for predecessors which not only replaced them but also covered the drawbacks for them. Its stable version was released in the year 2019 and now is currently with the latest version 6.6. The Gradle project when constructed it consists of one or more than one project. These projects consist of tasks. Let us understand the basics of both terms. 1. Gradle Projects: The projects created by Gradle are a web application or a JAR file. These projects are a combination of one or more tasks. These projects are capable to be deployed on the various development life cycles. A Gradle project can be described as building a wall with bricks N in number which can be termed as tasks. 2. Gradle Tasks: The tasks are the functions which are responsible for a specific role. These tasks are responsible for the creating of classes, Javadoc, or publish archives into the repository which makes the whole development of the Gradle project. These tasks help Gradle decide what input is to be processed for a specific output. Again tasks can be categorized into two different ways: Default Task: These are the predefined tasks that are provided to users by the Gradle. These are provided to users prior which executes when the users do not declare any task on his own. For example, init and wrapper the default tasks provided to users into a Gradle project Custom Task: Custom tasks are the tasks that are developed by the developer to perform a user-defined task. These are developed to run a specific role in a project. Let’s take a look at how to develop a Custom Task below. Example: Printing Welcome to GeeksforGeeks! with a task in Gradle. Java build.gradle : task hello{ doLast { println 'Welcome to GeeksforGeeks!' }} Output: > gradle -q hello Welcome to GeeksforGeeks! IDE support: Gradle supports a variety of IDE (Integrated Development Environment). This is a built tool that supports multiple development environments. Familiar with Java: Gradle projects need Java environment JVM to run. Features of Gradle are also similar to Java. It also supports the API’s which are supported by Java and it is the biggest advantage for developers and it makes it versatile. Tasks & Repository Support: Gradle tool supports the features of Ant and Maven build tools. It allows the Ant project to get imported into the Gradle environment. It also supports for the Maven repository to get imported and allows the infrastructure to be used in an existing project. Builds: Gradle provides build’s for necessary tasks only as if it only compiles the changes which are done previous the last build. It reduces the load time. Free and Open Source: Gradle is an open-source built tool that makes it user friendly and it is licensed under ASL (Apache License). Multiple Design Build Support: Gradle built tools implements multiple builds supports as while designing a root project it may contain several sub-projects and these projects can have multiple more projects. With the help of Gradle, one can easily build the layout. Declarative Builds: The Groovy language of Gradle provides declarative language elements. It checks the previous source code for the changes and then compiles. Scalability: Applications created with Gradle are highly scalable as it increases productivity. It allows us to work into model infrastructure which helps the work to get organized. Deep API: With the support of this API developers can easily customize the configuration and monitor the execution behavior. Free open source: Gradle is an open-source project which has good community support. Ease of movement: Gradle has a feature of adapting any project structure. It also supports the creation of plugins, which helps the project development. Technical Expertise: To built tasks with Gradle prior technical skills are required. Language Dependency: To use Gradle one needs to have basic knowledge of Groovy or Java language. Integration: Adding features is quite complex as it needs to get configured properly before into action. Understandability: Gradle documentation is quite comprehensive. It requires the knowledge of terms in prior. adnanirshad158 android GBlog Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Aug, 2021" }, { "code": null, "e": 705, "s": 53, "text": "Gradle is an excellent open-source construction tool that is capable of the development of any kind of software. This tool was developed by a gaggle of developers named Hans Dockter, Szczepan Faber Adam Murdoch, Luke Daley, Peter Niederwieser, Daz DeBoer, and Rene Gröschkebefore 13 years before. It is an automation tool that is based on Apache Ant and Apache Maven. This tool is capable of developing applications with industry standards and supports a variety of languages including Groovy, C++, Java, Scala, and C. Gradle also is capable of controlling the development tasks with compilation and packaging to testing, deployment, and publishing. " }, { "code": null, "e": 1026, "s": 705, "text": "Gradle is the most stable tool when is compared to the Ant and Maven. This tool was released in late 2007 initially as an alternative for predecessors which not only replaced them but also covered the drawbacks for them. Its stable version was released in the year 2019 and now is currently with the latest version 6.6. " }, { "code": null, "e": 1185, "s": 1026, "text": "The Gradle project when constructed it consists of one or more than one project. These projects consist of tasks. Let us understand the basics of both terms. " }, { "code": null, "e": 1909, "s": 1185, "text": "1. Gradle Projects: The projects created by Gradle are a web application or a JAR file. These projects are a combination of one or more tasks. These projects are capable to be deployed on the various development life cycles. A Gradle project can be described as building a wall with bricks N in number which can be termed as tasks. 2. Gradle Tasks: The tasks are the functions which are responsible for a specific role. These tasks are responsible for the creating of classes, Javadoc, or publish archives into the repository which makes the whole development of the Gradle project. These tasks help Gradle decide what input is to be processed for a specific output. Again tasks can be categorized into two different ways: " }, { "code": null, "e": 2184, "s": 1909, "text": "Default Task: These are the predefined tasks that are provided to users by the Gradle. These are provided to users prior which executes when the users do not declare any task on his own. For example, init and wrapper the default tasks provided to users into a Gradle project" }, { "code": null, "e": 2406, "s": 2184, "text": "Custom Task: Custom tasks are the tasks that are developed by the developer to perform a user-defined task. These are developed to run a specific role in a project. Let’s take a look at how to develop a Custom Task below." }, { "code": null, "e": 2475, "s": 2406, "text": "Example: Printing Welcome to GeeksforGeeks! with a task in Gradle. " }, { "code": null, "e": 2480, "s": 2475, "text": "Java" }, { "code": "build.gradle : task hello{ doLast { println 'Welcome to GeeksforGeeks!' }}", "e": 2571, "s": 2480, "text": null }, { "code": null, "e": 2580, "s": 2571, "text": "Output: " }, { "code": null, "e": 2624, "s": 2580, "text": "> gradle -q hello\nWelcome to GeeksforGeeks!" }, { "code": null, "e": 2778, "s": 2624, "text": "IDE support: Gradle supports a variety of IDE (Integrated Development Environment). This is a built tool that supports multiple development environments." }, { "code": null, "e": 3022, "s": 2778, "text": "Familiar with Java: Gradle projects need Java environment JVM to run. Features of Gradle are also similar to Java. It also supports the API’s which are supported by Java and it is the biggest advantage for developers and it makes it versatile." }, { "code": null, "e": 3308, "s": 3022, "text": "Tasks & Repository Support: Gradle tool supports the features of Ant and Maven build tools. It allows the Ant project to get imported into the Gradle environment. It also supports for the Maven repository to get imported and allows the infrastructure to be used in an existing project." }, { "code": null, "e": 3466, "s": 3308, "text": "Builds: Gradle provides build’s for necessary tasks only as if it only compiles the changes which are done previous the last build. It reduces the load time." }, { "code": null, "e": 3599, "s": 3466, "text": "Free and Open Source: Gradle is an open-source built tool that makes it user friendly and it is licensed under ASL (Apache License)." }, { "code": null, "e": 3865, "s": 3599, "text": "Multiple Design Build Support: Gradle built tools implements multiple builds supports as while designing a root project it may contain several sub-projects and these projects can have multiple more projects. With the help of Gradle, one can easily build the layout." }, { "code": null, "e": 4025, "s": 3865, "text": "Declarative Builds: The Groovy language of Gradle provides declarative language elements. It checks the previous source code for the changes and then compiles." }, { "code": null, "e": 4207, "s": 4025, "text": "Scalability: Applications created with Gradle are highly scalable as it increases productivity. It allows us to work into model infrastructure which helps the work to get organized." }, { "code": null, "e": 4332, "s": 4207, "text": "Deep API: With the support of this API developers can easily customize the configuration and monitor the execution behavior." }, { "code": null, "e": 4417, "s": 4332, "text": "Free open source: Gradle is an open-source project which has good community support." }, { "code": null, "e": 4570, "s": 4417, "text": "Ease of movement: Gradle has a feature of adapting any project structure. It also supports the creation of plugins, which helps the project development." }, { "code": null, "e": 4655, "s": 4570, "text": "Technical Expertise: To built tasks with Gradle prior technical skills are required." }, { "code": null, "e": 4752, "s": 4655, "text": "Language Dependency: To use Gradle one needs to have basic knowledge of Groovy or Java language." }, { "code": null, "e": 4857, "s": 4752, "text": "Integration: Adding features is quite complex as it needs to get configured properly before into action." }, { "code": null, "e": 4966, "s": 4857, "text": "Understandability: Gradle documentation is quite comprehensive. It requires the knowledge of terms in prior." }, { "code": null, "e": 4981, "s": 4966, "text": "adnanirshad158" }, { "code": null, "e": 4989, "s": 4981, "text": "android" }, { "code": null, "e": 4995, "s": 4989, "text": "GBlog" }, { "code": null, "e": 5000, "s": 4995, "text": "Java" }, { "code": null, "e": 5005, "s": 5000, "text": "Java" } ]
Find the middle digit of a given Number
06 May, 2021 Given a number N, the task is to find the middle digit of the given number N. If the number has two middle digits then print the first middle digit. Examples: Input: N = 12345 Output: 3 Input: N = 98562 Output: 5 Approach: The middle digit of any number N can be given by The length(len) of the given Number can be calculated as For example: If N = 12345 len = (int)log10(12345) + 1 = 5 Therefore, First half of N = N/105/2 = N/102 = 123 Therefore middle digit of N = last digit of First half of N = (First half of N) % 10 = 123 % 10 = 3 Below code is the implementation of the above approach: C++ Java Python3 C# Javascript // Program to find middle digit of number #include <bits/stdc++.h>using namespace std; // Function to find the middle digitint middleDigit(int n){ // Find total number of digits int digits = (int)log10(n) + 1; // Find middle digit n = (int)(n / pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver programint main(){ // Given Number N int N = 98562; // Function call cout << middleDigit(N) << "\n"; return 0;} // Java program to find middle digit of numberclass GFG{ // Function to find the middle digitstatic int middleDigit(int n){ // Find total number of digits int digits = (int)Math.log10(n) + 1; // Find middle digit n = (int)(n / Math.pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver Codepublic static void main(String[] args){ // Given number N int N = 98562; // Function call System.out.println(middleDigit(N));}} // This code is contributed by rutvik_56 # Python3 Program to find middle digit of numberimport math # Function to find the middle digitdef middleDigit(n): # Find total number of digits digits = math.log10(n) + 1; # Find middle digit n = int((n // math.pow(10, digits // 2))) % 10; # Return middle digit return n; # Driver program # Given Number NN = 98562; # Function callprint(middleDigit(N)) # This code is contributed by Code_Mech // C# program to find middle digit of numberusing System; class GFG{ // Function to find the middle digitstatic int middleDigit(int n){ // Find total number of digits int digits = (int)Math.Log10(n) + 1; // Find middle digit n = (int)(n / Math.Pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver codestatic void Main(){ // Given number N int N = 98562; // Function call Console.WriteLine(middleDigit(N));}} // This code is contributed by divyeshrabadiya07 <script>// Program to find middle digit of number // Function to find the middle digitfunction middleDigit(n){ // Find total number of digits let digits = parseInt(Math.log10(n) + 1); // Find middle digit n = parseInt(parseInt(n / Math.pow(10, parseInt(digits / 2))) % 10); // Return middle digit return n;} // Driver program// Given Number Nlet N = 98562; // Function calldocument.write(middleDigit(N)); // This code is contributed by subham348.</script> 5 Time Complexity: O(1) Auxiliary Space: O(1) rutvik_56 divyeshrabadiya07 Code_Mech dewantipandeydp rohitsingh07052 subham348 ManasChhabra2 number-digits Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2021" }, { "code": null, "e": 201, "s": 52, "text": "Given a number N, the task is to find the middle digit of the given number N. If the number has two middle digits then print the first middle digit." }, { "code": null, "e": 213, "s": 201, "text": "Examples: " }, { "code": null, "e": 240, "s": 213, "text": "Input: N = 12345 Output: 3" }, { "code": null, "e": 269, "s": 240, "text": "Input: N = 98562 Output: 5 " }, { "code": null, "e": 329, "s": 269, "text": "Approach: The middle digit of any number N can be given by " }, { "code": null, "e": 387, "s": 329, "text": "The length(len) of the given Number can be calculated as " }, { "code": null, "e": 402, "s": 387, "text": "For example: " }, { "code": null, "e": 599, "s": 402, "text": "If N = 12345 len = (int)log10(12345) + 1 = 5 Therefore, First half of N = N/105/2 = N/102 = 123 Therefore middle digit of N = last digit of First half of N = (First half of N) % 10 = 123 % 10 = 3 " }, { "code": null, "e": 656, "s": 599, "text": "Below code is the implementation of the above approach: " }, { "code": null, "e": 660, "s": 656, "text": "C++" }, { "code": null, "e": 665, "s": 660, "text": "Java" }, { "code": null, "e": 673, "s": 665, "text": "Python3" }, { "code": null, "e": 676, "s": 673, "text": "C#" }, { "code": null, "e": 687, "s": 676, "text": "Javascript" }, { "code": "// Program to find middle digit of number #include <bits/stdc++.h>using namespace std; // Function to find the middle digitint middleDigit(int n){ // Find total number of digits int digits = (int)log10(n) + 1; // Find middle digit n = (int)(n / pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver programint main(){ // Given Number N int N = 98562; // Function call cout << middleDigit(N) << \"\\n\"; return 0;}", "e": 1166, "s": 687, "text": null }, { "code": "// Java program to find middle digit of numberclass GFG{ // Function to find the middle digitstatic int middleDigit(int n){ // Find total number of digits int digits = (int)Math.log10(n) + 1; // Find middle digit n = (int)(n / Math.pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver Codepublic static void main(String[] args){ // Given number N int N = 98562; // Function call System.out.println(middleDigit(N));}} // This code is contributed by rutvik_56 ", "e": 1688, "s": 1166, "text": null }, { "code": "# Python3 Program to find middle digit of numberimport math # Function to find the middle digitdef middleDigit(n): # Find total number of digits digits = math.log10(n) + 1; # Find middle digit n = int((n // math.pow(10, digits // 2))) % 10; # Return middle digit return n; # Driver program # Given Number NN = 98562; # Function callprint(middleDigit(N)) # This code is contributed by Code_Mech", "e": 2103, "s": 1688, "text": null }, { "code": "// C# program to find middle digit of numberusing System; class GFG{ // Function to find the middle digitstatic int middleDigit(int n){ // Find total number of digits int digits = (int)Math.Log10(n) + 1; // Find middle digit n = (int)(n / Math.Pow(10, digits / 2)) % 10; // Return middle digit return n;} // Driver codestatic void Main(){ // Given number N int N = 98562; // Function call Console.WriteLine(middleDigit(N));}} // This code is contributed by divyeshrabadiya07 ", "e": 2648, "s": 2103, "text": null }, { "code": "<script>// Program to find middle digit of number // Function to find the middle digitfunction middleDigit(n){ // Find total number of digits let digits = parseInt(Math.log10(n) + 1); // Find middle digit n = parseInt(parseInt(n / Math.pow(10, parseInt(digits / 2))) % 10); // Return middle digit return n;} // Driver program// Given Number Nlet N = 98562; // Function calldocument.write(middleDigit(N)); // This code is contributed by subham348.</script>", "e": 3124, "s": 2648, "text": null }, { "code": null, "e": 3126, "s": 3124, "text": "5" }, { "code": null, "e": 3150, "s": 3128, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3172, "s": 3150, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3182, "s": 3172, "text": "rutvik_56" }, { "code": null, "e": 3200, "s": 3182, "text": "divyeshrabadiya07" }, { "code": null, "e": 3210, "s": 3200, "text": "Code_Mech" }, { "code": null, "e": 3226, "s": 3210, "text": "dewantipandeydp" }, { "code": null, "e": 3242, "s": 3226, "text": "rohitsingh07052" }, { "code": null, "e": 3252, "s": 3242, "text": "subham348" }, { "code": null, "e": 3266, "s": 3252, "text": "ManasChhabra2" }, { "code": null, "e": 3280, "s": 3266, "text": "number-digits" }, { "code": null, "e": 3293, "s": 3280, "text": "Mathematical" }, { "code": null, "e": 3312, "s": 3293, "text": "School Programming" }, { "code": null, "e": 3325, "s": 3312, "text": "Mathematical" } ]
Python | Numpy np.cholesky() method
11 Nov, 2019 With the help of np.cholesky() method, we can get the cholesky decomposition by using np.cholesky() method. Syntax : np.cholesky(matrix)Return : Return the cholesky decomposition. Example #1 :In this example we can see that by using np.cholesky() method, we are able to get the cholesky decomposition in the form of matrix using this method. # import numpyimport numpy as np a = np.array([[2, -3j], [5j, 15]])# using np.cholesky() methodgfg = np.linalg.cholesky(a) print(gfg) Output : [[1.41421356 + 0.j, 0. + 0.j][0. + 3.53553391j, 1.58113883 + 0.j]] Example #2 : # import numpyimport numpy as np a = np.array([[12, -13j], [4j, 8]])# using np.cholesky() methodgfg = np.linalg.cholesky(a) print(gfg) Output : [[3.46410162 + 0.j, 0. + 0.j][0. + 1.15470054j, 2.5819889 + 0.j]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2019" }, { "code": null, "e": 136, "s": 28, "text": "With the help of np.cholesky() method, we can get the cholesky decomposition by using np.cholesky() method." }, { "code": null, "e": 208, "s": 136, "text": "Syntax : np.cholesky(matrix)Return : Return the cholesky decomposition." }, { "code": null, "e": 370, "s": 208, "text": "Example #1 :In this example we can see that by using np.cholesky() method, we are able to get the cholesky decomposition in the form of matrix using this method." }, { "code": "# import numpyimport numpy as np a = np.array([[2, -3j], [5j, 15]])# using np.cholesky() methodgfg = np.linalg.cholesky(a) print(gfg)", "e": 506, "s": 370, "text": null }, { "code": null, "e": 515, "s": 506, "text": "Output :" }, { "code": null, "e": 582, "s": 515, "text": "[[1.41421356 + 0.j, 0. + 0.j][0. + 3.53553391j, 1.58113883 + 0.j]]" }, { "code": null, "e": 595, "s": 582, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np a = np.array([[12, -13j], [4j, 8]])# using np.cholesky() methodgfg = np.linalg.cholesky(a) print(gfg)", "e": 732, "s": 595, "text": null }, { "code": null, "e": 741, "s": 732, "text": "Output :" }, { "code": null, "e": 807, "s": 741, "text": "[[3.46410162 + 0.j, 0. + 0.j][0. + 1.15470054j, 2.5819889 + 0.j]]" }, { "code": null, "e": 820, "s": 807, "text": "Python-numpy" }, { "code": null, "e": 827, "s": 820, "text": "Python" } ]
CSS | word-wrap Property
02 Jan, 2019 The word-wrap property in CSS is used to break long word and wrap into the next line. It defines whether to break words when the content exceeds the boundaries of its container. Syntax: word-wrap: normal|break-word|initial|inherit; Property Value: normal: It is the default value, The lines can only be broken at normal break points (spaces, non-alphanumeric characters, etc.).Syntax:word-wrap: normal;Example:<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:normal; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> Output: Syntax: word-wrap: normal; Example: <!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:normal; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> Output: break-word: Words that exceed the width of the container will be arbitrarily broken to fit within the container’s bounds.Syntax:word-wrap: break-word;Example:<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:break-word; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> Syntax: word-wrap: break-word; Example: <!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:break-word; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> initial: It is used to set word-wrap property to its default value. inherit: This property is inherited from its parent. Supported Browsers: The browser supported by word-wrap property are listed below: Google Chrome 4.0 Internet Explore 5.5 Firefox 3.5 Safari 3.1 Opera 10.5 CSS-Properties Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript Roadmap to Learn JavaScript For Beginners How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jan, 2019" }, { "code": null, "e": 232, "s": 54, "text": "The word-wrap property in CSS is used to break long word and wrap into the next line. It defines whether to break words when the content exceeds the boundaries of its container." }, { "code": null, "e": 240, "s": 232, "text": "Syntax:" }, { "code": null, "e": 286, "s": 240, "text": "word-wrap: normal|break-word|initial|inherit;" }, { "code": null, "e": 302, "s": 286, "text": "Property Value:" }, { "code": null, "e": 892, "s": 302, "text": "normal: It is the default value, The lines can only be broken at normal break points (spaces, non-alphanumeric characters, etc.).Syntax:word-wrap: normal;Example:<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:normal; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> Output:" }, { "code": null, "e": 900, "s": 892, "text": "Syntax:" }, { "code": null, "e": 919, "s": 900, "text": "word-wrap: normal;" }, { "code": null, "e": 928, "s": 919, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:normal; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> ", "e": 1349, "s": 928, "text": null }, { "code": null, "e": 1357, "s": 1349, "text": "Output:" }, { "code": null, "e": 1940, "s": 1357, "text": "break-word: Words that exceed the width of the container will be arbitrarily broken to fit within the container’s bounds.Syntax:word-wrap: break-word;Example:<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:break-word; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> " }, { "code": null, "e": 1948, "s": 1940, "text": "Syntax:" }, { "code": null, "e": 1971, "s": 1948, "text": "word-wrap: break-word;" }, { "code": null, "e": 1980, "s": 1971, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> word-wrap property </title> <style> div { word-wrap:break-word; width: 150px; border: 1px solid black; } </style> </head> <body> <div> GeeksforGeeks:AComputerSciencePortalForGeeks </div> </body></html> ", "e": 2405, "s": 1980, "text": null }, { "code": null, "e": 2473, "s": 2405, "text": "initial: It is used to set word-wrap property to its default value." }, { "code": null, "e": 2526, "s": 2473, "text": "inherit: This property is inherited from its parent." }, { "code": null, "e": 2608, "s": 2526, "text": "Supported Browsers: The browser supported by word-wrap property are listed below:" }, { "code": null, "e": 2626, "s": 2608, "text": "Google Chrome 4.0" }, { "code": null, "e": 2647, "s": 2626, "text": "Internet Explore 5.5" }, { "code": null, "e": 2659, "s": 2647, "text": "Firefox 3.5" }, { "code": null, "e": 2670, "s": 2659, "text": "Safari 3.1" }, { "code": null, "e": 2681, "s": 2670, "text": "Opera 10.5" }, { "code": null, "e": 2696, "s": 2681, "text": "CSS-Properties" }, { "code": null, "e": 2703, "s": 2696, "text": "Picked" }, { "code": null, "e": 2727, "s": 2703, "text": "Technical Scripter 2018" }, { "code": null, "e": 2731, "s": 2727, "text": "CSS" }, { "code": null, "e": 2750, "s": 2731, "text": "Technical Scripter" }, { "code": null, "e": 2767, "s": 2750, "text": "Web Technologies" }, { "code": null, "e": 2865, "s": 2767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2913, "s": 2865, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2975, "s": 2913, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3025, "s": 2975, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3083, "s": 3025, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3120, "s": 3083, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3153, "s": 3120, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3215, "s": 3153, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3276, "s": 3215, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3318, "s": 3276, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Scala Identifiers
11 Nov, 2021 In programming languages, Identifiers are used for identification purpose. In Scala, an identifier can be a class name, method name, variable name or an object name. For example : class GFG{ var a: Int = 20 } object Main { def main(args: Array[String]) { var ob = new GFG(); } } In the above program we have 6 identifiers: GFG: Class name a: Variable name Main: Object name main: Method name args: Variable name ob: Object name There are certain rules for defining a valid Scala identifier. These rules must be followed, otherwise we get a compile-time error. Scala identifiers are case-sensitive. Scala does not allows you to use keyword as an identifier. Reserved Words can’t be used as an identifier like $ etc. Scala only allowed those identifiers which are created using below four types of identifiers. There is no limit on the length of the identifier, but it is advisable to use an optimum length of 4 – 15 letters only. Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid Scala identifier. Example: Scala // Scala program to demonstrate// Identifiers object Main{ // Main method def main(args: Array[String]) { // Valid Identifiers var `name` = "Siya"; var _age = 20; var Branch = "Computer Science"; println("Name:" +`name`); println("Age:" +_age); println("Branch:" +Branch); }} Output: Name:Siya Age:20 Branch:Computer Science In the above example, valid identifiers are: Main, main, args, `name`, _age, Branch, + and keywords are: Object, def, var, println Scala supports four types of identifiers: Alphanumeric Identifiers: These identifiers are those identifiers which start with a letter(capital or small letter) or an underscore and followed by letters, digits, or underscores.Example of valid alphanumeric identifiers: _GFG, geeks123, _1_Gee_23, Geeks Example of Invalid alphanumeric identifiers: 123G, $Geeks, -geeks Example: Scala // Scala program to demonstrate// Alphanumeric Identifiers object Main{ // Main method def main(args: Array[String]) { // main, _name1, and Tuto_rial are // valid alphanumeric identifiers var _name1: String = "GeeksforGeeks" var Tuto_rial: String = "Scala" println(_name1); println(Tuto_rial); }} Output: GeeksforGeeks Scala Operator Identifiers: These are those identifiers which contain one or more operator character like +, :, ?, ~, or # etc. Example of valid operator identifiers: +, ++ Example: Scala // Scala program to demonstrate// Operator Identifiers object Main{ // Main method def main(args: Array[String]) { // main, x, y, and sum are valid // alphanumeric identifiers var x:Int = 20; var y:Int = 10; // Here, + is a operator identifier // which is used to add two values var sum = x + y; println("Display the result of + identifier:"); println(sum); }} Output: Display the result of + identifier: 30 Mixed Identifiers: These are those identifiers which contains alphanumeric identifiers followed by undersoce and an operator identifier. Example of valid mixed identifiers: unary_+, sum_= Example: Scala // Scala program to demonstrate// Mixed Identifiers object Main{ // Main method def main(args: Array[String]) { // num_+ is a valid mixed identifier var num_+ = 20; println("Display the result of mixed identifier:"); println(num_+); }} Output: Display the result of mixed identifier: 20 Literal Identifiers: These are those identifiers in which an arbitrary string enclosed with back ticks (`....`) . Example of valid mixed identifiers: `Geeks`, `name` Example: Scala // Scala program to demonstrate// Literal Identifiers object Main{ // Main method def main(args: Array[String]) { // `name` and `age` are valid literal identifiers var `name` = "Siya" var `age` = 20 println("Name:" +`name`); println("Age:" +`age`); }} Output: Name:Siya Age:20 kapoorsagar226 abhishek0719kadiyan simmytarika5 Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Type Casting in Scala Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example Enumeration in Scala
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2021" }, { "code": null, "e": 236, "s": 54, "text": "In programming languages, Identifiers are used for identification purpose. In Scala, an identifier can be a class name, method name, variable name or an object name. For example : " }, { "code": null, "e": 355, "s": 236, "text": "class GFG{\n var a: Int = 20\n}\nobject Main {\n def main(args: Array[String]) {\n var ob = new GFG();\n }\n}" }, { "code": null, "e": 400, "s": 355, "text": "In the above program we have 6 identifiers: " }, { "code": null, "e": 416, "s": 400, "text": "GFG: Class name" }, { "code": null, "e": 433, "s": 416, "text": "a: Variable name" }, { "code": null, "e": 451, "s": 433, "text": "Main: Object name" }, { "code": null, "e": 469, "s": 451, "text": "main: Method name" }, { "code": null, "e": 489, "s": 469, "text": "args: Variable name" }, { "code": null, "e": 506, "s": 489, "text": "ob: Object name " }, { "code": null, "e": 640, "s": 506, "text": "There are certain rules for defining a valid Scala identifier. These rules must be followed, otherwise we get a compile-time error. " }, { "code": null, "e": 678, "s": 640, "text": "Scala identifiers are case-sensitive." }, { "code": null, "e": 737, "s": 678, "text": "Scala does not allows you to use keyword as an identifier." }, { "code": null, "e": 795, "s": 737, "text": "Reserved Words can’t be used as an identifier like $ etc." }, { "code": null, "e": 889, "s": 795, "text": "Scala only allowed those identifiers which are created using below four types of identifiers." }, { "code": null, "e": 1009, "s": 889, "text": "There is no limit on the length of the identifier, but it is advisable to use an optimum length of 4 – 15 letters only." }, { "code": null, "e": 1116, "s": 1009, "text": "Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid Scala identifier." }, { "code": null, "e": 1126, "s": 1116, "text": "Example: " }, { "code": null, "e": 1132, "s": 1126, "text": "Scala" }, { "code": "// Scala program to demonstrate// Identifiers object Main{ // Main method def main(args: Array[String]) { // Valid Identifiers var `name` = \"Siya\"; var _age = 20; var Branch = \"Computer Science\"; println(\"Name:\" +`name`); println(\"Age:\" +_age); println(\"Branch:\" +Branch); }}", "e": 1455, "s": 1132, "text": null }, { "code": null, "e": 1465, "s": 1455, "text": "Output: " }, { "code": null, "e": 1506, "s": 1465, "text": "Name:Siya\nAge:20\nBranch:Computer Science" }, { "code": null, "e": 1553, "s": 1506, "text": "In the above example, valid identifiers are: " }, { "code": null, "e": 1595, "s": 1553, "text": "Main, main, args, `name`, _age, Branch, +" }, { "code": null, "e": 1614, "s": 1595, "text": "and keywords are: " }, { "code": null, "e": 1640, "s": 1614, "text": "Object, def, var, println" }, { "code": null, "e": 1685, "s": 1642, "text": "Scala supports four types of identifiers: " }, { "code": null, "e": 1911, "s": 1685, "text": "Alphanumeric Identifiers: These identifiers are those identifiers which start with a letter(capital or small letter) or an underscore and followed by letters, digits, or underscores.Example of valid alphanumeric identifiers: " }, { "code": null, "e": 1945, "s": 1911, "text": " _GFG, geeks123, _1_Gee_23, Geeks" }, { "code": null, "e": 1991, "s": 1945, "text": "Example of Invalid alphanumeric identifiers: " }, { "code": null, "e": 2012, "s": 1991, "text": "123G, $Geeks, -geeks" }, { "code": null, "e": 2022, "s": 2012, "text": "Example: " }, { "code": null, "e": 2028, "s": 2022, "text": "Scala" }, { "code": "// Scala program to demonstrate// Alphanumeric Identifiers object Main{ // Main method def main(args: Array[String]) { // main, _name1, and Tuto_rial are // valid alphanumeric identifiers var _name1: String = \"GeeksforGeeks\" var Tuto_rial: String = \"Scala\" println(_name1); println(Tuto_rial); }}", "e": 2374, "s": 2028, "text": null }, { "code": null, "e": 2383, "s": 2374, "text": "Output: " }, { "code": null, "e": 2403, "s": 2383, "text": "GeeksforGeeks\nScala" }, { "code": null, "e": 2565, "s": 2403, "text": "Operator Identifiers: These are those identifiers which contain one or more operator character like +, :, ?, ~, or # etc. Example of valid operator identifiers: " }, { "code": null, "e": 2573, "s": 2565, "text": " +, ++ " }, { "code": null, "e": 2583, "s": 2573, "text": "Example: " }, { "code": null, "e": 2589, "s": 2583, "text": "Scala" }, { "code": "// Scala program to demonstrate// Operator Identifiers object Main{ // Main method def main(args: Array[String]) { // main, x, y, and sum are valid // alphanumeric identifiers var x:Int = 20; var y:Int = 10; // Here, + is a operator identifier // which is used to add two values var sum = x + y; println(\"Display the result of + identifier:\"); println(sum); }}", "e": 3008, "s": 2589, "text": null }, { "code": null, "e": 3017, "s": 3008, "text": "Output: " }, { "code": null, "e": 3056, "s": 3017, "text": "Display the result of + identifier:\n30" }, { "code": null, "e": 3230, "s": 3056, "text": "Mixed Identifiers: These are those identifiers which contains alphanumeric identifiers followed by undersoce and an operator identifier. Example of valid mixed identifiers: " }, { "code": null, "e": 3247, "s": 3230, "text": " unary_+, sum_= " }, { "code": null, "e": 3257, "s": 3247, "text": "Example: " }, { "code": null, "e": 3263, "s": 3257, "text": "Scala" }, { "code": "// Scala program to demonstrate// Mixed Identifiers object Main{ // Main method def main(args: Array[String]) { // num_+ is a valid mixed identifier var num_+ = 20; println(\"Display the result of mixed identifier:\"); println(num_+); }}", "e": 3537, "s": 3263, "text": null }, { "code": null, "e": 3546, "s": 3537, "text": "Output: " }, { "code": null, "e": 3589, "s": 3546, "text": "Display the result of mixed identifier:\n20" }, { "code": null, "e": 3740, "s": 3589, "text": "Literal Identifiers: These are those identifiers in which an arbitrary string enclosed with back ticks (`....`) . Example of valid mixed identifiers: " }, { "code": null, "e": 3757, "s": 3740, "text": "`Geeks`, `name` " }, { "code": null, "e": 3767, "s": 3757, "text": "Example: " }, { "code": null, "e": 3773, "s": 3767, "text": "Scala" }, { "code": "// Scala program to demonstrate// Literal Identifiers object Main{ // Main method def main(args: Array[String]) { // `name` and `age` are valid literal identifiers var `name` = \"Siya\" var `age` = 20 println(\"Name:\" +`name`); println(\"Age:\" +`age`); }}", "e": 4066, "s": 3773, "text": null }, { "code": null, "e": 4075, "s": 4066, "text": "Output: " }, { "code": null, "e": 4092, "s": 4075, "text": "Name:Siya\nAge:20" }, { "code": null, "e": 4107, "s": 4092, "text": "kapoorsagar226" }, { "code": null, "e": 4127, "s": 4107, "text": "abhishek0719kadiyan" }, { "code": null, "e": 4140, "s": 4127, "text": "simmytarika5" }, { "code": null, "e": 4146, "s": 4140, "text": "Scala" }, { "code": null, "e": 4159, "s": 4146, "text": "Scala-Basics" }, { "code": null, "e": 4165, "s": 4159, "text": "Scala" }, { "code": null, "e": 4263, "s": 4165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4281, "s": 4263, "text": "For Loop in Scala" }, { "code": null, "e": 4302, "s": 4281, "text": "Scala | map() method" }, { "code": null, "e": 4325, "s": 4302, "text": "Scala | flatMap Method" }, { "code": null, "e": 4355, "s": 4325, "text": "String concatenation in Scala" }, { "code": null, "e": 4381, "s": 4355, "text": "Scala | reduce() Function" }, { "code": null, "e": 4403, "s": 4381, "text": "Type Casting in Scala" }, { "code": null, "e": 4443, "s": 4403, "text": "Scala List filter() method with example" }, { "code": null, "e": 4496, "s": 4443, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 4541, "s": 4496, "text": "Scala String substring() method with example" } ]
File Handling in R Programming
22 Jul, 2020 In R Programming, handling of files such as reading and writing files can be done by using in-built functions present in R base package. In this article, let us discuss reading and writing of CSV files, creating a file, renaming a file, check the existence of the file, listing all files in the working directory, copying files and creating directories. Using file.create() function, a new file can be created from console or truncates if already exists. The function returns a TRUE logical value if file is created otherwise, returns FALSE. Syntax:file.create(” “) Parameters:” “: name of the file is passed in ” ” that has to be created Example: # Create a file# The file created can be seen# in your working directoryfile.create("GFG.txt") Output: [1] TRUE write.table() function in R programming is used to write an object to a file. This function is present in utils package in R and writes data frame or matrix object to any type of file. Syntax:write.table(x, file) Parameters:x: indicates the object that has to be written into the filefile: indicates the name of the file that has to be written Example: # Write iris dataset# into the txt filewrite.table(x = iris[1:10, ], file = "GFG.txt") Output: The file.rename() function renames the file and return a logical value. The function renames files but not directories. Syntax:file.rename(from, to) Parameters:from: indicates current file name or pathto: indicates new file name or path Example: # Rename file GFG.txt to newGFG.txtfile.rename("GFG.txt", "newGFG.txt") Output: [1] TRUE A file exists or not in current working directory can be checked using file.exists() function. It returns TRUE logical value if file exists, otherwise returns FALSE. Syntax:file.exists(” “) Parameters:” “: name of the file that has to be searched in the current working directory is passed in ” ” Example: # Check for GFG>txtfile.exists("GFG.txt") # Check for newGFG.txtfile.exists("newGFG.txt") Output: [1] FALSE [1] TRUE Using read.table() function in R, files can be read and output is shown as dataframe. This functions helps in analyzing the dataframe for further computations. Syntax:read.table(file) Parameters:file: indicates the name of the file that has to be read Example: # Reading txt filenew.iris <- read.table(file = "GFG.txt") # Printprint(new.iris) X Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 1 5.1 3.5 1.4 0.2 setosa 2 2 4.9 3.0 1.4 0.2 setosa 3 3 4.7 3.2 1.3 0.2 setosa 4 4 4.6 3.1 1.5 0.2 setosa 5 5 5.0 3.6 1.4 0.2 setosa 6 6 5.4 3.9 1.7 0.4 setosa 7 7 4.6 3.4 1.4 0.3 setosa 8 8 5.0 3.4 1.5 0.2 setosa 9 9 4.4 2.9 1.4 0.2 setosa 10 10 4.9 3.1 1.5 0.1 setosa Using list.files() function, all files of specified path will be shown in the output. If path is not passed in the function parameter, files present in current working directory is shown as output. Syntax:list.files(path) Parameters:path: indicates the pathTo know about more optional parameters, use below command in console: help(“list.files”) Example: # Show all files in# current working directorylist.files() Output: [1] "Bandicam" "Bluetooth Folder" [3] "Book1.xlsx" "Custom Office Templates" [5] "desktop.ini" "list.xlsx" [7] "My Music" "My Pictures" [9] "My Videos" "newGFG.txt" [11] "Visual Studio 2012" The file.copy() function in R helps to create a copy of specified file from console itself. Syntax:file.copy(from, to) Parameters:from: indicates the file path that has to be copiedto: indicates the path where it has to be copiedTo know about more optional parameters, use below command in console: help(“file.copy”) Example: # Copyingfile.copy("C:/Users/Utkarsh/Documents/ newGFG.txt", "E:/") # List the files in E:/ drivelist.files("E:/") Output: [1] TRUE [1] "$RECYCLE.BIN" "Counter-Strike Global Offensive" [3] "Home" "newGFG.txt" [5] "System Volume Information" The dir.create() function creates a directory in the path specified in the function parameter. If path is not specified in function parameter, directory is created in current working directory. Syntax:dir.create(path) Parameters:path: indicates the path where directory has to be created with directory name at the end of the path Example: # Without specifying the path,# directory will be created in # current working directorydir.create("GFG") # List fileslist.files() Output: [1] "Bandicam" "Bluetooth Folder" [3] "Book1.xlsx" "Custom Office Templates" [5] "desktop.ini" "GFG" [7] "list.xlsx" "My Music" [9] "My Pictures" "My Videos" [11] "newGFG.txt" "Visual Studio 2012" Picked R-FileHandling R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2020" }, { "code": null, "e": 382, "s": 28, "text": "In R Programming, handling of files such as reading and writing files can be done by using in-built functions present in R base package. In this article, let us discuss reading and writing of CSV files, creating a file, renaming a file, check the existence of the file, listing all files in the working directory, copying files and creating directories." }, { "code": null, "e": 570, "s": 382, "text": "Using file.create() function, a new file can be created from console or truncates if already exists. The function returns a TRUE logical value if file is created otherwise, returns FALSE." }, { "code": null, "e": 594, "s": 570, "text": "Syntax:file.create(” “)" }, { "code": null, "e": 667, "s": 594, "text": "Parameters:” “: name of the file is passed in ” ” that has to be created" }, { "code": null, "e": 676, "s": 667, "text": "Example:" }, { "code": "# Create a file# The file created can be seen# in your working directoryfile.create(\"GFG.txt\")", "e": 771, "s": 676, "text": null }, { "code": null, "e": 779, "s": 771, "text": "Output:" }, { "code": null, "e": 789, "s": 779, "text": "[1] TRUE\n" }, { "code": null, "e": 974, "s": 789, "text": "write.table() function in R programming is used to write an object to a file. This function is present in utils package in R and writes data frame or matrix object to any type of file." }, { "code": null, "e": 1002, "s": 974, "text": "Syntax:write.table(x, file)" }, { "code": null, "e": 1133, "s": 1002, "text": "Parameters:x: indicates the object that has to be written into the filefile: indicates the name of the file that has to be written" }, { "code": null, "e": 1142, "s": 1133, "text": "Example:" }, { "code": "# Write iris dataset# into the txt filewrite.table(x = iris[1:10, ], file = \"GFG.txt\")", "e": 1240, "s": 1142, "text": null }, { "code": null, "e": 1248, "s": 1240, "text": "Output:" }, { "code": null, "e": 1368, "s": 1248, "text": "The file.rename() function renames the file and return a logical value. The function renames files but not directories." }, { "code": null, "e": 1397, "s": 1368, "text": "Syntax:file.rename(from, to)" }, { "code": null, "e": 1485, "s": 1397, "text": "Parameters:from: indicates current file name or pathto: indicates new file name or path" }, { "code": null, "e": 1494, "s": 1485, "text": "Example:" }, { "code": "# Rename file GFG.txt to newGFG.txtfile.rename(\"GFG.txt\", \"newGFG.txt\")", "e": 1566, "s": 1494, "text": null }, { "code": null, "e": 1574, "s": 1566, "text": "Output:" }, { "code": null, "e": 1584, "s": 1574, "text": "[1] TRUE\n" }, { "code": null, "e": 1750, "s": 1584, "text": "A file exists or not in current working directory can be checked using file.exists() function. It returns TRUE logical value if file exists, otherwise returns FALSE." }, { "code": null, "e": 1774, "s": 1750, "text": "Syntax:file.exists(” “)" }, { "code": null, "e": 1881, "s": 1774, "text": "Parameters:” “: name of the file that has to be searched in the current working directory is passed in ” ”" }, { "code": null, "e": 1890, "s": 1881, "text": "Example:" }, { "code": "# Check for GFG>txtfile.exists(\"GFG.txt\") # Check for newGFG.txtfile.exists(\"newGFG.txt\")", "e": 1981, "s": 1890, "text": null }, { "code": null, "e": 1989, "s": 1981, "text": "Output:" }, { "code": null, "e": 2009, "s": 1989, "text": "[1] FALSE\n[1] TRUE\n" }, { "code": null, "e": 2169, "s": 2009, "text": "Using read.table() function in R, files can be read and output is shown as dataframe. This functions helps in analyzing the dataframe for further computations." }, { "code": null, "e": 2193, "s": 2169, "text": "Syntax:read.table(file)" }, { "code": null, "e": 2261, "s": 2193, "text": "Parameters:file: indicates the name of the file that has to be read" }, { "code": null, "e": 2270, "s": 2261, "text": "Example:" }, { "code": "# Reading txt filenew.iris <- read.table(file = \"GFG.txt\") # Printprint(new.iris)", "e": 2353, "s": 2270, "text": null }, { "code": null, "e": 3058, "s": 2353, "text": " X Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 1 5.1 3.5 1.4 0.2 setosa\n2 2 4.9 3.0 1.4 0.2 setosa\n3 3 4.7 3.2 1.3 0.2 setosa\n4 4 4.6 3.1 1.5 0.2 setosa\n5 5 5.0 3.6 1.4 0.2 setosa\n6 6 5.4 3.9 1.7 0.4 setosa\n7 7 4.6 3.4 1.4 0.3 setosa\n8 8 5.0 3.4 1.5 0.2 setosa\n9 9 4.4 2.9 1.4 0.2 setosa\n10 10 4.9 3.1 1.5 0.1 setosa\n" }, { "code": null, "e": 3256, "s": 3058, "text": "Using list.files() function, all files of specified path will be shown in the output. If path is not passed in the function parameter, files present in current working directory is shown as output." }, { "code": null, "e": 3280, "s": 3256, "text": "Syntax:list.files(path)" }, { "code": null, "e": 3404, "s": 3280, "text": "Parameters:path: indicates the pathTo know about more optional parameters, use below command in console: help(“list.files”)" }, { "code": null, "e": 3413, "s": 3404, "text": "Example:" }, { "code": "# Show all files in# current working directorylist.files()", "e": 3472, "s": 3413, "text": null }, { "code": null, "e": 3480, "s": 3472, "text": "Output:" }, { "code": null, "e": 3792, "s": 3480, "text": " [1] \"Bandicam\" \"Bluetooth Folder\" \n [3] \"Book1.xlsx\" \"Custom Office Templates\"\n [5] \"desktop.ini\" \"list.xlsx\" \n [7] \"My Music\" \"My Pictures\" \n [9] \"My Videos\" \"newGFG.txt\" \n[11] \"Visual Studio 2012\"\n" }, { "code": null, "e": 3884, "s": 3792, "text": "The file.copy() function in R helps to create a copy of specified file from console itself." }, { "code": null, "e": 3911, "s": 3884, "text": "Syntax:file.copy(from, to)" }, { "code": null, "e": 4109, "s": 3911, "text": "Parameters:from: indicates the file path that has to be copiedto: indicates the path where it has to be copiedTo know about more optional parameters, use below command in console: help(“file.copy”)" }, { "code": null, "e": 4118, "s": 4109, "text": "Example:" }, { "code": "# Copyingfile.copy(\"C:/Users/Utkarsh/Documents/ newGFG.txt\", \"E:/\") # List the files in E:/ drivelist.files(\"E:/\")", "e": 4244, "s": 4118, "text": null }, { "code": null, "e": 4252, "s": 4244, "text": "Output:" }, { "code": null, "e": 4438, "s": 4252, "text": "[1] TRUE\n[1] \"$RECYCLE.BIN\" \"Counter-Strike Global Offensive\"\n[3] \"Home\" \"newGFG.txt\" \n[5] \"System Volume Information\"\n" }, { "code": null, "e": 4632, "s": 4438, "text": "The dir.create() function creates a directory in the path specified in the function parameter. If path is not specified in function parameter, directory is created in current working directory." }, { "code": null, "e": 4656, "s": 4632, "text": "Syntax:dir.create(path)" }, { "code": null, "e": 4769, "s": 4656, "text": "Parameters:path: indicates the path where directory has to be created with directory name at the end of the path" }, { "code": null, "e": 4778, "s": 4769, "text": "Example:" }, { "code": "# Without specifying the path,# directory will be created in # current working directorydir.create(\"GFG\") # List fileslist.files()", "e": 4910, "s": 4778, "text": null }, { "code": null, "e": 4918, "s": 4910, "text": "Output:" }, { "code": null, "e": 5257, "s": 4918, "text": " [1] \"Bandicam\" \"Bluetooth Folder\" \n [3] \"Book1.xlsx\" \"Custom Office Templates\"\n [5] \"desktop.ini\" \"GFG\" \n [7] \"list.xlsx\" \"My Music\" \n [9] \"My Pictures\" \"My Videos\" \n[11] \"newGFG.txt\" \"Visual Studio 2012\" \n" }, { "code": null, "e": 5264, "s": 5257, "text": "Picked" }, { "code": null, "e": 5279, "s": 5264, "text": "R-FileHandling" }, { "code": null, "e": 5290, "s": 5279, "text": "R Language" } ]
String Subsequence Game | Practice | GeeksforGeeks
Given a string return all unique possible subsequences which start with vowel and end with consonant. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. NOTE: Return all the unique subsequences in lexicographically sorted order. Example 1: Input: S = "abc" Output: "ab", "ac", "abc" Explanation: "ab", "ac", "abc" are the all possible subsequences which start with vowel and end with consonant. Example 2: Input: S = "aab" Output: "ab", "aab" Explanation: "ab", "aab" are the all possible subsequences which start with vowel and end with consonant. Your Task: You dont need to read input or print anything. Complete the function allPossileSubsequences() which takes S as input parameter and returns all possible subsequences which start with vowel and end with consonant. Expected Time Complexity: O(n*logn*2n) Expected Auxiliary Space: O(2n) Constraints: 1<= |S| <=18 +1 abhiiishek075 days ago EASY PEASY CPP RECURSIVE :- bool isVowel(char ch){ return ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'; } void solve(string s,int i,string str,set<string>&ans){ if(i>=s.size()){ // base constion if(str.size()>=2){ if(isVowel(str[0]) && !isVowel(str[str.size()-1])) ans.insert(str); } return; } solve(s,i+1,str+s[i],ans); //pick solve(s,i+1,str,ans); // not pick } set<string> allPossibleSubsequences(string S) { // code here set<string>ans; string str=""; solve(S,0,str,ans); return ans; } 0 sgupta0782 weeks ago class Solution { public: /* b d f h j n p t v z */ bool checkString(string s){ int sz=s.size(); if(s[0]=='a' || s[0]=='e' || s[0]=='i' || s[0]=='o' || s[0]=='u'){ if((s[sz-1]>='b' && s[sz-1]<='d') || (s[sz-1]>='f' && s[sz-1]<='h') || (s[sz-1]>='j' && s[sz-1]<='n') || (s[sz-1]>='p' && s[sz-1]<='t') || (s[sz-1]>='v' && s[sz-1]<='z')){ return true; } else{ return false; } } else{ return false; } } void getAll(int index, string S, set<string>& st, string& ans){ if(index>=S.size()){ if(checkString(ans)){ st.insert(ans); } return; } ans+=S[index]; getAll(index+1, S, st, ans); ans=ans.substr(0, ans.size()-1); getAll(index+1, S, st, ans); } set<string> allPossibleSubsequences(string S) { // code here set<string> st; string ans=""; getAll(0, S, st, ans); return st; } }; 0 premranjan880463 weeks ago set<string>st; void solve(string S, int i, string curr) { if(i==S.length()) { string str=curr; int n=str.size(); if(str.size()>=2) { if((str[0]=='a' || str[0]=='e' || str[0]=='i'|| str[0]=='u'|| str[0]=='o') && (str[n-1]!='a'&& str[n-1]!='e'&& str[n-1]!='i'&& str[n-1]!='u'&& str[n-1]!='o')) st.insert(str); } return; } solve(S,i+1,curr); solve(S,i+1,curr+S[i]); } set<string> allPossibleSubsequences(string S) { solve(S,0,""); return st; } 0 prakashish3 weeks ago Java Most Efficient Solution class Solution { static TreeSet<String> allPossibleSubsequences(String s) { // code here TreeSet<String> set = new TreeSet<>(); ArrayList<String> list = new ArrayList<>(); getSub(list,s,0,new StringBuilder()); for(String str : list){ if(str.length() > 1 && isVowel(str.charAt(0)) && !isVowel(str.charAt(str.length()-1))){ set.add(str); } } return set; } static boolean isVowel(char ch){ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u'){ return true; } return false; } static void getSub(ArrayList<String> str , String s, int idx, StringBuilder base){ if(idx == s.length()){ str.add(base.toString()); return; } getSub(str, s,idx+1,base); base.append(s.charAt(idx)); getSub(str, s,idx+1,base); base.deleteCharAt(base.length()-1); } } 0 ayushsunariya4583 weeks ago C++ Powerset Solution bool isVowel(char& c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } void solve(int i, string& s, string &f, set<string>&k) { if (i == s.length()) { if(isVowel(f[0]) && !isVowel(f[f.length()-1])) k.insert(f); return; } //picking f = f + s[i]; solve(i + 1, s, f, k); //poping out while backtracking f.pop_back(); solve(i + 1, s, f, k); } set<string> allPossibleSubsequences(string s) { // code here string f=""; set<string>k; solve(0,s,f,k); return k; } 0 abinashm200674ca2 months ago char c=op.front(); bool op1 = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); c=op.back(); bool op2 = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); if(op1 && !op2) { ans.insert(op); } if(ip.length()==0)return ; solve(ip.substr(1),op+ip[0],index+1 ); solve(ip.substr(1),op,index+1 ); 0 putyavka2 months ago vector<int> V; // vowels string T; // current string void recur(string& S, int idx, set<string>& R) { if (T.size() && V[T[0]] && !V[T.back()]) R.insert(T); for (int i = idx; i < S.size(); i++) { T.push_back(S[i]); recur(S, i + 1, R); T.pop_back(); } } set<string> allPossibleSubsequences(string S) { V.resize(128); V['a'] = V['e'] = V['i'] = V['o'] = V['u'] = 1; set<string> R; recur(S, 0, R); return R; } 0 meghnareddy2 months ago class Solution { static TreeSet<String> allPossibleSubsequences(String s) { // code here TreeSet<String> res = new TreeSet<>(); List<String> ll = new ArrayList<>(); print_subs(s, "",ll); List<Character> vowels= Arrays.asList('a','e','i','o','u'); for(String a:ll){ if(a.length()>1 && !a.equals("-1")){ char c=a.charAt(0); char last=a.charAt(a.length()-1); if(vowels.contains(c) && !vowels.contains(last)){ res.add(a); } } } return res; } public static List<String> print_subs(String s, String output, List<String> ll){ if(s.length()==0){ ll.add(output); return ll; } print_subs(s.substring(1), output,ll); print_subs(s.substring(1), output+s.charAt(0),ll); return ll; } } +1 aloksinghbais023 months ago C++ solution having time complexity as O((2^n)*n*log(n)) and space complexity as O((2^n)+n) is as follows :- Execution Time :- 0.33 / 2.37 sec bool isValid(string output){ if(output.length() <= 1) return (false); char ch1 = output[0]; char ch2 = output[output.length()-1]; if(!(ch1 == 'a' || ch1 == 'e' || ch1 == 'i' || ch1 == 'o' || ch1 == 'u')) return (false); if(ch2 == 'a' || ch2 == 'e' || ch2 == 'i' || ch2 == 'o' || ch2 == 'u') return (false); return (true); } void helper(string output,int ind,string s,int n,set<string> &ans){ if(ind == n){ if(isValid(output)) ans.insert(output); return; } char ch = s[ind]; helper(output,ind+1,s,n,ans); helper(output+ch,ind+1,s,n,ans); } set<string> allPossibleSubsequences(string S) { string output; set<string> ans; helper(output,0,S,S.length(),ans); return (ans); } +1 balajies4 months ago There was some problem with python driver code please fix it. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 565, "s": 238, "text": "Given a string return all unique possible subsequences which start with vowel and end with consonant. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.\nNOTE: Return all the unique subsequences in lexicographically sorted order. \n\nExample 1:" }, { "code": null, "e": 724, "s": 565, "text": "Input: S = \"abc\"\nOutput: \"ab\", \"ac\", \"abc\" \nExplanation: \"ab\", \"ac\", \"abc\" are \nthe all possible subsequences which \nstart with vowel and end with consonant.\n" }, { "code": null, "e": 735, "s": 724, "text": "Example 2:" }, { "code": null, "e": 880, "s": 735, "text": "Input: S = \"aab\"\nOutput: \"ab\", \"aab\"\nExplanation: \"ab\", \"aab\" are the all \npossible subsequences which start \nwith vowel and end with consonant." }, { "code": null, "e": 1205, "s": 880, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function allPossileSubsequences() which takes S as input parameter and returns all possible subsequences which start with vowel and end with consonant.\n\nExpected Time Complexity: O(n*logn*2n)\nExpected Auxiliary Space: O(2n)\n\nConstraints:\n1<= |S| <=18" }, { "code": null, "e": 1208, "s": 1205, "text": "+1" }, { "code": null, "e": 1231, "s": 1208, "text": "abhiiishek075 days ago" }, { "code": null, "e": 1259, "s": 1231, "text": "EASY PEASY CPP RECURSIVE :-" }, { "code": null, "e": 1959, "s": 1259, "text": " bool isVowel(char ch){\n return ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u';\n }\n void solve(string s,int i,string str,set<string>&ans){\n if(i>=s.size()){ // base constion\n if(str.size()>=2){\n if(isVowel(str[0]) && !isVowel(str[str.size()-1]))\n ans.insert(str);\n }\n return;\n }\n solve(s,i+1,str+s[i],ans); //pick\n solve(s,i+1,str,ans); // not pick\n }\n set<string> allPossibleSubsequences(string S) {\n // code here\n set<string>ans;\n string str=\"\";\n solve(S,0,str,ans);\n return ans;\n }" }, { "code": null, "e": 1961, "s": 1959, "text": "0" }, { "code": null, "e": 1982, "s": 1961, "text": "sgupta0782 weeks ago" }, { "code": null, "e": 3138, "s": 1982, "text": "class Solution {\n public:\n \n /*\n b d\n f h\n j n\n p t\n v z\n */\n \n bool checkString(string s){\n int sz=s.size();\n if(s[0]=='a' || s[0]=='e' || s[0]=='i' || s[0]=='o' || s[0]=='u'){\n if((s[sz-1]>='b' && s[sz-1]<='d') || (s[sz-1]>='f' && s[sz-1]<='h') || (s[sz-1]>='j' && s[sz-1]<='n') \n || (s[sz-1]>='p' && s[sz-1]<='t') || (s[sz-1]>='v' && s[sz-1]<='z')){\n return true;\n } else{\n return false;\n }\n \n } else{\n return false;\n }\n }\n \n void getAll(int index, string S, set<string>& st, string& ans){\n if(index>=S.size()){\n if(checkString(ans)){\n st.insert(ans);\n }\n return;\n }\n \n ans+=S[index];\n getAll(index+1, S, st, ans);\n \n ans=ans.substr(0, ans.size()-1);\n getAll(index+1, S, st, ans);\n }\n \n set<string> allPossibleSubsequences(string S) {\n // code here\n set<string> st;\n string ans=\"\";\n getAll(0, S, st, ans);\n return st;\n }\n};" }, { "code": null, "e": 3140, "s": 3138, "text": "0" }, { "code": null, "e": 3167, "s": 3140, "text": "premranjan880463 weeks ago" }, { "code": null, "e": 3778, "s": 3167, "text": " set<string>st; void solve(string S, int i, string curr) { if(i==S.length()) { string str=curr; int n=str.size(); if(str.size()>=2) { if((str[0]=='a' || str[0]=='e' || str[0]=='i'|| str[0]=='u'|| str[0]=='o') && (str[n-1]!='a'&& str[n-1]!='e'&& str[n-1]!='i'&& str[n-1]!='u'&& str[n-1]!='o')) st.insert(str); } return; } solve(S,i+1,curr); solve(S,i+1,curr+S[i]); } set<string> allPossibleSubsequences(string S) { solve(S,0,\"\"); return st; }" }, { "code": null, "e": 3780, "s": 3778, "text": "0" }, { "code": null, "e": 3802, "s": 3780, "text": "prakashish3 weeks ago" }, { "code": null, "e": 3832, "s": 3802, "text": "Java Most Efficient Solution " }, { "code": null, "e": 4809, "s": 3832, "text": "class Solution {\n static TreeSet<String> allPossibleSubsequences(String s) {\n // code here\n TreeSet<String> set = new TreeSet<>();\n ArrayList<String> list = new ArrayList<>();\n getSub(list,s,0,new StringBuilder());\n for(String str : list){\n if(str.length() > 1 && isVowel(str.charAt(0)) && !isVowel(str.charAt(str.length()-1))){\n set.add(str);\n } \n }\n return set;\n }\n static boolean isVowel(char ch){\n if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u'){\n return true;\n }\n return false;\n }\n static void getSub(ArrayList<String> str , String s, int idx, StringBuilder base){\n if(idx == s.length()){\n str.add(base.toString());\n return;\n }\n getSub(str, s,idx+1,base);\n base.append(s.charAt(idx));\n getSub(str, s,idx+1,base);\n base.deleteCharAt(base.length()-1);\n }\n}" }, { "code": null, "e": 4813, "s": 4811, "text": "0" }, { "code": null, "e": 4841, "s": 4813, "text": "ayushsunariya4583 weeks ago" }, { "code": null, "e": 4863, "s": 4841, "text": "C++ Powerset Solution" }, { "code": null, "e": 5471, "s": 4863, "text": " bool isVowel(char& c){\n return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');\n }\n void solve(int i, string& s, string &f, set<string>&k) {\n \tif (i == s.length()) {\n \t if(isVowel(f[0]) && !isVowel(f[f.length()-1]))\n \t\t k.insert(f);\n \t\treturn;\n \t}\n \t//picking \n \tf = f + s[i];\n \tsolve(i + 1, s, f, k);\n \t//poping out while backtracking\n \tf.pop_back();\n \tsolve(i + 1, s, f, k);\n }\n set<string> allPossibleSubsequences(string s) {\n // code here\n string f=\"\";\n set<string>k;\n solve(0,s,f,k);\n return k;\n }" }, { "code": null, "e": 5473, "s": 5471, "text": "0" }, { "code": null, "e": 5502, "s": 5473, "text": "abinashm200674ca2 months ago" }, { "code": null, "e": 5863, "s": 5502, "text": "char c=op.front(); bool op1 = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); c=op.back(); bool op2 = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); if(op1 && !op2) { ans.insert(op); } if(ip.length()==0)return ; solve(ip.substr(1),op+ip[0],index+1 ); solve(ip.substr(1),op,index+1 );" }, { "code": null, "e": 5865, "s": 5863, "text": "0" }, { "code": null, "e": 5886, "s": 5865, "text": "putyavka2 months ago" }, { "code": null, "e": 6360, "s": 5886, "text": "vector<int> V; // vowels\nstring T; // current string\nvoid recur(string& S, int idx, set<string>& R) {\n if (T.size() && V[T[0]] && !V[T.back()])\n R.insert(T);\n for (int i = idx; i < S.size(); i++) {\n T.push_back(S[i]);\n recur(S, i + 1, R);\n T.pop_back();\n }\n}\nset<string> allPossibleSubsequences(string S) {\n V.resize(128);\n V['a'] = V['e'] = V['i'] =\n V['o'] = V['u'] = 1;\n set<string> R;\n recur(S, 0, R);\n return R;\n}" }, { "code": null, "e": 6362, "s": 6360, "text": "0" }, { "code": null, "e": 6386, "s": 6362, "text": "meghnareddy2 months ago" }, { "code": null, "e": 7278, "s": 6386, "text": "class Solution { static TreeSet<String> allPossibleSubsequences(String s) { // code here TreeSet<String> res = new TreeSet<>(); List<String> ll = new ArrayList<>(); print_subs(s, \"\",ll); List<Character> vowels= Arrays.asList('a','e','i','o','u'); for(String a:ll){ if(a.length()>1 && !a.equals(\"-1\")){ char c=a.charAt(0); char last=a.charAt(a.length()-1); if(vowels.contains(c) && !vowels.contains(last)){ res.add(a); } } } return res; } public static List<String> print_subs(String s, String output, List<String> ll){ if(s.length()==0){ ll.add(output); return ll; } print_subs(s.substring(1), output,ll); print_subs(s.substring(1), output+s.charAt(0),ll); return ll; } }" }, { "code": null, "e": 7281, "s": 7278, "text": "+1" }, { "code": null, "e": 7309, "s": 7281, "text": "aloksinghbais023 months ago" }, { "code": null, "e": 7419, "s": 7309, "text": "C++ solution having time complexity as O((2^n)*n*log(n)) and space complexity as O((2^n)+n) is as follows :- " }, { "code": null, "e": 7455, "s": 7421, "text": "Execution Time :- 0.33 / 2.37 sec" }, { "code": null, "e": 8308, "s": 7457, "text": "bool isValid(string output){ if(output.length() <= 1) return (false); char ch1 = output[0]; char ch2 = output[output.length()-1]; if(!(ch1 == 'a' || ch1 == 'e' || ch1 == 'i' || ch1 == 'o' || ch1 == 'u')) return (false); if(ch2 == 'a' || ch2 == 'e' || ch2 == 'i' || ch2 == 'o' || ch2 == 'u') return (false); return (true); } void helper(string output,int ind,string s,int n,set<string> &ans){ if(ind == n){ if(isValid(output)) ans.insert(output); return; } char ch = s[ind]; helper(output,ind+1,s,n,ans); helper(output+ch,ind+1,s,n,ans); } set<string> allPossibleSubsequences(string S) { string output; set<string> ans; helper(output,0,S,S.length(),ans); return (ans); }" }, { "code": null, "e": 8311, "s": 8308, "text": "+1" }, { "code": null, "e": 8332, "s": 8311, "text": "balajies4 months ago" }, { "code": null, "e": 8394, "s": 8332, "text": "There was some problem with python driver code please fix it." }, { "code": null, "e": 8540, "s": 8394, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8576, "s": 8540, "text": " Login to access your submissions. " }, { "code": null, "e": 8586, "s": 8576, "text": "\nProblem\n" }, { "code": null, "e": 8596, "s": 8586, "text": "\nContest\n" }, { "code": null, "e": 8659, "s": 8596, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8844, "s": 8659, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9128, "s": 8844, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 9274, "s": 9128, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 9351, "s": 9274, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 9392, "s": 9351, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 9420, "s": 9392, "text": "Disable browser extensions." }, { "code": null, "e": 9491, "s": 9420, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 9678, "s": 9491, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
ISNUMERIC() Function in SQL Server
18 Jan, 2021 ISNUMERIC() function :This function in SQL Server is used to check if the stated expression is numeric or not. Features : This function is used to check if the given expression is numeric or not. This function returns 1 if the given expression is in numerical form. This function returns 0 if the given expression is not numeric. This function comes under Advanced Functions. This function accepts only one parameter namely expression. Syntax : ISNUMERIC(expression) Parameter :This method accepts only one parameter as given below : expression : Specified expression or the value which is to be checked if its numeric or not. Returns :It returns 1 if the specified value is numeric form else it returns 0. Example-1 :Using ISNUMERIC() function and getting the output. SELECT ISNUMERIC(1352); Output : 1 Here, 1 is returned as the stated value is numeric. Example-2 :Using ISNUMERIC() function and getting the output. SELECT ISNUMERIC('abd'); Output : 0 Here, 0 is returned as output as the stated expression is not numeric. Example-3 :Using ISNUMERIC() function and getting the output using a variable. DECLARE @exp INT; SET @exp = 44; SELECT ISNUMERIC(@exp); Output : 1 Example-4 :Using ISNUMERIC() function and getting the output using multiplication operation and a variable as well. DECLARE @exp INT; SET @exp = 30*7; SELECT ISNUMERIC(@exp); Output : 1 Application :This function is used to test if the stated expression is numeric or not. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2021" }, { "code": null, "e": 139, "s": 28, "text": "ISNUMERIC() function :This function in SQL Server is used to check if the stated expression is numeric or not." }, { "code": null, "e": 150, "s": 139, "text": "Features :" }, { "code": null, "e": 224, "s": 150, "text": "This function is used to check if the given expression is numeric or not." }, { "code": null, "e": 294, "s": 224, "text": "This function returns 1 if the given expression is in numerical form." }, { "code": null, "e": 358, "s": 294, "text": "This function returns 0 if the given expression is not numeric." }, { "code": null, "e": 404, "s": 358, "text": "This function comes under Advanced Functions." }, { "code": null, "e": 464, "s": 404, "text": "This function accepts only one parameter namely expression." }, { "code": null, "e": 473, "s": 464, "text": "Syntax :" }, { "code": null, "e": 496, "s": 473, "text": "ISNUMERIC(expression)\n" }, { "code": null, "e": 563, "s": 496, "text": "Parameter :This method accepts only one parameter as given below :" }, { "code": null, "e": 656, "s": 563, "text": "expression : Specified expression or the value which is to be checked if its numeric or not." }, { "code": null, "e": 736, "s": 656, "text": "Returns :It returns 1 if the specified value is numeric form else it returns 0." }, { "code": null, "e": 798, "s": 736, "text": "Example-1 :Using ISNUMERIC() function and getting the output." }, { "code": null, "e": 823, "s": 798, "text": "SELECT ISNUMERIC(1352);\n" }, { "code": null, "e": 832, "s": 823, "text": "Output :" }, { "code": null, "e": 834, "s": 832, "text": "1" }, { "code": null, "e": 886, "s": 834, "text": "Here, 1 is returned as the stated value is numeric." }, { "code": null, "e": 948, "s": 886, "text": "Example-2 :Using ISNUMERIC() function and getting the output." }, { "code": null, "e": 974, "s": 948, "text": "SELECT ISNUMERIC('abd');\n" }, { "code": null, "e": 983, "s": 974, "text": "Output :" }, { "code": null, "e": 985, "s": 983, "text": "0" }, { "code": null, "e": 1056, "s": 985, "text": "Here, 0 is returned as output as the stated expression is not numeric." }, { "code": null, "e": 1135, "s": 1056, "text": "Example-3 :Using ISNUMERIC() function and getting the output using a variable." }, { "code": null, "e": 1193, "s": 1135, "text": "DECLARE @exp INT;\nSET @exp = 44;\nSELECT ISNUMERIC(@exp);\n" }, { "code": null, "e": 1202, "s": 1193, "text": "Output :" }, { "code": null, "e": 1204, "s": 1202, "text": "1" }, { "code": null, "e": 1320, "s": 1204, "text": "Example-4 :Using ISNUMERIC() function and getting the output using multiplication operation and a variable as well." }, { "code": null, "e": 1380, "s": 1320, "text": "DECLARE @exp INT;\nSET @exp = 30*7;\nSELECT ISNUMERIC(@exp);\n" }, { "code": null, "e": 1389, "s": 1380, "text": "Output :" }, { "code": null, "e": 1391, "s": 1389, "text": "1" }, { "code": null, "e": 1478, "s": 1391, "text": "Application :This function is used to test if the stated expression is numeric or not." }, { "code": null, "e": 1487, "s": 1478, "text": "DBMS-SQL" }, { "code": null, "e": 1498, "s": 1487, "text": "SQL-Server" }, { "code": null, "e": 1502, "s": 1498, "text": "SQL" }, { "code": null, "e": 1506, "s": 1502, "text": "SQL" } ]
Minimize the absolute difference of sum of two subsets
08 Jun, 2022 Given a number n, divide first n natural numbers (1, 2, ...n) into two subsets such that difference between sums of two subsets is minimum.Examples: Input : n = 4 Output : First subset sum = 5, Second subset sum = 5. Difference = 0 Explanation: Subset 1: 1 4 Subset 2: 2 3 Input : n = 6 Output: First subset sum = 10, Second subset sum = 11. Difference = 1 Explanation : Subset 1: 1 3 6 Subset 2: 2 4 5 Approach: The approach is based on the fact that any four consecutive numbers can be divided into two groups by putting middle two elements in one group and corner elements in other group. So, if n is a multiple of 4 then their difference will be 0, hence the summation of one set will be half of the summation of N elements which can be calculated by using sum = n*(n+1)/2There are three other cases to consider in which we cannot divide into groups of 4, which will leave a remainder of 1, 2 and 3: a) If it leaves a remainder of 1, then all other n-1 elements are clubbed into group of 4 hence their sum will be int(sum/2) and the other half sum will be int(sum/2+1) and their difference will always be 1. b) Above mentioned steps will be followed in case of n%4 == 2 also. Here we form groups of size 4 for elements from 3 onward. Remaining elements would be 1 and 2. 1 goes in one group and 2 goes in other group. c) When n%4 == 3, then club n-3 elements into groups of 4. The left out elements will be 1, 2 and 3, in which 1 and 2 will go to one set and 3 to the other set which eventually makes the difference to be 0 and summation of each set to be sum/2.Below is the implementation of the above approach: CPP Java Python3 C# PHP Javascript // CPP program to Minimize the absolute// difference of sum of two subsets#include <bits/stdc++.h>using namespace std; // function to print differencevoid subsetDifference(int n){ // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { cout << "First subset sum = " << s / 2; cout << "\nSecond subset sum = " << s / 2; cout << "\nDifference = " << 0; } else { // if remainder 1 or 2. In case of remainder // 2, we divide elements from 3 to n in groups // of size 4 and put 1 in one group and 2 in // group. This also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { cout << "First subset sum = " << s / 2; cout << "\nSecond subset sum = " << s / 2 + 1; cout << "\nDifference = " << 1; } // We put elements from 4 to n in groups of // size 4. Remaining elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { cout << "First subset sum = " << s / 2; cout << "\nSecond subset sum = " << s / 2; cout << "\nDifference = " << 0; } }} // driver program to test the above functionint main(){ int n = 6; subsetDifference(n); return 0;} // Java program for Minimize the absolute// difference of sum of two subsetsimport java.util.*; class GFG { // function to print difference static void subsetDifference(int n) { // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { System.out.println("First subset sum = " + s / 2); System.out.println("Second subset sum = " + s / 2); System.out.println("Difference = " + 0); } else { // if remainder 1 or 2. In case of remainder // 2, we divide elements from 3 to n in groups // of size 4 and put 1 in one group and 2 in // group. This also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { System.out.println("First subset sum = " + s / 2); System.out.println("Second subset sum = " + ((s / 2) + 1)); System.out.println("Difference = " + 1); } // We put elements from 4 to n in groups of // size 4. Remaining elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { System.out.println("First subset sum = " + s / 2); System.out.println("Second subset sum = " + s / 2); System.out.println("Difference = " + 0); } } } /* Driver program to test above function */ public static void main(String[] args) { int n = 6; subsetDifference(n); }} // This code is contributed by Arnav Kr. Mandal. # Python3 code to Minimize the absolute# difference of sum of two subsets # function to print differencedef subsetDifference( n ): # summation of n elements s = int(n * (n + 1) / 2) # if divisible by 4 if n % 4 == 0: print("First subset sum = ", int(s / 2)) print("Second subset sum = ",int(s / 2)) print("Difference = " , 0) else: # if remainder 1 or 2. In case of remainder # 2, we divide elements from 3 to n in groups # of size 4 and put 1 in one group and 2 in # group. This also makes difference 1. if n % 4 == 1 or n % 4 == 2: print("First subset sum = ",int(s/2)) print("Second subset sum = ",int(s/2)+1) print("Difference = ", 1) # We put elements from 4 to n in groups of # size 4. Remaining elements 1, 2 and 3 can # be divided as (1, 2) and (3). else: print("First subset sum = ", int(s / 2)) print("Second subset sum = ",int(s / 2)) print("Difference = " , 0) # driver code to test the above functionn = 6subsetDifference(n) # This code is contributed by "Sharad_Bhardwaj". // C# program for Minimize the absolute// difference of sum of two subsetsusing System; class GFG { // function to print difference static void subsetDifference(int n) { // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { Console.WriteLine("First " + "subset sum = " + s / 2); Console.WriteLine("Second " + "subset sum = " + s / 2); Console.WriteLine("Difference" + " = " + 0); } else { // if remainder 1 or 2. In case // of remainder 2, we divide // elements from 3 to n in groups // of size 4 and put 1 in one // group and 2 in group. This // also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { Console.WriteLine("First " + "subset sum = " + s / 2); Console.WriteLine("Second " + "subset sum = " + ((s / 2) + 1)); Console.WriteLine("Difference" + " = " + 1); } // We put elements from 4 to n // in groups of size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { Console.WriteLine("First " + "subset sum = " + s / 2); Console.WriteLine("Second " + "subset sum = " + s / 2); Console.WriteLine("Difference" + " = " + 0); } } } /* Driver program to test above function */ public static void Main() { int n = 6; subsetDifference(n); }} // This code is contributed by vt_m. <?php// PHP program to Minimize the absolute// difference of sum of two subsets // function to print differencefunction subsetDifference($n){ // summation of n elements $s = $n * ($n + 1) / 2; // if divisible by 4 if ($n % 4 == 0) { echo "First subset sum = " ,floor($s / 2); echo "\nSecond subset sum = " ,floor($s / 2); echo "\nDifference = " , 0; } else { // if remainder 1 or 2. // In case of remainder // 2, we divide elements // from 3 to n in groups // of size 4 and put 1 in // one group and 2 in // group. This also makes // difference 1. if ($n % 4 == 1 || $n % 4 == 2) { echo"First subset sum = " , floor($s / 2); echo "\nSecond subset sum = " , floor($s / 2 + 1); echo"\nDifference = " ,1; } // We put elements from 4 // to n in groups of // size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) // and (3). else { echo "First subset sum = " ,floor($s / 2); echo "\nSecond subset sum = " , floor($s / 2); echo"\nDifference = " , 0; } }} // Driver code $n = 6; subsetDifference($n); // This code is contributed by anuj_67.?> <script>// Javascript program to Minimize the absolute// difference of sum of two subsets // function to print differencefunction subsetDifference(n){ // summation of n elements let s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { document.write("First subset sum = " + Math.floor(s / 2)); document.write("<br> Second subset sum = " + Math.floor(s / 2)); document.write("<br> Difference = " + 0); } else { // if remainder 1 or 2. // In case of remainder // 2, we divide elements // from 3 to n in groups // of size 4 and put 1 in // one group and 2 in // group. This also makes // difference 1. if (n % 4 == 1 || n % 4 == 2) { document.write("First subset sum = " + Math.floor(s / 2)); document.write("<br> Second subset sum = " + Math.floor(s / 2 + 1)); document.write("<br> Difference = " + 1); } // We put elements from 4 // to n in groups of // size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) // and (3). else { document.write( "First subset sum = " + Math.floor(s / 2)); document.write( "<br> Second subset sum = " + Math.floor(s / 2)); document.write("<br> Difference = " + 0); } }} // Driver code let n = 6; subsetDifference(n); // This code is contributed by _saurabh_jaiswal.</script> First subset sum = 10 Second subset sum = 11 Difference = 1 Time Complexity: O(1)Auxiliary Space: O(1) vt_m _saurabh_jaiswal rohitsingh57 number-theory subset Mathematical number-theory Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 205, "s": 54, "text": "Given a number n, divide first n natural numbers (1, 2, ...n) into two subsets such that difference between sums of two subsets is minimum.Examples: " }, { "code": null, "e": 502, "s": 205, "text": "Input : n = 4\nOutput : First subset sum = 5, \n Second subset sum = 5.\n Difference = 0\nExplanation:\nSubset 1: 1 4 \nSubset 2: 2 3 \n\nInput : n = 6 \nOutput: First subset sum = 10, \n Second subset sum = 11.\n Difference = 1\nExplanation : \nSubset 1: 1 3 6 \nSubset 2: 2 4 5 " }, { "code": null, "e": 1720, "s": 504, "text": "Approach: The approach is based on the fact that any four consecutive numbers can be divided into two groups by putting middle two elements in one group and corner elements in other group. So, if n is a multiple of 4 then their difference will be 0, hence the summation of one set will be half of the summation of N elements which can be calculated by using sum = n*(n+1)/2There are three other cases to consider in which we cannot divide into groups of 4, which will leave a remainder of 1, 2 and 3: a) If it leaves a remainder of 1, then all other n-1 elements are clubbed into group of 4 hence their sum will be int(sum/2) and the other half sum will be int(sum/2+1) and their difference will always be 1. b) Above mentioned steps will be followed in case of n%4 == 2 also. Here we form groups of size 4 for elements from 3 onward. Remaining elements would be 1 and 2. 1 goes in one group and 2 goes in other group. c) When n%4 == 3, then club n-3 elements into groups of 4. The left out elements will be 1, 2 and 3, in which 1 and 2 will go to one set and 3 to the other set which eventually makes the difference to be 0 and summation of each set to be sum/2.Below is the implementation of the above approach: " }, { "code": null, "e": 1724, "s": 1720, "text": "CPP" }, { "code": null, "e": 1729, "s": 1724, "text": "Java" }, { "code": null, "e": 1737, "s": 1729, "text": "Python3" }, { "code": null, "e": 1740, "s": 1737, "text": "C#" }, { "code": null, "e": 1744, "s": 1740, "text": "PHP" }, { "code": null, "e": 1755, "s": 1744, "text": "Javascript" }, { "code": "// CPP program to Minimize the absolute// difference of sum of two subsets#include <bits/stdc++.h>using namespace std; // function to print differencevoid subsetDifference(int n){ // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { cout << \"First subset sum = \" << s / 2; cout << \"\\nSecond subset sum = \" << s / 2; cout << \"\\nDifference = \" << 0; } else { // if remainder 1 or 2. In case of remainder // 2, we divide elements from 3 to n in groups // of size 4 and put 1 in one group and 2 in // group. This also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { cout << \"First subset sum = \" << s / 2; cout << \"\\nSecond subset sum = \" << s / 2 + 1; cout << \"\\nDifference = \" << 1; } // We put elements from 4 to n in groups of // size 4. Remaining elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { cout << \"First subset sum = \" << s / 2; cout << \"\\nSecond subset sum = \" << s / 2; cout << \"\\nDifference = \" << 0; } }} // driver program to test the above functionint main(){ int n = 6; subsetDifference(n); return 0;}", "e": 3121, "s": 1755, "text": null }, { "code": "// Java program for Minimize the absolute// difference of sum of two subsetsimport java.util.*; class GFG { // function to print difference static void subsetDifference(int n) { // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { System.out.println(\"First subset sum = \" + s / 2); System.out.println(\"Second subset sum = \" + s / 2); System.out.println(\"Difference = \" + 0); } else { // if remainder 1 or 2. In case of remainder // 2, we divide elements from 3 to n in groups // of size 4 and put 1 in one group and 2 in // group. This also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { System.out.println(\"First subset sum = \" + s / 2); System.out.println(\"Second subset sum = \" + ((s / 2) + 1)); System.out.println(\"Difference = \" + 1); } // We put elements from 4 to n in groups of // size 4. Remaining elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { System.out.println(\"First subset sum = \" + s / 2); System.out.println(\"Second subset sum = \" + s / 2); System.out.println(\"Difference = \" + 0); } } } /* Driver program to test above function */ public static void main(String[] args) { int n = 6; subsetDifference(n); }} // This code is contributed by Arnav Kr. Mandal.", "e": 4765, "s": 3121, "text": null }, { "code": "# Python3 code to Minimize the absolute# difference of sum of two subsets # function to print differencedef subsetDifference( n ): # summation of n elements s = int(n * (n + 1) / 2) # if divisible by 4 if n % 4 == 0: print(\"First subset sum = \", int(s / 2)) print(\"Second subset sum = \",int(s / 2)) print(\"Difference = \" , 0) else: # if remainder 1 or 2. In case of remainder # 2, we divide elements from 3 to n in groups # of size 4 and put 1 in one group and 2 in # group. This also makes difference 1. if n % 4 == 1 or n % 4 == 2: print(\"First subset sum = \",int(s/2)) print(\"Second subset sum = \",int(s/2)+1) print(\"Difference = \", 1) # We put elements from 4 to n in groups of # size 4. Remaining elements 1, 2 and 3 can # be divided as (1, 2) and (3). else: print(\"First subset sum = \", int(s / 2)) print(\"Second subset sum = \",int(s / 2)) print(\"Difference = \" , 0) # driver code to test the above functionn = 6subsetDifference(n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 5950, "s": 4765, "text": null }, { "code": "// C# program for Minimize the absolute// difference of sum of two subsetsusing System; class GFG { // function to print difference static void subsetDifference(int n) { // summation of n elements int s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { Console.WriteLine(\"First \" + \"subset sum = \" + s / 2); Console.WriteLine(\"Second \" + \"subset sum = \" + s / 2); Console.WriteLine(\"Difference\" + \" = \" + 0); } else { // if remainder 1 or 2. In case // of remainder 2, we divide // elements from 3 to n in groups // of size 4 and put 1 in one // group and 2 in group. This // also makes difference 1. if (n % 4 == 1 || n % 4 == 2) { Console.WriteLine(\"First \" + \"subset sum = \" + s / 2); Console.WriteLine(\"Second \" + \"subset sum = \" + ((s / 2) + 1)); Console.WriteLine(\"Difference\" + \" = \" + 1); } // We put elements from 4 to n // in groups of size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) and (3). else { Console.WriteLine(\"First \" + \"subset sum = \" + s / 2); Console.WriteLine(\"Second \" + \"subset sum = \" + s / 2); Console.WriteLine(\"Difference\" + \" = \" + 0); } } } /* Driver program to test above function */ public static void Main() { int n = 6; subsetDifference(n); }} // This code is contributed by vt_m.", "e": 7971, "s": 5950, "text": null }, { "code": "<?php// PHP program to Minimize the absolute// difference of sum of two subsets // function to print differencefunction subsetDifference($n){ // summation of n elements $s = $n * ($n + 1) / 2; // if divisible by 4 if ($n % 4 == 0) { echo \"First subset sum = \" ,floor($s / 2); echo \"\\nSecond subset sum = \" ,floor($s / 2); echo \"\\nDifference = \" , 0; } else { // if remainder 1 or 2. // In case of remainder // 2, we divide elements // from 3 to n in groups // of size 4 and put 1 in // one group and 2 in // group. This also makes // difference 1. if ($n % 4 == 1 || $n % 4 == 2) { echo\"First subset sum = \" , floor($s / 2); echo \"\\nSecond subset sum = \" , floor($s / 2 + 1); echo\"\\nDifference = \" ,1; } // We put elements from 4 // to n in groups of // size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) // and (3). else { echo \"First subset sum = \" ,floor($s / 2); echo \"\\nSecond subset sum = \" , floor($s / 2); echo\"\\nDifference = \" , 0; } }} // Driver code $n = 6; subsetDifference($n); // This code is contributed by anuj_67.?>", "e": 9381, "s": 7971, "text": null }, { "code": "<script>// Javascript program to Minimize the absolute// difference of sum of two subsets // function to print differencefunction subsetDifference(n){ // summation of n elements let s = n * (n + 1) / 2; // if divisible by 4 if (n % 4 == 0) { document.write(\"First subset sum = \" + Math.floor(s / 2)); document.write(\"<br> Second subset sum = \" + Math.floor(s / 2)); document.write(\"<br> Difference = \" + 0); } else { // if remainder 1 or 2. // In case of remainder // 2, we divide elements // from 3 to n in groups // of size 4 and put 1 in // one group and 2 in // group. This also makes // difference 1. if (n % 4 == 1 || n % 4 == 2) { document.write(\"First subset sum = \" + Math.floor(s / 2)); document.write(\"<br> Second subset sum = \" + Math.floor(s / 2 + 1)); document.write(\"<br> Difference = \" + 1); } // We put elements from 4 // to n in groups of // size 4. Remaining // elements 1, 2 and 3 can // be divided as (1, 2) // and (3). else { document.write( \"First subset sum = \" + Math.floor(s / 2)); document.write( \"<br> Second subset sum = \" + Math.floor(s / 2)); document.write(\"<br> Difference = \" + 0); } }} // Driver code let n = 6; subsetDifference(n); // This code is contributed by _saurabh_jaiswal.</script>", "e": 10886, "s": 9381, "text": null }, { "code": null, "e": 10946, "s": 10886, "text": "First subset sum = 10\nSecond subset sum = 11\nDifference = 1" }, { "code": null, "e": 10989, "s": 10946, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 10994, "s": 10989, "text": "vt_m" }, { "code": null, "e": 11011, "s": 10994, "text": "_saurabh_jaiswal" }, { "code": null, "e": 11024, "s": 11011, "text": "rohitsingh57" }, { "code": null, "e": 11038, "s": 11024, "text": "number-theory" }, { "code": null, "e": 11045, "s": 11038, "text": "subset" }, { "code": null, "e": 11058, "s": 11045, "text": "Mathematical" }, { "code": null, "e": 11072, "s": 11058, "text": "number-theory" }, { "code": null, "e": 11085, "s": 11072, "text": "Mathematical" }, { "code": null, "e": 11092, "s": 11085, "text": "subset" } ]
Python | Pandas Series.str.startswith()
17 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas startswith() is yet another method to search and filter text data in Series or Data Frame. This method is Similar to Python’s startswith() method, but has different parameters and it works on Pandas objects only. Hence .str has to be prefixed everytime before calling this method, so that the compiler knows that it’s different from default function. Syntax: Series.str.startswith(pat, na=nan) Parameters:pat: String to be searched. (Regex are not accepted)na: Used to set what should be displayed if the value in series is NULL. Return type: Boolean series which is True where the value has the passed string in the start. To download the CSV used in code, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: Returning Bool seriesIn this example, the college column is checked if elements have “G” in the start of string using the str.startswith() function. A Boolean series is returned which is true at the index position where string has “G” in the start. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # String to be searched in start of string search ="G" # boolean series returneddata["College"].str.startswith(search) Output:As shown in the output image, The bool series is having True at the index position where the College column was having “G” in the starting. It can also be compared by looking at the image of original data frame. Example #2: Handling NULL valuesThe most important part in data analysis is handling Null values. As it can be seen in the above output image, the Boolean series is having NaN wherever the value in College column was empty or NaN. If this boolean series is passed into data frame, it will give an error. Hence, the NaN values need to be handled using na Parameter. It can be set to string too, but since bool series is used to pass and return respective value, it should be set to a Bool value only.In this example, na Parameter is set to False. So wherever the College column is having Null value, the Bool series will store False instead of NaN. After that, the series is passed again to data frame to display only True values. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # String to be searched in start of string search ="G" # boolean series returned with False at place of NaNbool_series = data["College"].str.startswith(search, na = False) # displaying filtered dataframedata[bool_series] Output:As shown in the output image, the data frame is having rows which have “G” in starting of string in the College column. NaN values are not displayed since the na parameter was set to False. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 600, "s": 242, "text": "Pandas startswith() is yet another method to search and filter text data in Series or Data Frame. This method is Similar to Python’s startswith() method, but has different parameters and it works on Pandas objects only. Hence .str has to be prefixed everytime before calling this method, so that the compiler knows that it’s different from default function." }, { "code": null, "e": 643, "s": 600, "text": "Syntax: Series.str.startswith(pat, na=nan)" }, { "code": null, "e": 779, "s": 643, "text": "Parameters:pat: String to be searched. (Regex are not accepted)na: Used to set what should be displayed if the value in series is NULL." }, { "code": null, "e": 873, "s": 779, "text": "Return type: Boolean series which is True where the value has the passed string in the start." }, { "code": null, "e": 919, "s": 873, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 1066, "s": 919, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 1327, "s": 1066, "text": "Example #1: Returning Bool seriesIn this example, the college column is checked if elements have “G” in the start of string using the str.startswith() function. A Boolean series is returned which is true at the index position where string has “G” in the start." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # String to be searched in start of string search =\"G\" # boolean series returneddata[\"College\"].str.startswith(search)", "e": 1604, "s": 1327, "text": null }, { "code": null, "e": 2553, "s": 1604, "text": "Output:As shown in the output image, The bool series is having True at the index position where the College column was having “G” in the starting. It can also be compared by looking at the image of original data frame. Example #2: Handling NULL valuesThe most important part in data analysis is handling Null values. As it can be seen in the above output image, the Boolean series is having NaN wherever the value in College column was empty or NaN. If this boolean series is passed into data frame, it will give an error. Hence, the NaN values need to be handled using na Parameter. It can be set to string too, but since bool series is used to pass and return respective value, it should be set to a Bool value only.In this example, na Parameter is set to False. So wherever the College column is having Null value, the Bool series will store False instead of NaN. After that, the series is passed again to data frame to display only True values." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # String to be searched in start of string search =\"G\" # boolean series returned with False at place of NaNbool_series = data[\"College\"].str.startswith(search, na = False) # displaying filtered dataframedata[bool_series]", "e": 2933, "s": 2553, "text": null }, { "code": null, "e": 3130, "s": 2933, "text": "Output:As shown in the output image, the data frame is having rows which have “G” in starting of string in the College column. NaN values are not displayed since the na parameter was set to False." }, { "code": null, "e": 3151, "s": 3130, "text": "Python pandas-series" }, { "code": null, "e": 3180, "s": 3151, "text": "Python pandas-series-methods" }, { "code": null, "e": 3194, "s": 3180, "text": "Python-pandas" }, { "code": null, "e": 3201, "s": 3194, "text": "Python" }, { "code": null, "e": 3299, "s": 3201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3317, "s": 3299, "text": "Python Dictionary" }, { "code": null, "e": 3359, "s": 3317, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3381, "s": 3359, "text": "Enumerate() in Python" }, { "code": null, "e": 3413, "s": 3381, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3442, "s": 3413, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3469, "s": 3442, "text": "Python Classes and Objects" }, { "code": null, "e": 3490, "s": 3469, "text": "Python OOPs Concepts" }, { "code": null, "e": 3513, "s": 3490, "text": "Introduction To PYTHON" }, { "code": null, "e": 3549, "s": 3513, "text": "Convert integer to string in Python" } ]
How to check if the provided value is an object created by the Object constructor in JavaScript ?
15 Apr, 2021 In this article, we will learn how to check if the provided value is an object created by the Object constructor in JavaScript. Almost all the values in JavaScript are objects except primitive values. Approach: We know that an object will have its own properties and methods. For any JavaScript object, there is a property known as the constructor property. This constructor property basically returns a reference to the constructor function that created the instance. For example, the constructor property of an array will return Array as the result. Similarly, for an object, it will return an Object. Note that these do not string values, rather references to the constructor function. The checking of a value, if it was created by the Object constructor, can simply be done by comparing the object’s constructor property value with the corresponding Object constructor function reference. This returns a boolean value depending upon the result of the comparison. Syntax: return (obj.constructor === Object); Example: HTML <html><body> <h1 style="color: green;"> GeeksforGeeks </h1> <h3>How to check whether an object is created by Object constructor or not</h3> <p>Click on the button to run all test cases</p> <p>Test Case 1: {}</p> <p>Created by Object constructor: <span id="testcase1"></span></p> <p>Test Case 2: new Object</p> <p>Created by Object constructor: <span id="testcase2"></span></p> <p>Test Case 3: new Object()</p> <p>Created by Object constructor: <span id="testcase3"></span></p> <p>Test Case 4: []</p> <p>Created by Object constructor: <span id="testcase4"></span></p> <p>Test Case 5: "GeeksforGeeks"</p> <p>Created by Object constructor: <span id="testcase5"></span></p> <button onclick="executeTestCases()">Run</button> <script> // Function to check if created by // Object constructor function checkCreatedByObjectConstructor(obj) { return obj.constructor === Object ? true : false } function executeTestCases() { document.getElementById("testcase1").textContent = checkCreatedByObjectConstructor({}); document.getElementById("testcase2").textContent = checkCreatedByObjectConstructor(new Object); document.getElementById("testcase3").textContent = checkCreatedByObjectConstructor(new Object()); document.getElementById("testcase4").textContent = checkCreatedByObjectConstructor([]); document.getElementById("testcase5").textContent = checkCreatedByObjectConstructor("GeeksforGeeks"); } </script></body></html> Output: javascript-object JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2021" }, { "code": null, "e": 229, "s": 28, "text": "In this article, we will learn how to check if the provided value is an object created by the Object constructor in JavaScript. Almost all the values in JavaScript are objects except primitive values." }, { "code": null, "e": 718, "s": 229, "text": "Approach: We know that an object will have its own properties and methods. For any JavaScript object, there is a property known as the constructor property. This constructor property basically returns a reference to the constructor function that created the instance. For example, the constructor property of an array will return Array as the result. Similarly, for an object, it will return an Object. Note that these do not string values, rather references to the constructor function. " }, { "code": null, "e": 996, "s": 718, "text": "The checking of a value, if it was created by the Object constructor, can simply be done by comparing the object’s constructor property value with the corresponding Object constructor function reference. This returns a boolean value depending upon the result of the comparison." }, { "code": null, "e": 1004, "s": 996, "text": "Syntax:" }, { "code": null, "e": 1041, "s": 1004, "text": "return (obj.constructor === Object);" }, { "code": null, "e": 1050, "s": 1041, "text": "Example:" }, { "code": null, "e": 1055, "s": 1050, "text": "HTML" }, { "code": "<html><body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3>How to check whether an object is created by Object constructor or not</h3> <p>Click on the button to run all test cases</p> <p>Test Case 1: {}</p> <p>Created by Object constructor: <span id=\"testcase1\"></span></p> <p>Test Case 2: new Object</p> <p>Created by Object constructor: <span id=\"testcase2\"></span></p> <p>Test Case 3: new Object()</p> <p>Created by Object constructor: <span id=\"testcase3\"></span></p> <p>Test Case 4: []</p> <p>Created by Object constructor: <span id=\"testcase4\"></span></p> <p>Test Case 5: \"GeeksforGeeks\"</p> <p>Created by Object constructor: <span id=\"testcase5\"></span></p> <button onclick=\"executeTestCases()\">Run</button> <script> // Function to check if created by // Object constructor function checkCreatedByObjectConstructor(obj) { return obj.constructor === Object ? true : false } function executeTestCases() { document.getElementById(\"testcase1\").textContent = checkCreatedByObjectConstructor({}); document.getElementById(\"testcase2\").textContent = checkCreatedByObjectConstructor(new Object); document.getElementById(\"testcase3\").textContent = checkCreatedByObjectConstructor(new Object()); document.getElementById(\"testcase4\").textContent = checkCreatedByObjectConstructor([]); document.getElementById(\"testcase5\").textContent = checkCreatedByObjectConstructor(\"GeeksforGeeks\"); } </script></body></html>", "e": 2627, "s": 1055, "text": null }, { "code": null, "e": 2635, "s": 2627, "text": "Output:" }, { "code": null, "e": 2653, "s": 2635, "text": "javascript-object" }, { "code": null, "e": 2674, "s": 2653, "text": "JavaScript-Questions" }, { "code": null, "e": 2681, "s": 2674, "text": "Picked" }, { "code": null, "e": 2692, "s": 2681, "text": "JavaScript" }, { "code": null, "e": 2709, "s": 2692, "text": "Web Technologies" }, { "code": null, "e": 2807, "s": 2709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2868, "s": 2807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2908, "s": 2868, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2949, "s": 2908, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2991, "s": 2949, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3013, "s": 2991, "text": "JavaScript | Promises" }, { "code": null, "e": 3046, "s": 3013, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3108, "s": 3046, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3169, "s": 3108, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3219, "s": 3169, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Seaborn.barplot() method in Python
16 Jun, 2021 Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well. A barplot is basically used to aggregate the categorical data according to some methods and by default it’s the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x-axis and a numerical column for the y-axis, and we see that it creates a plot taking a mean per categorical column. Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x000002BC3EB5C4C8>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=0.75, errcolor=’.26′, errwidth=None, capsize=None, dodge=True, ax=None, **kwargs,) Parameters : Following steps are used : Import Seaborn Load Dataset from Seaborn as it contain good collection of datasets. Plot Bar graph using seaborn.barplot() method. Below is the implementation : Example 1: Python3 # importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', data = df) # Show the plotplt.show() Output: Example 2: Python3 # importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df) # Show the plotplt.show() Output: Example 3: Python3 # importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df, palette = "Blues") # Show the plotplt.show() Output: Example 4: Python3 # importing the required libraryimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df, estimator = np.median, ci = 0) # Show the plotplt.show() Output: ankthon abhishek0719kadiyan Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2021" }, { "code": null, "e": 492, "s": 53, "text": "Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well." }, { "code": null, "e": 853, "s": 492, "text": "A barplot is basically used to aggregate the categorical data according to some methods and by default it’s the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x-axis and a numerical column for the y-axis, and we see that it creates a plot taking a mean per categorical column." }, { "code": null, "e": 1159, "s": 853, "text": "Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x000002BC3EB5C4C8>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=0.75, errcolor=’.26′, errwidth=None, capsize=None, dodge=True, ax=None, **kwargs,) " }, { "code": null, "e": 1172, "s": 1159, "text": "Parameters :" }, { "code": null, "e": 1199, "s": 1172, "text": "Following steps are used :" }, { "code": null, "e": 1214, "s": 1199, "text": "Import Seaborn" }, { "code": null, "e": 1283, "s": 1214, "text": "Load Dataset from Seaborn as it contain good collection of datasets." }, { "code": null, "e": 1330, "s": 1283, "text": "Plot Bar graph using seaborn.barplot() method." }, { "code": null, "e": 1360, "s": 1330, "text": "Below is the implementation :" }, { "code": null, "e": 1371, "s": 1360, "text": "Example 1:" }, { "code": null, "e": 1379, "s": 1371, "text": "Python3" }, { "code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', data = df) # Show the plotplt.show()", "e": 1660, "s": 1379, "text": null }, { "code": null, "e": 1668, "s": 1660, "text": "Output:" }, { "code": null, "e": 1679, "s": 1668, "text": "Example 2:" }, { "code": null, "e": 1687, "s": 1679, "text": "Python3" }, { "code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df) # Show the plotplt.show()", "e": 1995, "s": 1687, "text": null }, { "code": null, "e": 2003, "s": 1995, "text": "Output:" }, { "code": null, "e": 2014, "s": 2003, "text": "Example 3:" }, { "code": null, "e": 2022, "s": 2014, "text": "Python3" }, { "code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df, palette = \"Blues\") # Show the plotplt.show()", "e": 2360, "s": 2022, "text": null }, { "code": null, "e": 2368, "s": 2360, "text": "Output:" }, { "code": null, "e": 2379, "s": 2368, "text": "Example 4:" }, { "code": null, "e": 2387, "s": 2379, "text": "Python3" }, { "code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who', y = 'fare', hue = 'class', data = df, estimator = np.median, ci = 0) # Show the plotplt.show()", "e": 2766, "s": 2387, "text": null }, { "code": null, "e": 2774, "s": 2766, "text": "Output:" }, { "code": null, "e": 2782, "s": 2774, "text": "ankthon" }, { "code": null, "e": 2802, "s": 2782, "text": "abhishek0719kadiyan" }, { "code": null, "e": 2817, "s": 2802, "text": "Python-Seaborn" }, { "code": null, "e": 2824, "s": 2817, "text": "Python" }, { "code": null, "e": 2922, "s": 2824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2940, "s": 2922, "text": "Python Dictionary" }, { "code": null, "e": 2982, "s": 2940, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3004, "s": 2982, "text": "Enumerate() in Python" }, { "code": null, "e": 3036, "s": 3004, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3065, "s": 3036, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3092, "s": 3065, "text": "Python Classes and Objects" }, { "code": null, "e": 3128, "s": 3092, "text": "Convert integer to string in Python" }, { "code": null, "e": 3149, "s": 3128, "text": "Python OOPs Concepts" }, { "code": null, "e": 3172, "s": 3149, "text": "Introduction To PYTHON" } ]
Find Excel column number from column title
15 Nov, 2021 We have discussed Conversion from column number to Excel Column name. In this post, reverse is discussed.Given a column title as appears in an Excel sheet, return its corresponding column number. column column number A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 Examples: Input: A Output: 1 A is the first column so the output is 1. Input: AA Output: 27 The columns are in order A, B, ..., Y, Z, AA .. So, there are 26 columns after which AA comes. Approach: The process is similar to binary to decimal conversion. For example, to convert AB, the formula is 26 * 1 + 2. As another example, To convert CDA, 3*26*26 + 4*26 + 1 = 26(3*26 + 4) + 1 = 26(0*26 + 3*26 + 4) + 1 So it is very much similar to converting binary to decimal keeping the base as 26. Take the input as string and the traverse the input string from the left to right and calculate the result as follows: result = 26*result + s[i] - 'A' + 1 . The result will be summation of . C++ Java Python3 C# Javascript // C++ program to return title to result// of excel sheet.#include <bits/stdc++.h> using namespace std; // Returns result when we pass title.int titleToNumber(string s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (const auto& c : s) { result *= 26; result += c - 'A' + 1; } return result;} // Driver functionint main(){ cout << titleToNumber("CDA") << endl; return 0;} // Java program to return title// to result of excel sheet.import java.util.*;import java.lang.*; class GFG{ // Returns result when we pass title.static int titleToNumber(String s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (int i = 0; i < s.length(); i++) { result *= 26; result += s.charAt(i) - 'A' + 1; } return result;} // Driver Codepublic static void main (String[] args){ System.out.print(titleToNumber("CDA"));}} // This code is contributed// by Akanksha Rai(Abby_akku) # Python program to return title to result# of excel sheet. # Returns result when we pass title.def titleToNumber(s): # This process is similar to binary-to- # decimal conversion result = 0; for B in range(len(s)): result *= 26; result += ord(s[B]) - ord('A') + 1; return result; # Driver functionprint(titleToNumber("CDA")); # This code contributed by Rajput-Ji // C# program to return title// to result of excel sheet.using System; class GFG{ // Returns result when we pass title.public static int titleToNumber(string s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (int i = 0; i < s.Length; i++) { result *= 26; result += s[i] - 'A' + 1; } return result;} // Driver Codepublic static void Main(string[] args){ Console.Write(titleToNumber("CDA"));}} // This code is contributed by Shrikant13 <script> // JavaScript program to return title// to result of excel sheet. // Returns result when we pass titlefunction titleToNumber(s){ // This process is similar to // binary-to-decimal conversion let result = 0; for (let i = 0; i < s.length; i++) { result *= 26; result += s[i].charCodeAt(0) - 'A'.charCodeAt(0) + 1; } return result;}// Driver Codedocument.write(titleToNumber("CDA")); // This code is contributed by avanitrachhadiya2155 </script> Output: 2133 Complexity Analysis: Time Complexity: O(n), where n is length of input string. Space Complexity: O(1). As no extra space is required. This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AnjaliSelvaraj Akanksha_Rai shrikanth13 Rajput-Ji andrew1234 avanitrachhadiya2155 prachisoda1234 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Convert string to char array in C++ Reverse words in a given string
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Nov, 2021" }, { "code": null, "e": 251, "s": 54, "text": "We have discussed Conversion from column number to Excel Column name. In this post, reverse is discussed.Given a column title as appears in an Excel sheet, return its corresponding column number. " }, { "code": null, "e": 349, "s": 251, "text": "column column number\n A -> 1\n B -> 2\n C -> 3\n ...\n Z -> 26\n AA -> 27\n AB -> 28 " }, { "code": null, "e": 361, "s": 349, "text": "Examples: " }, { "code": null, "e": 539, "s": 361, "text": "Input: A\nOutput: 1\nA is the first column so the output is 1.\n\nInput: AA\nOutput: 27\nThe columns are in order A, B, ..., Y, Z, AA ..\nSo, there are 26 columns after which AA comes." }, { "code": null, "e": 684, "s": 541, "text": "Approach: The process is similar to binary to decimal conversion. For example, to convert AB, the formula is 26 * 1 + 2. As another example, " }, { "code": null, "e": 764, "s": 684, "text": "To convert CDA,\n3*26*26 + 4*26 + 1\n= 26(3*26 + 4) + 1\n= 26(0*26 + 3*26 + 4) + 1" }, { "code": null, "e": 968, "s": 764, "text": "So it is very much similar to converting binary to decimal keeping the base as 26. Take the input as string and the traverse the input string from the left to right and calculate the result as follows: " }, { "code": null, "e": 1004, "s": 968, "text": "result = 26*result + s[i] - 'A' + 1" }, { "code": null, "e": 1041, "s": 1004, "text": ". The result will be summation of . " }, { "code": null, "e": 1045, "s": 1041, "text": "C++" }, { "code": null, "e": 1050, "s": 1045, "text": "Java" }, { "code": null, "e": 1058, "s": 1050, "text": "Python3" }, { "code": null, "e": 1061, "s": 1058, "text": "C#" }, { "code": null, "e": 1072, "s": 1061, "text": "Javascript" }, { "code": "// C++ program to return title to result// of excel sheet.#include <bits/stdc++.h> using namespace std; // Returns result when we pass title.int titleToNumber(string s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (const auto& c : s) { result *= 26; result += c - 'A' + 1; } return result;} // Driver functionint main(){ cout << titleToNumber(\"CDA\") << endl; return 0;}", "e": 1523, "s": 1072, "text": null }, { "code": "// Java program to return title// to result of excel sheet.import java.util.*;import java.lang.*; class GFG{ // Returns result when we pass title.static int titleToNumber(String s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (int i = 0; i < s.length(); i++) { result *= 26; result += s.charAt(i) - 'A' + 1; } return result;} // Driver Codepublic static void main (String[] args){ System.out.print(titleToNumber(\"CDA\"));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 2083, "s": 1523, "text": null }, { "code": "# Python program to return title to result# of excel sheet. # Returns result when we pass title.def titleToNumber(s): # This process is similar to binary-to- # decimal conversion result = 0; for B in range(len(s)): result *= 26; result += ord(s[B]) - ord('A') + 1; return result; # Driver functionprint(titleToNumber(\"CDA\")); # This code contributed by Rajput-Ji", "e": 2476, "s": 2083, "text": null }, { "code": "// C# program to return title// to result of excel sheet.using System; class GFG{ // Returns result when we pass title.public static int titleToNumber(string s){ // This process is similar to // binary-to-decimal conversion int result = 0; for (int i = 0; i < s.Length; i++) { result *= 26; result += s[i] - 'A' + 1; } return result;} // Driver Codepublic static void Main(string[] args){ Console.Write(titleToNumber(\"CDA\"));}} // This code is contributed by Shrikant13", "e": 2984, "s": 2476, "text": null }, { "code": "<script> // JavaScript program to return title// to result of excel sheet. // Returns result when we pass titlefunction titleToNumber(s){ // This process is similar to // binary-to-decimal conversion let result = 0; for (let i = 0; i < s.length; i++) { result *= 26; result += s[i].charCodeAt(0) - 'A'.charCodeAt(0) + 1; } return result;}// Driver Codedocument.write(titleToNumber(\"CDA\")); // This code is contributed by avanitrachhadiya2155 </script>", "e": 3471, "s": 2984, "text": null }, { "code": null, "e": 3481, "s": 3471, "text": "Output: " }, { "code": null, "e": 3486, "s": 3481, "text": "2133" }, { "code": null, "e": 3509, "s": 3486, "text": "Complexity Analysis: " }, { "code": null, "e": 3567, "s": 3509, "text": "Time Complexity: O(n), where n is length of input string." }, { "code": null, "e": 3622, "s": 3567, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 4043, "s": 3622, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4058, "s": 4043, "text": "AnjaliSelvaraj" }, { "code": null, "e": 4071, "s": 4058, "text": "Akanksha_Rai" }, { "code": null, "e": 4083, "s": 4071, "text": "shrikanth13" }, { "code": null, "e": 4093, "s": 4083, "text": "Rajput-Ji" }, { "code": null, "e": 4104, "s": 4093, "text": "andrew1234" }, { "code": null, "e": 4125, "s": 4104, "text": "avanitrachhadiya2155" }, { "code": null, "e": 4140, "s": 4125, "text": "prachisoda1234" }, { "code": null, "e": 4148, "s": 4140, "text": "Strings" }, { "code": null, "e": 4156, "s": 4148, "text": "Strings" }, { "code": null, "e": 4254, "s": 4156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4299, "s": 4254, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 4356, "s": 4299, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 4431, "s": 4356, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 4467, "s": 4431, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 4505, "s": 4467, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 4566, "s": 4505, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 4618, "s": 4566, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 4663, "s": 4618, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 4699, "s": 4663, "text": "Convert string to char array in C++" } ]
Python | Measure similarity between two sentences using cosine similarity
10 Jul, 2020 Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them.Similarity = (A.B) / (||A||.||B||) where A and B are vectors. Cosine similarity and nltk toolkit module are used in this program. To execute this program nltk must be installed in your system. In order to install nltk module follow the steps below – 1. Open terminal(Linux). 2. sudo pip3 install nltk 3. python3 4. import nltk 5. nltk.download(‘all’) Functions used: nltk.tokenize: It is used for tokenization. Tokenization is the process by which big quantity of text is divided into smaller parts called tokens. word_tokenize(X) split the given sentence X into words and return list. nltk.corpus: In this program, it is used to get a list of stopwords. A stop word is a commonly used word (such as “the”, “a”, “an”, “in”). # Program to measure the similarity between # two sentences using cosine similarity.from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize # X = input("Enter first string: ").lower()# Y = input("Enter second string: ").lower()X ="I love horror movies"Y ="Lights out is a horror movie" # tokenizationX_list = word_tokenize(X) Y_list = word_tokenize(Y) # sw contains the list of stopwordssw = stopwords.words('english') l1 =[];l2 =[] # remove stop words from the stringX_set = {w for w in X_list if not w in sw} Y_set = {w for w in Y_list if not w in sw} # form a set containing keywords of both strings rvector = X_set.union(Y_set) for w in rvector: if w in X_set: l1.append(1) # create a vector else: l1.append(0) if w in Y_set: l2.append(1) else: l2.append(0)c = 0 # cosine formula for i in range(len(rvector)): c+= l1[i]*l2[i]cosine = c / float((sum(l1)*sum(l2))**0.5)print("similarity: ", cosine) Output: similarity: 0.2886751345948129 Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI 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": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 241, "s": 28, "text": "Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them.Similarity = (A.B) / (||A||.||B||) where A and B are vectors." }, { "code": null, "e": 429, "s": 241, "text": "Cosine similarity and nltk toolkit module are used in this program. To execute this program nltk must be installed in your system. In order to install nltk module follow the steps below –" }, { "code": null, "e": 530, "s": 429, "text": "1. Open terminal(Linux).\n2. sudo pip3 install nltk\n3. python3\n4. import nltk\n5. nltk.download(‘all’)" }, { "code": null, "e": 546, "s": 530, "text": "Functions used:" }, { "code": null, "e": 765, "s": 546, "text": "nltk.tokenize: It is used for tokenization. Tokenization is the process by which big quantity of text is divided into smaller parts called tokens. word_tokenize(X) split the given sentence X into words and return list." }, { "code": null, "e": 904, "s": 765, "text": "nltk.corpus: In this program, it is used to get a list of stopwords. A stop word is a commonly used word (such as “the”, “a”, “an”, “in”)." }, { "code": "# Program to measure the similarity between # two sentences using cosine similarity.from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize # X = input(\"Enter first string: \").lower()# Y = input(\"Enter second string: \").lower()X =\"I love horror movies\"Y =\"Lights out is a horror movie\" # tokenizationX_list = word_tokenize(X) Y_list = word_tokenize(Y) # sw contains the list of stopwordssw = stopwords.words('english') l1 =[];l2 =[] # remove stop words from the stringX_set = {w for w in X_list if not w in sw} Y_set = {w for w in Y_list if not w in sw} # form a set containing keywords of both strings rvector = X_set.union(Y_set) for w in rvector: if w in X_set: l1.append(1) # create a vector else: l1.append(0) if w in Y_set: l2.append(1) else: l2.append(0)c = 0 # cosine formula for i in range(len(rvector)): c+= l1[i]*l2[i]cosine = c / float((sum(l1)*sum(l2))**0.5)print(\"similarity: \", cosine)", "e": 1847, "s": 904, "text": null }, { "code": null, "e": 1855, "s": 1847, "text": "Output:" }, { "code": null, "e": 1888, "s": 1855, "text": "similarity: 0.2886751345948129\n" }, { "code": null, "e": 1916, "s": 1888, "text": "Natural-language-processing" }, { "code": null, "e": 1928, "s": 1916, "text": "Python-nltk" }, { "code": null, "e": 1945, "s": 1928, "text": "Machine Learning" }, { "code": null, "e": 1952, "s": 1945, "text": "Python" }, { "code": null, "e": 1969, "s": 1952, "text": "Machine Learning" }, { "code": null, "e": 2067, "s": 1969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2090, "s": 2067, "text": "ML | Linear Regression" }, { "code": null, "e": 2113, "s": 2090, "text": "Reinforcement learning" }, { "code": null, "e": 2150, "s": 2113, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 2190, "s": 2150, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2214, "s": 2190, "text": "Search Algorithms in AI" }, { "code": null, "e": 2242, "s": 2214, "text": "Read JSON file using Python" }, { "code": null, "e": 2292, "s": 2242, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2314, "s": 2292, "text": "Python map() function" } ]
Python | Change column names and row indexes in Pandas DataFrame
16 May, 2020 Given a Pandas DataFrame, let’s see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns. Each row is a measurement of some instance while column is a vector which contains data for some specific attribute/variable. Each dataframe column has a homogeneous data throughout any specific column but dataframe rows can contain homogeneous or heterogeneous data throughout any specific row. Unlike two dimensional array, pandas dataframe axes are labeled. Pandas Dataframe type has two attributes called ‘columns’ and ‘index’ which can be used to change the column names as well as the row indexes. Create a DataFrame using dictionary. # first import the librariesimport pandas as pd # Create a dataFrame using dictionarydf=pd.DataFrame({"Name":['Tom','Nick','John','Peter'], "Age":[15,26,17,28]}) # Creates a dataFrame with# 2 columns and 4 rowsdf Method #1: Changing the column name and row index using df.columns and df.index attribute.In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......].# Let's rename already created dataFrame. # Check the current column names# using "columns" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedfMethod #2: Using rename() function with dictionary to change a single column# let's change the first column name# from "A" to "a" using rename() functiondf = df.rename(columns = {"Col_1":"Mod_col"}) dfChange multiple column names simultaneously –# We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({"Mod_col":"Col_1","B":"Col_2"}, axis='columns') dfMethod #3: Using Lambda Function to rename the columns.A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda functiondf = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdfMethod #4 : Using values attribute to rename the columns.We can use values attribute directly on the column whose name we want to change.df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndfLet’s change the row index using the Lambda function.# To change the row indexesdf = pd.DataFrame({"A":['Tom','Nick','John','Peter'], "B":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) dfNow, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter.df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df Method #1: Changing the column name and row index using df.columns and df.index attribute.In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......].# Let's rename already created dataFrame. # Check the current column names# using "columns" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedf In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......]. # Let's rename already created dataFrame. # Check the current column names# using "columns" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedf Method #2: Using rename() function with dictionary to change a single column# let's change the first column name# from "A" to "a" using rename() functiondf = df.rename(columns = {"Col_1":"Mod_col"}) dfChange multiple column names simultaneously –# We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({"Mod_col":"Col_1","B":"Col_2"}, axis='columns') df # let's change the first column name# from "A" to "a" using rename() functiondf = df.rename(columns = {"Col_1":"Mod_col"}) df Change multiple column names simultaneously – # We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({"Mod_col":"Col_1","B":"Col_2"}, axis='columns') df Method #3: Using Lambda Function to rename the columns.A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda functiondf = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdf A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda function df = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdf Method #4 : Using values attribute to rename the columns.We can use values attribute directly on the column whose name we want to change.df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndfLet’s change the row index using the Lambda function.# To change the row indexesdf = pd.DataFrame({"A":['Tom','Nick','John','Peter'], "B":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) dfNow, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter.df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df We can use values attribute directly on the column whose name we want to change. df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndf Let’s change the row index using the Lambda function. # To change the row indexesdf = pd.DataFrame({"A":['Tom','Nick','John','Peter'], "B":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) df Now, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter. df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df Shubham__Ranjan pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2020" }, { "code": null, "e": 112, "s": 28, "text": "Given a Pandas DataFrame, let’s see how to change its column names and row indexes." }, { "code": null, "e": 272, "s": 112, "text": "About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame." }, { "code": null, "e": 305, "s": 272, "text": "It consists of rows and columns." }, { "code": null, "e": 431, "s": 305, "text": "Each row is a measurement of some instance while column is a vector which contains data for some specific attribute/variable." }, { "code": null, "e": 601, "s": 431, "text": "Each dataframe column has a homogeneous data throughout any specific column but dataframe rows can contain homogeneous or heterogeneous data throughout any specific row." }, { "code": null, "e": 666, "s": 601, "text": "Unlike two dimensional array, pandas dataframe axes are labeled." }, { "code": null, "e": 809, "s": 666, "text": "Pandas Dataframe type has two attributes called ‘columns’ and ‘index’ which can be used to change the column names as well as the row indexes." }, { "code": null, "e": 846, "s": 809, "text": "Create a DataFrame using dictionary." }, { "code": "# first import the librariesimport pandas as pd # Create a dataFrame using dictionarydf=pd.DataFrame({\"Name\":['Tom','Nick','John','Peter'], \"Age\":[15,26,17,28]}) # Creates a dataFrame with# 2 columns and 4 rowsdf", "e": 1078, "s": 846, "text": null }, { "code": null, "e": 3410, "s": 1078, "text": "Method #1: Changing the column name and row index using df.columns and df.index attribute.In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......].# Let's rename already created dataFrame. # Check the current column names# using \"columns\" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedfMethod #2: Using rename() function with dictionary to change a single column# let's change the first column name# from \"A\" to \"a\" using rename() functiondf = df.rename(columns = {\"Col_1\":\"Mod_col\"}) dfChange multiple column names simultaneously –# We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({\"Mod_col\":\"Col_1\",\"B\":\"Col_2\"}, axis='columns') dfMethod #3: Using Lambda Function to rename the columns.A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda functiondf = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdfMethod #4 : Using values attribute to rename the columns.We can use values attribute directly on the column whose name we want to change.df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndfLet’s change the row index using the Lambda function.# To change the row indexesdf = pd.DataFrame({\"A\":['Tom','Nick','John','Peter'], \"B\":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) dfNow, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter.df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df" }, { "code": null, "e": 4043, "s": 3410, "text": "Method #1: Changing the column name and row index using df.columns and df.index attribute.In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......].# Let's rename already created dataFrame. # Check the current column names# using \"columns\" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedf" }, { "code": null, "e": 4312, "s": 4043, "text": "In order to change the column names, we provide a Python list containing the names for column df.columns= ['First_col', 'Second_col', 'Third_col', .....].In order to change the row indexes, we also provide a python list to it df.index=['row1', 'row2', 'row3', ......]." }, { "code": "# Let's rename already created dataFrame. # Check the current column names# using \"columns\" attribute.# df.columns # Change the column namesdf.columns =['Col_1', 'Col_2'] # Change the row indexesdf.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4'] # printing the data framedf", "e": 4587, "s": 4312, "text": null }, { "code": null, "e": 5021, "s": 4587, "text": "Method #2: Using rename() function with dictionary to change a single column# let's change the first column name# from \"A\" to \"a\" using rename() functiondf = df.rename(columns = {\"Col_1\":\"Mod_col\"}) dfChange multiple column names simultaneously –# We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({\"Mod_col\":\"Col_1\",\"B\":\"Col_2\"}, axis='columns') df" }, { "code": "# let's change the first column name# from \"A\" to \"a\" using rename() functiondf = df.rename(columns = {\"Col_1\":\"Mod_col\"}) df", "e": 5148, "s": 5021, "text": null }, { "code": null, "e": 5194, "s": 5148, "text": "Change multiple column names simultaneously –" }, { "code": "# We can change multiple column names by # passing a dictionary of old names and # new names, to the rename() function.df = df.rename({\"Mod_col\":\"Col_1\",\"B\":\"Col_2\"}, axis='columns') df", "e": 5381, "s": 5194, "text": null }, { "code": null, "e": 5780, "s": 5381, "text": "Method #3: Using Lambda Function to rename the columns.A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda functiondf = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdf" }, { "code": null, "e": 6042, "s": 5780, "text": "A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda function" }, { "code": "df = df.rename(columns=lambda x: x+'x') # this will modify all the column namesdf", "e": 6125, "s": 6042, "text": null }, { "code": null, "e": 6994, "s": 6125, "text": "Method #4 : Using values attribute to rename the columns.We can use values attribute directly on the column whose name we want to change.df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndfLet’s change the row index using the Lambda function.# To change the row indexesdf = pd.DataFrame({\"A\":['Tom','Nick','John','Peter'], \"B\":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) dfNow, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter.df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df" }, { "code": null, "e": 7075, "s": 6994, "text": "We can use values attribute directly on the column whose name we want to change." }, { "code": "df.columns.values[1] = 'Student_Age' # this will modify the name of the first columndf", "e": 7163, "s": 7075, "text": null }, { "code": null, "e": 7217, "s": 7163, "text": "Let’s change the row index using the Lambda function." }, { "code": "# To change the row indexesdf = pd.DataFrame({\"A\":['Tom','Nick','John','Peter'], \"B\":[25,16,27,18]}) # this will increase the row index value by 10 for each rowdf = df.rename(index = lambda x: x + 10) df", "e": 7441, "s": 7217, "text": null }, { "code": null, "e": 7626, "s": 7441, "text": "Now, if we want to change the row indexes and column names simultaneously, then it can be achieved using rename() function and passing both column and index attribute as the parameter." }, { "code": "df = df.rename(index = lambda x: x + 5, columns = lambda x: x +'x') # increase all the row index label by value 5# append a value 'x' at the end of each column name. df", "e": 7811, "s": 7626, "text": null }, { "code": null, "e": 7827, "s": 7811, "text": "Shubham__Ranjan" }, { "code": null, "e": 7852, "s": 7827, "text": "pandas-dataframe-program" }, { "code": null, "e": 7859, "s": 7852, "text": "Picked" }, { "code": null, "e": 7883, "s": 7859, "text": "Python pandas-dataFrame" }, { "code": null, "e": 7897, "s": 7883, "text": "Python-pandas" }, { "code": null, "e": 7921, "s": 7897, "text": "Technical Scripter 2018" }, { "code": null, "e": 7928, "s": 7921, "text": "Python" }, { "code": null, "e": 7947, "s": 7928, "text": "Technical Scripter" }, { "code": null, "e": 8045, "s": 7947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8063, "s": 8045, "text": "Python Dictionary" }, { "code": null, "e": 8105, "s": 8063, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8127, "s": 8105, "text": "Enumerate() in Python" }, { "code": null, "e": 8162, "s": 8127, "text": "Read a file line by line in Python" }, { "code": null, "e": 8188, "s": 8162, "text": "Python String | replace()" }, { "code": null, "e": 8220, "s": 8188, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8249, "s": 8220, "text": "*args and **kwargs in Python" }, { "code": null, "e": 8276, "s": 8249, "text": "Python Classes and Objects" }, { "code": null, "e": 8306, "s": 8276, "text": "Iterate over a list in Python" } ]
numpy.roots() function – Python
11 Jun, 2020 numpy.roots() function return the roots of a polynomial with coefficients given in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Syntax : numpy.roots(p) Parameters :p : [array_like] Rank-1 array of polynomial coefficients. Return : [ndarray] An array containing the roots of the polynomial. Code #1 : # Python program explaining# numpy.roots() function # importing numpy as geek import numpy as geek p = [1, 2, 3] gfg = geek.roots(p) print (gfg) Output : [-1.+1.41421356j -1.-1.41421356j] Code #2 : # Python program explaining# numpy.roots() function # importing numpy as geek import numpy as geek p = [3.2, 2, 1] gfg = geek.roots(p) print (gfg) Output : [-0.3125+0.46351241j -0.3125-0.46351241j] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2020" }, { "code": null, "e": 298, "s": 28, "text": "numpy.roots() function return the roots of a polynomial with coefficients given in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]" }, { "code": null, "e": 322, "s": 298, "text": "Syntax : numpy.roots(p)" }, { "code": null, "e": 392, "s": 322, "text": "Parameters :p : [array_like] Rank-1 array of polynomial coefficients." }, { "code": null, "e": 460, "s": 392, "text": "Return : [ndarray] An array containing the roots of the polynomial." }, { "code": null, "e": 470, "s": 460, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.roots() function # importing numpy as geek import numpy as geek p = [1, 2, 3] gfg = geek.roots(p) print (gfg)", "e": 624, "s": 470, "text": null }, { "code": null, "e": 633, "s": 624, "text": "Output :" }, { "code": null, "e": 668, "s": 633, "text": "[-1.+1.41421356j -1.-1.41421356j]\n" }, { "code": null, "e": 679, "s": 668, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.roots() function # importing numpy as geek import numpy as geek p = [3.2, 2, 1] gfg = geek.roots(p) print (gfg)", "e": 839, "s": 679, "text": null }, { "code": null, "e": 848, "s": 839, "text": "Output :" }, { "code": null, "e": 891, "s": 848, "text": "[-0.3125+0.46351241j -0.3125-0.46351241j]\n" }, { "code": null, "e": 904, "s": 891, "text": "Python-numpy" }, { "code": null, "e": 911, "s": 904, "text": "Python" }, { "code": null, "e": 1009, "s": 911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1027, "s": 1009, "text": "Python Dictionary" }, { "code": null, "e": 1069, "s": 1027, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1091, "s": 1069, "text": "Enumerate() in Python" }, { "code": null, "e": 1126, "s": 1091, "text": "Read a file line by line in Python" }, { "code": null, "e": 1152, "s": 1126, "text": "Python String | replace()" }, { "code": null, "e": 1184, "s": 1152, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1213, "s": 1184, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1240, "s": 1213, "text": "Python Classes and Objects" }, { "code": null, "e": 1270, "s": 1240, "text": "Iterate over a list in Python" } ]
Selecting rows in pandas DataFrame based on conditions - GeeksforGeeks
10 Jun, 2021 Let’s see how to Select rows based on some conditions in Pandas DataFrame. YouTubeGeeksforGeeks507K subscribersSelecting Rows in Pandas DataFrame Based on Conditions | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=D9FwM-76Cns" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Code #1 : Selecting all the rows from the given dataframe in which ‘Percentage’ is greater than 80 using basic method. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78] } # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) # selecting rows based on conditionrslt_df = dataframe[dataframe['Percentage'] > 80] print('\nResult dataframe :\n', rslt_df) Output : Code #2 : Selecting all the rows from the given dataframe in which ‘Percentage’ is greater than 80 using loc[]. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Percentage'] > 80] print('\nResult dataframe :\n', rslt_df) Output : Code #3 : Selecting all the rows from the given dataframe in which ‘Percentage’ is not equal to 95 using loc[]. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Percentage'] != 95] print('\nResult dataframe :\n', rslt_df) Output : Code #1 : Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using basic method. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) options = ['Math', 'Commerce'] # selecting rows based on conditionrslt_df = dataframe[dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df) Output : Code #2 : Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using loc[]. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) options = ['Math', 'Commerce'] # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df) Output : Code #3 : Selecting all the rows from the given dataframe in which ‘Stream’ is not present in the options list using .loc[]. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe.loc[~dataframe['Stream'].isin(options)] print('\nresult dataframe :\n', rslt_df) Output : Code #1 : Selecting all the rows from the given dataframe in which ‘Age’ is equal to 21 and ‘Stream’ is present in the options list using basic method. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe[(dataframe['Age'] == 21) & dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df) Output : Code #2 : Selecting all the rows from the given dataframe in which ‘Age’ is equal to 21 and ‘Stream’ is present in the options list using .loc[]. # importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe.loc[(dataframe['Age'] == 21) & dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df) Output : pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python isupper(), islower(), lower(), upper() in Python and their applications
[ { "code": null, "e": 26103, "s": 26075, "text": "\n10 Jun, 2021" }, { "code": null, "e": 26178, "s": 26103, "text": "Let’s see how to Select rows based on some conditions in Pandas DataFrame." }, { "code": null, "e": 27031, "s": 26178, "text": "YouTubeGeeksforGeeks507K subscribersSelecting Rows in Pandas DataFrame Based on Conditions | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=D9FwM-76Cns\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 27150, "s": 27031, "text": "Code #1 : Selecting all the rows from the given dataframe in which ‘Percentage’ is greater than 80 using basic method." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78] } # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) # selecting rows based on conditionrslt_df = dataframe[dataframe['Percentage'] > 80] print('\\nResult dataframe :\\n', rslt_df)", "e": 27694, "s": 27150, "text": null }, { "code": null, "e": 27703, "s": 27694, "text": "Output :" }, { "code": null, "e": 27815, "s": 27703, "text": "Code #2 : Selecting all the rows from the given dataframe in which ‘Percentage’ is greater than 80 using loc[]." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Percentage'] > 80] print('\\nResult dataframe :\\n', rslt_df)", "e": 28364, "s": 27815, "text": null }, { "code": null, "e": 28373, "s": 28364, "text": "Output :" }, { "code": null, "e": 28485, "s": 28373, "text": "Code #3 : Selecting all the rows from the given dataframe in which ‘Percentage’ is not equal to 95 using loc[]." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Percentage'] != 95] print('\\nResult dataframe :\\n', rslt_df)", "e": 29035, "s": 28485, "text": null }, { "code": null, "e": 29044, "s": 29035, "text": "Output :" }, { "code": null, "e": 29171, "s": 29044, "text": "Code #1 : Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using basic method." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) options = ['Math', 'Commerce'] # selecting rows based on conditionrslt_df = dataframe[dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)", "e": 29753, "s": 29171, "text": null }, { "code": null, "e": 29762, "s": 29753, "text": "Output :" }, { "code": null, "e": 29882, "s": 29762, "text": "Code #2 : Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using loc[]." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) options = ['Math', 'Commerce'] # selecting rows based on conditionrslt_df = dataframe.loc[dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)", "e": 30468, "s": 29882, "text": null }, { "code": null, "e": 30477, "s": 30468, "text": "Output :" }, { "code": null, "e": 30602, "s": 30477, "text": "Code #3 : Selecting all the rows from the given dataframe in which ‘Stream’ is not present in the options list using .loc[]." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe.loc[~dataframe['Stream'].isin(options)] print('\\nresult dataframe :\\n', rslt_df)", "e": 31188, "s": 30602, "text": null }, { "code": null, "e": 31197, "s": 31188, "text": "Output :" }, { "code": null, "e": 31349, "s": 31197, "text": "Code #1 : Selecting all the rows from the given dataframe in which ‘Age’ is equal to 21 and ‘Stream’ is present in the options list using basic method." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe[(dataframe['Age'] == 21) & dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)", "e": 31966, "s": 31349, "text": null }, { "code": null, "e": 31975, "s": 31966, "text": "Output :" }, { "code": null, "e": 32121, "s": 31975, "text": "Code #2 : Selecting all the rows from the given dataframe in which ‘Age’ is equal to 21 and ‘Stream’ is present in the options list using .loc[]." }, { "code": "# importing pandasimport pandas as pd record = { 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ], 'Age': [21, 19, 20, 18, 17, 21], 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage': [88, 92, 95, 70, 65, 78]} # create a dataframedataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", dataframe) options = ['Math', 'Science'] # selecting rows based on conditionrslt_df = dataframe.loc[(dataframe['Age'] == 21) & dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)", "e": 32746, "s": 32121, "text": null }, { "code": null, "e": 32755, "s": 32746, "text": "Output :" }, { "code": null, "e": 32780, "s": 32755, "text": "pandas-dataframe-program" }, { "code": null, "e": 32787, "s": 32780, "text": "Picked" }, { "code": null, "e": 32811, "s": 32787, "text": "Python pandas-dataFrame" }, { "code": null, "e": 32825, "s": 32811, "text": "Python-pandas" }, { "code": null, "e": 32849, "s": 32825, "text": "Technical Scripter 2018" }, { "code": null, "e": 32856, "s": 32849, "text": "Python" }, { "code": null, "e": 32875, "s": 32856, "text": "Technical Scripter" }, { "code": null, "e": 32973, "s": 32875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33005, "s": 32973, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33027, "s": 33005, "text": "Enumerate() in Python" }, { "code": null, "e": 33069, "s": 33027, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33098, "s": 33069, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33135, "s": 33098, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 33171, "s": 33135, "text": "Convert integer to string in Python" }, { "code": null, "e": 33213, "s": 33171, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33255, "s": 33213, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33280, "s": 33255, "text": "sum() function in Python" } ]
The Battle of the Neighborhoods — Open a Movie Theater in Montreal | by Tony Xu | Towards Data Science
I followed IBM Data Science Professional Certificate in Coursera, it’s composed of 9 courses in this professional certificate. There are pretty good examples of the courses. The final assignment is to finish a project called the Capstone project which requests you to leverage Foursquare APIs to fetch the data from API calls and utilize the folium map library to visualize data analysis. It’s quite a good opportunity to practice data science methodology and toolset in this project. In this project, we will cover all phases in the data science life cycle to resolve a problem. And we will dive into the following tools/library in data science: Folium library, including choropleth map, heatmap in map view Honeycomb Grid for Folium map Google Geocoding APIs Foursquare APIs K-Means Clustering Algorithm Horizontal Bar Chart Pandas, Numpy, Shapely Ok, let’s get started. In this project, we are going to look for an optimal location to open a movie theater. Specifically, this report can provide a reference for stakeholders who are interested in opening a movie theater in Montreal, Quebec, Canada. Montreal is the second-largest city in Canada and the largest city in the province of Quebec, located along the Saint Lawrence River at its junction with the Ottawa River. It sits on an island. In this report, we will focus on all areas on the Montreal island. There are many movie theaters on Montreal island, we will conclude where are the existing movie theaters. Then we will use a clustering model to find similar areas on the island considering demographic data of each borough and region. The preferred area shall be distant from existing movie theaters. We will use data science tools to fetch the raw data, visualize it then generate a few most promising areas based on the above criteria. In the meanwhile, we will also explain the advantage and traits for the candidates, so that stakeholders can make the final decision base on the analysis. Based on the definition of our problem, factors that may impact our decision are: Demographic information, e.g. population, density, education, age, income Number of existing shopping malls in the neighborhood and nearby Number of existing movie theaters in the neighborhood and nearby We decided to use a regularly spaced grid of locations all around the whole Montreal island, to define our neighborhoods. Concretely, we will use popular hexagon honeycomb to define our neighborhoods. In this project, we will fetch or extract data from the following data sources: Montreal census information of the 2016 year Centers of hexagon neighborhoods will be generated algorithmically and approximate addresses of centers of those areas will be obtained using Google Geocoding API Shopping malls and movie theaters data in every neighborhood will be obtained using Foursquare API Coordinate of Montreal center will be obtained using Google Geocoding API of well known Montreal location Montreal borough shapefile is obtained from Carto To show the Montreal island boundary in the folium map, we need a geojson definition file for Montreal island. We downloaded this shapefile from the Carto website. The file is in JSON format, containing boundary definition for every borough or municipality in Montreal island. We will visualize this geojson definition file with a folium map in the next step. folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the leaflet.js library. Manipulate your data in Python, then visualize it in on a Leaflet map via folium.1 It’s not difficult to use folium, just required a few lines of code to show Montreal island with boundary data. Next step, we want to generate candidate cells in the map, more specifically, only within Montreal island. It’s popular to use the honeycomb hexagon grid when dealing with problems related to the map. Unlike circle, there is no spacing among hexagons which make sure no missing area. Furthermore, the distance between any two adjacent hexagons is the same. Unfortunately, Folium doesn’t provide native support to draw hexagon in the map view, we have to write some code to support this feature. We write a method to calculate the hexagon vertices’ coordinates by giving centroids coordinates and length of the side. After that, we generate a honeycomb hexagon grid throughout the island. Looks great! 😄 So far we created a honeycomb grid on the island and we generated the center coordinates for each hexagon. We will use Google Geocoding API to reversely lookup the address accordingly. The Google Geocoding API is a service that provides geocoding and reverse geocoding of addresses.2 It requires a Google API key to use this set of APIs. It can be applied from Google Developer Console. Let’s put all the data in a Pandas Dataframe, and show the first 10 items. Each row contains the center address of a hexagon and corresponding latitude and longitude degrees which are in WGS84 spherical coordinate system, X/Y columns are in UTM Cartesian coordinate system which uses the common metric unit — meter or kilometer. The Foursquare Places API offers real-time access to Foursquare’s global database of rich venue data and user content to power your location-based experiences in your app or website.3 Now we generated all the candidate neighborhoods on Montreal island, we will get all movie theaters information using Foursquare API. From Foursquare API documentation, we can find the corresponding movie theater category in Venue Categories. The corresponding ID of Movie Theater in Foursquare API is 4bf58dd8d48988d17f941735 which is under Arts & Entertainment main category. It contains several sub-categories: Drive-in Theater, id: 56aa371be4b08b9a8d5734de Indie Movie Theater, id: 4bf58dd8d48988d17e941735 Multiplex, id: 4bf58dd8d48988d180941735 Unlike coffee shops, restaurants everywhere, there aren’t lots of movie theaters in the region, it also makes sense since we don’t expect movie theater in every neighborhood. Let’s fetch all the movie theaters on Montreal island first. To do so, we will fetch movie theaters data in each borough and municipality. From the response of Foursquare APIs, there are a total of 44 movie theaters on Montreal island. Let’s plot it in a map view. Let’s show it in heatmap using the positron style. From heatmap, we can see the movie theaters are mainly concentrated in downtown areas and the center of the island. Usually, there are also a lot of shopping malls nearby, let’s pull out the shopping centers data on Montreal island using Foursquare APIs. From Foursquare API documentation, there are several categories related to shopping malls or shopping centers. We will fetch all shopping malls data in the above categories and show them on the map with movie theaters data. From the map view, we can see movie theater is located near shopping malls in most scenarios. Our target area shall have more shopping malls and fewer movie theaters nearby. Before that, we need to cluster all the candidate hexagons based on certain information, in this project, we pull out census data as major features for clustering. Now we will fetch census information of each borough or municipalities on Montreal island. The latest data was collected in 2016. We can get it from the Montreal city official website. It’s a pretty big excel file containing a lot of data, I modified some sheets a bit to extract data easier into Pandas Dataframe. We only focus on several basic census information: Population, Density, Age, Education and Income. Next, we will show census data distribution on a choropleth map. A Choropleth Map is a map composed of colored polygons. It is used to represent spatial variations of a quantity.4 We also show shopping centers and movie theaters’ locations on the same map. From the above choropleth maps, we can see movie theaters are mostly located in areas with a higher population. Same for shopping centers’ locations. Moreover, most movie theaters locate in the area with lower revenue. Regions with higher revenue have fewer shopping centers and movie theaters. So far, we retrieved all the necessary raw data we needed and visualized them. In the following steps, we will manipulate these datasets, extract data, and generate new features for the machine learning algorithm. Finally, we will find out the best suitable place to open a movie theater on Montreal island. The business purpose of this project is to find a suitable place on Montreal island to open a movie theater. Now we retrieved the following data: All movie theaters data on Montreal islandAll shopping centers data on Montreal island2016 Montreal census data for each borough, concretely, Population, Density, Age, Education and Income data for each borough or municipality within Montreal islandBoundary data of each borough and municipality on Montreal island All movie theaters data on Montreal island All shopping centers data on Montreal island 2016 Montreal census data for each borough, concretely, Population, Density, Age, Education and Income data for each borough or municipality within Montreal island Boundary data of each borough and municipality on Montreal island We also generated a honeycomb hexagons grid throughout the whole Montreal Island. Based on the above raw data, we will try to generate new features accordingly, e.g. census information for each candidate cell, and the number of movie theaters and shopping malls in local and nearby. In the final step, we will focus on the most promising areas with more shopping malls and fewer movie theaters. And we will also present the candidate hexagon cells in the map view for stakeholders to make the final decision. We got the basis census information of each borough and municipality. We want to get the census information for each candidate hexagon cell accordingly, we calculate those census information based on borough and municipality which intersects with the cell. If a hexagon is in one borough completely, we will use the borough’s census info as hexagon’s one. So it means for all hexagons inside one borough, we will treat them the same for census feature. Accordingly, if a hexagon has a 50% intersection with two boroughs respectively, we will generate the census data of this hexagon, 50% ratio from these two boroughs respectively. Based on this rule, we can calculate the census for all hexagons. Let’s merge this data frame with the previous location data frame and generate a new one: candidates_df which contains basic information on each hexagon. We print several rows of this data frame. candidates_df.iloc[200:206] Looking good. Now we have census information in each hexagon area. Then we will calculate the shopping center and movie theaters related information for each hexagon area. We will calculate the following features for shopping malls and movie theaters: The number of shopping malls and movie theaters within the current hexagon cell.The number of shopping malls and movie theaters within 1 km away from the center of the hexagon cell.A number of shopping malls and movie theaters within 3 km away from the center of the hexagon cell. The number of shopping malls and movie theaters within the current hexagon cell. The number of shopping malls and movie theaters within 1 km away from the center of the hexagon cell. A number of shopping malls and movie theaters within 3 km away from the center of the hexagon cell. Now we prepared all the data we need, we can use the K-Means clustering algorithm to group the similar candidate hexagon areas into clusters. We pick up census features and the number of shopping malls and the number of movie theaters as input features. We will run an evaluation step first to select the best K which is the number of categories in the algorithm. We use the Sum of Squared Distance and Silhouette Score two methods to evaluate the K-Means algorithm for different K. Sum of Squared Distance measures error between data points and their assigned clusters’ centroids. Smaller means better. Silhouette Score focuses on minimizing the sum of squared distance inside the cluster as well, meanwhile, it also tries to maximize the distance between its neighborhoods. From its definition, the bigger the value is, the better K is. From the figure, we can see Sum of Squared Distance going down when K becomes bigger. When K=2,3, Silhouette Score is higher, but SSE is still high at that time, we choose K=10 for this project, it's a balanced number for both Sum of Squared Distance and Silhouette Score. Let’s run the K-Means algorithm again with k=10. Let’s visualize clustering results with a different color in the map view. Let’s put everything together on one map view: Clusters in colors for hexagonsShopping malls in blue pointMovie theaters in redpoint with yellow ring Clusters in colors for hexagons Shopping malls in blue point Movie theaters in redpoint with yellow ring From the cluster plot in the above map view, we can see there is one cluster in light blue composed of 4 hexagons in downtown, there are full of movie theaters and shopping malls in this cluster. The purple cluster contains the area with a lot of shopping malls. The light green cluster contains more shopping malls and movie theaters except for the downtown cluster. Let’s assign weights to all three movie theaters related features and combine them into one feature. Same for shopping malls. It’s easier for sorting. We will calculate weighted Mall Score and weighted Cinema Score, then generate a new Score feature for sorting. The higher final score is, it means there are more shopping malls and fewer movie theaters. Cluster 7 have the highest score, it has more shopping malls and fewer movie theaters. Let’s explore more characteristics of cluster 7. There are 40 hexagons in Cluster 7 with an average of 0.77 Malls in local and 0.0 Cinemas in local. Let’s plot all clusters for comparison of each feature in a bar chart using matplotlib.pyplot library. We highlight Cluster 7 which is our target cluster. From the bar chart, we can see that Cluster 7 has the most population and density among all the clusters. Furthermore, it has fairly more shopping centers in the hexagon area or nearby and relatively fewer movie theaters. Next, we sort all hexagons in Cluster 7 by Score in descending order and pick the first 5 hexagons. They will be our first choice position to open a movie theater. As the above statistics information, there are 1~3 shopping malls in local and more shopping malls nearby, but without any movie theater within 1 km. Looks quite good selections. Let’s plot Cluster 7 hexagons in the map view, gray out the other clusters and highlight our 5 choices as well. This concludes our analysis. We have found out 5 most promising zones with more shopping malls nearby and fewer movie theaters around the area. Each zone is in regular hexagon shape which is popular in map view. The zones in the cluster have the most population and density comparing with other clusters. We generated hexagon areas all over Montreal island. And we group them into 10 clusters according to census data information including population, density, age, education, and income. Shopping center information and existing movie theaters information are also considered when running the clustering algorithm. From data analysis and visualization, we can see movie theaters are always located near shopping malls usually, which inspired us to find out the area with more shopping malls and fewer movie theaters. After the K-Means Clustering machine learning algorithm, we got the cluster with most shopping malls nearby and fewer movie theaters on average. We also discovered the other characteristics of the cluster. It shows the cluster has the most population and density which implies the highest traffic among all the clusters. There are 40 hexagon areas in this cluster, we sort all these hexagon areas by shopping malls and movie theaters info in descending order which targets to cover more shopping malls and fewer movie theaters in the local cell or nearby. We draw our conclusion with the 5 most promising hexagon areas satisfying all our conditions. These recommended zones shall be a good starting point for further analysis. There are also other factors which could be taken into account, e.g. real traffic data and the revenue of every movie theater, parking lots nearby. They will be helpful to find more accurate results. The purpose of this project is to find an area on Montreal island to open a movie theater. After fetching data from several data sources and process them into a clean data frame, applying the K-Means clustering algorithm, we picked the cluster with more shopping malls and fewer movie theaters on average. By sorting all candidate areas in the cluster, we get the most 5 promising zones which are used as starting points for final exploration by stakeholders. The final decision on optimal movie theater’s location will be made by stakeholders based on specific characteristics of neighborhoods and locations in every recommended zone, taking into consideration additional factors like the parking lot of each location, traffic of existing movie theaters in the cluster, and current revenue of them, etc. https://github.com/kyokin78/Coursera_Capstone/blob/project/CapstoneProject_OpenCinemaInMontreal.ipynb Capstone Project — Open an Italian Restaurant in Berlin, Germany
[ { "code": null, "e": 346, "s": 172, "text": "I followed IBM Data Science Professional Certificate in Coursera, it’s composed of 9 courses in this professional certificate. There are pretty good examples of the courses." }, { "code": null, "e": 657, "s": 346, "text": "The final assignment is to finish a project called the Capstone project which requests you to leverage Foursquare APIs to fetch the data from API calls and utilize the folium map library to visualize data analysis. It’s quite a good opportunity to practice data science methodology and toolset in this project." }, { "code": null, "e": 819, "s": 657, "text": "In this project, we will cover all phases in the data science life cycle to resolve a problem. And we will dive into the following tools/library in data science:" }, { "code": null, "e": 881, "s": 819, "text": "Folium library, including choropleth map, heatmap in map view" }, { "code": null, "e": 911, "s": 881, "text": "Honeycomb Grid for Folium map" }, { "code": null, "e": 933, "s": 911, "text": "Google Geocoding APIs" }, { "code": null, "e": 949, "s": 933, "text": "Foursquare APIs" }, { "code": null, "e": 978, "s": 949, "text": "K-Means Clustering Algorithm" }, { "code": null, "e": 999, "s": 978, "text": "Horizontal Bar Chart" }, { "code": null, "e": 1022, "s": 999, "text": "Pandas, Numpy, Shapely" }, { "code": null, "e": 1045, "s": 1022, "text": "Ok, let’s get started." }, { "code": null, "e": 1274, "s": 1045, "text": "In this project, we are going to look for an optimal location to open a movie theater. Specifically, this report can provide a reference for stakeholders who are interested in opening a movie theater in Montreal, Quebec, Canada." }, { "code": null, "e": 1836, "s": 1274, "text": "Montreal is the second-largest city in Canada and the largest city in the province of Quebec, located along the Saint Lawrence River at its junction with the Ottawa River. It sits on an island. In this report, we will focus on all areas on the Montreal island. There are many movie theaters on Montreal island, we will conclude where are the existing movie theaters. Then we will use a clustering model to find similar areas on the island considering demographic data of each borough and region. The preferred area shall be distant from existing movie theaters." }, { "code": null, "e": 2128, "s": 1836, "text": "We will use data science tools to fetch the raw data, visualize it then generate a few most promising areas based on the above criteria. In the meanwhile, we will also explain the advantage and traits for the candidates, so that stakeholders can make the final decision base on the analysis." }, { "code": null, "e": 2210, "s": 2128, "text": "Based on the definition of our problem, factors that may impact our decision are:" }, { "code": null, "e": 2284, "s": 2210, "text": "Demographic information, e.g. population, density, education, age, income" }, { "code": null, "e": 2349, "s": 2284, "text": "Number of existing shopping malls in the neighborhood and nearby" }, { "code": null, "e": 2414, "s": 2349, "text": "Number of existing movie theaters in the neighborhood and nearby" }, { "code": null, "e": 2615, "s": 2414, "text": "We decided to use a regularly spaced grid of locations all around the whole Montreal island, to define our neighborhoods. Concretely, we will use popular hexagon honeycomb to define our neighborhoods." }, { "code": null, "e": 2695, "s": 2615, "text": "In this project, we will fetch or extract data from the following data sources:" }, { "code": null, "e": 2740, "s": 2695, "text": "Montreal census information of the 2016 year" }, { "code": null, "e": 2903, "s": 2740, "text": "Centers of hexagon neighborhoods will be generated algorithmically and approximate addresses of centers of those areas will be obtained using Google Geocoding API" }, { "code": null, "e": 3002, "s": 2903, "text": "Shopping malls and movie theaters data in every neighborhood will be obtained using Foursquare API" }, { "code": null, "e": 3108, "s": 3002, "text": "Coordinate of Montreal center will be obtained using Google Geocoding API of well known Montreal location" }, { "code": null, "e": 3158, "s": 3108, "text": "Montreal borough shapefile is obtained from Carto" }, { "code": null, "e": 3322, "s": 3158, "text": "To show the Montreal island boundary in the folium map, we need a geojson definition file for Montreal island. We downloaded this shapefile from the Carto website." }, { "code": null, "e": 3518, "s": 3322, "text": "The file is in JSON format, containing boundary definition for every borough or municipality in Montreal island. We will visualize this geojson definition file with a folium map in the next step." }, { "code": null, "e": 3724, "s": 3518, "text": "folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the leaflet.js library. Manipulate your data in Python, then visualize it in on a Leaflet map via folium.1" }, { "code": null, "e": 3836, "s": 3724, "text": "It’s not difficult to use folium, just required a few lines of code to show Montreal island with boundary data." }, { "code": null, "e": 4193, "s": 3836, "text": "Next step, we want to generate candidate cells in the map, more specifically, only within Montreal island. It’s popular to use the honeycomb hexagon grid when dealing with problems related to the map. Unlike circle, there is no spacing among hexagons which make sure no missing area. Furthermore, the distance between any two adjacent hexagons is the same." }, { "code": null, "e": 4331, "s": 4193, "text": "Unfortunately, Folium doesn’t provide native support to draw hexagon in the map view, we have to write some code to support this feature." }, { "code": null, "e": 4452, "s": 4331, "text": "We write a method to calculate the hexagon vertices’ coordinates by giving centroids coordinates and length of the side." }, { "code": null, "e": 4524, "s": 4452, "text": "After that, we generate a honeycomb hexagon grid throughout the island." }, { "code": null, "e": 4539, "s": 4524, "text": "Looks great! 😄" }, { "code": null, "e": 4724, "s": 4539, "text": "So far we created a honeycomb grid on the island and we generated the center coordinates for each hexagon. We will use Google Geocoding API to reversely lookup the address accordingly." }, { "code": null, "e": 4823, "s": 4724, "text": "The Google Geocoding API is a service that provides geocoding and reverse geocoding of addresses.2" }, { "code": null, "e": 4926, "s": 4823, "text": "It requires a Google API key to use this set of APIs. It can be applied from Google Developer Console." }, { "code": null, "e": 5001, "s": 4926, "text": "Let’s put all the data in a Pandas Dataframe, and show the first 10 items." }, { "code": null, "e": 5255, "s": 5001, "text": "Each row contains the center address of a hexagon and corresponding latitude and longitude degrees which are in WGS84 spherical coordinate system, X/Y columns are in UTM Cartesian coordinate system which uses the common metric unit — meter or kilometer." }, { "code": null, "e": 5439, "s": 5255, "text": "The Foursquare Places API offers real-time access to Foursquare’s global database of rich venue data and user content to power your location-based experiences in your app or website.3" }, { "code": null, "e": 5573, "s": 5439, "text": "Now we generated all the candidate neighborhoods on Montreal island, we will get all movie theaters information using Foursquare API." }, { "code": null, "e": 5853, "s": 5573, "text": "From Foursquare API documentation, we can find the corresponding movie theater category in Venue Categories. The corresponding ID of Movie Theater in Foursquare API is 4bf58dd8d48988d17f941735 which is under Arts & Entertainment main category. It contains several sub-categories:" }, { "code": null, "e": 5900, "s": 5853, "text": "Drive-in Theater, id: 56aa371be4b08b9a8d5734de" }, { "code": null, "e": 5950, "s": 5900, "text": "Indie Movie Theater, id: 4bf58dd8d48988d17e941735" }, { "code": null, "e": 5990, "s": 5950, "text": "Multiplex, id: 4bf58dd8d48988d180941735" }, { "code": null, "e": 6165, "s": 5990, "text": "Unlike coffee shops, restaurants everywhere, there aren’t lots of movie theaters in the region, it also makes sense since we don’t expect movie theater in every neighborhood." }, { "code": null, "e": 6304, "s": 6165, "text": "Let’s fetch all the movie theaters on Montreal island first. To do so, we will fetch movie theaters data in each borough and municipality." }, { "code": null, "e": 6430, "s": 6304, "text": "From the response of Foursquare APIs, there are a total of 44 movie theaters on Montreal island. Let’s plot it in a map view." }, { "code": null, "e": 6481, "s": 6430, "text": "Let’s show it in heatmap using the positron style." }, { "code": null, "e": 6736, "s": 6481, "text": "From heatmap, we can see the movie theaters are mainly concentrated in downtown areas and the center of the island. Usually, there are also a lot of shopping malls nearby, let’s pull out the shopping centers data on Montreal island using Foursquare APIs." }, { "code": null, "e": 6847, "s": 6736, "text": "From Foursquare API documentation, there are several categories related to shopping malls or shopping centers." }, { "code": null, "e": 6960, "s": 6847, "text": "We will fetch all shopping malls data in the above categories and show them on the map with movie theaters data." }, { "code": null, "e": 7054, "s": 6960, "text": "From the map view, we can see movie theater is located near shopping malls in most scenarios." }, { "code": null, "e": 7134, "s": 7054, "text": "Our target area shall have more shopping malls and fewer movie theaters nearby." }, { "code": null, "e": 7298, "s": 7134, "text": "Before that, we need to cluster all the candidate hexagons based on certain information, in this project, we pull out census data as major features for clustering." }, { "code": null, "e": 7483, "s": 7298, "text": "Now we will fetch census information of each borough or municipalities on Montreal island. The latest data was collected in 2016. We can get it from the Montreal city official website." }, { "code": null, "e": 7613, "s": 7483, "text": "It’s a pretty big excel file containing a lot of data, I modified some sheets a bit to extract data easier into Pandas Dataframe." }, { "code": null, "e": 7712, "s": 7613, "text": "We only focus on several basic census information: Population, Density, Age, Education and Income." }, { "code": null, "e": 7777, "s": 7712, "text": "Next, we will show census data distribution on a choropleth map." }, { "code": null, "e": 7892, "s": 7777, "text": "A Choropleth Map is a map composed of colored polygons. It is used to represent spatial variations of a quantity.4" }, { "code": null, "e": 7969, "s": 7892, "text": "We also show shopping centers and movie theaters’ locations on the same map." }, { "code": null, "e": 8264, "s": 7969, "text": "From the above choropleth maps, we can see movie theaters are mostly located in areas with a higher population. Same for shopping centers’ locations. Moreover, most movie theaters locate in the area with lower revenue. Regions with higher revenue have fewer shopping centers and movie theaters." }, { "code": null, "e": 8572, "s": 8264, "text": "So far, we retrieved all the necessary raw data we needed and visualized them. In the following steps, we will manipulate these datasets, extract data, and generate new features for the machine learning algorithm. Finally, we will find out the best suitable place to open a movie theater on Montreal island." }, { "code": null, "e": 8681, "s": 8572, "text": "The business purpose of this project is to find a suitable place on Montreal island to open a movie theater." }, { "code": null, "e": 8718, "s": 8681, "text": "Now we retrieved the following data:" }, { "code": null, "e": 9033, "s": 8718, "text": "All movie theaters data on Montreal islandAll shopping centers data on Montreal island2016 Montreal census data for each borough, concretely, Population, Density, Age, Education and Income data for each borough or municipality within Montreal islandBoundary data of each borough and municipality on Montreal island" }, { "code": null, "e": 9076, "s": 9033, "text": "All movie theaters data on Montreal island" }, { "code": null, "e": 9121, "s": 9076, "text": "All shopping centers data on Montreal island" }, { "code": null, "e": 9285, "s": 9121, "text": "2016 Montreal census data for each borough, concretely, Population, Density, Age, Education and Income data for each borough or municipality within Montreal island" }, { "code": null, "e": 9351, "s": 9285, "text": "Boundary data of each borough and municipality on Montreal island" }, { "code": null, "e": 9433, "s": 9351, "text": "We also generated a honeycomb hexagons grid throughout the whole Montreal Island." }, { "code": null, "e": 9634, "s": 9433, "text": "Based on the above raw data, we will try to generate new features accordingly, e.g. census information for each candidate cell, and the number of movie theaters and shopping malls in local and nearby." }, { "code": null, "e": 9860, "s": 9634, "text": "In the final step, we will focus on the most promising areas with more shopping malls and fewer movie theaters. And we will also present the candidate hexagon cells in the map view for stakeholders to make the final decision." }, { "code": null, "e": 10117, "s": 9860, "text": "We got the basis census information of each borough and municipality. We want to get the census information for each candidate hexagon cell accordingly, we calculate those census information based on borough and municipality which intersects with the cell." }, { "code": null, "e": 10313, "s": 10117, "text": "If a hexagon is in one borough completely, we will use the borough’s census info as hexagon’s one. So it means for all hexagons inside one borough, we will treat them the same for census feature." }, { "code": null, "e": 10492, "s": 10313, "text": "Accordingly, if a hexagon has a 50% intersection with two boroughs respectively, we will generate the census data of this hexagon, 50% ratio from these two boroughs respectively." }, { "code": null, "e": 10558, "s": 10492, "text": "Based on this rule, we can calculate the census for all hexagons." }, { "code": null, "e": 10754, "s": 10558, "text": "Let’s merge this data frame with the previous location data frame and generate a new one: candidates_df which contains basic information on each hexagon. We print several rows of this data frame." }, { "code": null, "e": 10782, "s": 10754, "text": "candidates_df.iloc[200:206]" }, { "code": null, "e": 10849, "s": 10782, "text": "Looking good. Now we have census information in each hexagon area." }, { "code": null, "e": 10954, "s": 10849, "text": "Then we will calculate the shopping center and movie theaters related information for each hexagon area." }, { "code": null, "e": 11034, "s": 10954, "text": "We will calculate the following features for shopping malls and movie theaters:" }, { "code": null, "e": 11315, "s": 11034, "text": "The number of shopping malls and movie theaters within the current hexagon cell.The number of shopping malls and movie theaters within 1 km away from the center of the hexagon cell.A number of shopping malls and movie theaters within 3 km away from the center of the hexagon cell." }, { "code": null, "e": 11396, "s": 11315, "text": "The number of shopping malls and movie theaters within the current hexagon cell." }, { "code": null, "e": 11498, "s": 11396, "text": "The number of shopping malls and movie theaters within 1 km away from the center of the hexagon cell." }, { "code": null, "e": 11598, "s": 11498, "text": "A number of shopping malls and movie theaters within 3 km away from the center of the hexagon cell." }, { "code": null, "e": 11740, "s": 11598, "text": "Now we prepared all the data we need, we can use the K-Means clustering algorithm to group the similar candidate hexagon areas into clusters." }, { "code": null, "e": 11852, "s": 11740, "text": "We pick up census features and the number of shopping malls and the number of movie theaters as input features." }, { "code": null, "e": 11962, "s": 11852, "text": "We will run an evaluation step first to select the best K which is the number of categories in the algorithm." }, { "code": null, "e": 12081, "s": 11962, "text": "We use the Sum of Squared Distance and Silhouette Score two methods to evaluate the K-Means algorithm for different K." }, { "code": null, "e": 12202, "s": 12081, "text": "Sum of Squared Distance measures error between data points and their assigned clusters’ centroids. Smaller means better." }, { "code": null, "e": 12437, "s": 12202, "text": "Silhouette Score focuses on minimizing the sum of squared distance inside the cluster as well, meanwhile, it also tries to maximize the distance between its neighborhoods. From its definition, the bigger the value is, the better K is." }, { "code": null, "e": 12759, "s": 12437, "text": "From the figure, we can see Sum of Squared Distance going down when K becomes bigger. When K=2,3, Silhouette Score is higher, but SSE is still high at that time, we choose K=10 for this project, it's a balanced number for both Sum of Squared Distance and Silhouette Score. Let’s run the K-Means algorithm again with k=10." }, { "code": null, "e": 12834, "s": 12759, "text": "Let’s visualize clustering results with a different color in the map view." }, { "code": null, "e": 12881, "s": 12834, "text": "Let’s put everything together on one map view:" }, { "code": null, "e": 12984, "s": 12881, "text": "Clusters in colors for hexagonsShopping malls in blue pointMovie theaters in redpoint with yellow ring" }, { "code": null, "e": 13016, "s": 12984, "text": "Clusters in colors for hexagons" }, { "code": null, "e": 13045, "s": 13016, "text": "Shopping malls in blue point" }, { "code": null, "e": 13089, "s": 13045, "text": "Movie theaters in redpoint with yellow ring" }, { "code": null, "e": 13285, "s": 13089, "text": "From the cluster plot in the above map view, we can see there is one cluster in light blue composed of 4 hexagons in downtown, there are full of movie theaters and shopping malls in this cluster." }, { "code": null, "e": 13457, "s": 13285, "text": "The purple cluster contains the area with a lot of shopping malls. The light green cluster contains more shopping malls and movie theaters except for the downtown cluster." }, { "code": null, "e": 13608, "s": 13457, "text": "Let’s assign weights to all three movie theaters related features and combine them into one feature. Same for shopping malls. It’s easier for sorting." }, { "code": null, "e": 13720, "s": 13608, "text": "We will calculate weighted Mall Score and weighted Cinema Score, then generate a new Score feature for sorting." }, { "code": null, "e": 13812, "s": 13720, "text": "The higher final score is, it means there are more shopping malls and fewer movie theaters." }, { "code": null, "e": 13948, "s": 13812, "text": "Cluster 7 have the highest score, it has more shopping malls and fewer movie theaters. Let’s explore more characteristics of cluster 7." }, { "code": null, "e": 14203, "s": 13948, "text": "There are 40 hexagons in Cluster 7 with an average of 0.77 Malls in local and 0.0 Cinemas in local. Let’s plot all clusters for comparison of each feature in a bar chart using matplotlib.pyplot library. We highlight Cluster 7 which is our target cluster." }, { "code": null, "e": 14425, "s": 14203, "text": "From the bar chart, we can see that Cluster 7 has the most population and density among all the clusters. Furthermore, it has fairly more shopping centers in the hexagon area or nearby and relatively fewer movie theaters." }, { "code": null, "e": 14589, "s": 14425, "text": "Next, we sort all hexagons in Cluster 7 by Score in descending order and pick the first 5 hexagons. They will be our first choice position to open a movie theater." }, { "code": null, "e": 14768, "s": 14589, "text": "As the above statistics information, there are 1~3 shopping malls in local and more shopping malls nearby, but without any movie theater within 1 km. Looks quite good selections." }, { "code": null, "e": 14880, "s": 14768, "text": "Let’s plot Cluster 7 hexagons in the map view, gray out the other clusters and highlight our 5 choices as well." }, { "code": null, "e": 15185, "s": 14880, "text": "This concludes our analysis. We have found out 5 most promising zones with more shopping malls nearby and fewer movie theaters around the area. Each zone is in regular hexagon shape which is popular in map view. The zones in the cluster have the most population and density comparing with other clusters." }, { "code": null, "e": 15496, "s": 15185, "text": "We generated hexagon areas all over Montreal island. And we group them into 10 clusters according to census data information including population, density, age, education, and income. Shopping center information and existing movie theaters information are also considered when running the clustering algorithm." }, { "code": null, "e": 15698, "s": 15496, "text": "From data analysis and visualization, we can see movie theaters are always located near shopping malls usually, which inspired us to find out the area with more shopping malls and fewer movie theaters." }, { "code": null, "e": 16019, "s": 15698, "text": "After the K-Means Clustering machine learning algorithm, we got the cluster with most shopping malls nearby and fewer movie theaters on average. We also discovered the other characteristics of the cluster. It shows the cluster has the most population and density which implies the highest traffic among all the clusters." }, { "code": null, "e": 16254, "s": 16019, "text": "There are 40 hexagon areas in this cluster, we sort all these hexagon areas by shopping malls and movie theaters info in descending order which targets to cover more shopping malls and fewer movie theaters in the local cell or nearby." }, { "code": null, "e": 16625, "s": 16254, "text": "We draw our conclusion with the 5 most promising hexagon areas satisfying all our conditions. These recommended zones shall be a good starting point for further analysis. There are also other factors which could be taken into account, e.g. real traffic data and the revenue of every movie theater, parking lots nearby. They will be helpful to find more accurate results." }, { "code": null, "e": 16716, "s": 16625, "text": "The purpose of this project is to find an area on Montreal island to open a movie theater." }, { "code": null, "e": 17085, "s": 16716, "text": "After fetching data from several data sources and process them into a clean data frame, applying the K-Means clustering algorithm, we picked the cluster with more shopping malls and fewer movie theaters on average. By sorting all candidate areas in the cluster, we get the most 5 promising zones which are used as starting points for final exploration by stakeholders." }, { "code": null, "e": 17430, "s": 17085, "text": "The final decision on optimal movie theater’s location will be made by stakeholders based on specific characteristics of neighborhoods and locations in every recommended zone, taking into consideration additional factors like the parking lot of each location, traffic of existing movie theaters in the cluster, and current revenue of them, etc." }, { "code": null, "e": 17532, "s": 17430, "text": "https://github.com/kyokin78/Coursera_Capstone/blob/project/CapstoneProject_OpenCinemaInMontreal.ipynb" } ]