title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to set the Background Color of the Label in C#? - GeeksforGeeks
30 Jun, 2019 In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the background color of the Label control using BackColor Property. It makes your label more attractive. You can set this property using two different methods: 1. Design-Time: It is the easiest method to set the BackColor property of the Label control using 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 Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the Label control to set the BackColor property of the Label.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the Label control programmatically with the help of given syntax: public virtual System.Drawing.Color BackColor { get; set; } Here, Color indicates the background color of the Label. Following steps are used to set the BackColor property of the Label: Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class Label mylab = new Label(); // Creating label using Label class Label mylab = new Label(); Step 2: After creating Label, set the BackColor property of the Label provided by the Label class.// Set BackColor property of the label mylab.BackColor = Color.LightBlue; // Set BackColor property of the label mylab.BackColor = Color.LightBlue; Step 3: And last add this Label control to form using Add() method.// Add this label to the form this.Controls.Add(mylab); 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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font("Calibri", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}}Output: // Add this label to the form this.Controls.Add(mylab); 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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font("Calibri", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}} Output: 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# C# | Class and Object Extension Method in C# C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 26377, "s": 26349, "text": "\n30 Jun, 2019" }, { "code": null, "e": 26700, "s": 26377, "text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the background color of the Label control using BackColor Property. It makes your label more attractive. You can set this property using two different methods:" }, { "code": null, "e": 26819, "s": 26700, "text": "1. Design-Time: It is the easiest method to set the BackColor property of the Label control using the following steps:" }, { "code": null, "e": 26935, "s": 26819, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 27110, "s": 26935, "text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need." }, { "code": null, "e": 27240, "s": 27110, "text": "Step 3: After drag and drop you will go to the properties of the Label control to set the BackColor property of the Label.Output:" }, { "code": null, "e": 27248, "s": 27240, "text": "Output:" }, { "code": null, "e": 27430, "s": 27248, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the Label control programmatically with the help of given syntax:" }, { "code": null, "e": 27490, "s": 27430, "text": "public virtual System.Drawing.Color BackColor { get; set; }" }, { "code": null, "e": 27616, "s": 27490, "text": "Here, Color indicates the background color of the Label. Following steps are used to set the BackColor property of the Label:" }, { "code": null, "e": 27764, "s": 27616, "text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n" }, { "code": null, "e": 27828, "s": 27764, "text": "// Creating label using Label class\nLabel mylab = new Label();\n" }, { "code": null, "e": 28001, "s": 27828, "text": "Step 2: After creating Label, set the BackColor property of the Label provided by the Label class.// Set BackColor property of the label\nmylab.BackColor = Color.LightBlue;\n" }, { "code": null, "e": 28076, "s": 28001, "text": "// Set BackColor property of the label\nmylab.BackColor = Color.LightBlue;\n" }, { "code": null, "e": 29069, "s": 28076, "text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font(\"Calibri\", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}}Output:" }, { "code": null, "e": 29126, "s": 29069, "text": "// Add this label to the form\nthis.Controls.Add(mylab);\n" }, { "code": null, "e": 29135, "s": 29126, "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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font(\"Calibri\", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}}", "e": 29990, "s": 29135, "text": null }, { "code": null, "e": 29998, "s": 29990, "text": "Output:" }, { "code": null, "e": 30001, "s": 29998, "text": "C#" }, { "code": null, "e": 30099, "s": 30001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30127, "s": 30099, "text": "C# Dictionary with examples" }, { "code": null, "e": 30142, "s": 30127, "text": "C# | Delegates" }, { "code": null, "e": 30165, "s": 30142, "text": "C# | Method Overriding" }, { "code": null, "e": 30187, "s": 30165, "text": "C# | Abstract Classes" }, { "code": null, "e": 30233, "s": 30187, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30255, "s": 30233, "text": "C# | Class and Object" }, { "code": null, "e": 30278, "s": 30255, "text": "Extension Method in C#" }, { "code": null, "e": 30296, "s": 30278, "text": "C# | Constructors" }, { "code": null, "e": 30336, "s": 30296, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
D3.js selection.html() Function - GeeksforGeeks
31 Aug, 2020 The selection.html() function is used to set the inner HTML on all the selected elements. If the value is constant then all the elements are given same value. A null value will clear the content of the element. Syntax: selection.html([value]); Parameters: This function accepts single parameter as mentioned above and described below: Value: It is of type string that sets the HTML to the document. Return Value: This function does not return anything. Example 1: In the following code, the HTML “p” element content is changed to “bold” text. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> p { background-color: #f2f2f2; padding: 10px; width: 200px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } </style></head> <body> <div> <h1 style="color:green;"> GeeksforGeeks </h1> <h4>D3.js selection.html() Function</h4> <p>Click Here!</p> </div> <script> function func() { // Selecting all p and setting // the innerHTML of the p var chk = d3.selectAll("p") .html("<b>This is from .html</b>"); var text = document.querySelector("p"); } let btn = document.querySelector("p"); btn.addEventListener("click", func); </script></body> </html> Output: Example 2: The following example clears the content using null. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> p { background-color: #f2f2f2; padding: 10px; width: 200px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } </style></head> <body> <div> <h1 style="color:green;"> GeeksforGeeks </h1> <h4>D3.js selection.html() Function</h4> <p><b>Click Here</b></p> </div> <script> function func() { // Selecting p and setting the // innerHTML of the p var chk = d3.selectAll("p") .html(null); var text = document.querySelector("p"); } let btn = document.querySelector("p"); btn.addEventListener("click", func); </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n31 Aug, 2020" }, { "code": null, "e": 26756, "s": 26545, "text": "The selection.html() function is used to set the inner HTML on all the selected elements. If the value is constant then all the elements are given same value. A null value will clear the content of the element." }, { "code": null, "e": 26764, "s": 26756, "text": "Syntax:" }, { "code": null, "e": 26789, "s": 26764, "text": "selection.html([value]);" }, { "code": null, "e": 26880, "s": 26789, "text": "Parameters: This function accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 26944, "s": 26880, "text": "Value: It is of type string that sets the HTML to the document." }, { "code": null, "e": 26998, "s": 26944, "text": "Return Value: This function does not return anything." }, { "code": null, "e": 27088, "s": 26998, "text": "Example 1: In the following code, the HTML “p” element content is changed to “bold” text." }, { "code": null, "e": 27093, "s": 27088, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> p { background-color: #f2f2f2; padding: 10px; width: 200px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } </style></head> <body> <div> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4>D3.js selection.html() Function</h4> <p>Click Here!</p> </div> <script> function func() { // Selecting all p and setting // the innerHTML of the p var chk = d3.selectAll(\"p\") .html(\"<b>This is from .html</b>\"); var text = document.querySelector(\"p\"); } let btn = document.querySelector(\"p\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 28166, "s": 27093, "text": null }, { "code": null, "e": 28174, "s": 28166, "text": "Output:" }, { "code": null, "e": 28238, "s": 28174, "text": "Example 2: The following example clears the content using null." }, { "code": null, "e": 28243, "s": 28238, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> p { background-color: #f2f2f2; padding: 10px; width: 200px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } </style></head> <body> <div> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4>D3.js selection.html() Function</h4> <p><b>Click Here</b></p> </div> <script> function func() { // Selecting p and setting the // innerHTML of the p var chk = d3.selectAll(\"p\") .html(null); var text = document.querySelector(\"p\"); } let btn = document.querySelector(\"p\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 29284, "s": 28243, "text": null }, { "code": null, "e": 29292, "s": 29284, "text": "Output:" }, { "code": null, "e": 29298, "s": 29292, "text": "D3.js" }, { "code": null, "e": 29309, "s": 29298, "text": "JavaScript" }, { "code": null, "e": 29326, "s": 29309, "text": "Web Technologies" }, { "code": null, "e": 29424, "s": 29326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29464, "s": 29424, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29525, "s": 29464, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29566, "s": 29525, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29588, "s": 29566, "text": "JavaScript | Promises" }, { "code": null, "e": 29642, "s": 29588, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29682, "s": 29642, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29715, "s": 29682, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29758, "s": 29715, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29808, "s": 29758, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
TypeScript | String localeCompare() Method - GeeksforGeeks
18 Jun, 2020 The localeCompare() is an inbuilt function in TypeScript which is used to get the number indicating whether a reference string comes before or after or is the same as the given string in sorted order. Syntax: string.localeCompare( param ) Parameter: This method accept a single parameter as mentioned above and described. param : This parameter is a string to be compared with string object. Return Value: This method returns the flowing. 0 is return, if the string is fully match. 1 is return, if the string is not match and the parameter value comes before the string object’s value. – A negative value is return, if the string is not match and the parameter value comes after the string object’s value. Example 1: JavaScript <script> // Original strings var str1 = new String('Geeksforgeeks'); var index = str1.localeCompare("Geeksforgeeks"); // Use of String localeCompare() Method console.log(index);</script> Output: 0 Example 2: JavaScript <script> // Original strings var str1 = new String('Geeksforgeeks'); var index = str1.localeCompare("Geeks"); // Use of String localeCompare() Method console.log(index);</script> Output: 1 TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25715, "s": 25687, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25924, "s": 25715, "text": "The localeCompare() is an inbuilt function in TypeScript which is used to get the number indicating whether a reference string comes before or after or is the same as the given string in sorted order. Syntax:" }, { "code": null, "e": 25956, "s": 25924, "text": "string.localeCompare( param ) \n" }, { "code": null, "e": 26040, "s": 25956, "text": "Parameter: This method accept a single parameter as mentioned above and described. " }, { "code": null, "e": 26110, "s": 26040, "text": "param : This parameter is a string to be compared with string object." }, { "code": null, "e": 26158, "s": 26110, "text": "Return Value: This method returns the flowing. " }, { "code": null, "e": 26201, "s": 26158, "text": "0 is return, if the string is fully match." }, { "code": null, "e": 26305, "s": 26201, "text": "1 is return, if the string is not match and the parameter value comes before the string object’s value." }, { "code": null, "e": 26425, "s": 26305, "text": "– A negative value is return, if the string is not match and the parameter value comes after the string object’s value." }, { "code": null, "e": 26437, "s": 26425, "text": "Example 1: " }, { "code": null, "e": 26448, "s": 26437, "text": "JavaScript" }, { "code": "<script> // Original strings var str1 = new String('Geeksforgeeks'); var index = str1.localeCompare(\"Geeksforgeeks\"); // Use of String localeCompare() Method console.log(index);</script>", "e": 26655, "s": 26448, "text": null }, { "code": null, "e": 26664, "s": 26655, "text": "Output: " }, { "code": null, "e": 26667, "s": 26664, "text": "0\n" }, { "code": null, "e": 26679, "s": 26667, "text": "Example 2: " }, { "code": null, "e": 26690, "s": 26679, "text": "JavaScript" }, { "code": "<script> // Original strings var str1 = new String('Geeksforgeeks'); var index = str1.localeCompare(\"Geeks\"); // Use of String localeCompare() Method console.log(index);</script>", "e": 26889, "s": 26690, "text": null }, { "code": null, "e": 26898, "s": 26889, "text": "Output: " }, { "code": null, "e": 26901, "s": 26898, "text": "1\n" }, { "code": null, "e": 26912, "s": 26901, "text": "TypeScript" }, { "code": null, "e": 26923, "s": 26912, "text": "JavaScript" }, { "code": null, "e": 26940, "s": 26923, "text": "Web Technologies" }, { "code": null, "e": 27038, "s": 26940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27078, "s": 27038, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27123, "s": 27078, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27184, "s": 27123, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27256, "s": 27184, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27308, "s": 27256, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27348, "s": 27308, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27381, "s": 27348, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27426, "s": 27381, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27469, "s": 27426, "text": "How to fetch data from an API in ReactJS ?" } ]
Parsing String of symbols to Expression - GeeksforGeeks
13 Aug, 2021 Given an expression as a string str consisting of numbers and basic arithmetic operators(+, -, *, /), the task is to solve the expression. Note that the numbers used in this program are single-digit numbers and parentheses are not allowed.Examples: Input: str = “3/3+4*6-9” Output: 16 Since (3 / 3) = 1 and (4 * 6) = 24. So the overall expression becomes (1 + 24 – 9) = 16Input: str = “9*5-4*5+9” Output: 16 Approach: A Stack class is created to store both numbers and operators (both as characters). The stack is a useful storage mechanism because, when parsing expressions, the last item stored needs to be accessed frequently; and a stack is a last-in-first-out (LIFO) container.Besides the Stack class, a class called express(short for expression) is also created, representing an entire arithmetic expression. Member functions for this class allow the user to initialize an object with an expression in the form of a string, parse the expression, and return the resulting arithmetic value.Here’s how an arithmetic expression is parsed. A pointer is started at the left and is iterated to look at each character. It can be either a number(always a single-digit character between 0 and 9) or an operator (the characters +, -, *, and /).If the character is a number, it is pushed onto the stack. The first operator encountered is also pushed into the stack. The trick is subsequent operators are handled. Note that the current operator can’t be executed because the number that follows it hasn’t been read yet. Finding an operator is merely the signal that we can execute the previous operator, which is stored on the stack. That is, if the sequence 2+3 is on the stack, we wait until we find another operator before carrying out the addition.Thus, whenever the current character is an operator (except the first), the previous number (3 in the preceding example) and the previous operator (+) are popped off the stack, placing them in the variables lastval and lastop. Finally, the first number (2) is popped and the arithmetic operation is carried on the two numbers (obtaining 5). However, when * and / which have higher precedence than + and – are encountered, the expression can’t be executed. In the expression 3+4/2, the + cant be executed until the division is performed. So, the 2 and the + are put back on the stack until the division is carried out.On the other hand, if the current operator is a + or -, the previous operator can be executed. That is when the + is encountered in the expression 4-5+6, it’s all right to execute the -, and when the – is encountered in 6/2-3, it’s okay to do the division. Table 10.1 shows the four possibilities. Below is the implementation of the above approach: CPP // C++ implementation of the approach#include <cstring>#include <iostream>using namespace std; // Length of expressions in charactersconst int LEN = 80; // Size of the stackconst int MAX = 40; class Stack {private: // Stack: array of characters char st[MAX]; // Number at top of the stack int top; public: Stack() { top = 0; } // Function to put a character in stack void push(char var) { st[++top] = var; } // Function to return a character off stack char pop() { return st[top--]; } // Function to get the top of the stack int gettop() { return top; }}; // Expression classclass Express {private: // Stack for analysis Stack s; // Pointer to input string char* pStr; // Length of the input string int len; public: Express(char* ptr) { pStr = ptr; len = strlen(pStr); } // Parse the input string void parse(); // Evaluate the stack int solve();}; void Express::parse(){ // Character from the input string char ch; // Last value char lastval; // Last operator char lastop; // For each input character for (int j = 0; j < len; j++) { ch = pStr[j]; // If it's a digit then save // the numerical value if (ch >= '0' && ch <= '9') s.push(ch - '0'); // If it's an operator else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { // If it is the first operator // then put it in the stack if (s.gettop() == 1) s.push(ch); // Not the first operator else { lastval = s.pop(); lastop = s.pop(); // If it is either '*' or '/' and the // last operator was either '+' or '-' if ((ch == '*' || ch == '/') && (lastop == '+' || lastop == '-')) { // Restore the last two pops s.push(lastop); s.push(lastval); } // In all the other cases else { // Perform the last operation switch (lastop) { // Push the result in the stack case '+': s.push(s.pop() + lastval); break; case '-': s.push(s.pop() - lastval); break; case '*': s.push(s.pop() * lastval); break; case '/': s.push(s.pop() / lastval); break; default: cout << "\nUnknown oper"; exit(1); } } s.push(ch); } } else { cout << "\nUnknown input character"; exit(1); } }} int Express::solve(){ // Remove the items from stack char lastval; while (s.gettop() > 1) { lastval = s.pop(); switch (s.pop()) { // Perform operation, push answer case '+': s.push(s.pop() + lastval); break; case '-': s.push(s.pop() - lastval); break; case '*': s.push(s.pop() * lastval); break; case '/': s.push(s.pop() / lastval); break; default: cout << "\nUnknown operator"; exit(1); } } return int(s.pop());} // Driver codeint main(){ char string[LEN] = "2+3*4/3-2"; // Make expression Express* eptr = new Express(string); // Parse it eptr->parse(); // Solve the expression cout << eptr->solve(); return 0;} 4 Time Complexity: O(N).Auxiliary Space: O(N). pankajsharmagfg Data Structures Stack Strings Data Structures Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Insertion in a B+ tree Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 26299, "s": 26271, "text": "\n13 Aug, 2021" }, { "code": null, "e": 26550, "s": 26299, "text": "Given an expression as a string str consisting of numbers and basic arithmetic operators(+, -, *, /), the task is to solve the expression. Note that the numbers used in this program are single-digit numbers and parentheses are not allowed.Examples: " }, { "code": null, "e": 26711, "s": 26550, "text": "Input: str = “3/3+4*6-9” Output: 16 Since (3 / 3) = 1 and (4 * 6) = 24. So the overall expression becomes (1 + 24 – 9) = 16Input: str = “9*5-4*5+9” Output: 16 " }, { "code": null, "e": 28966, "s": 26713, "text": "Approach: A Stack class is created to store both numbers and operators (both as characters). The stack is a useful storage mechanism because, when parsing expressions, the last item stored needs to be accessed frequently; and a stack is a last-in-first-out (LIFO) container.Besides the Stack class, a class called express(short for expression) is also created, representing an entire arithmetic expression. Member functions for this class allow the user to initialize an object with an expression in the form of a string, parse the expression, and return the resulting arithmetic value.Here’s how an arithmetic expression is parsed. A pointer is started at the left and is iterated to look at each character. It can be either a number(always a single-digit character between 0 and 9) or an operator (the characters +, -, *, and /).If the character is a number, it is pushed onto the stack. The first operator encountered is also pushed into the stack. The trick is subsequent operators are handled. Note that the current operator can’t be executed because the number that follows it hasn’t been read yet. Finding an operator is merely the signal that we can execute the previous operator, which is stored on the stack. That is, if the sequence 2+3 is on the stack, we wait until we find another operator before carrying out the addition.Thus, whenever the current character is an operator (except the first), the previous number (3 in the preceding example) and the previous operator (+) are popped off the stack, placing them in the variables lastval and lastop. Finally, the first number (2) is popped and the arithmetic operation is carried on the two numbers (obtaining 5). However, when * and / which have higher precedence than + and – are encountered, the expression can’t be executed. In the expression 3+4/2, the + cant be executed until the division is performed. So, the 2 and the + are put back on the stack until the division is carried out.On the other hand, if the current operator is a + or -, the previous operator can be executed. That is when the + is encountered in the expression 4-5+6, it’s all right to execute the -, and when the – is encountered in 6/2-3, it’s okay to do the division. Table 10.1 shows the four possibilities. " }, { "code": null, "e": 29020, "s": 28968, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29024, "s": 29020, "text": "CPP" }, { "code": "// C++ implementation of the approach#include <cstring>#include <iostream>using namespace std; // Length of expressions in charactersconst int LEN = 80; // Size of the stackconst int MAX = 40; class Stack {private: // Stack: array of characters char st[MAX]; // Number at top of the stack int top; public: Stack() { top = 0; } // Function to put a character in stack void push(char var) { st[++top] = var; } // Function to return a character off stack char pop() { return st[top--]; } // Function to get the top of the stack int gettop() { return top; }}; // Expression classclass Express {private: // Stack for analysis Stack s; // Pointer to input string char* pStr; // Length of the input string int len; public: Express(char* ptr) { pStr = ptr; len = strlen(pStr); } // Parse the input string void parse(); // Evaluate the stack int solve();}; void Express::parse(){ // Character from the input string char ch; // Last value char lastval; // Last operator char lastop; // For each input character for (int j = 0; j < len; j++) { ch = pStr[j]; // If it's a digit then save // the numerical value if (ch >= '0' && ch <= '9') s.push(ch - '0'); // If it's an operator else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { // If it is the first operator // then put it in the stack if (s.gettop() == 1) s.push(ch); // Not the first operator else { lastval = s.pop(); lastop = s.pop(); // If it is either '*' or '/' and the // last operator was either '+' or '-' if ((ch == '*' || ch == '/') && (lastop == '+' || lastop == '-')) { // Restore the last two pops s.push(lastop); s.push(lastval); } // In all the other cases else { // Perform the last operation switch (lastop) { // Push the result in the stack case '+': s.push(s.pop() + lastval); break; case '-': s.push(s.pop() - lastval); break; case '*': s.push(s.pop() * lastval); break; case '/': s.push(s.pop() / lastval); break; default: cout << \"\\nUnknown oper\"; exit(1); } } s.push(ch); } } else { cout << \"\\nUnknown input character\"; exit(1); } }} int Express::solve(){ // Remove the items from stack char lastval; while (s.gettop() > 1) { lastval = s.pop(); switch (s.pop()) { // Perform operation, push answer case '+': s.push(s.pop() + lastval); break; case '-': s.push(s.pop() - lastval); break; case '*': s.push(s.pop() * lastval); break; case '/': s.push(s.pop() / lastval); break; default: cout << \"\\nUnknown operator\"; exit(1); } } return int(s.pop());} // Driver codeint main(){ char string[LEN] = \"2+3*4/3-2\"; // Make expression Express* eptr = new Express(string); // Parse it eptr->parse(); // Solve the expression cout << eptr->solve(); return 0;}", "e": 32873, "s": 29024, "text": null }, { "code": null, "e": 32875, "s": 32873, "text": "4" }, { "code": null, "e": 32923, "s": 32877, "text": "Time Complexity: O(N).Auxiliary Space: O(N). " }, { "code": null, "e": 32939, "s": 32923, "text": "pankajsharmagfg" }, { "code": null, "e": 32955, "s": 32939, "text": "Data Structures" }, { "code": null, "e": 32961, "s": 32955, "text": "Stack" }, { "code": null, "e": 32969, "s": 32961, "text": "Strings" }, { "code": null, "e": 32985, "s": 32969, "text": "Data Structures" }, { "code": null, "e": 32993, "s": 32985, "text": "Strings" }, { "code": null, "e": 32999, "s": 32993, "text": "Stack" }, { "code": null, "e": 33097, "s": 32999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33124, "s": 33097, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33160, "s": 33124, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 33219, "s": 33160, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 33267, "s": 33219, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 33290, "s": 33267, "text": "Insertion in a B+ tree" }, { "code": null, "e": 33338, "s": 33290, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33358, "s": 33338, "text": "Stack Class in Java" }, { "code": null, "e": 33374, "s": 33358, "text": "Stack in Python" }, { "code": null, "e": 33449, "s": 33374, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python Program for Coin Change | DP-7 - GeeksforGeeks
20 Dec, 2021 Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5. Following is a simple recursive implementation of the Coin Change problem. Python3 # Recursive Python3 program for# coin change problem. # Returns the count of ways we can sum# S[0...m-1] coins to get sum ndef count(S, m, n ): # If n is 0 then there is 1 # solution (do not include any coin) if (n == 0): return 1 # If n is less than 0 then no # solution exists if (n < 0): return 0; # If there are no coins and n # is greater than 0, then no # solution exist if (m <=0 and n >= 1): return 0 # count is sum of solutions (i) # including S[m-1] (ii) excluding S[m-1] return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); # Driver program to test above functionarr = [1, 2, 3]m = len(arr)print(count(arr, m, 4)) # This code is contributed by Smitha Dinesh Semwal Python # Dynamic Programming Python implementation of Coin # Change problemdef count(S, m, n): # We need n+1 rows as the table is constructed # in bottom up manner using the base case 0 value # case (n = 0) table = [[0 for x in range(m)] for x in range(n+1)] # Fill the entries for 0 value case (n = 0) for i in range(m): table[0][i] = 1 # Fill rest of the table entries in bottom up manner for i in range(1, n+1): for j in range(m): # Count of solutions including S[j] x = table[i - S[j]][j] if i-S[j] >= 0 else 0 # Count of solutions excluding S[j] y = table[i][j-1] if j >= 1 else 0 # total count table[i][j] = x + y return table[n][m-1] # Driver program to test above functionarr = [1, 2, 3]m = len(arr)n = 4print(count(arr, m, n)) # This code is contributed by Bhavya Jain Python # Dynamic Programming Python implementation of Coin # Change problemdef count(S, m, n): # table[i] will be storing the number of solutions for # value i. We need n+1 rows as the table is constructed # in bottom up manner using the base case (n = 0) # Initialize all table values as 0 table = [0 for k in range(n+1)] # Base case (If given value is 0) table[0] = 1 # Pick all coins one by one and update the table[] values # after the index greater than or equal to the value of the # picked coin for i in range(0,m): for j in range(S[i],n+1): table[j] += table[j-S[i]] return table[n] # Driver program to test above functionarr = [1, 2, 3]m = len(arr)n = 4x = count(arr, m, n)print (x) # This code is contributed by Afzal Ansari Please refer complete article on Coin Change | DP-7 for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backward iteration in Python Appending to list in Python dictionary Python | Remove punctuation from string Python program to find smallest number in a list Python | Check if a given object is list or not Python | Create list of numbers with given range Generating Word Cloud in Python Python program to find number of days between two given dates How to inverse a matrix using NumPy Reading an excel file using Python openpyxl module
[ { "code": null, "e": 26097, "s": 26069, "text": "\n20 Dec, 2021" }, { "code": null, "e": 26303, "s": 26097, "text": "Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\\’t matter." }, { "code": null, "e": 26561, "s": 26303, "text": "For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5." }, { "code": null, "e": 26636, "s": 26561, "text": "Following is a simple recursive implementation of the Coin Change problem." }, { "code": null, "e": 26644, "s": 26636, "text": "Python3" }, { "code": "# Recursive Python3 program for# coin change problem. # Returns the count of ways we can sum# S[0...m-1] coins to get sum ndef count(S, m, n ): # If n is 0 then there is 1 # solution (do not include any coin) if (n == 0): return 1 # If n is less than 0 then no # solution exists if (n < 0): return 0; # If there are no coins and n # is greater than 0, then no # solution exist if (m <=0 and n >= 1): return 0 # count is sum of solutions (i) # including S[m-1] (ii) excluding S[m-1] return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); # Driver program to test above functionarr = [1, 2, 3]m = len(arr)print(count(arr, m, 4)) # This code is contributed by Smitha Dinesh Semwal", "e": 27394, "s": 26644, "text": null }, { "code": null, "e": 27401, "s": 27394, "text": "Python" }, { "code": "# Dynamic Programming Python implementation of Coin # Change problemdef count(S, m, n): # We need n+1 rows as the table is constructed # in bottom up manner using the base case 0 value # case (n = 0) table = [[0 for x in range(m)] for x in range(n+1)] # Fill the entries for 0 value case (n = 0) for i in range(m): table[0][i] = 1 # Fill rest of the table entries in bottom up manner for i in range(1, n+1): for j in range(m): # Count of solutions including S[j] x = table[i - S[j]][j] if i-S[j] >= 0 else 0 # Count of solutions excluding S[j] y = table[i][j-1] if j >= 1 else 0 # total count table[i][j] = x + y return table[n][m-1] # Driver program to test above functionarr = [1, 2, 3]m = len(arr)n = 4print(count(arr, m, n)) # This code is contributed by Bhavya Jain", "e": 28294, "s": 27401, "text": null }, { "code": null, "e": 28301, "s": 28294, "text": "Python" }, { "code": "# Dynamic Programming Python implementation of Coin # Change problemdef count(S, m, n): # table[i] will be storing the number of solutions for # value i. We need n+1 rows as the table is constructed # in bottom up manner using the base case (n = 0) # Initialize all table values as 0 table = [0 for k in range(n+1)] # Base case (If given value is 0) table[0] = 1 # Pick all coins one by one and update the table[] values # after the index greater than or equal to the value of the # picked coin for i in range(0,m): for j in range(S[i],n+1): table[j] += table[j-S[i]] return table[n] # Driver program to test above functionarr = [1, 2, 3]m = len(arr)n = 4x = count(arr, m, n)print (x) # This code is contributed by Afzal Ansari", "e": 29093, "s": 28301, "text": null }, { "code": null, "e": 29163, "s": 29093, "text": "Please refer complete article on Coin Change | DP-7 for more details!" }, { "code": null, "e": 29179, "s": 29163, "text": "Python Programs" }, { "code": null, "e": 29277, "s": 29179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29306, "s": 29277, "text": "Backward iteration in Python" }, { "code": null, "e": 29345, "s": 29306, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 29385, "s": 29345, "text": "Python | Remove punctuation from string" }, { "code": null, "e": 29434, "s": 29385, "text": "Python program to find smallest number in a list" }, { "code": null, "e": 29482, "s": 29434, "text": "Python | Check if a given object is list or not" }, { "code": null, "e": 29531, "s": 29482, "text": "Python | Create list of numbers with given range" }, { "code": null, "e": 29563, "s": 29531, "text": "Generating Word Cloud in Python" }, { "code": null, "e": 29625, "s": 29563, "text": "Python program to find number of days between two given dates" }, { "code": null, "e": 29661, "s": 29625, "text": "How to inverse a matrix using NumPy" } ]
D3.js | d3.color() Function - GeeksforGeeks
02 Dec, 2019 The d3.color() function in D3.js is used to parse the specified CSS color used as parameter of the function and return RGB or HSL color. If specifier is not given, then null is returned. Syntax: d3.color(color); Parameters: This function accepts single parameter color which specifies the CSS color. Return Value: This function returns the RGB or HSL color value of the specified CSS color taken as the parameter of the function. Below programs illustrate the d3.color() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title>d3.color() function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Calling the d3.color() function function // with some parameters var color1 = d3.color("red"); var color2 = d3.color("green"); var color3 = d3.color("blue"); // Getting the RGB or HSL values console.log(color1); console.log(color2); console.log(color3); </script></body> </html> Output: {"r":255, "g":0, "b":0, "opacity":1} {"r":0, "g":128, "b":0, "opacity":1} {"r":0, "g":0, "b":255, "opacity":1} Example 2: <!DOCTYPE html><html> <head> <title>d3.color() function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Calling the d3.color() function function // without any parameters var color = d3.color(); // Getting the RGB or HSL values console.log(color); </script></body> </html> Output: null Reference: https://devdocs.io/d3~5/d3-color#color Akanksha_Rai D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25409, "s": 25381, "text": "\n02 Dec, 2019" }, { "code": null, "e": 25596, "s": 25409, "text": "The d3.color() function in D3.js is used to parse the specified CSS color used as parameter of the function and return RGB or HSL color. If specifier is not given, then null is returned." }, { "code": null, "e": 25604, "s": 25596, "text": "Syntax:" }, { "code": null, "e": 25621, "s": 25604, "text": "d3.color(color);" }, { "code": null, "e": 25709, "s": 25621, "text": "Parameters: This function accepts single parameter color which specifies the CSS color." }, { "code": null, "e": 25839, "s": 25709, "text": "Return Value: This function returns the RGB or HSL color value of the specified CSS color taken as the parameter of the function." }, { "code": null, "e": 25899, "s": 25839, "text": "Below programs illustrate the d3.color() function in D3.js:" }, { "code": null, "e": 25910, "s": 25899, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>d3.color() function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Calling the d3.color() function function // with some parameters var color1 = d3.color(\"red\"); var color2 = d3.color(\"green\"); var color3 = d3.color(\"blue\"); // Getting the RGB or HSL values console.log(color1); console.log(color2); console.log(color3); </script></body> </html>", "e": 26431, "s": 25910, "text": null }, { "code": null, "e": 26439, "s": 26431, "text": "Output:" }, { "code": null, "e": 26551, "s": 26439, "text": "{\"r\":255, \"g\":0, \"b\":0, \"opacity\":1}\n{\"r\":0, \"g\":128, \"b\":0, \"opacity\":1}\n{\"r\":0, \"g\":0, \"b\":255, \"opacity\":1}\n" }, { "code": null, "e": 26562, "s": 26551, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title>d3.color() function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Calling the d3.color() function function // without any parameters var color = d3.color(); // Getting the RGB or HSL values console.log(color); </script></body> </html>", "e": 26945, "s": 26562, "text": null }, { "code": null, "e": 26953, "s": 26945, "text": "Output:" }, { "code": null, "e": 26959, "s": 26953, "text": "null\n" }, { "code": null, "e": 27009, "s": 26959, "text": "Reference: https://devdocs.io/d3~5/d3-color#color" }, { "code": null, "e": 27022, "s": 27009, "text": "Akanksha_Rai" }, { "code": null, "e": 27028, "s": 27022, "text": "D3.js" }, { "code": null, "e": 27039, "s": 27028, "text": "JavaScript" }, { "code": null, "e": 27056, "s": 27039, "text": "Web Technologies" }, { "code": null, "e": 27154, "s": 27056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27194, "s": 27154, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27239, "s": 27194, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27300, "s": 27239, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27372, "s": 27300, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27424, "s": 27372, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27464, "s": 27424, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27497, "s": 27464, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27542, "s": 27497, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27585, "s": 27542, "text": "How to fetch data from an API in ReactJS ?" } ]
C# Program to Count the Files Based on Extension using LINQ - GeeksforGeeks
09 Dec, 2021 Given files, now we count the files based on extension using LINQ. We are considering all types of file formats like pdf, txt, xml and going to count these files based on the extension. For that, we have to know the following methods: Path.GetExtension(): This method is used to get an extension of the given path. TrimStart(): This method is used to cut the path and starts with the given string. ToLower(): This method is used to convert the string to lower. GroupBy(): This function is used to group the data that shares the common attribute from the specified sequence or list. count(): This method is used to get the total number of elements from the given sequence. Example: Input: {myfile1.txt, myfile2.txt, myfile3.xml} Output: 3 file ---> txt 1 file ---> xml Input: {file12.txt, file23.xml, file45.pdf} Output: 1 file ---> txt 1 file ---> xml 1 file ---> pdf Approach: Create a list of files with different extensions. Read the files using .GetExtension() method. Then convert the file extensions into lower case to remove case sensitiveness. Then apply trim function before this and use groupby method to get same file extensions in to one group and then use count function to count file extensions which are already in group. var result = files.Select(f => Path.GetExtension(f) .TrimStart('.').ToLower()) .GroupBy(y => y, (ex, excnt) => new { Extension = ex, Count = excnt.Count() }); Display the file count and extension using file count foreach (var i in result) { Console.WriteLine(i.Count + " File --> " + i.Extension + " format "); } Example: C# // C# program to count the files according // to their extensionusing System;using System.IO;using System.Linq; class GFG{ public static void Main(){ // Declare files with different extensions string[] files = { "171fa07058.txt", "171fa07058.pdf", "171fa07058.xml", "171fa07058.txt", "171fa07058.txt", "171fa07058.xml" }; // Group by files with an extension var result = files.Select(f => Path.GetExtension(f) .TrimStart('.').ToLower()) .GroupBy(y => y, (ex, excnt) => new { Extension = ex, Count = excnt.Count() }); // Display the final result foreach (var i in result) { Console.WriteLine(i.Count + " File --> " + i.Extension + " format "); }}} Output: 3 File --> txt format 1 File --> pdf format 2 File --> xml format CSharp LINQ Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Convert String to Character Array in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Socket Programming in C# C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 25547, "s": 25519, "text": "\n09 Dec, 2021" }, { "code": null, "e": 25782, "s": 25547, "text": "Given files, now we count the files based on extension using LINQ. We are considering all types of file formats like pdf, txt, xml and going to count these files based on the extension. For that, we have to know the following methods:" }, { "code": null, "e": 25862, "s": 25782, "text": "Path.GetExtension(): This method is used to get an extension of the given path." }, { "code": null, "e": 25945, "s": 25862, "text": "TrimStart(): This method is used to cut the path and starts with the given string." }, { "code": null, "e": 26008, "s": 25945, "text": "ToLower(): This method is used to convert the string to lower." }, { "code": null, "e": 26129, "s": 26008, "text": "GroupBy(): This function is used to group the data that shares the common attribute from the specified sequence or list." }, { "code": null, "e": 26219, "s": 26129, "text": "count(): This method is used to get the total number of elements from the given sequence." }, { "code": null, "e": 26228, "s": 26219, "text": "Example:" }, { "code": null, "e": 26448, "s": 26228, "text": "Input: {myfile1.txt, myfile2.txt, myfile3.xml}\nOutput: 3 file ---> txt\n 1 file ---> xml\n \nInput: {file12.txt, file23.xml, file45.pdf}\nOutput: 1 file ---> txt\n 1 file ---> xml\n 1 file ---> pdf" }, { "code": null, "e": 26458, "s": 26448, "text": "Approach:" }, { "code": null, "e": 26508, "s": 26458, "text": "Create a list of files with different extensions." }, { "code": null, "e": 26817, "s": 26508, "text": "Read the files using .GetExtension() method. Then convert the file extensions into lower case to remove case sensitiveness. Then apply trim function before this and use groupby method to get same file extensions in to one group and then use count function to count file extensions which are already in group." }, { "code": null, "e": 27186, "s": 26817, "text": "var result = files.Select(f => Path.GetExtension(f)\n .TrimStart('.').ToLower())\n .GroupBy(y => y, (ex, excnt) => new\n {\n Extension = ex,\n Count = excnt.Count()\n });\n " }, { "code": null, "e": 27240, "s": 27186, "text": "Display the file count and extension using file count" }, { "code": null, "e": 27367, "s": 27240, "text": "foreach (var i in result)\n{\n Console.WriteLine(i.Count + \" File --> \" + \n i.Extension + \" format \");\n}" }, { "code": null, "e": 27376, "s": 27367, "text": "Example:" }, { "code": null, "e": 27379, "s": 27376, "text": "C#" }, { "code": "// C# program to count the files according // to their extensionusing System;using System.IO;using System.Linq; class GFG{ public static void Main(){ // Declare files with different extensions string[] files = { \"171fa07058.txt\", \"171fa07058.pdf\", \"171fa07058.xml\", \"171fa07058.txt\", \"171fa07058.txt\", \"171fa07058.xml\" }; // Group by files with an extension var result = files.Select(f => Path.GetExtension(f) .TrimStart('.').ToLower()) .GroupBy(y => y, (ex, excnt) => new { Extension = ex, Count = excnt.Count() }); // Display the final result foreach (var i in result) { Console.WriteLine(i.Count + \" File --> \" + i.Extension + \" format \"); }}}", "e": 28339, "s": 27379, "text": null }, { "code": null, "e": 28347, "s": 28339, "text": "Output:" }, { "code": null, "e": 28415, "s": 28347, "text": "3 File --> txt format \n1 File --> pdf format \n2 File --> xml format" }, { "code": null, "e": 28427, "s": 28415, "text": "CSharp LINQ" }, { "code": null, "e": 28434, "s": 28427, "text": "Picked" }, { "code": null, "e": 28437, "s": 28434, "text": "C#" }, { "code": null, "e": 28449, "s": 28437, "text": "C# Programs" }, { "code": null, "e": 28547, "s": 28449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28570, "s": 28547, "text": "Extension Method in C#" }, { "code": null, "e": 28598, "s": 28570, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28615, "s": 28598, "text": "C# | Inheritance" }, { "code": null, "e": 28637, "s": 28615, "text": "Partial Classes in C#" }, { "code": null, "e": 28666, "s": 28637, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28706, "s": 28666, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28740, "s": 28706, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 28786, "s": 28740, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 28811, "s": 28786, "text": "Socket Programming in C#" } ]
new Operator vs newInstance() Method in Java - GeeksforGeeks
24 Apr, 2022 In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used. In general, the new operator is used to create objects, but if we want to decide the type of object to be created at runtime, there is no way we can use new operator. In this case, we have to use the newInstance() method. Let us discuss the new operator. In Java, object creation takes place in 3 steps as listed: object instantiation and object initialization, and constructor invocation. Datatype variable; As we will use the new keyword, the compiler interprets the variable as an object Datatype object = new Constructor(); Example: Java // Java Program to Illustrate new Operator // Importing required classesimport java.util.*; // Main classclass GFG { // Main drive method public static void main(String[] args) { // List<Integer> al; // Ny now al is just a variable // Now creating object using new operator List<Integer> al = new ArrayList<>(); // Adding elements to above List al.add(1); al.add(4); al.add(3); // Printing elements of List System.out.print(al); }} [1, 4, 3] Note: We can use it with constructor too where we wanted to call object not variables. Now if we come up with to newInstance() method which is present inside java.lang package inside Class class. As we already discussed it is used where we load the class from remote sources. Consider a scenario where we connect to the database later using our java program for execution. It can be more evidently explained with the JDBC example. Remember there we used the Class.forName() method to load registers dynamically and there we used newInstance() method on top of it to create objects dynamically. Example: Java // Java Program to Demonstrate Working of newInstance()// Method present inside java.lang.Class // Class 1// Class 2class A { int a;}class B { int b;} // Class 3// Main classpublic class GFG { // Method 1 // To create an instance of class whose name is // passed as a string 'c'. public static void fun(String c) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Creating an object of type 'c' Object obj = Class.forName(c).newInstance(); // Printing the type of object created System.out.println("Object created for class:" + obj.getClass().getName()); } // Method 2 // Main driver method public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Calling above method over "A" fun("A"); }} Output: Output Explanation: forName() method returns the class ‘Class’ object on which we are calling newInstance() method which will return the object of that class that we are passing as a command-line argument. If the passed class doesn’t exist then ClassNotFoundException will occur. InstantionException will occur if the passed class doesn’t contain the default constructor as newInstance() method internally calls the default constructor of that particular class. IllegalAccessException will occur if we don’t have access to the definition of the specified class definition. Related Article: Reflection in Java This article is contributed by Gaurav Miglani. 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. solankimayank Difference Between Java Java 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 IPv4 and IPv6 Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Differences between JDK, JRE and JVM Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26039, "s": 26011, "text": "\n24 Apr, 2022" }, { "code": null, "e": 26357, "s": 26039, "text": "In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used." }, { "code": null, "e": 26579, "s": 26357, "text": "In general, the new operator is used to create objects, but if we want to decide the type of object to be created at runtime, there is no way we can use new operator. In this case, we have to use the newInstance() method." }, { "code": null, "e": 26748, "s": 26579, "text": "Let us discuss the new operator. In Java, object creation takes place in 3 steps as listed: object instantiation and object initialization, and constructor invocation." }, { "code": null, "e": 26768, "s": 26748, "text": "Datatype variable; " }, { "code": null, "e": 26850, "s": 26768, "text": "As we will use the new keyword, the compiler interprets the variable as an object" }, { "code": null, "e": 26887, "s": 26850, "text": "Datatype object = new Constructor();" }, { "code": null, "e": 26896, "s": 26887, "text": "Example:" }, { "code": null, "e": 26901, "s": 26896, "text": "Java" }, { "code": "// Java Program to Illustrate new Operator // Importing required classesimport java.util.*; // Main classclass GFG { // Main drive method public static void main(String[] args) { // List<Integer> al; // Ny now al is just a variable // Now creating object using new operator List<Integer> al = new ArrayList<>(); // Adding elements to above List al.add(1); al.add(4); al.add(3); // Printing elements of List System.out.print(al); }}", "e": 27419, "s": 26901, "text": null }, { "code": null, "e": 27429, "s": 27419, "text": "[1, 4, 3]" }, { "code": null, "e": 27516, "s": 27429, "text": "Note: We can use it with constructor too where we wanted to call object not variables." }, { "code": null, "e": 27706, "s": 27516, "text": "Now if we come up with to newInstance() method which is present inside java.lang package inside Class class. As we already discussed it is used where we load the class from remote sources. " }, { "code": null, "e": 28026, "s": 27706, "text": "Consider a scenario where we connect to the database later using our java program for execution. It can be more evidently explained with the JDBC example. Remember there we used the Class.forName() method to load registers dynamically and there we used newInstance() method on top of it to create objects dynamically. " }, { "code": null, "e": 28035, "s": 28026, "text": "Example:" }, { "code": null, "e": 28040, "s": 28035, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of newInstance()// Method present inside java.lang.Class // Class 1// Class 2class A { int a;}class B { int b;} // Class 3// Main classpublic class GFG { // Method 1 // To create an instance of class whose name is // passed as a string 'c'. public static void fun(String c) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Creating an object of type 'c' Object obj = Class.forName(c).newInstance(); // Printing the type of object created System.out.println(\"Object created for class:\" + obj.getClass().getName()); } // Method 2 // Main driver method public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // Calling above method over \"A\" fun(\"A\"); }}", "e": 29010, "s": 28040, "text": null }, { "code": null, "e": 29018, "s": 29010, "text": "Output:" }, { "code": null, "e": 29225, "s": 29018, "text": "Output Explanation: forName() method returns the class ‘Class’ object on which we are calling newInstance() method which will return the object of that class that we are passing as a command-line argument. " }, { "code": null, "e": 29300, "s": 29225, "text": "If the passed class doesn’t exist then ClassNotFoundException will occur. " }, { "code": null, "e": 29483, "s": 29300, "text": "InstantionException will occur if the passed class doesn’t contain the default constructor as newInstance() method internally calls the default constructor of that particular class. " }, { "code": null, "e": 29594, "s": 29483, "text": "IllegalAccessException will occur if we don’t have access to the definition of the specified class definition." }, { "code": null, "e": 29630, "s": 29594, "text": "Related Article: Reflection in Java" }, { "code": null, "e": 30053, "s": 29630, "text": "This article is contributed by Gaurav Miglani. 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": 30067, "s": 30053, "text": "solankimayank" }, { "code": null, "e": 30086, "s": 30067, "text": "Difference Between" }, { "code": null, "e": 30091, "s": 30086, "text": "Java" }, { "code": null, "e": 30096, "s": 30091, "text": "Java" }, { "code": null, "e": 30194, "s": 30096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30255, "s": 30194, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30289, "s": 30255, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 30357, "s": 30289, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 30389, "s": 30357, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 30426, "s": 30389, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 30441, "s": 30426, "text": "Arrays in Java" }, { "code": null, "e": 30485, "s": 30441, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30507, "s": 30485, "text": "For-each loop in Java" }, { "code": null, "e": 30558, "s": 30507, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python | Sort tuple list by Nth element of tuple - GeeksforGeeks
11 May, 2020 Sometimes, while working with Python list, we can come across a problem in which we need to sort list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sort() + lambdaThe combination of above functions can be used to perform this task. In this, we just pass a lambda function to sort() with appropriate tuple element index according to which sort has to be performed. # Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + lambda # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] # printing original listprint("The original list is : " + str(test_list)) # index according to which sort to performN = 1 # Sort tuple list by Nth element of tuple# using sort() + lambdatest_list.sort(key = lambda x: x[N]) # printing result print("List after sorting tuple by Nth index sort : " + str(test_list)) The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)] Method #2 : Using sort() + itemgetter()This is similar to the above method. The difference is just that we use itemgetter(), to perform this task that is done by lambda in above method. # Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + itemgetter()from operator import itemgetter # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] # printing original listprint("The original list is : " + str(test_list)) # index according to which sort to performN = 1 # Sort tuple list by Nth element of tuple# using sort() + itemgetter()test_list.sort(key = itemgetter(N)) # printing result print("List after sorting tuple by Nth index sort : " + str(test_list)) The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)] Python list-programs Python-sort Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25455, "s": 25427, "text": "\n11 May, 2020" }, { "code": null, "e": 25779, "s": 25455, "text": "Sometimes, while working with Python list, we can come across a problem in which we need to sort list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26013, "s": 25779, "text": "Method #1 : Using sort() + lambdaThe combination of above functions can be used to perform this task. In this, we just pass a lambda function to sort() with appropriate tuple element index according to which sort has to be performed." }, { "code": "# Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + lambda # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] # printing original listprint(\"The original list is : \" + str(test_list)) # index according to which sort to performN = 1 # Sort tuple list by Nth element of tuple# using sort() + lambdatest_list.sort(key = lambda x: x[N]) # printing result print(\"List after sorting tuple by Nth index sort : \" + str(test_list))", "e": 26512, "s": 26013, "text": null }, { "code": null, "e": 26671, "s": 26512, "text": "The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]\nList after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]\n" }, { "code": null, "e": 26859, "s": 26673, "text": "Method #2 : Using sort() + itemgetter()This is similar to the above method. The difference is just that we use itemgetter(), to perform this task that is done by lambda in above method." }, { "code": "# Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + itemgetter()from operator import itemgetter # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)] # printing original listprint(\"The original list is : \" + str(test_list)) # index according to which sort to performN = 1 # Sort tuple list by Nth element of tuple# using sort() + itemgetter()test_list.sort(key = itemgetter(N)) # printing result print(\"List after sorting tuple by Nth index sort : \" + str(test_list))", "e": 27400, "s": 26859, "text": null }, { "code": null, "e": 27559, "s": 27400, "text": "The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]\nList after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]\n" }, { "code": null, "e": 27580, "s": 27559, "text": "Python list-programs" }, { "code": null, "e": 27592, "s": 27580, "text": "Python-sort" }, { "code": null, "e": 27599, "s": 27592, "text": "Python" }, { "code": null, "e": 27615, "s": 27599, "text": "Python Programs" }, { "code": null, "e": 27713, "s": 27615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27748, "s": 27713, "text": "Read a file line by line in Python" }, { "code": null, "e": 27780, "s": 27748, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27802, "s": 27780, "text": "Enumerate() in Python" }, { "code": null, "e": 27844, "s": 27802, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27874, "s": 27844, "text": "Iterate over a list in Python" }, { "code": null, "e": 27917, "s": 27874, "text": "Python program to convert a list to string" }, { "code": null, "e": 27939, "s": 27917, "text": "Defaultdict in Python" }, { "code": null, "e": 27978, "s": 27939, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28024, "s": 27978, "text": "Python | Split string into list of characters" } ]
Java Program to Find Area of Rectangle Using Method Overloading - GeeksforGeeks
04 Dec, 2020 A rectangle is a simple flat figure in a plane. It has four sides and four right-angles. In a rectangle all four sides are not of equal length like a square, sides opposite to each other have equal length and both the diagonals of the rectangle have equal length. Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. In this article, we will learn how to find the area of the rectangle using the method overloading. The area of the rectangle is the product of its length and width/breadth. We can simply calculate the area of the rectangle using the following formula: Formula: Area of the rectangle: A = S * T Here, S is the length of the rectangle and T is the breadth/width of the rectangle. Below is the implementation of the above approach: Java // Java program to find the area of// the rectangle using Method Overloadingimport java.io.*; class Rectangle { // Overloaded Area() function to // calculate the area of the rectangle // It takes two double parameters void Area(double S, double T) { System.out.println("Area of the rectangle: " + S * T); } // Overloaded Area() function to // calculate the area of the rectangle. // It takes two float parameters void Area(int S, int T) { System.out.println("Area of the rectangle: " + S * T); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Rectangle class Rectangle obj = new Rectangle(); // Calling function obj.Area(20, 10); obj.Area(10.5, 5.5); }} Area of the rectangle: 200 Area of the rectangle: 57.75 Time Complexity: O(1) Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25489, "s": 25225, "text": "A rectangle is a simple flat figure in a plane. It has four sides and four right-angles. In a rectangle all four sides are not of equal length like a square, sides opposite to each other have equal length and both the diagonals of the rectangle have equal length." }, { "code": null, "e": 25684, "s": 25489, "text": "Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. " }, { "code": null, "e": 25783, "s": 25684, "text": "In this article, we will learn how to find the area of the rectangle using the method overloading." }, { "code": null, "e": 25936, "s": 25783, "text": "The area of the rectangle is the product of its length and width/breadth. We can simply calculate the area of the rectangle using the following formula:" }, { "code": null, "e": 25945, "s": 25936, "text": "Formula:" }, { "code": null, "e": 25978, "s": 25945, "text": "Area of the rectangle: A = S * T" }, { "code": null, "e": 26062, "s": 25978, "text": "Here, S is the length of the rectangle and T is the breadth/width of the rectangle." }, { "code": null, "e": 26113, "s": 26062, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26118, "s": 26113, "text": "Java" }, { "code": "// Java program to find the area of// the rectangle using Method Overloadingimport java.io.*; class Rectangle { // Overloaded Area() function to // calculate the area of the rectangle // It takes two double parameters void Area(double S, double T) { System.out.println(\"Area of the rectangle: \" + S * T); } // Overloaded Area() function to // calculate the area of the rectangle. // It takes two float parameters void Area(int S, int T) { System.out.println(\"Area of the rectangle: \" + S * T); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Rectangle class Rectangle obj = new Rectangle(); // Calling function obj.Area(20, 10); obj.Area(10.5, 5.5); }}", "e": 26977, "s": 26118, "text": null }, { "code": null, "e": 27034, "s": 26977, "text": "Area of the rectangle: 200\nArea of the rectangle: 57.75\n" }, { "code": null, "e": 27056, "s": 27034, "text": "Time Complexity: O(1)" }, { "code": null, "e": 27063, "s": 27056, "text": "Picked" }, { "code": null, "e": 27068, "s": 27063, "text": "Java" }, { "code": null, "e": 27082, "s": 27068, "text": "Java Programs" }, { "code": null, "e": 27087, "s": 27082, "text": "Java" }, { "code": null, "e": 27185, "s": 27087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27200, "s": 27185, "text": "Stream In Java" }, { "code": null, "e": 27221, "s": 27200, "text": "Constructors in Java" }, { "code": null, "e": 27240, "s": 27221, "text": "Exceptions in Java" }, { "code": null, "e": 27270, "s": 27240, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27316, "s": 27270, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27342, "s": 27316, "text": "Java Programming Examples" }, { "code": null, "e": 27376, "s": 27342, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27423, "s": 27376, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27455, "s": 27423, "text": "How to Iterate HashMap in Java?" } ]
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks
09 Dec, 2021 Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As it can be seen that the length (size) of the array above made is 9. But what if there is a requirement to change this length (size). For Example, If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5. Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12. This procedure is referred to as Dynamic Memory Allocation in C.Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: malloc()calloc()free()realloc() malloc() calloc() free() realloc() Let’s look at each of them in greater detail. The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int));Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a NULL pointer. Example: C #include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array printf("Enter number of elements:"); scanf("%d",&n); printf("Entered number of elements: %d\n", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0;} Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5, “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are:It initializes each block with a default value ‘0’.It has two parameters or arguments as compare to malloc(). “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are: It initializes each block with a default value ‘0’. It has two parameters or arguments as compare to malloc(). Syntax: ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element. For Example: ptr = (float*) calloc(25, sizeof(float));This statement allocates contiguous space in memory for 25 elements each with the size of the float. If space is insufficient, allocation fails and returns a NULL pointer. Example: C #include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %d\n", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by calloc or not if (ptr == NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.\n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0;} Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr); Example: C #include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int *ptr, *ptr1; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %d\n", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using calloc() ptr1 = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL || ptr1 == NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); // Free the memory free(ptr); printf("Malloc Memory successfully freed.\n"); // Memory has been successfully allocated printf("\nMemory successfully allocated using calloc.\n"); // Free the memory free(ptr1); printf("Calloc Memory successfully freed.\n"); } return 0;} Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed. “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'. If space is insufficient, allocation fails and returns a NULL pointer. Example: C #include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %d\n", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.\n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } // Get the new size for the array n = 10; printf("\n\nEnter the new size of the array: %d\n", n); // Dynamically re-allocate memory using realloc() ptr = realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf("Memory successfully re-allocated using realloc.\n"); // Get the new elements of the array for (i = 5; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } free(ptr); } return 0;} Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, One another example for realloc() method is: C #include <stdio.h>#include <stdlib.h>int main(){ int index = 0, i = 0, n, *marks; // this marks pointer hold the base address // of the block created int ans; marks = (int*)malloc(sizeof( int)); // dynamically allocate memory using malloc // check if the memory is successfully allocated by // malloc or not? if (marks == NULL) { printf("memory cannot be allocated"); } else { // memory has successfully allocated printf("Memory has been successfully allocated by " "using malloc\n"); printf("\n marks = %pc\n", marks); // print the base or beginning // address of allocated memory do { printf("\n Enter Marks\n"); scanf("%d", &marks[index]); // Get the marks printf("would you like to add more(1/0): "); scanf("%d", &ans); if (ans == 1) { index++; marks = (int*)realloc( marks, (index + 1) * sizeof( int)); // Dynamically reallocate // memory by using realloc // check if the memory is successfully // allocated by realloc or not? if (marks == NULL) { printf("memory cannot be allocated"); } else { printf("Memory has been successfully " "reallocated using realloc:\n"); printf( "\n base address of marks are:%pc", marks); ////print the base or ///beginning address of ///allocated memory } } } while (ans == 1); // print the marks of the students for (i = 0; i <= index; i++) { printf("marks of students %d are: %d\n ", i, marks[i]); } free(marks); } return 0;} Output: newcollegetalent Navfal menariyanarayanlal AnujMehla khushboogoyal499 C Basics Dynamic Memory Allocation C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ TCP Server-Client implementation in C Different methods to reverse a string in C/C++ Structures in C Exception Handling in C++
[ { "code": null, "e": 25681, "s": 25653, "text": "\n09 Dec, 2021" }, { "code": null, "e": 25882, "s": 25681, "text": "Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. " }, { "code": null, "e": 26032, "s": 25882, "text": "As it can be seen that the length (size) of the array above made is 9. But what if there is a requirement to change this length (size). For Example, " }, { "code": null, "e": 26275, "s": 26032, "text": "If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5." }, { "code": null, "e": 26538, "s": 26275, "text": "Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12." }, { "code": null, "e": 26952, "s": 26538, "text": "This procedure is referred to as Dynamic Memory Allocation in C.Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: " }, { "code": null, "e": 26984, "s": 26952, "text": "malloc()calloc()free()realloc()" }, { "code": null, "e": 26993, "s": 26984, "text": "malloc()" }, { "code": null, "e": 27002, "s": 26993, "text": "calloc()" }, { "code": null, "e": 27009, "s": 27002, "text": "free()" }, { "code": null, "e": 27019, "s": 27009, "text": "realloc()" }, { "code": null, "e": 27065, "s": 27019, "text": "Let’s look at each of them in greater detail." }, { "code": null, "e": 27409, "s": 27065, "text": "The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. " }, { "code": null, "e": 27418, "s": 27409, "text": "Syntax: " }, { "code": null, "e": 27468, "s": 27418, "text": "ptr = (cast-type*) malloc(byte-size)\nFor Example:" }, { "code": null, "e": 27674, "s": 27468, "text": "ptr = (int*) malloc(100 * sizeof(int));Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. " }, { "code": null, "e": 27745, "s": 27674, "text": "If space is insufficient, allocation fails and returns a NULL pointer." }, { "code": null, "e": 27755, "s": 27745, "text": "Example: " }, { "code": null, "e": 27757, "s": 27755, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array printf(\"Enter number of elements:\"); scanf(\"%d\",&n); printf(\"Entered number of elements: %d\\n\", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf(\"Memory not allocated.\\n\"); exit(0); } else { // Memory has been successfully allocated printf(\"Memory successfully allocated using malloc.\\n\"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf(\"The elements of the array are: \"); for (i = 0; i < n; ++i) { printf(\"%d, \", ptr[i]); } } return 0;}", "e": 28745, "s": 27757, "text": null }, { "code": null, "e": 28863, "s": 28745, "text": "Enter number of elements: 5\nMemory successfully allocated using malloc.\nThe elements of the array are: 1, 2, 3, 4, 5," }, { "code": null, "e": 29198, "s": 28865, "text": "“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are:It initializes each block with a default value ‘0’.It has two parameters or arguments as compare to malloc()." }, { "code": null, "e": 29422, "s": 29198, "text": "“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are:" }, { "code": null, "e": 29474, "s": 29422, "text": "It initializes each block with a default value ‘0’." }, { "code": null, "e": 29533, "s": 29474, "text": "It has two parameters or arguments as compare to malloc()." }, { "code": null, "e": 29542, "s": 29533, "text": "Syntax: " }, { "code": null, "e": 29662, "s": 29542, "text": "ptr = (cast-type*)calloc(n, element-size);\nhere, n is the no. of elements and element-size is the size of each element." }, { "code": null, "e": 29676, "s": 29662, "text": "For Example: " }, { "code": null, "e": 29819, "s": 29676, "text": "ptr = (float*) calloc(25, sizeof(float));This statement allocates contiguous space in memory for 25 elements each with the size of the float. " }, { "code": null, "e": 29890, "s": 29819, "text": "If space is insufficient, allocation fails and returns a NULL pointer." }, { "code": null, "e": 29899, "s": 29890, "text": "Example:" }, { "code": null, "e": 29901, "s": 29899, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf(\"Enter number of elements: %d\\n\", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by calloc or not if (ptr == NULL) { printf(\"Memory not allocated.\\n\"); exit(0); } else { // Memory has been successfully allocated printf(\"Memory successfully allocated using calloc.\\n\"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf(\"The elements of the array are: \"); for (i = 0; i < n; ++i) { printf(\"%d, \", ptr[i]); } } return 0;}", "e": 30837, "s": 29901, "text": null }, { "code": null, "e": 30955, "s": 30837, "text": "Enter number of elements: 5\nMemory successfully allocated using calloc.\nThe elements of the array are: 1, 2, 3, 4, 5," }, { "code": null, "e": 31253, "s": 30957, "text": "“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it." }, { "code": null, "e": 31262, "s": 31253, "text": "Syntax: " }, { "code": null, "e": 31273, "s": 31262, "text": "free(ptr);" }, { "code": null, "e": 31282, "s": 31273, "text": "Example:" }, { "code": null, "e": 31284, "s": 31282, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int *ptr, *ptr1; int n, i; // Get the number of elements for the array n = 5; printf(\"Enter number of elements: %d\\n\", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using calloc() ptr1 = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL || ptr1 == NULL) { printf(\"Memory not allocated.\\n\"); exit(0); } else { // Memory has been successfully allocated printf(\"Memory successfully allocated using malloc.\\n\"); // Free the memory free(ptr); printf(\"Malloc Memory successfully freed.\\n\"); // Memory has been successfully allocated printf(\"\\nMemory successfully allocated using calloc.\\n\"); // Free the memory free(ptr1); printf(\"Calloc Memory successfully freed.\\n\"); } return 0;}", "e": 32369, "s": 31284, "text": null }, { "code": null, "e": 32554, "s": 32369, "text": "Enter number of elements: 5\nMemory successfully allocated using malloc.\nMalloc Memory successfully freed.\n\nMemory successfully allocated using calloc.\nCalloc Memory successfully freed." }, { "code": null, "e": 32967, "s": 32556, "text": "“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value." }, { "code": null, "e": 32976, "s": 32967, "text": "Syntax: " }, { "code": null, "e": 33056, "s": 32976, "text": "ptr = realloc(ptr, newSize);\n\nwhere ptr is reallocated with new size 'newSize'." }, { "code": null, "e": 33127, "s": 33056, "text": "If space is insufficient, allocation fails and returns a NULL pointer." }, { "code": null, "e": 33136, "s": 33127, "text": "Example:" }, { "code": null, "e": 33138, "s": 33136, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf(\"Enter number of elements: %d\\n\", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf(\"Memory not allocated.\\n\"); exit(0); } else { // Memory has been successfully allocated printf(\"Memory successfully allocated using calloc.\\n\"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf(\"The elements of the array are: \"); for (i = 0; i < n; ++i) { printf(\"%d, \", ptr[i]); } // Get the new size for the array n = 10; printf(\"\\n\\nEnter the new size of the array: %d\\n\", n); // Dynamically re-allocate memory using realloc() ptr = realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf(\"Memory successfully re-allocated using realloc.\\n\"); // Get the new elements of the array for (i = 5; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf(\"The elements of the array are: \"); for (i = 0; i < n; ++i) { printf(\"%d, \", ptr[i]); } free(ptr); } return 0;}", "e": 34717, "s": 33138, "text": null }, { "code": null, "e": 34983, "s": 34717, "text": "Enter number of elements: 5\nMemory successfully allocated using calloc.\nThe elements of the array are: 1, 2, 3, 4, 5, \n\nEnter the new size of the array: 10\nMemory successfully re-allocated using realloc.\nThe elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10," }, { "code": null, "e": 35030, "s": 34985, "text": "One another example for realloc() method is:" }, { "code": null, "e": 35032, "s": 35030, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h>int main(){ int index = 0, i = 0, n, *marks; // this marks pointer hold the base address // of the block created int ans; marks = (int*)malloc(sizeof( int)); // dynamically allocate memory using malloc // check if the memory is successfully allocated by // malloc or not? if (marks == NULL) { printf(\"memory cannot be allocated\"); } else { // memory has successfully allocated printf(\"Memory has been successfully allocated by \" \"using malloc\\n\"); printf(\"\\n marks = %pc\\n\", marks); // print the base or beginning // address of allocated memory do { printf(\"\\n Enter Marks\\n\"); scanf(\"%d\", &marks[index]); // Get the marks printf(\"would you like to add more(1/0): \"); scanf(\"%d\", &ans); if (ans == 1) { index++; marks = (int*)realloc( marks, (index + 1) * sizeof( int)); // Dynamically reallocate // memory by using realloc // check if the memory is successfully // allocated by realloc or not? if (marks == NULL) { printf(\"memory cannot be allocated\"); } else { printf(\"Memory has been successfully \" \"reallocated using realloc:\\n\"); printf( \"\\n base address of marks are:%pc\", marks); ////print the base or ///beginning address of ///allocated memory } } } while (ans == 1); // print the marks of the students for (i = 0; i <= index; i++) { printf(\"marks of students %d are: %d\\n \", i, marks[i]); } free(marks); } return 0;}", "e": 37105, "s": 35032, "text": null }, { "code": null, "e": 37113, "s": 37105, "text": "Output:" }, { "code": null, "e": 37130, "s": 37113, "text": "newcollegetalent" }, { "code": null, "e": 37137, "s": 37130, "text": "Navfal" }, { "code": null, "e": 37156, "s": 37137, "text": "menariyanarayanlal" }, { "code": null, "e": 37166, "s": 37156, "text": "AnujMehla" }, { "code": null, "e": 37183, "s": 37166, "text": "khushboogoyal499" }, { "code": null, "e": 37192, "s": 37183, "text": "C Basics" }, { "code": null, "e": 37218, "s": 37192, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 37229, "s": 37218, "text": "C Language" }, { "code": null, "e": 37327, "s": 37229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37349, "s": 37327, "text": "Function Pointer in C" }, { "code": null, "e": 37366, "s": 37349, "text": "Substring in C++" }, { "code": null, "e": 37378, "s": 37366, "text": "fork() in C" }, { "code": null, "e": 37403, "s": 37378, "text": "std::string class in C++" }, { "code": null, "e": 37430, "s": 37403, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 37462, "s": 37430, "text": "Command line arguments in C/C++" }, { "code": null, "e": 37500, "s": 37462, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 37547, "s": 37500, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 37563, "s": 37547, "text": "Structures in C" } ]
AVL Tree | Set 1 (Insertion) - GeeksforGeeks
19 Feb, 2022 AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. An Example Tree that is an AVL Tree The above tree is AVL because differences between heights of left and right subtrees for every node is less than or equal to 1.An Example Tree that is NOT an AVL Tree The above tree is not AVL because differences between heights of left and right subtrees for 8 and 12 is greater than 1.Why AVL Trees? Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that height of the tree remains O(Logn) after every insertion and deletion, then we can guarantee an upper bound of O(Logn) for all these operations. The height of an AVL tree is always O(Logn) where n is the number of nodes in the tree (See this video lecture for proof). Insertion To make sure that the given tree remains AVL after every insertion, we must augment the standard BST insert operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation T1, T2 and T3 are subtrees of the tree rooted with y (on the left side) or x (on the right side) y x / \ Right Rotation / \ x T3 - - - - - - - > T1 y / \ < - - - - - - - / \ T1 T2 Left Rotation T2 T3 Keys in both of the above trees follow the following order keys(T1) < key(x) < keys(T2) < key(y) < keys(T3) So BST property is not violated anywhere. Steps to follow for insertion Let the newly inserted node be w 1) Perform standard BST insert for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the child of z that comes on the path from w to z and x be the grandchild of z that comes on the path from w to z. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case)Following are the operations to be performed in above mentioned 4 cases. In all of the cases, we only need to re-balance the subtree rooted with z and the complete tree becomes balanced as the height of subtree (After appropriate rotations) rooted with z becomes same as it was before insertion. (See this video lecture for proof)a) Left Left Case T1, T2, T3 and T4 are subtrees. z y / \ / \ y T4 Right Rotate (z) x z / \ - - - - - - - - -> / \ / \ x T3 T1 T2 T3 T4 / \ T1 T2 b) Left Right Case z z x / \ / \ / \ y T4 Left Rotate (y) x T4 Right Rotate(z) y z / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ T1 x y T3 T1 T2 T3 T4 / \ / \ T2 T3 T1 T2 c) Right Right Case z y / \ / \ T1 y Left Rotate(z) z x / \ - - - - - - - -> / \ / \ T2 x T1 T2 T3 T4 / \ T3 T4 d) Right Left Case z z x / \ / \ / \ T1 y Right Rotate (y) T1 x Left Rotate(z) z y / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ x T4 T2 y T1 T2 T3 T4 / \ / \ T2 T3 T3 T4 Insertion Examples: Implementation Following is the implementation for AVL Tree Insertion. The following implementation uses the recursive BST insert to insert a new node. In the recursive BST insert, after insertion, we get pointers to all ancestors one by one in a bottom-up manner. So we don’t need parent pointer to travel up. The recursive code itself travels up and visits all the ancestors of the newly inserted node. 1) Perform the normal BST insertion. 2) The current node must be one of the ancestors of the newly inserted node. Update the height of the current node. 3) Get the balance factor (left subtree height – right subtree height) of the current node. 4) If balance factor is greater than 1, then the current node is unbalanced and we are either in Left Left case or left Right case. To check whether it is left left case or not, compare the newly inserted key with the key in left subtree root. 5) If balance factor is less than -1, then the current node is unbalanced and we are either in Right Right case or Right-Left case. To check whether it is Right Right case or not, compare the newly inserted key with the key in right subtree root. C++ C Java Python3 C# Javascript // C++ program to insert a node in AVL tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get the// height of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Recursive function to insert a key// in the subtree rooted with node and// returns the new root of the subtree.Node* insert(Node* node, int key){ /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys are not allowed in BST return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << " "; preOrder(root->left); preOrder(root->right); }} // Driver Codeint main(){ Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ cout << "Preorder traversal of the " "constructed AVL tree is \n"; preOrder(root); return 0;} // This code is contributed by// rathbhupendra // C program to insert a node in AVL tree#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct Node{ int key; struct Node *left; struct Node *right; int height;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get the height of the treeint height(struct Node *N){ if (N == NULL) return 0; return 1+max(height(N->left), height(N->right));} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 0; // new node is initially added at leaf return(node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = height(y); x->height = height(x); // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = height(x); y->height = height(y); // Return new root return y;} // Get Balance factor of node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Recursive function to insert a key in the subtree rooted// with node and returns the new root of the subtree.struct Node* insert(struct Node* node, int key){ /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys are not allowed in BST return node; /* 2. Update height of this ancestor node */ node->height = height(node); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} // A utility function to print preorder traversal// of the tree.// The function also prints height of every nodevoid preOrder(struct Node *root){ if(root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ printf("Preorder traversal of the constructed AVL" " tree is \n"); preOrder(root); return 0;} // Java program for insertion in AVL Treeclass Node { int key, height; Node left, right; Node(int d) { key = d; height = 1; }} class AVLTree { Node root; // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Duplicate keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node void preOrder(Node node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ System.out.println("Preorder traversal" + " of constructed tree is : "); tree.preOrder(tree.root); }}// This code has been contributed by Mayank Jaiswal # Python code to insert a node in AVL tree # Generic tree node classclass TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 # AVL tree class which supports the# Insert operationclass AVL_Tree(object): # Recursive function to insert key in # subtree rooted with node and returns # new root of subtree. def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) elif key < root.val: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def preOrder(self, root): if not root: return print("{0} ".format(root.val), end="") self.preOrder(root.left) self.preOrder(root.right) # Driver program to test above functionmyTree = AVL_Tree()root = None root = myTree.insert(root, 10)root = myTree.insert(root, 20)root = myTree.insert(root, 30)root = myTree.insert(root, 40)root = myTree.insert(root, 50)root = myTree.insert(root, 25) """The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50""" # Preorder Traversalprint("Preorder traversal of the", "constructed AVL tree is")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak // C# program for insertion in AVL Treeusing System; class Node{ public int key, height; public Node left, right; public Node(int d) { key = d; height = 1; }} public class AVLTree{ Node root; // A utility function to get // the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Duplicate keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node void preOrder(Node node) { if (node != null) { Console.Write(node.key + " "); preOrder(node.left); preOrder(node.right); } } // Driver code public static void Main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ Console.Write("Preorder traversal" + " of constructed tree is : "); tree.preOrder(tree.root); }} // This code has been contributed// by PrinciRaj1992 <script> // JavaScript program for insertion in AVL Tree class Node { constructor(d) { this.key = d; this.height = 1; this.left = null; this.right = null; } } class AVLTree { constructor() { this.root = null; } // A utility function to get // the height of the tree height(N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers max(a, b) { return a > b ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. rightRotate(y) { var x = y.left; var T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = this.max(this.height(y.left), this.height(y.right)) + 1; x.height = this.max(this.height(x.left), this.height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. leftRotate(x) { var y = x.right; var T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = this.max(this.height(x.left), this.height(x.right)) + 1; y.height = this.max(this.height(y.left), this.height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N getBalance(N) { if (N == null) return 0; return this.height(N.left) - this.height(N.right); } insert(node, key) { /* 1. Perform the normal BST insertion */ if (node == null) return new Node(key); if (key < node.key) node.left = this.insert(node.left, key); else if (key > node.key) node.right = this.insert(node.right, key); // Duplicate keys not allowed else return node; /* 2. Update height of this ancestor node */ node.height = 1 + this.max(this.height(node.left), this.height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ var balance = this.getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return this.rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return this.leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = this.leftRotate(node.left); return this.rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = this.rightRotate(node.right); return this.leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node preOrder(node) { if (node != null) { document.write(node.key + " "); this.preOrder(node.left); this.preOrder(node.right); } } } // Driver code var tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ document.write( "Preorder traversal of the " + "constructed AVL tree is <br>" ); tree.preOrder(tree.root); </script> Output: Preorder traversal of the constructed AVL tree is 30 20 10 25 40 50 Time Complexity: The rotation operations (left and right rotate) take constant time as only a few pointers are being changed there. Updating the height and getting the balance factor also takes constant time. So the time complexity of AVL insert remains same as BST insert which is O(h) where h is the height of the tree. Since AVL tree is balanced, the height is O(Logn). So time complexity of AVL insert is O(Logn).Comparison with Red Black Tree The AVL tree and other self-balancing search trees like Red Black are useful to get all basic operations done in O(log n) time. The AVL trees are more balanced compared to Red-Black Trees, but they may cause more rotations during insertion and deletion. So if your application involves many frequent insertions and deletions, then Red Black trees should be preferred. And if the insertions and deletions are less frequent and search is the more frequent operation, then AVL tree should be preferred over Red Black Tree.Following is the post for delete. AVL Tree | Set 2 (Deletion)Following are some posts that have used self-balancing search trees.Median in a stream of integers (running integers) Maximum of all subarrays of size k Count smaller elements on right side References: IITD Video Lecture on AVL Tree Introduction IITD Video Lecture on AVL Tree Insertion and DeletionPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 rathbhupendra Akanksha_Rai sohamshinde04 nocturnalstoryteller rdtank kaiwenzheng644 Amazon AVL-Tree Citicorp Informatica MakeMyTrip Morgan Stanley Oracle Oxigen Wallet Self-Balancing-BST Snapdeal Advanced Data Structure Binary Search Tree Tree Morgan Stanley Amazon Snapdeal MakeMyTrip Oracle Oxigen Wallet Informatica Citicorp Binary Search Tree Tree AVL-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) Ordered Set and GNU C++ PBDS Disjoint Set Data Structures A program to check if a binary tree is BST or not Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Find the node with minimum value in a Binary Search Tree
[ { "code": null, "e": 26033, "s": 26005, "text": "\n19 Feb, 2022" }, { "code": null, "e": 26228, "s": 26033, "text": "AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. An Example Tree that is an AVL Tree " }, { "code": null, "e": 26396, "s": 26228, "text": "The above tree is AVL because differences between heights of left and right subtrees for every node is less than or equal to 1.An Example Tree that is NOT an AVL Tree " }, { "code": null, "e": 27015, "s": 26396, "text": "The above tree is not AVL because differences between heights of left and right subtrees for 8 and 12 is greater than 1.Why AVL Trees? Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that height of the tree remains O(Logn) after every insertion and deletion, then we can guarantee an upper bound of O(Logn) for all these operations. The height of an AVL tree is always O(Logn) where n is the number of nodes in the tree (See this video lecture for proof). " }, { "code": null, "e": 27360, "s": 27015, "text": "Insertion To make sure that the given tree remains AVL after every insertion, we must augment the standard BST insert operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation" }, { "code": null, "e": 27833, "s": 27360, "text": "T1, T2 and T3 are subtrees of the tree \nrooted with y (on the left side) or x (on \nthe right side) \n y x\n / \\ Right Rotation / \\\n x T3 - - - - - - - > T1 y \n / \\ < - - - - - - - / \\\n T1 T2 Left Rotation T2 T3\nKeys in both of the above trees follow the \nfollowing order \n keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)\nSo BST property is not violated anywhere." }, { "code": null, "e": 29004, "s": 27833, "text": "Steps to follow for insertion Let the newly inserted node be w 1) Perform standard BST insert for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the child of z that comes on the path from w to z and x be the grandchild of z that comes on the path from w to z. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case)Following are the operations to be performed in above mentioned 4 cases. In all of the cases, we only need to re-balance the subtree rooted with z and the complete tree becomes balanced as the height of subtree (After appropriate rotations) rooted with z becomes same as it was before insertion. (See this video lecture for proof)a) Left Left Case " }, { "code": null, "e": 29325, "s": 29004, "text": "T1, T2, T3 and T4 are subtrees.\n z y \n / \\ / \\\n y T4 Right Rotate (z) x z\n / \\ - - - - - - - - -> / \\ / \\ \n x T3 T1 T2 T3 T4\n / \\\n T1 T2" }, { "code": null, "e": 29345, "s": 29325, "text": "b) Left Right Case " }, { "code": null, "e": 29770, "s": 29345, "text": " z z x\n / \\ / \\ / \\ \n y T4 Left Rotate (y) x T4 Right Rotate(z) y z\n / \\ - - - - - - - - -> / \\ - - - - - - - -> / \\ / \\\nT1 x y T3 T1 T2 T3 T4\n / \\ / \\\n T2 T3 T1 T2" }, { "code": null, "e": 29791, "s": 29770, "text": "c) Right Right Case " }, { "code": null, "e": 30018, "s": 29791, "text": " z y\n / \\ / \\ \nT1 y Left Rotate(z) z x\n / \\ - - - - - - - -> / \\ / \\\n T2 x T1 T2 T3 T4\n / \\\n T3 T4" }, { "code": null, "e": 30038, "s": 30018, "text": "d) Right Left Case " }, { "code": null, "e": 30454, "s": 30038, "text": " z z x\n / \\ / \\ / \\ \nT1 y Right Rotate (y) T1 x Left Rotate(z) z y\n / \\ - - - - - - - - -> / \\ - - - - - - - -> / \\ / \\\n x T4 T2 y T1 T2 T3 T4\n / \\ / \\\nT2 T3 T3 T4" }, { "code": null, "e": 30476, "s": 30454, "text": "Insertion Examples: " }, { "code": null, "e": 31626, "s": 30484, "text": "Implementation Following is the implementation for AVL Tree Insertion. The following implementation uses the recursive BST insert to insert a new node. In the recursive BST insert, after insertion, we get pointers to all ancestors one by one in a bottom-up manner. So we don’t need parent pointer to travel up. The recursive code itself travels up and visits all the ancestors of the newly inserted node. 1) Perform the normal BST insertion. 2) The current node must be one of the ancestors of the newly inserted node. Update the height of the current node. 3) Get the balance factor (left subtree height – right subtree height) of the current node. 4) If balance factor is greater than 1, then the current node is unbalanced and we are either in Left Left case or left Right case. To check whether it is left left case or not, compare the newly inserted key with the key in left subtree root. 5) If balance factor is less than -1, then the current node is unbalanced and we are either in Right Right case or Right-Left case. To check whether it is Right Right case or not, compare the newly inserted key with the key in right subtree root. " }, { "code": null, "e": 31630, "s": 31626, "text": "C++" }, { "code": null, "e": 31632, "s": 31630, "text": "C" }, { "code": null, "e": 31637, "s": 31632, "text": "Java" }, { "code": null, "e": 31645, "s": 31637, "text": "Python3" }, { "code": null, "e": 31648, "s": 31645, "text": "C#" }, { "code": null, "e": 31659, "s": 31648, "text": "Javascript" }, { "code": "// C++ program to insert a node in AVL tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get the// height of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Recursive function to insert a key// in the subtree rooted with node and// returns the new root of the subtree.Node* insert(Node* node, int key){ /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys are not allowed in BST return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << \" \"; preOrder(root->left); preOrder(root->right); }} // Driver Codeint main(){ Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50 */ cout << \"Preorder traversal of the \" \"constructed AVL tree is \\n\"; preOrder(root); return 0;} // This code is contributed by// rathbhupendra", "e": 35737, "s": 31659, "text": null }, { "code": "// C program to insert a node in AVL tree#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct Node{ int key; struct Node *left; struct Node *right; int height;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get the height of the treeint height(struct Node *N){ if (N == NULL) return 0; return 1+max(height(N->left), height(N->right));} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 0; // new node is initially added at leaf return(node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = height(y); x->height = height(x); // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = height(x); y->height = height(y); // Return new root return y;} // Get Balance factor of node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Recursive function to insert a key in the subtree rooted// with node and returns the new root of the subtree.struct Node* insert(struct Node* node, int key){ /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys are not allowed in BST return node; /* 2. Update height of this ancestor node */ node->height = height(node); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} // A utility function to print preorder traversal// of the tree.// The function also prints height of every nodevoid preOrder(struct Node *root){ if(root != NULL) { printf(\"%d \", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50 */ printf(\"Preorder traversal of the constructed AVL\" \" tree is \\n\"); preOrder(root); return 0;}", "e": 39649, "s": 35737, "text": null }, { "code": "// Java program for insertion in AVL Treeclass Node { int key, height; Node left, right; Node(int d) { key = d; height = 1; }} class AVLTree { Node root; // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Duplicate keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node void preOrder(Node node) { if (node != null) { System.out.print(node.key + \" \"); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50 */ System.out.println(\"Preorder traversal\" + \" of constructed tree is : \"); tree.preOrder(tree.root); }}// This code has been contributed by Mayank Jaiswal", "e": 43612, "s": 39649, "text": null }, { "code": "# Python code to insert a node in AVL tree # Generic tree node classclass TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 # AVL tree class which supports the# Insert operationclass AVL_Tree(object): # Recursive function to insert key in # subtree rooted with node and returns # new root of subtree. def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) elif key < root.val: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def preOrder(self, root): if not root: return print(\"{0} \".format(root.val), end=\"\") self.preOrder(root.left) self.preOrder(root.right) # Driver program to test above functionmyTree = AVL_Tree()root = None root = myTree.insert(root, 10)root = myTree.insert(root, 20)root = myTree.insert(root, 30)root = myTree.insert(root, 40)root = myTree.insert(root, 50)root = myTree.insert(root, 25) \"\"\"The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50\"\"\" # Preorder Traversalprint(\"Preorder traversal of the\", \"constructed AVL tree is\")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak", "e": 46976, "s": 43612, "text": null }, { "code": "// C# program for insertion in AVL Treeusing System; class Node{ public int key, height; public Node left, right; public Node(int d) { key = d; height = 1; }} public class AVLTree{ Node root; // A utility function to get // the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else // Duplicate keys not allowed return node; /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node void preOrder(Node node) { if (node != null) { Console.Write(node.key + \" \"); preOrder(node.left); preOrder(node.right); } } // Driver code public static void Main(String[] args) { AVLTree tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50 */ Console.Write(\"Preorder traversal\" + \" of constructed tree is : \"); tree.preOrder(tree.root); }} // This code has been contributed// by PrinciRaj1992", "e": 51113, "s": 46976, "text": null }, { "code": "<script> // JavaScript program for insertion in AVL Tree class Node { constructor(d) { this.key = d; this.height = 1; this.left = null; this.right = null; } } class AVLTree { constructor() { this.root = null; } // A utility function to get // the height of the tree height(N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers max(a, b) { return a > b ? a : b; } // A utility function to right // rotate subtree rooted with y // See the diagram given above. rightRotate(y) { var x = y.left; var T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = this.max(this.height(y.left), this.height(y.right)) + 1; x.height = this.max(this.height(x.left), this.height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. leftRotate(x) { var y = x.right; var T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = this.max(this.height(x.left), this.height(x.right)) + 1; y.height = this.max(this.height(y.left), this.height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N getBalance(N) { if (N == null) return 0; return this.height(N.left) - this.height(N.right); } insert(node, key) { /* 1. Perform the normal BST insertion */ if (node == null) return new Node(key); if (key < node.key) node.left = this.insert(node.left, key); else if (key > node.key) node.right = this.insert(node.right, key); // Duplicate keys not allowed else return node; /* 2. Update height of this ancestor node */ node.height = 1 + this.max(this.height(node.left), this.height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ var balance = this.getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return this.rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return this.leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = this.leftRotate(node.left); return this.rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = this.rightRotate(node.right); return this.leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder traversal // of the tree. // The function also prints height of every node preOrder(node) { if (node != null) { document.write(node.key + \" \"); this.preOrder(node.left); this.preOrder(node.right); } } } // Driver code var tree = new AVLTree(); /* Constructing tree given in the above figure */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 20); tree.root = tree.insert(tree.root, 30); tree.root = tree.insert(tree.root, 40); tree.root = tree.insert(tree.root, 50); tree.root = tree.insert(tree.root, 25); /* The constructed AVL Tree would be 30 / \\ 20 40 / \\ \\ 10 25 50 */ document.write( \"Preorder traversal of the \" + \"constructed AVL tree is <br>\" ); tree.preOrder(tree.root); </script>", "e": 55375, "s": 51113, "text": null }, { "code": null, "e": 55384, "s": 55375, "text": "Output: " }, { "code": null, "e": 55456, "s": 55384, "text": " Preorder traversal of the constructed AVL tree is\n 30 20 10 25 40 50" }, { "code": null, "e": 56674, "s": 55456, "text": "Time Complexity: The rotation operations (left and right rotate) take constant time as only a few pointers are being changed there. Updating the height and getting the balance factor also takes constant time. So the time complexity of AVL insert remains same as BST insert which is O(h) where h is the height of the tree. Since AVL tree is balanced, the height is O(Logn). So time complexity of AVL insert is O(Logn).Comparison with Red Black Tree The AVL tree and other self-balancing search trees like Red Black are useful to get all basic operations done in O(log n) time. The AVL trees are more balanced compared to Red-Black Trees, but they may cause more rotations during insertion and deletion. So if your application involves many frequent insertions and deletions, then Red Black trees should be preferred. And if the insertions and deletions are less frequent and search is the more frequent operation, then AVL tree should be preferred over Red Black Tree.Following is the post for delete. AVL Tree | Set 2 (Deletion)Following are some posts that have used self-balancing search trees.Median in a stream of integers (running integers) Maximum of all subarrays of size k Count smaller elements on right side" }, { "code": null, "e": 56909, "s": 56674, "text": "References: IITD Video Lecture on AVL Tree Introduction IITD Video Lecture on AVL Tree Insertion and DeletionPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 56923, "s": 56909, "text": "princiraj1992" }, { "code": null, "e": 56937, "s": 56923, "text": "rathbhupendra" }, { "code": null, "e": 56950, "s": 56937, "text": "Akanksha_Rai" }, { "code": null, "e": 56964, "s": 56950, "text": "sohamshinde04" }, { "code": null, "e": 56985, "s": 56964, "text": "nocturnalstoryteller" }, { "code": null, "e": 56992, "s": 56985, "text": "rdtank" }, { "code": null, "e": 57007, "s": 56992, "text": "kaiwenzheng644" }, { "code": null, "e": 57014, "s": 57007, "text": "Amazon" }, { "code": null, "e": 57023, "s": 57014, "text": "AVL-Tree" }, { "code": null, "e": 57032, "s": 57023, "text": "Citicorp" }, { "code": null, "e": 57044, "s": 57032, "text": "Informatica" }, { "code": null, "e": 57055, "s": 57044, "text": "MakeMyTrip" }, { "code": null, "e": 57070, "s": 57055, "text": "Morgan Stanley" }, { "code": null, "e": 57077, "s": 57070, "text": "Oracle" }, { "code": null, "e": 57091, "s": 57077, "text": "Oxigen Wallet" }, { "code": null, "e": 57110, "s": 57091, "text": "Self-Balancing-BST" }, { "code": null, "e": 57119, "s": 57110, "text": "Snapdeal" }, { "code": null, "e": 57143, "s": 57119, "text": "Advanced Data Structure" }, { "code": null, "e": 57162, "s": 57143, "text": "Binary Search Tree" }, { "code": null, "e": 57167, "s": 57162, "text": "Tree" }, { "code": null, "e": 57182, "s": 57167, "text": "Morgan Stanley" }, { "code": null, "e": 57189, "s": 57182, "text": "Amazon" }, { "code": null, "e": 57198, "s": 57189, "text": "Snapdeal" }, { "code": null, "e": 57209, "s": 57198, "text": "MakeMyTrip" }, { "code": null, "e": 57216, "s": 57209, "text": "Oracle" }, { "code": null, "e": 57230, "s": 57216, "text": "Oxigen Wallet" }, { "code": null, "e": 57242, "s": 57230, "text": "Informatica" }, { "code": null, "e": 57251, "s": 57242, "text": "Citicorp" }, { "code": null, "e": 57270, "s": 57251, "text": "Binary Search Tree" }, { "code": null, "e": 57275, "s": 57270, "text": "Tree" }, { "code": null, "e": 57284, "s": 57275, "text": "AVL-Tree" }, { "code": null, "e": 57382, "s": 57284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57416, "s": 57382, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 57456, "s": 57416, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 57498, "s": 57456, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 57527, "s": 57498, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 57556, "s": 57527, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 57606, "s": 57556, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 57635, "s": 57606, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 57670, "s": 57635, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 57710, "s": 57670, "text": "Inorder Successor in Binary Search Tree" } ]
Jupyter and tensorboard in tmux and ssh | by Fabio M. Graetz | Towards Data Science
In recent posts, I described how you can set up your personal deep learning workstation and how you can switch it on and access it remotely. In this short article, I explain how I usually set up my remote working environment with tmux and check on my phone on the progress of my calculations. tmux is a terminal multiplexer, allowing a user to access multiple separate terminal sessions inside a single terminal window or remote terminal session. First, add the following lines to your .ssh/config on your laptop. Look here if you want a slightly more detailed instruction on how to access your computer remotely. Host workstation HostName <hostname> User <username> Port <port> LocalForward 8888 localhost:8888 LocalForward 6006 localhost:6006 Now you can log in by typing ssh workstation. Type tmux new -s <sessionname> to launch tmux. I usually split the screen vertically by typing Ctrl-b % and then horizontally by typing Ctrl-b ". With Ctrl-b o you can navigate to the next pane. I usually go to the top right pane, start my virtual environment with source active <name> and launch a jupyter notebook by typing jupyter-notebook. Copy the link into the browser on your laptop. Next, we start tensorboard. Type Ctrl-b o to move the cursor to the next pane in tmux. Activate the virtual environment and start tensorboard by typing tensorboard --logdir=<log directory>. Open a new tab in the browser on your laptop and go to http://localhost:6006. Now tensorboard should be running as well (in case it is not working, make sure that tensorboard really uses port 6006 as in my case). Now comes the best part: When you stop working, simply type Ctrl-b d to detach from the tmux session and when you want to continue working, type tmux attach -t <sessionname> and you are back where you left off! Unfortunately, I don’t think that there is a way to close a jupyter notebook, while it continues running in the background, and come back to it later. What I often do, when I want to leave something calculating overnight, is converting it to python by typing jupyter-nbconvert --to script <name>.ipynb. Now, simply run the .py, detach from the tmux session and come back the next day to look at the output. If someone knows a better way, please leave a comment, I’d be thrilled to know. Here are some other very useful shortcuts for tmux: # session managementtmux ls (or tmux list-sessions)tmux new -s session-nameCtrl-b d Detach from sessiontmux attach -t [session name]tmux kill-session -t session-nameCtrl-b c Create new windowCtrl-b d Detach current clientCtrl-b l Move to previously selected windowCtrl-b n Move to the next windowCtrl-b p Move to the previous windowCtrl-b & Kill the current windowCtrl-b , Rename the current windowCtrl-b q Show pane numbers (used to switch between panes)Ctrl-b o Switch to the next paneCtrl-b ? List all keybindings# moving between windowsCtrl-b n (Move to the next window)Ctrl-b p (Move to the previous window)Ctrl-b l (Move to the previously selected window)Ctrl-b w (List all windows / window numbers)Ctrl-b window number (Move to the specified window number, thedefault bindings are from 0 -- 9)# Tiling commandsCtrl-b % (Split the window vertically)CTRL-b " (Split window horizontally)Ctrl-b o (Goto next pane)Ctrl-b q (Show pane numbers, when the numbers show up type the key to go to that pane)Ctrl-b { (Move the current pane left)Ctrl-b } (Move the current pane right)Ctrl-b x kill current pane# Make a pane its own windowCtrl-b : "break-pane" Another useful hint: If you use hyperdash you can track on your phone how your model is doing without having to log in to your computer: hyperdash run -n "DQN Breakout" python DQN.py I hope this saves you a lot of time :) Have fun!
[ { "code": null, "e": 312, "s": 171, "text": "In recent posts, I described how you can set up your personal deep learning workstation and how you can switch it on and access it remotely." }, { "code": null, "e": 464, "s": 312, "text": "In this short article, I explain how I usually set up my remote working environment with tmux and check on my phone on the progress of my calculations." }, { "code": null, "e": 618, "s": 464, "text": "tmux is a terminal multiplexer, allowing a user to access multiple separate terminal sessions inside a single terminal window or remote terminal session." }, { "code": null, "e": 785, "s": 618, "text": "First, add the following lines to your .ssh/config on your laptop. Look here if you want a slightly more detailed instruction on how to access your computer remotely." }, { "code": null, "e": 936, "s": 785, "text": "Host workstation HostName <hostname> User <username> Port <port> LocalForward 8888 localhost:8888 LocalForward 6006 localhost:6006" }, { "code": null, "e": 1776, "s": 936, "text": "Now you can log in by typing ssh workstation. Type tmux new -s <sessionname> to launch tmux. I usually split the screen vertically by typing Ctrl-b % and then horizontally by typing Ctrl-b \". With Ctrl-b o you can navigate to the next pane. I usually go to the top right pane, start my virtual environment with source active <name> and launch a jupyter notebook by typing jupyter-notebook. Copy the link into the browser on your laptop. Next, we start tensorboard. Type Ctrl-b o to move the cursor to the next pane in tmux. Activate the virtual environment and start tensorboard by typing tensorboard --logdir=<log directory>. Open a new tab in the browser on your laptop and go to http://localhost:6006. Now tensorboard should be running as well (in case it is not working, make sure that tensorboard really uses port 6006 as in my case)." }, { "code": null, "e": 1987, "s": 1776, "text": "Now comes the best part: When you stop working, simply type Ctrl-b d to detach from the tmux session and when you want to continue working, type tmux attach -t <sessionname> and you are back where you left off!" }, { "code": null, "e": 2474, "s": 1987, "text": "Unfortunately, I don’t think that there is a way to close a jupyter notebook, while it continues running in the background, and come back to it later. What I often do, when I want to leave something calculating overnight, is converting it to python by typing jupyter-nbconvert --to script <name>.ipynb. Now, simply run the .py, detach from the tmux session and come back the next day to look at the output. If someone knows a better way, please leave a comment, I’d be thrilled to know." }, { "code": null, "e": 2526, "s": 2474, "text": "Here are some other very useful shortcuts for tmux:" }, { "code": null, "e": 3679, "s": 2526, "text": "# session managementtmux ls (or tmux list-sessions)tmux new -s session-nameCtrl-b d Detach from sessiontmux attach -t [session name]tmux kill-session -t session-nameCtrl-b c Create new windowCtrl-b d Detach current clientCtrl-b l Move to previously selected windowCtrl-b n Move to the next windowCtrl-b p Move to the previous windowCtrl-b & Kill the current windowCtrl-b , Rename the current windowCtrl-b q Show pane numbers (used to switch between panes)Ctrl-b o Switch to the next paneCtrl-b ? List all keybindings# moving between windowsCtrl-b n (Move to the next window)Ctrl-b p (Move to the previous window)Ctrl-b l (Move to the previously selected window)Ctrl-b w (List all windows / window numbers)Ctrl-b window number (Move to the specified window number, thedefault bindings are from 0 -- 9)# Tiling commandsCtrl-b % (Split the window vertically)CTRL-b \" (Split window horizontally)Ctrl-b o (Goto next pane)Ctrl-b q (Show pane numbers, when the numbers show up type the key to go to that pane)Ctrl-b { (Move the current pane left)Ctrl-b } (Move the current pane right)Ctrl-b x kill current pane# Make a pane its own windowCtrl-b : \"break-pane\"" }, { "code": null, "e": 3816, "s": 3679, "text": "Another useful hint: If you use hyperdash you can track on your phone how your model is doing without having to log in to your computer:" }, { "code": null, "e": 3862, "s": 3816, "text": "hyperdash run -n \"DQN Breakout\" python DQN.py" } ]
How To Tag Any Image Using Deep Learning | by Tyler Folkman | Towards Data Science
You probably have photos, right? You probably want those photos tagged automatically for you, right? But you also don’t want to write a ton of code to do so. Read on to learn how to use deep learning and Pytorch to tag any photo with less than 60 lines of code. The best part is, you’ll only have to change about 3 lines of code to get it to work for your own images! An extremely common machine learning problem is to classify or tag an image. Image classification is when you have a predefined set of classes for which you want to assign images. Let’s say you work at a Zoo and are always forgetting the names of all the monkey species. It would be great if you had a way to automatically classify various pictures of monkeys with the appropriate species. Why monkeys, you ask? Because there is an available dataset on Kaggle. :) This dataset contains about 1,400 images of 10 different species of monkeys. Here is a picture of the white-headed capuchin: And one of the patas monkey: Having data is key. For your own problem, make sure you have some images that are already tagged. My recommendation would be to get at least 50 tagged images per class. Once you have your images, let’s get them organized correctly. You will need to create two folders: “training” and “validation”. Your photos in the training folder will be used to train our deep learning model. The validation photos will be used to make sure our model is tuned well. Within each folder, make a folder for each tag you have. For our monkeys, we have 10 tags, we will call them n0-n9. Thus, our folder structure looks like this: └── training ├── n0 ├── n1 ├── n2 ├── n3 ├── n4 ├── n5 ├── n6 ├── n7 ├── n8 └── n9└── validation ├── n0 ├── n1 ├── n2 ├── n3 ├── n4 ├── n5 ├── n6 ├── n7 ├── n8 └── n9 Then, place the appropriate images within each folder. Maybe put 70% of your tagged images in training, 20% in validation, and leave 10% out for testing. We will also maintain a mapping from n0-n9 to the actual species names, so we don’t forget: Label, Latin Name , Common Name n0 , alouatta_palliata , mantled_howler n1 , erythrocebus_patas , patas_monkey n2 , cacajao_calvus , bald_uakari n3 , macaca_fuscata , japanese_macaque n4 , cebuella_pygmea , pygmy_marmoset n5 , cebus_capucinus , white_headed_capuchin n6 , mico_argentatus , silvery_marmoset n7 , saimiri_sciureus , common_squirrel_monkey n8 , aotus_nigriceps , black_headed_night_monkey n9 , trachypithecus_johnii , nilgiri_langur An extremely popular neural network architecture for tagging images is ResNet-50. It does a good job balancing accuracy and complexity. I won’t go into depth on this deep learning model, but you can learn more here. For our purposes, just know its a really good model for image classification and you should be able to train it in a reasonable time if you have access to a GPU. If you don’t, take a look at Google Colab to get access to free GPU resources. One of the tricks we will use when training our model will be to use the idea of fine-tuning to hopefully be able to learn how to accurately tag with only a few examples. Fine-tuning starts our model with weights already trained on another dataset. We then further tune the weights using our own data. A very common dataset to use as the starting point for fine-tuning is the ImageNet dataset. This dataset originally contained about 1 million images and 1,000 classes or tags. The breadth of image tags tends to make it a good dataset for fine-tuning. Besides fine-tuning, there are other tricks we can apply to help our deep learning model train well on our data. For example, using a learning rate finder to pick the best learning rate. Implementing all these best practices and keeping track of all the training steps can lead to a lot of code. To avoid all of this boilerplate, we are going to use Pytorch Lightning. I love this library. I find it really helps me to organize my Pytorch code well and avoid dumb mistakes such as forgetting to zero out my gradients. We will use Pytorch Lightning by writing a class that implements the LightningModule. Here is the bulk of our code and then we’ll walk you through it: class ImagenetTransferLearning(LightningModule): def __init__(self, hparams): super().__init__() # init a pretrained resnet self.hparams = hparams self.classifier = models.resnet50(pretrained=True) num_ftrs = self.classifier.fc.in_features self.classifier.fc = nn.Linear(num_ftrs, self.hparams.num_target_classes) def forward(self, x): return self.classifier(x) def training_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) tensorboard_logs = {'train_loss': loss} return {'loss': loss, 'log': tensorboard_logs} def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.hparams.lr) def train_dataloader(self): train_transforms = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = datasets.ImageFolder(self.hparams.train_dir, train_transforms) loader = data.DataLoader(dataset, batch_size=self.hparams.batch_size, num_workers=4, shuffle=True) return loader def validation_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) tensorboard_logs = {'val_loss': loss} return {'val_loss': loss, 'log': tensorboard_logs} def validation_epoch_end(self, outputs): avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean() tensorboard_logs = {'val_loss': avg_loss} return {'val_loss': avg_loss, 'log': tensorboard_logs} def val_dataloader(self): val_transforms = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = datasets.ImageFolder(self.hparams.val_dir, val_transforms) loader = data.DataLoader(dataset, batch_size=self.hparams.batch_size, num_workers=4) return loader The first function we define is init(). This is the function we use to initialize our model. We start with the pre-trained Resnet50 from Pytorch and modify it slightly so that it predicts the appropriate number of classes. The number of classes or tags you want to predict is passed as part of hparams as num_target_classes. Next, we have the forward() function. This one is simple, we just pass the input passed to it through our network. Then we have the training_step() function. This function takes two inputs — the batch and the batch index. Within the function, all we need to define is what we want to happen during each training step. For this model, it is very simple. We pass the data through self() which is our neural network and then calculate the cross-entropy as our loss. For this function, it is standard to return a dictionary with the calculated loss as well as a log variable for Tensorboard. One of the great benefits of Pytorch Lightning is that if you do this, you get Tensorboard logging for basically free, which is super nice! The configure_optimizers() function is used to define your optimizer. We will use the Adam optimizer and pass the learning rate via our hparams. Lastly, for training, you have the train_dataloader() function. This is the function that takes care of loading your training data and passing it to your training step. We make sure to define our transforms to size the images and scale them in the same way our Resnet was pre-trained. We also apply some data augmentation with RandomResizedCrop() and RandomHorizontalFlip(). I then load the data with Pytorch’s ImageFolder() function. This function loads images from a folder as long as the folder follows the structure we defined previously. The data is passed to a DataLoader() which is what Pytorch uses to actually load the data. Within this function, we can define items such as the batch_size. We pass the batch_size as a hyper-parameter via hparams. Since we also have validation data, we can define the exact same functions except they are not for the validation data: validation_step() and val_dataloader(). These functions are very similar. Some of the differences are we no longer do data augmentation and our step returns val_loss. The validation section also has an additional function: validation_epoch_end(). This defines what should be done with the validation results at the end of an epoch. We just simply return the average validation loss. You can also do this for the training step as well if you wish. Now that we have done the heavy lifting of defining all the necessary steps, we can sit back and let Pytorch Lightning do it’s magic. First, let’s define our hyper-parameters (Pytorch Lightning expects it as an argparse Namespace): hparams = Namespace(train_dir = <PATH TO YOUR TRAINING DIRECTORY>, val_dir = <PATH TO YOUR VALIDATION DIRECTORY>, num_target_classes = <NUMBER OF TAGS/CLASSES>, lr = 0.001, batch_size=8) I set the batch size pretty small to work with pretty much any GPU. Next, we initialize our model and train! model = ImagenetTransferLearning(hparams)trainer = Trainer(gpus=1, early_stop_checkpoint=True, auto_lr_find=True, max_epochs=50 ) The Trainer() is where the real magic happens. First, we tell it how many GPUs to train on, then we let it know to stop training early if the val_loss doesn’t improve, and one of the coolest options is auto_lr_finder. This tells the trainer to use an algorithm to find the best learning rate for our model and data and then use that rate instead of the rate we specified. Note: this only works if you pass hparams to your model and there is a lr value within your hparams. Lastly, to avoid running for too long we set the max_epochs to 50. If you’ve done much deep learning you can appreciate the cleanliness of our Trainer(). We didn’t have to write a single loop over our data, its all taken care of for us. If we moved our code over to a machine with 8 GPUs, all we have to do is change gpus to 8. That’s it. If we got access to TPUs, Pytorch Lightning also supports those and you just turn on the option. At some point, you should definitely check out the docs on all the great options the Trainer() provides. So — how well did our model do at tagging monkeys? Pytorch Lightning automatically checkpoints the model with the best validation results, which for me, happened at epoch 26. I loaded up that model with this code: model = ImagenetTransferLearning.load_from_checkpoint(<PATH TO MODEL>) And with this code, made predictions on all my validation data: model.eval()val_outs = []truth_outs = []for val_batch in tqdm(model.val_dataloader()): x, y = val_batch truth_outs.extend(y.numpy().tolist()) val_out = model(x) val_outs.extend(val_out.detach().numpy().argmax(1).tolist()) Here is my classification report (using scikit-learn): precision recall f1-score support 0 0.89 0.92 0.91 26 1 0.93 0.89 0.91 28 2 1.00 0.93 0.96 27 3 0.97 0.93 0.95 30 4 1.00 0.88 0.94 26 5 1.00 1.00 1.00 28 6 1.00 1.00 1.00 26 7 1.00 0.96 0.98 28 8 0.93 1.00 0.96 27 9 0.84 1.00 0.91 26 micro avg 0.95 0.95 0.95 272 macro avg 0.96 0.95 0.95 272weighted avg 0.96 0.95 0.95 272 Not bad! I was able to average a 0.95 f1-score and my lowest f1-score for a class was 0.91. These are validation results, though, so they are very likely to be optimistic. To get a better representation of how well our model does we need to predict on images not in the training nor validation sets. I didn’t take the time to create an entire test set, but I did grab 2 random images from Google of monkeys. In fact, those images are the 2 images at the top of this post. And our model was able to predict them both correctly! Also, here are the Tensorboard graphs for the training: It’s safe to say that we are now, thanks to our deep learning model, experts on monkey species. :) The beautiful part is you can now easily go and classify any images you want. All you have to do is tag some of your own images, organize them appropriately (as discussed above), and change 3 lines of code. hparams = Namespace(train_dir = <PATH TO YOUR TRAINING DIRECTORY>, val_dir = <PATH TO YOUR VALIDATION DIRECTORY>, num_target_classes = <NUMBER OF TAGS/CLASSES>, lr = 0.001, batch_size=8) The only 3 lines you need to update are the values for train_dir, val_dir, and num_target_classes. That’s it! So — go do it for yourself and let me know what cool things you classify! Get your FREE copy of 11 INCREDIBLY useful resources to MASTER data science
[ { "code": null, "e": 205, "s": 172, "text": "You probably have photos, right?" }, { "code": null, "e": 273, "s": 205, "text": "You probably want those photos tagged automatically for you, right?" }, { "code": null, "e": 330, "s": 273, "text": "But you also don’t want to write a ton of code to do so." }, { "code": null, "e": 540, "s": 330, "text": "Read on to learn how to use deep learning and Pytorch to tag any photo with less than 60 lines of code. The best part is, you’ll only have to change about 3 lines of code to get it to work for your own images!" }, { "code": null, "e": 720, "s": 540, "text": "An extremely common machine learning problem is to classify or tag an image. Image classification is when you have a predefined set of classes for which you want to assign images." }, { "code": null, "e": 930, "s": 720, "text": "Let’s say you work at a Zoo and are always forgetting the names of all the monkey species. It would be great if you had a way to automatically classify various pictures of monkeys with the appropriate species." }, { "code": null, "e": 1129, "s": 930, "text": "Why monkeys, you ask? Because there is an available dataset on Kaggle. :) This dataset contains about 1,400 images of 10 different species of monkeys. Here is a picture of the white-headed capuchin:" }, { "code": null, "e": 1158, "s": 1129, "text": "And one of the patas monkey:" }, { "code": null, "e": 1327, "s": 1158, "text": "Having data is key. For your own problem, make sure you have some images that are already tagged. My recommendation would be to get at least 50 tagged images per class." }, { "code": null, "e": 1611, "s": 1327, "text": "Once you have your images, let’s get them organized correctly. You will need to create two folders: “training” and “validation”. Your photos in the training folder will be used to train our deep learning model. The validation photos will be used to make sure our model is tuned well." }, { "code": null, "e": 1771, "s": 1611, "text": "Within each folder, make a folder for each tag you have. For our monkeys, we have 10 tags, we will call them n0-n9. Thus, our folder structure looks like this:" }, { "code": null, "e": 1998, "s": 1771, "text": "└── training ├── n0 ├── n1 ├── n2 ├── n3 ├── n4 ├── n5 ├── n6 ├── n7 ├── n8 └── n9└── validation ├── n0 ├── n1 ├── n2 ├── n3 ├── n4 ├── n5 ├── n6 ├── n7 ├── n8 └── n9" }, { "code": null, "e": 2152, "s": 1998, "text": "Then, place the appropriate images within each folder. Maybe put 70% of your tagged images in training, 20% in validation, and leave 10% out for testing." }, { "code": null, "e": 2244, "s": 2152, "text": "We will also maintain a mapping from n0-n9 to the actual species names, so we don’t forget:" }, { "code": null, "e": 2884, "s": 2244, "text": "Label, Latin Name , Common Name n0 , alouatta_palliata , mantled_howler n1 , erythrocebus_patas , patas_monkey n2 , cacajao_calvus\t , bald_uakari n3 , macaca_fuscata\t , japanese_macaque n4 , cebuella_pygmea\t , pygmy_marmoset n5 , cebus_capucinus\t , white_headed_capuchin n6 , mico_argentatus\t , silvery_marmoset n7 , saimiri_sciureus\t , common_squirrel_monkey n8 , aotus_nigriceps\t , black_headed_night_monkey n9 , trachypithecus_johnii , nilgiri_langur" }, { "code": null, "e": 3341, "s": 2884, "text": "An extremely popular neural network architecture for tagging images is ResNet-50. It does a good job balancing accuracy and complexity. I won’t go into depth on this deep learning model, but you can learn more here. For our purposes, just know its a really good model for image classification and you should be able to train it in a reasonable time if you have access to a GPU. If you don’t, take a look at Google Colab to get access to free GPU resources." }, { "code": null, "e": 3512, "s": 3341, "text": "One of the tricks we will use when training our model will be to use the idea of fine-tuning to hopefully be able to learn how to accurately tag with only a few examples." }, { "code": null, "e": 3894, "s": 3512, "text": "Fine-tuning starts our model with weights already trained on another dataset. We then further tune the weights using our own data. A very common dataset to use as the starting point for fine-tuning is the ImageNet dataset. This dataset originally contained about 1 million images and 1,000 classes or tags. The breadth of image tags tends to make it a good dataset for fine-tuning." }, { "code": null, "e": 4081, "s": 3894, "text": "Besides fine-tuning, there are other tricks we can apply to help our deep learning model train well on our data. For example, using a learning rate finder to pick the best learning rate." }, { "code": null, "e": 4412, "s": 4081, "text": "Implementing all these best practices and keeping track of all the training steps can lead to a lot of code. To avoid all of this boilerplate, we are going to use Pytorch Lightning. I love this library. I find it really helps me to organize my Pytorch code well and avoid dumb mistakes such as forgetting to zero out my gradients." }, { "code": null, "e": 4563, "s": 4412, "text": "We will use Pytorch Lightning by writing a class that implements the LightningModule. Here is the bulk of our code and then we’ll walk you through it:" }, { "code": null, "e": 6741, "s": 4563, "text": "class ImagenetTransferLearning(LightningModule): def __init__(self, hparams): super().__init__() # init a pretrained resnet self.hparams = hparams self.classifier = models.resnet50(pretrained=True) num_ftrs = self.classifier.fc.in_features self.classifier.fc = nn.Linear(num_ftrs, self.hparams.num_target_classes) def forward(self, x): return self.classifier(x) def training_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) tensorboard_logs = {'train_loss': loss} return {'loss': loss, 'log': tensorboard_logs} def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.hparams.lr) def train_dataloader(self): train_transforms = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = datasets.ImageFolder(self.hparams.train_dir, train_transforms) loader = data.DataLoader(dataset, batch_size=self.hparams.batch_size, num_workers=4, shuffle=True) return loader def validation_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) tensorboard_logs = {'val_loss': loss} return {'val_loss': loss, 'log': tensorboard_logs} def validation_epoch_end(self, outputs): avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean() tensorboard_logs = {'val_loss': avg_loss} return {'val_loss': avg_loss, 'log': tensorboard_logs} def val_dataloader(self): val_transforms = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = datasets.ImageFolder(self.hparams.val_dir, val_transforms) loader = data.DataLoader(dataset, batch_size=self.hparams.batch_size, num_workers=4) return loader" }, { "code": null, "e": 7066, "s": 6741, "text": "The first function we define is init(). This is the function we use to initialize our model. We start with the pre-trained Resnet50 from Pytorch and modify it slightly so that it predicts the appropriate number of classes. The number of classes or tags you want to predict is passed as part of hparams as num_target_classes." }, { "code": null, "e": 7181, "s": 7066, "text": "Next, we have the forward() function. This one is simple, we just pass the input passed to it through our network." }, { "code": null, "e": 7794, "s": 7181, "text": "Then we have the training_step() function. This function takes two inputs — the batch and the batch index. Within the function, all we need to define is what we want to happen during each training step. For this model, it is very simple. We pass the data through self() which is our neural network and then calculate the cross-entropy as our loss. For this function, it is standard to return a dictionary with the calculated loss as well as a log variable for Tensorboard. One of the great benefits of Pytorch Lightning is that if you do this, you get Tensorboard logging for basically free, which is super nice!" }, { "code": null, "e": 7939, "s": 7794, "text": "The configure_optimizers() function is used to define your optimizer. We will use the Adam optimizer and pass the learning rate via our hparams." }, { "code": null, "e": 8696, "s": 7939, "text": "Lastly, for training, you have the train_dataloader() function. This is the function that takes care of loading your training data and passing it to your training step. We make sure to define our transforms to size the images and scale them in the same way our Resnet was pre-trained. We also apply some data augmentation with RandomResizedCrop() and RandomHorizontalFlip(). I then load the data with Pytorch’s ImageFolder() function. This function loads images from a folder as long as the folder follows the structure we defined previously. The data is passed to a DataLoader() which is what Pytorch uses to actually load the data. Within this function, we can define items such as the batch_size. We pass the batch_size as a hyper-parameter via hparams." }, { "code": null, "e": 8983, "s": 8696, "text": "Since we also have validation data, we can define the exact same functions except they are not for the validation data: validation_step() and val_dataloader(). These functions are very similar. Some of the differences are we no longer do data augmentation and our step returns val_loss." }, { "code": null, "e": 9263, "s": 8983, "text": "The validation section also has an additional function: validation_epoch_end(). This defines what should be done with the validation results at the end of an epoch. We just simply return the average validation loss. You can also do this for the training step as well if you wish." }, { "code": null, "e": 9495, "s": 9263, "text": "Now that we have done the heavy lifting of defining all the necessary steps, we can sit back and let Pytorch Lightning do it’s magic. First, let’s define our hyper-parameters (Pytorch Lightning expects it as an argparse Namespace):" }, { "code": null, "e": 9754, "s": 9495, "text": "hparams = Namespace(train_dir = <PATH TO YOUR TRAINING DIRECTORY>, val_dir = <PATH TO YOUR VALIDATION DIRECTORY>, num_target_classes = <NUMBER OF TAGS/CLASSES>, lr = 0.001, batch_size=8)" }, { "code": null, "e": 9822, "s": 9754, "text": "I set the batch size pretty small to work with pretty much any GPU." }, { "code": null, "e": 9863, "s": 9822, "text": "Next, we initialize our model and train!" }, { "code": null, "e": 10060, "s": 9863, "text": "model = ImagenetTransferLearning(hparams)trainer = Trainer(gpus=1, early_stop_checkpoint=True, auto_lr_find=True, max_epochs=50 )" }, { "code": null, "e": 10600, "s": 10060, "text": "The Trainer() is where the real magic happens. First, we tell it how many GPUs to train on, then we let it know to stop training early if the val_loss doesn’t improve, and one of the coolest options is auto_lr_finder. This tells the trainer to use an algorithm to find the best learning rate for our model and data and then use that rate instead of the rate we specified. Note: this only works if you pass hparams to your model and there is a lr value within your hparams. Lastly, to avoid running for too long we set the max_epochs to 50." }, { "code": null, "e": 11074, "s": 10600, "text": "If you’ve done much deep learning you can appreciate the cleanliness of our Trainer(). We didn’t have to write a single loop over our data, its all taken care of for us. If we moved our code over to a machine with 8 GPUs, all we have to do is change gpus to 8. That’s it. If we got access to TPUs, Pytorch Lightning also supports those and you just turn on the option. At some point, you should definitely check out the docs on all the great options the Trainer() provides." }, { "code": null, "e": 11288, "s": 11074, "text": "So — how well did our model do at tagging monkeys? Pytorch Lightning automatically checkpoints the model with the best validation results, which for me, happened at epoch 26. I loaded up that model with this code:" }, { "code": null, "e": 11359, "s": 11288, "text": "model = ImagenetTransferLearning.load_from_checkpoint(<PATH TO MODEL>)" }, { "code": null, "e": 11423, "s": 11359, "text": "And with this code, made predictions on all my validation data:" }, { "code": null, "e": 11657, "s": 11423, "text": "model.eval()val_outs = []truth_outs = []for val_batch in tqdm(model.val_dataloader()): x, y = val_batch truth_outs.extend(y.numpy().tolist()) val_out = model(x) val_outs.extend(val_out.detach().numpy().argmax(1).tolist())" }, { "code": null, "e": 11712, "s": 11657, "text": "Here is my classification report (using scikit-learn):" }, { "code": null, "e": 12441, "s": 11712, "text": "precision recall f1-score support 0 0.89 0.92 0.91 26 1 0.93 0.89 0.91 28 2 1.00 0.93 0.96 27 3 0.97 0.93 0.95 30 4 1.00 0.88 0.94 26 5 1.00 1.00 1.00 28 6 1.00 1.00 1.00 26 7 1.00 0.96 0.98 28 8 0.93 1.00 0.96 27 9 0.84 1.00 0.91 26 micro avg 0.95 0.95 0.95 272 macro avg 0.96 0.95 0.95 272weighted avg 0.96 0.95 0.95 272" }, { "code": null, "e": 12533, "s": 12441, "text": "Not bad! I was able to average a 0.95 f1-score and my lowest f1-score for a class was 0.91." }, { "code": null, "e": 12741, "s": 12533, "text": "These are validation results, though, so they are very likely to be optimistic. To get a better representation of how well our model does we need to predict on images not in the training nor validation sets." }, { "code": null, "e": 12968, "s": 12741, "text": "I didn’t take the time to create an entire test set, but I did grab 2 random images from Google of monkeys. In fact, those images are the 2 images at the top of this post. And our model was able to predict them both correctly!" }, { "code": null, "e": 13024, "s": 12968, "text": "Also, here are the Tensorboard graphs for the training:" }, { "code": null, "e": 13123, "s": 13024, "text": "It’s safe to say that we are now, thanks to our deep learning model, experts on monkey species. :)" }, { "code": null, "e": 13330, "s": 13123, "text": "The beautiful part is you can now easily go and classify any images you want. All you have to do is tag some of your own images, organize them appropriately (as discussed above), and change 3 lines of code." }, { "code": null, "e": 13589, "s": 13330, "text": "hparams = Namespace(train_dir = <PATH TO YOUR TRAINING DIRECTORY>, val_dir = <PATH TO YOUR VALIDATION DIRECTORY>, num_target_classes = <NUMBER OF TAGS/CLASSES>, lr = 0.001, batch_size=8)" }, { "code": null, "e": 13773, "s": 13589, "text": "The only 3 lines you need to update are the values for train_dir, val_dir, and num_target_classes. That’s it! So — go do it for yourself and let me know what cool things you classify!" } ]
How to Extract Text from PDF. Learn to use Python to extract text... | by Costas Andreou | Towards Data Science
In this blog, we are going to examine the most popular libraries for processing PDFs with Python. A lot of information is shared in the form of PDF, and often we need to extract some details for further processing. To assist it in my research in identifying the most popular python libraries, I looked across StackOverflow, Reddit and generally lots of google searches. I identified numerous packages, each with its own strengths and weakness. Specifically, users across the internet seem to be using: PyPDF2, Textract, tika, pdfPlumber, pdfMiner. During my research, however, for one reason or another, I was only able to get 3 of these libraries to work as expected. For some of these libraries, the set up was too complicated (missing dependencies, strange error messages, etc.) Let us quickly review all these libraries anyway. The good news with PyPDF2 was that it was a breeze to install. The documentation is somewhat lacking easy examples to follow, but pay close enough attention, and you can figure it out eventually. The bad news, however, is that the results were not great. As you can see, it identified the right text, but for some reason, it broke it up into multiple lines. The code: import PyPDF2fhandle = open(r'D:\examplepdf.pdf', 'rb')pdfReader = PyPDF2.PdfFileReader(fhandle)pagehandle = pdfReader.getPage(0)print(pagehandle.extractText()) Off to a promising start with the number of people raving about this library. The documentation is also good. Unfortunately, the latest version has a bug which throws an error every time you try to extract text from a PDF. Following the bug through the library’s dev forum, there may be a fix in the works. Fingers crossed. Apache Tika has a python library which apparently lets you extract text from PDFs. Installing the Python library is simple enough, but it will not work unless you have JAVA installed. At least that is the theory. I did not want to install JAVA; hence I remained at: “RuntimeError: Unable to start Tika server.” error. According to this medium blog (no affiliation), however, once you get it working, it is terrific. So, let’s go with 2/5 rating. The code would apparently look something like: from tika import parserfile = r'D:\examplepdf.pdf'file_data = parser.from_file(file)text = file_data['content']print(text) Right when I started losing faith in the existence of a simple to use python library for mining text out of pdfs, across comes pdfPlumber. The documentation is not too bad; within minutes, the whole thing gets going. The results are as good as they can be. Worth noting, however, that the library does specifically say that it works best on machine-generated PDFs rather than scanned documents; which is what I used. The code: import pdfplumberwith pdfplumber.open(r'D:\examplepdf.pdf') as pdf: first_page = pdf.pages[0] print(first_page.extract_text()) I will be honest; in a typical pythonic way, I glanced at the documentation (twice!) and failed to understand how I was meant to run this package; this includes pdfMiner (not version 3 that I am reviewing here, as well). I even installed it and tried a few things with no success. Alas, to my rescue comes a kind stranger in StackOverflow. Once you go through the example provided, it is actually easy to follow. Oh, and the results are as good as you would expect: The code can be found in the linked StackOverflow post. Another way that this problem could be addressed is by transforming the PDF file into an image. This could be done either programmatically or by taking a screenshot of each page. Once you have the image files, you can use the tesseract library to extract the text out of them: towardsdatascience.com Before you go, if you liked this article, you may also like:
[ { "code": null, "e": 387, "s": 172, "text": "In this blog, we are going to examine the most popular libraries for processing PDFs with Python. A lot of information is shared in the form of PDF, and often we need to extract some details for further processing." }, { "code": null, "e": 720, "s": 387, "text": "To assist it in my research in identifying the most popular python libraries, I looked across StackOverflow, Reddit and generally lots of google searches. I identified numerous packages, each with its own strengths and weakness. Specifically, users across the internet seem to be using: PyPDF2, Textract, tika, pdfPlumber, pdfMiner." }, { "code": null, "e": 954, "s": 720, "text": "During my research, however, for one reason or another, I was only able to get 3 of these libraries to work as expected. For some of these libraries, the set up was too complicated (missing dependencies, strange error messages, etc.)" }, { "code": null, "e": 1004, "s": 954, "text": "Let us quickly review all these libraries anyway." }, { "code": null, "e": 1200, "s": 1004, "text": "The good news with PyPDF2 was that it was a breeze to install. The documentation is somewhat lacking easy examples to follow, but pay close enough attention, and you can figure it out eventually." }, { "code": null, "e": 1259, "s": 1200, "text": "The bad news, however, is that the results were not great." }, { "code": null, "e": 1362, "s": 1259, "text": "As you can see, it identified the right text, but for some reason, it broke it up into multiple lines." }, { "code": null, "e": 1372, "s": 1362, "text": "The code:" }, { "code": null, "e": 1533, "s": 1372, "text": "import PyPDF2fhandle = open(r'D:\\examplepdf.pdf', 'rb')pdfReader = PyPDF2.PdfFileReader(fhandle)pagehandle = pdfReader.getPage(0)print(pagehandle.extractText())" }, { "code": null, "e": 1643, "s": 1533, "text": "Off to a promising start with the number of people raving about this library. The documentation is also good." }, { "code": null, "e": 1857, "s": 1643, "text": "Unfortunately, the latest version has a bug which throws an error every time you try to extract text from a PDF. Following the bug through the library’s dev forum, there may be a fix in the works. Fingers crossed." }, { "code": null, "e": 2041, "s": 1857, "text": "Apache Tika has a python library which apparently lets you extract text from PDFs. Installing the Python library is simple enough, but it will not work unless you have JAVA installed." }, { "code": null, "e": 2175, "s": 2041, "text": "At least that is the theory. I did not want to install JAVA; hence I remained at: “RuntimeError: Unable to start Tika server.” error." }, { "code": null, "e": 2303, "s": 2175, "text": "According to this medium blog (no affiliation), however, once you get it working, it is terrific. So, let’s go with 2/5 rating." }, { "code": null, "e": 2350, "s": 2303, "text": "The code would apparently look something like:" }, { "code": null, "e": 2473, "s": 2350, "text": "from tika import parserfile = r'D:\\examplepdf.pdf'file_data = parser.from_file(file)text = file_data['content']print(text)" }, { "code": null, "e": 2612, "s": 2473, "text": "Right when I started losing faith in the existence of a simple to use python library for mining text out of pdfs, across comes pdfPlumber." }, { "code": null, "e": 2730, "s": 2612, "text": "The documentation is not too bad; within minutes, the whole thing gets going. The results are as good as they can be." }, { "code": null, "e": 2890, "s": 2730, "text": "Worth noting, however, that the library does specifically say that it works best on machine-generated PDFs rather than scanned documents; which is what I used." }, { "code": null, "e": 2900, "s": 2890, "text": "The code:" }, { "code": null, "e": 3033, "s": 2900, "text": "import pdfplumberwith pdfplumber.open(r'D:\\examplepdf.pdf') as pdf: first_page = pdf.pages[0] print(first_page.extract_text())" }, { "code": null, "e": 3314, "s": 3033, "text": "I will be honest; in a typical pythonic way, I glanced at the documentation (twice!) and failed to understand how I was meant to run this package; this includes pdfMiner (not version 3 that I am reviewing here, as well). I even installed it and tried a few things with no success." }, { "code": null, "e": 3499, "s": 3314, "text": "Alas, to my rescue comes a kind stranger in StackOverflow. Once you go through the example provided, it is actually easy to follow. Oh, and the results are as good as you would expect:" }, { "code": null, "e": 3555, "s": 3499, "text": "The code can be found in the linked StackOverflow post." }, { "code": null, "e": 3734, "s": 3555, "text": "Another way that this problem could be addressed is by transforming the PDF file into an image. This could be done either programmatically or by taking a screenshot of each page." }, { "code": null, "e": 3832, "s": 3734, "text": "Once you have the image files, you can use the tesseract library to extract the text out of them:" }, { "code": null, "e": 3855, "s": 3832, "text": "towardsdatascience.com" } ]
How to Install PyGTK in Python on MacOS? - GeeksforGeeks
22 Nov, 2021 PyGTK is a Python package or module that enables developers to work with GTK+ GUI Toolkit. This is how WikiBooks describes GTK+: “GTK+ is a highly usable, feature rich toolkit for creating graphical user interfaces which boasts cross platform compatibility and an easy to use API.” And this is how gtk.org the official website of GTK markets it: Offering a complete set of UI elements, GTK is suitable for projects ranging from small one-off tools to complete application suites. Although Python comes with a built-in module called Tkinter which is used to make simple GUI applications. But many developers are unsatisfied by the appearance of the application made by it and it is not even feature-rich so as to help in making elaborate software. Therefore GTK+ in association with Python is considered to be a great alternative to Tkinter. Although the GTK library supports many programming languages such as C, JavaScript, Perl, Rust, and Vala. But it is most widely used in association with Python which employs a language wrapper to fully utilize the capabilities of the official GNOME binding to produce the most stable applications. GTK library comes jam-packed with features that enable developers to do whatever they want. Here are some of the main selling points of GTK. Portability Stability Language Binging Interfaces OpenSource API Accommodation Foundations Listing some of the famous applications which are made by this GTK are as follows: GIMP Transmission Evolution Polati Games of all sorts Etc. Below we will go through all the steps to install PyGTK in the macOS operating system in detail. Step 1: Install Python Although Python comes pre-installed in most macOS, however, it should be upgraded for the best performance or better saying to avoid unwanted errors. To check if Python is already installed in the system or not open the Terminal app and run the command below: python --version If the above command does not return any version number then, it means that Python is not pre-installed and if it returned any number such as 3. N.N then you may check if an upgrade is available or not. To see the full guide for the Python installation on macOS visit here. Step 2: Install HomeBrew Homebrew is open-source software that facilitated the management of packages in Mac and Linux-based operating systems. It basically gives developers the power to install, remove, upgrade, downgrade, etc a package from the terminal itself. To install Homebrew in our system we only need to run a simple command in the terminal that is given below: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" Once the above command gets executed you can check if it has been installed correctly by running the below command: brew help If it returns any output then our work is done properly, if not then re-installed homebrew using the above command. Step 3: Install GTK+ Now the last thing to do is to install GTK+ collection libraries in our system to later include this in Python projects. Since we have installed Homebrew in the previous step this step is going to be a breeze. All that is needed is the execution of the below command: brew install gtk+ Once this process is done all you need is a quick reboot of the system and you should be ready to roll a new Python project with PyGTK in it. Although there is no quick way to find out GTK+ has been installed properly or not but you will surely find out while working with it. But one thing that we can do to be sure of that to run the same installation command again. What it will do is first it will check if the program is already installed or not. If it is not installed already then it will start the installation but now that we have installed it should return a warning. As we can see in the above image we get a warning that gtk+ is already installed, so that is our confirmation of the same. One other thing that one might do is, issue a command to check the version of gtk package. The command is given below. gtk-launch --version So with everything set now, you are ready to roll a project! how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 24561, "s": 24533, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24690, "s": 24561, "text": "PyGTK is a Python package or module that enables developers to work with GTK+ GUI Toolkit. This is how WikiBooks describes GTK+:" }, { "code": null, "e": 24843, "s": 24690, "text": "“GTK+ is a highly usable, feature rich toolkit for creating graphical user interfaces which boasts cross platform compatibility and an easy to use API.”" }, { "code": null, "e": 24907, "s": 24843, "text": "And this is how gtk.org the official website of GTK markets it:" }, { "code": null, "e": 25041, "s": 24907, "text": "Offering a complete set of UI elements, GTK is suitable for projects ranging from small one-off tools to complete application suites." }, { "code": null, "e": 25700, "s": 25041, "text": "Although Python comes with a built-in module called Tkinter which is used to make simple GUI applications. But many developers are unsatisfied by the appearance of the application made by it and it is not even feature-rich so as to help in making elaborate software. Therefore GTK+ in association with Python is considered to be a great alternative to Tkinter. Although the GTK library supports many programming languages such as C, JavaScript, Perl, Rust, and Vala. But it is most widely used in association with Python which employs a language wrapper to fully utilize the capabilities of the official GNOME binding to produce the most stable applications." }, { "code": null, "e": 25842, "s": 25700, "text": "GTK library comes jam-packed with features that enable developers to do whatever they want. Here are some of the main selling points of GTK." }, { "code": null, "e": 25854, "s": 25842, "text": "Portability" }, { "code": null, "e": 25864, "s": 25854, "text": "Stability" }, { "code": null, "e": 25881, "s": 25864, "text": "Language Binging" }, { "code": null, "e": 25892, "s": 25881, "text": "Interfaces" }, { "code": null, "e": 25903, "s": 25892, "text": "OpenSource" }, { "code": null, "e": 25907, "s": 25903, "text": "API" }, { "code": null, "e": 25921, "s": 25907, "text": "Accommodation" }, { "code": null, "e": 25933, "s": 25921, "text": "Foundations" }, { "code": null, "e": 26016, "s": 25933, "text": "Listing some of the famous applications which are made by this GTK are as follows:" }, { "code": null, "e": 26021, "s": 26016, "text": "GIMP" }, { "code": null, "e": 26034, "s": 26021, "text": "Transmission" }, { "code": null, "e": 26044, "s": 26034, "text": "Evolution" }, { "code": null, "e": 26051, "s": 26044, "text": "Polati" }, { "code": null, "e": 26070, "s": 26051, "text": "Games of all sorts" }, { "code": null, "e": 26075, "s": 26070, "text": "Etc." }, { "code": null, "e": 26172, "s": 26075, "text": "Below we will go through all the steps to install PyGTK in the macOS operating system in detail." }, { "code": null, "e": 26195, "s": 26172, "text": "Step 1: Install Python" }, { "code": null, "e": 26346, "s": 26195, "text": "Although Python comes pre-installed in most macOS, however, it should be upgraded for the best performance or better saying to avoid unwanted errors. " }, { "code": null, "e": 26456, "s": 26346, "text": "To check if Python is already installed in the system or not open the Terminal app and run the command below:" }, { "code": null, "e": 26473, "s": 26456, "text": "python --version" }, { "code": null, "e": 26747, "s": 26473, "text": "If the above command does not return any version number then, it means that Python is not pre-installed and if it returned any number such as 3. N.N then you may check if an upgrade is available or not. To see the full guide for the Python installation on macOS visit here." }, { "code": null, "e": 26772, "s": 26747, "text": "Step 2: Install HomeBrew" }, { "code": null, "e": 27012, "s": 26772, "text": "Homebrew is open-source software that facilitated the management of packages in Mac and Linux-based operating systems. It basically gives developers the power to install, remove, upgrade, downgrade, etc a package from the terminal itself." }, { "code": null, "e": 27120, "s": 27012, "text": "To install Homebrew in our system we only need to run a simple command in the terminal that is given below:" }, { "code": null, "e": 27216, "s": 27120, "text": "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"" }, { "code": null, "e": 27333, "s": 27216, "text": "Once the above command gets executed you can check if it has been installed correctly by running the below command: " }, { "code": null, "e": 27343, "s": 27333, "text": "brew help" }, { "code": null, "e": 27459, "s": 27343, "text": "If it returns any output then our work is done properly, if not then re-installed homebrew using the above command." }, { "code": null, "e": 27480, "s": 27459, "text": "Step 3: Install GTK+" }, { "code": null, "e": 27748, "s": 27480, "text": "Now the last thing to do is to install GTK+ collection libraries in our system to later include this in Python projects. Since we have installed Homebrew in the previous step this step is going to be a breeze. All that is needed is the execution of the below command:" }, { "code": null, "e": 27766, "s": 27748, "text": "brew install gtk+" }, { "code": null, "e": 28344, "s": 27766, "text": "Once this process is done all you need is a quick reboot of the system and you should be ready to roll a new Python project with PyGTK in it. Although there is no quick way to find out GTK+ has been installed properly or not but you will surely find out while working with it. But one thing that we can do to be sure of that to run the same installation command again. What it will do is first it will check if the program is already installed or not. If it is not installed already then it will start the installation but now that we have installed it should return a warning." }, { "code": null, "e": 28587, "s": 28344, "text": "As we can see in the above image we get a warning that gtk+ is already installed, so that is our confirmation of the same. One other thing that one might do is, issue a command to check the version of gtk package. The command is given below. " }, { "code": null, "e": 28608, "s": 28587, "text": "gtk-launch --version" }, { "code": null, "e": 28669, "s": 28608, "text": "So with everything set now, you are ready to roll a project!" }, { "code": null, "e": 28684, "s": 28669, "text": "how-to-install" }, { "code": null, "e": 28691, "s": 28684, "text": "Picked" }, { "code": null, "e": 28698, "s": 28691, "text": "How To" }, { "code": null, "e": 28717, "s": 28698, "text": "Installation Guide" }, { "code": null, "e": 28815, "s": 28717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28824, "s": 28815, "text": "Comments" }, { "code": null, "e": 28837, "s": 28824, "text": "Old Comments" }, { "code": null, "e": 28871, "s": 28837, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28920, "s": 28871, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 28978, "s": 28920, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29020, "s": 28978, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29080, "s": 29020, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29113, "s": 29080, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29147, "s": 29113, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29182, "s": 29147, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29240, "s": 29182, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
How to make a countdown timer in Android?
Before getting into an example, we should know what is a countdown timer in android. Count down timer as simple as we see in watches and mobile phones. we can set count down time after completion of time it will stop and get 0 values. There are four methods are available to use countdown timer as shown below - onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking. onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish(). start() - It is used to call countdown timer. cancel() - It is used to cancel countdown timer. This example demonstrates how to integrate countdown timer with textview. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:id="@+id/layout" android:gravity="center" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/counttime" android:layout_width="match_parent" android:gravity="center" android:textSize="30sp" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have declared a text view. it going to print countdown timer. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public int counter; @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView counttime=findViewById(R.id.counttime); new CountDownTimer(50000,1000) { @Override public void onTick(long millisUntilFinished) { counttime.setText(String.valueOf(counter)); counter++; } @Override public void onFinish() { counttime.setText("Finished"); } }.start(); } } In the above code, we have declare 50s and time interval is 1s. It going to print ms time in textview as shown onTick method and after done time intervals it will print the result as "Finished". Step 4 − No need to change manifest.xml Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above screen, it shows time counting points. After done counting time means 50 sec it will show the result as shown below- Click here to download the project code
[ { "code": null, "e": 1297, "s": 1062, "text": "Before getting into an example, we should know what is a countdown timer in android. Count down timer as simple as we see in watches and mobile phones. we can set count down time after completion of time it will stop and get 0 values." }, { "code": null, "e": 1374, "s": 1297, "text": "There are four methods are available to use countdown timer as shown below -" }, { "code": null, "e": 1507, "s": 1374, "text": "onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking." }, { "code": null, "e": 1612, "s": 1507, "text": "onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish()." }, { "code": null, "e": 1658, "s": 1612, "text": "start() - It is used to call countdown timer." }, { "code": null, "e": 1707, "s": 1658, "text": "cancel() - It is used to cancel countdown timer." }, { "code": null, "e": 1781, "s": 1707, "text": "This example demonstrates how to integrate countdown timer with textview." }, { "code": null, "e": 1910, "s": 1781, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1975, "s": 1910, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2469, "s": 1975, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:id=\"@+id/layout\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/counttime\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:textSize=\"30sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2553, "s": 2469, "text": "In the above code, we have declared a text view. it going to print countdown timer." }, { "code": null, "e": 2610, "s": 2553, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3638, "s": 2610, "text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.CountDownTimer;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RatingBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n public int counter;\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView counttime=findViewById(R.id.counttime);\n new CountDownTimer(50000,1000) {\n @Override\n public void onTick(long millisUntilFinished) {\n counttime.setText(String.valueOf(counter));\n counter++;\n }\n @Override\n public void onFinish() {\n counttime.setText(\"Finished\");\n }\n }.start();\n }\n}" }, { "code": null, "e": 3833, "s": 3638, "text": "In the above code, we have declare 50s and time interval is 1s. It going to print ms time in textview as shown onTick method and after done time intervals it will print the result as \"Finished\"." }, { "code": null, "e": 3873, "s": 3833, "text": "Step 4 − No need to change manifest.xml" }, { "code": null, "e": 4223, "s": 3873, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4353, "s": 4223, "text": "In the above screen, it shows time counting points. After done counting time means 50 sec it will show the result as shown below-" }, { "code": null, "e": 4393, "s": 4353, "text": "Click here to download the project code" } ]
Greatest number among three given numbers in PL/SQL - GeeksforGeeks
14 Aug, 2021 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given three numbers and the task is to find greatest among them. Examples: Input: a = 46, b = 67, c = 21 Output: 67 Input: a = 9887, b = 4554, c = 212 Output: 9887 Approach is to consider the first number and compare it with other two numbers. Similarly, check with second and third.Below is the required implementation: SQL --To find the greatest number-- among given three numbersDECLARE --a assigning with 46 a NUMBER := 46; --b assigning with 67 b NUMBER := 67; --c assigning with 21 c NUMBER := 21;BEGIN --block start --If condition start IF a > b AND a > c THEN --if a is greater then print a dbms_output.Put_line('Greatest number is ' ||a); ELSIF b > a AND b > c THEN --if b is greater then print b dbms_output.Put_line('Greatest number is ' ||b); ELSE --if c is greater then print c dbms_output.Put_line('Greatest number is ' ||c); END IF;--end if conditionEND;--End program Output: Greatest number is 67 sagar0719kumar SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between SQL and NoSQL What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL - ORDER BY
[ { "code": null, "e": 24340, "s": 24312, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24649, "s": 24340, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given three numbers and the task is to find greatest among them. " }, { "code": null, "e": 24661, "s": 24649, "text": "Examples: " }, { "code": null, "e": 24751, "s": 24661, "text": "Input: a = 46, b = 67, c = 21\nOutput: 67\n\nInput: a = 9887, b = 4554, c = 212\nOutput: 9887" }, { "code": null, "e": 24909, "s": 24751, "text": "Approach is to consider the first number and compare it with other two numbers. Similarly, check with second and third.Below is the required implementation: " }, { "code": null, "e": 24913, "s": 24909, "text": "SQL" }, { "code": "--To find the greatest number-- among given three numbersDECLARE --a assigning with 46 a NUMBER := 46; --b assigning with 67 b NUMBER := 67; --c assigning with 21 c NUMBER := 21;BEGIN --block start --If condition start IF a > b AND a > c THEN --if a is greater then print a dbms_output.Put_line('Greatest number is ' ||a); ELSIF b > a AND b > c THEN --if b is greater then print b dbms_output.Put_line('Greatest number is ' ||b); ELSE --if c is greater then print c dbms_output.Put_line('Greatest number is ' ||c); END IF;--end if conditionEND;--End program ", "e": 25631, "s": 24913, "text": null }, { "code": null, "e": 25639, "s": 25631, "text": "Output:" }, { "code": null, "e": 25661, "s": 25639, "text": "Greatest number is 67" }, { "code": null, "e": 25676, "s": 25661, "text": "sagar0719kumar" }, { "code": null, "e": 25687, "s": 25676, "text": "SQL-PL/SQL" }, { "code": null, "e": 25691, "s": 25687, "text": "SQL" }, { "code": null, "e": 25695, "s": 25691, "text": "SQL" }, { "code": null, "e": 25793, "s": 25695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25804, "s": 25793, "text": "CTE in SQL" }, { "code": null, "e": 25870, "s": 25804, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25894, "s": 25870, "text": "SQL Interview Questions" }, { "code": null, "e": 25933, "s": 25894, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25978, "s": 25933, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26010, "s": 25978, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26043, "s": 26010, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 26075, "s": 26043, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26153, "s": 26075, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" } ]
etags - Unix, Linux Command
ctags [-aCdgImRVh] [-BtTuvwx] [-l language] [-o tagfile] [-r regexp] [--append] [--backward-search] [--cxref] [--defines] [--forward-search] [--globals] [--ignore-indentation] [--language=language] [--members] [--output=tagfile] [--regex=regexp] [--ignore-case-regex=regexp] [--typedefs] [--typedefs-and-c++] [--update] [--no-warn] [--help] [--version] file ... where tagregexp is used to match the lines that must be tagged. It should not match useless characters. If the match is such that more characters than needed are unavoidably matched by tagregexp, it may be useful to add a nameregexp, to narrow down the tag scope. ctags ignores regexps without a nameregexp. The syntax of regexps is the same as in emacs, augmented with intervals of the form \{m,n\}, as in ed or grep. Here are some examples. All the regexps are quoted to protect them from shell interpretation. Tag the DEFVAR macros in the emacs source files: --regex\=’/[ \t]*DEFVAR_[A-Z_ \t(]+"\([^"]+\)"\/’ Tag VHDL files (this example is a single long line, broken here for formatting reasons): --language\=none --regex=’/[ \t]*\(ARCHITECTURE\|\ CONFIGURATION\) +[^ ]* +OF/’ --regex\=’/[ \t]*\ \(ATTRIBUTE\|ENTITY\|FUNCTION\|PACKAGE\( BODY\)?\ \|PROCEDURE\|PROCESS\|TYPE\)[ \t]+\([^ \t(]+\)/\3/’ Tag TCL files (this last example shows the usage of a tagregexp): --lang\=none --regex\=’/proc[ \t]+\([^ \t]+\)/\1/’ A regexp can be preceded by {lang}, thus restricting it to match lines of files of the specified language. Use etags --help to obtain a list of the recognised languages. This feature is particularly useful inside regex files. A regex file contains one regex per line. Empty lines, and those lines beginning with space or tab are ignored. Lines beginning with @ are references to regex files whose name follows the @ sign. Other lines are considered regular expressions like those following --regex. For example, the command etags --regex=@regex.file *.c reads the regexes contained in the file regex.file. Navigating the source code using vi or emacs editor could be quite a task especially if the code has multiple files. gctags utility can be quite handy in such a situation. Using gctags vi can be converted into a beautiful source code browser. Example given below is for C program but same can be applied for other languages like C++, java, Perl, etc. Type gctags --h for to see supported languages. Consider below source code: gctags_example.c #include <stdio.h> // Function Declarations int areaRectangle(int length, int breadth); float areaCircle(int radius); int square(int num); void dummy(); #define PI 3.14 typedef struct { int memberInt; float memberFloat; char memberChar; } myStruct; int rectangle; float circle; int areaRectangle(int length, int breadth) { return(length * breadth); } float areaCircle(int radius) { return(PI * square(radius)); } int square(int num) { return(num * num); } int main() { rectangle = areaRectangle(10, 5); circle = areaCircle(20); printf("Area of rectangle: %f", rectangle); printf("Area of circle: %f", circle); return(0); } $ gctags --declarations --defines --global --members --output=example.tags --no-warn gctags_example.c $ ls example.tags gctags_example.c $ cat example.tags Mgctags_example gctags_example.c /^int main()$/ PI gctags_example.c 9 areaCircle gctags_example.c /^float areaCircle(int radius);$/ areaRectangle gctags_example.c /^int areaRectangle(int length, int breadth);$/ circle gctags_example.c 18 dummy gctags_example.c /^void dummy();$/ memberChar gctags_example.c 14 memberFloat gctags_example.c 13 memberInt gctags_example.c 12 myStruct gctags_example.c 15 rectangle gctags_example.c 17 square gctags_example.c /^int square(int num);$/ $ gctags -R --declarations --defines --global --members --output=example.tags --no-warn *.c *.hae :set tags=<path to tags> 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10945, "s": 10577, "text": "\nctags [-aCdgImRVh] [-BtTuvwx] [-l language]\n\n[-o tagfile] [-r regexp]\n\n[--append] [--backward-search]\n[--cxref] [--defines] [--forward-search]\n[--globals] [--ignore-indentation]\n[--language=language] [--members]\n[--output=tagfile] [--regex=regexp]\n[--ignore-case-regex=regexp]\n[--typedefs] [--typedefs-and-c++]\n[--update] [--no-warn]\n[--help] [--version]\nfile ...\n\n\n" }, { "code": null, "e": 11465, "s": 10945, "text": "\nwhere tagregexp is used to match the lines that must be tagged.\nIt should not match useless characters. If the match is\nsuch that more characters than needed are unavoidably matched by\ntagregexp, it may be useful to add a nameregexp, to\nnarrow down the tag scope. ctags ignores regexps without a\nnameregexp. The syntax of regexps is the same as in emacs,\naugmented with intervals of the form \\{m,n\\}, as in ed or\ngrep.\n\nHere are some examples. All the regexps are quoted to protect them\nfrom shell interpretation.\n" }, { "code": null, "e": 11567, "s": 11465, "text": "\nTag the DEFVAR macros in the emacs source files:\n\n--regex\\=’/[ \\t]*DEFVAR_[A-Z_ \\t(]+\"\\([^\"]+\\)\"\\/’\n" }, { "code": null, "e": 11860, "s": 11567, "text": "\nTag VHDL files (this example is a single long line, broken here for\nformatting reasons):\n\n--language\\=none --regex=’/[ \\t]*\\(ARCHITECTURE\\|\\\nCONFIGURATION\\) +[^ ]* +OF/’ --regex\\=’/[ \\t]*\\\n\\(ATTRIBUTE\\|ENTITY\\|FUNCTION\\|PACKAGE\\( BODY\\)?\\\n\\|PROCEDURE\\|PROCESS\\|TYPE\\)[ \\t]+\\([^ \\t(]+\\)/\\3/’\n" }, { "code": null, "e": 11980, "s": 11860, "text": "\nTag TCL files (this last example shows the usage of a tagregexp):\n\n--lang\\=none --regex\\=’/proc[ \\t]+\\([^ \\t]+\\)/\\1/’\n" }, { "code": null, "e": 12597, "s": 11980, "text": "\nA regexp can be preceded by {lang}, thus restricting it to match\nlines of files of the specified language. Use etags --help to obtain\na list of the recognised languages. This feature is particularly useful inside\nregex files. A regex file contains one regex per line. Empty lines,\nand those lines beginning with space or tab are ignored. Lines beginning\nwith @ are references to regex files whose name follows the @ sign. Other\nlines are considered regular expressions like those following --regex.\n\nFor example, the command\n\netags --regex=@regex.file *.c\n\nreads the regexes contained in the file regex.file.\n" }, { "code": null, "e": 12842, "s": 12599, "text": "Navigating the source code using vi or emacs editor could be quite a task especially if the code has multiple files.\ngctags utility can be quite handy in such a situation. Using gctags vi can be converted into a beautiful source code browser." }, { "code": null, "e": 12998, "s": 12842, "text": "Example given below is for C program but same can be applied for other languages like C++, java, Perl, etc. Type gctags --h for to see supported languages." }, { "code": null, "e": 13043, "s": 12998, "text": "Consider below source code: gctags_example.c" }, { "code": null, "e": 13755, "s": 13043, "text": "#include <stdio.h>\n// Function Declarations\nint areaRectangle(int length, int breadth);\nfloat areaCircle(int radius);\nint square(int num);\nvoid dummy();\n#define PI 3.14\ntypedef struct {\n int memberInt;\n float memberFloat;\n char memberChar;\n} myStruct;\nint rectangle;\nfloat circle;\nint areaRectangle(int length, int breadth)\n{\n return(length * breadth);\n}\nfloat areaCircle(int radius)\n{\n return(PI * square(radius));\n}\nint square(int num)\n{\n return(num * num);\n}\nint main()\n{\n rectangle = areaRectangle(10, 5);\n circle = areaCircle(20);\n printf(\"Area of rectangle: %f\", rectangle);\n printf(\"Area of circle: %f\", circle);\n return(0);\n}\n" }, { "code": null, "e": 13858, "s": 13755, "text": "$ gctags --declarations --defines --global --members --output=example.tags --no-warn gctags_example.c\n" }, { "code": null, "e": 13895, "s": 13858, "text": "$ ls\nexample.tags gctags_example.c\n" }, { "code": null, "e": 14523, "s": 13895, "text": "$ cat example.tags\nMgctags_example gctags_example.c /^int main()$/\nPI gctags_example.c 9\nareaCircle gctags_example.c /^float areaCircle(int radius);$/\nareaRectangle gctags_example.c /^int areaRectangle(int length, int breadth);$/\ncircle gctags_example.c 18\ndummy gctags_example.c /^void dummy();$/\nmemberChar gctags_example.c 14\nmemberFloat gctags_example.c 13\nmemberInt gctags_example.c 12\nmyStruct gctags_example.c 15\nrectangle gctags_example.c 17\nsquare gctags_example.c /^int square(int num);$/\n" }, { "code": null, "e": 14622, "s": 14523, "text": "$ gctags -R --declarations --defines --global --members --output=example.tags --no-warn *.c *.hae\n" }, { "code": null, "e": 14648, "s": 14622, "text": ":set tags=<path to tags>\n" }, { "code": null, "e": 14683, "s": 14648, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14711, "s": 14683, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14745, "s": 14711, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14762, "s": 14745, "text": " Frahaan Hussain" }, { "code": null, "e": 14795, "s": 14762, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14806, "s": 14795, "text": " Pradeep D" }, { "code": null, "e": 14841, "s": 14806, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14857, "s": 14841, "text": " Musab Zayadneh" }, { "code": null, "e": 14890, "s": 14857, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14902, "s": 14890, "text": " GUHARAJANM" }, { "code": null, "e": 14934, "s": 14902, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14942, "s": 14934, "text": " Uplatz" }, { "code": null, "e": 14949, "s": 14942, "text": " Print" }, { "code": null, "e": 14960, "s": 14949, "text": " Add Notes" } ]
Convert a List of String to a comma separated String in Java - GeeksforGeeks
11 Dec, 2018 Given a List of String, the task is to convert the List to a comma separated String in Java. Examples: Input: List<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: List<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" Approach: This can be achieved with the help of join() method of String as follows. Get the List of String.Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters.Print the String. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters. Print the String. Below is the implementation of the above approach: Program: // Java program to convert List of String// to comma separated String import java.util.*; public class GFG { public static void main(String args[]) { // Get the List of String List<String> list = new ArrayList<>( Arrays .asList("Geeks", "ForGeeks", "GeeksForGeeks")); // Print the List of String System.out.println("List of String: " + list); // Convert the List of String to String String string = String.join(", ", list); // Print the comma separated String System.out.println("Comma separated String: " + string); }} Java-List-Programs Java-String-Programs Java-Strings Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24418, "s": 24390, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24511, "s": 24418, "text": "Given a List of String, the task is to convert the List to a comma separated String in Java." }, { "code": null, "e": 24521, "s": 24511, "text": "Examples:" }, { "code": null, "e": 24684, "s": 24521, "text": "Input: List<String> = [\"Geeks\", \"ForGeeks\", \"GeeksForGeeks\"]\nOutput: \"Geeks, For, Geeks\"\n\nInput: List<String> = [\"G\", \"e\", \"e\", \"k\", \"s\"]\nOutput: \"G, e, e, k, s\"\n" }, { "code": null, "e": 24768, "s": 24684, "text": "Approach: This can be achieved with the help of join() method of String as follows." }, { "code": null, "e": 24932, "s": 24768, "text": "Get the List of String.Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters.Print the String." }, { "code": null, "e": 24956, "s": 24932, "text": "Get the List of String." }, { "code": null, "e": 25080, "s": 24956, "text": "Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters." }, { "code": null, "e": 25098, "s": 25080, "text": "Print the String." }, { "code": null, "e": 25149, "s": 25098, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25158, "s": 25149, "text": "Program:" }, { "code": "// Java program to convert List of String// to comma separated String import java.util.*; public class GFG { public static void main(String args[]) { // Get the List of String List<String> list = new ArrayList<>( Arrays .asList(\"Geeks\", \"ForGeeks\", \"GeeksForGeeks\")); // Print the List of String System.out.println(\"List of String: \" + list); // Convert the List of String to String String string = String.join(\", \", list); // Print the comma separated String System.out.println(\"Comma separated String: \" + string); }}", "e": 25878, "s": 25158, "text": null }, { "code": null, "e": 25897, "s": 25878, "text": "Java-List-Programs" }, { "code": null, "e": 25918, "s": 25897, "text": "Java-String-Programs" }, { "code": null, "e": 25931, "s": 25918, "text": "Java-Strings" }, { "code": null, "e": 25936, "s": 25931, "text": "Java" }, { "code": null, "e": 25950, "s": 25936, "text": "Java Programs" }, { "code": null, "e": 25963, "s": 25950, "text": "Java-Strings" }, { "code": null, "e": 25968, "s": 25963, "text": "Java" }, { "code": null, "e": 26066, "s": 25968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26098, "s": 26066, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26117, "s": 26098, "text": "Interfaces in Java" }, { "code": null, "e": 26135, "s": 26117, "text": "ArrayList in Java" }, { "code": null, "e": 26167, "s": 26135, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26187, "s": 26167, "text": "Stack Class in Java" }, { "code": null, "e": 26215, "s": 26187, "text": "Initializing a List in Java" }, { "code": null, "e": 26259, "s": 26215, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26285, "s": 26259, "text": "Java Programming Examples" }, { "code": null, "e": 26319, "s": 26285, "text": "Convert Double to Integer in Java" } ]
How to import data into SAS? - GeeksforGeeks
23 Jul, 2019 Entering Data Directly: You can enter numbers of lines of data directly in SAS program by using a DATALINES statement.The keywords are as follows:DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata; INPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; Dollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; DATALINES: To refer that lines following DATALINES statement a real data.DATALINES; PROC PRINT: To display out the contents of data set in output window.proc print; RUN: The DATA step ends with a RUN statement to run the complete code.run; Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output:You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;OutputReading Delimited Data:The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options.Syntax:Infile 'file-description' dlm=', 'While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':'Example:DATA outdata; INFILE Datalines dlm =", "; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run;Output: Entering Data Directly: You can enter numbers of lines of data directly in SAS program by using a DATALINES statement.The keywords are as follows:DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata; INPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; Dollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; DATALINES: To refer that lines following DATALINES statement a real data.DATALINES; PROC PRINT: To display out the contents of data set in output window.proc print; RUN: The DATA step ends with a RUN statement to run the complete code.run; Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output:You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;Output The keywords are as follows: DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata; DATA outdata; INPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; INPUT age gender $ dept obs1 obs2 obs3; Dollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; INPUT age gender $ dept obs1 obs2 obs3; DATALINES: To refer that lines following DATALINES statement a real data.DATALINES; DATALINES; PROC PRINT: To display out the contents of data set in output window.proc print; proc print; RUN: The DATA step ends with a RUN statement to run the complete code.run; Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output: run; Example: DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run; Output: You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;Output Example: DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run; Output Reading Delimited Data:The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options.Syntax:Infile 'file-description' dlm=', 'While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':'Example:DATA outdata; INFILE Datalines dlm =", "; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run;Output: The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options. Syntax: Infile 'file-description' dlm=', ' While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':' While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'x infile 'file-description' dlm='09'x While using colon delimiter, the syntax would beinfile 'file-description' dlm=':' infile 'file-description' dlm=':' Example: DATA outdata; INFILE Datalines dlm =", "; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run; Output: SAS Programming Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments All forms of formatted scanf() in C Difference Between Imperative and Declarative Programming Difference between while and do-while loop in C, C++, Java Top 10 Programming Languages to Learn in 2022 Prolog | An Introduction Header Guard in C++ Lists in Prolog Scope of Variable in R DataFrame Operations in R Top 10 Fastest Programming Languages
[ { "code": null, "e": 24477, "s": 24449, "text": "\n23 Jul, 2019" }, { "code": null, "e": 26481, "s": 24477, "text": "Entering Data Directly: You can enter numbers of lines of data directly in SAS program by using a DATALINES statement.The keywords are as follows:DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata;\nINPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; \nDollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; \nDATALINES: To refer that lines following DATALINES statement a real data.DATALINES; \nPROC PRINT: To display out the contents of data set in output window.proc print;\nRUN: The DATA step ends with a RUN statement to run the complete code.run;\nExample:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output:You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;OutputReading Delimited Data:The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options.Syntax:Infile 'file-description' dlm=', 'While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':'Example:DATA outdata; INFILE Datalines dlm =\", \"; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run;Output:" }, { "code": null, "e": 27823, "s": 26481, "text": "Entering Data Directly: You can enter numbers of lines of data directly in SAS program by using a DATALINES statement.The keywords are as follows:DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata;\nINPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; \nDollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; \nDATALINES: To refer that lines following DATALINES statement a real data.DATALINES; \nPROC PRINT: To display out the contents of data set in output window.proc print;\nRUN: The DATA step ends with a RUN statement to run the complete code.run;\nExample:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output:You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;Output" }, { "code": null, "e": 27852, "s": 27823, "text": "The keywords are as follows:" }, { "code": null, "e": 28023, "s": 27852, "text": "DATA: The DATA step always starts with a DATA statement. The purpose of the DATA statement is to tell SAS that you are creating a new data set i.e. outdata.DATA outdata;\n" }, { "code": null, "e": 28038, "s": 28023, "text": "DATA outdata;\n" }, { "code": null, "e": 28128, "s": 28038, "text": "INPUT: To define the variables used in data set.INPUT age gender $ dept obs1 obs2 obs3; \n" }, { "code": null, "e": 28170, "s": 28128, "text": "INPUT age gender $ dept obs1 obs2 obs3; \n" }, { "code": null, "e": 28264, "s": 28170, "text": "Dollar sign ($): To declare variable as a character.INPUT age gender $ dept obs1 obs2 obs3; \n" }, { "code": null, "e": 28306, "s": 28264, "text": "INPUT age gender $ dept obs1 obs2 obs3; \n" }, { "code": null, "e": 28392, "s": 28306, "text": "DATALINES: To refer that lines following DATALINES statement a real data.DATALINES; \n" }, { "code": null, "e": 28405, "s": 28392, "text": "DATALINES; \n" }, { "code": null, "e": 28487, "s": 28405, "text": "PROC PRINT: To display out the contents of data set in output window.proc print;\n" }, { "code": null, "e": 28500, "s": 28487, "text": "proc print;\n" }, { "code": null, "e": 28883, "s": 28500, "text": "RUN: The DATA step ends with a RUN statement to run the complete code.run;\nExample:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;Output:" }, { "code": null, "e": 28889, "s": 28883, "text": "run;\n" }, { "code": null, "e": 28898, "s": 28889, "text": "Example:" }, { "code": "DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; DATALINES; 25 M 3 17 6 2424 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 734 M 1 7 7 1431 F 2 2 1 2222 F 5 20 5 232 M 4 21 8 1841 M 4 7 9 2524 M 5 10 17 2031 F 4 21 25 732 M 3 9 9 5;proc print;run;", "e": 29191, "s": 28898, "text": null }, { "code": null, "e": 29199, "s": 29191, "text": "Output:" }, { "code": null, "e": 29495, "s": 29199, "text": "You can also use CARDS instead of DATALINES. Both means the same. There is no difference between these two keywords.Example:DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;Output" }, { "code": null, "e": 29504, "s": 29495, "text": "Example:" }, { "code": "DATA outdata; INPUT age gender $ dept obs1 obs2 obs3; CARDS; 24 F 1 19 25 731 F 4 24 10 2033 M 2 19 23 822 M 1 14 23 1222 F 5 1 23 931 M 1 8 21 7;proc print;run;", "e": 29670, "s": 29504, "text": null }, { "code": null, "e": 29677, "s": 29670, "text": "Output" }, { "code": null, "e": 30340, "s": 29677, "text": "Reading Delimited Data:The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options.Syntax:Infile 'file-description' dlm=', 'While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':'Example:DATA outdata; INFILE Datalines dlm =\", \"; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run;Output:" }, { "code": null, "e": 30534, "s": 30340, "text": "The default delimiter is blank. If you have a data file with other delimiters such as comma or tab you need to define the delimiter before defining the variables using INFILE and DLM = options." }, { "code": null, "e": 30542, "s": 30534, "text": "Syntax:" }, { "code": null, "e": 30577, "s": 30542, "text": "Infile 'file-description' dlm=', '" }, { "code": null, "e": 30740, "s": 30577, "text": "While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'xWhile using colon delimiter, the syntax would beinfile 'file-description' dlm=':'" }, { "code": null, "e": 30822, "s": 30740, "text": "While using tab delimiter, the syntax would beinfile 'file-description' dlm='09'x" }, { "code": null, "e": 30858, "s": 30822, "text": "infile 'file-description' dlm='09'x" }, { "code": null, "e": 30940, "s": 30858, "text": "While using colon delimiter, the syntax would beinfile 'file-description' dlm=':'" }, { "code": null, "e": 30974, "s": 30940, "text": "infile 'file-description' dlm=':'" }, { "code": null, "e": 30983, "s": 30974, "text": "Example:" }, { "code": "DATA outdata; INFILE Datalines dlm =\", \"; INPUT age gender $ dept obs1 obs2 obs3; Datalines; 34, M, 1, 7, 7, 1431, F, 2, 2, 1, 2222, F, 5, 20, 5, 232, M, 4, 21, 8, 1841, M, 4, 7, 9, 2524, M, 5, 10, 17, 20;proc print;run;", "e": 31212, "s": 30983, "text": null }, { "code": null, "e": 31220, "s": 31212, "text": "Output:" }, { "code": null, "e": 31236, "s": 31220, "text": "SAS Programming" }, { "code": null, "e": 31257, "s": 31236, "text": "Programming Language" }, { "code": null, "e": 31355, "s": 31257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31364, "s": 31355, "text": "Comments" }, { "code": null, "e": 31377, "s": 31364, "text": "Old Comments" }, { "code": null, "e": 31413, "s": 31377, "text": "All forms of formatted scanf() in C" }, { "code": null, "e": 31471, "s": 31413, "text": "Difference Between Imperative and Declarative Programming" }, { "code": null, "e": 31530, "s": 31471, "text": "Difference between while and do-while loop in C, C++, Java" }, { "code": null, "e": 31576, "s": 31530, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 31601, "s": 31576, "text": "Prolog | An Introduction" }, { "code": null, "e": 31621, "s": 31601, "text": "Header Guard in C++" }, { "code": null, "e": 31637, "s": 31621, "text": "Lists in Prolog" }, { "code": null, "e": 31660, "s": 31637, "text": "Scope of Variable in R" }, { "code": null, "e": 31686, "s": 31660, "text": "DataFrame Operations in R" } ]
SQL - Date Functions
The following table has a list of all the important Date and Time related functions available through SQL. There are various other functions supported by your RDBMS. The given list is based on MySQL RDBMS. Adds dates Adds time Converts from one timezone to another Returns the current date Synonyms for CURDATE() Synonyms for CURTIME() Synonyms for NOW() Returns the current time Adds two dates Formats date as specified Subtracts two dates Extracts the date part of a date or datetime expression Subtracts two dates Synonym for DAYOFMONTH() Returns the name of the weekday Returns the day of the month (1-31) Returns the weekday index of the argument Returns the day of the year (1-366) Extracts part of a date Converts a day number to a date Formats date as a UNIX timestamp Extracts the hour Returns the last day of the month for the argument Synonym for NOW() Synonym for NOW() Creates a date from the year and day of year MAKETIME() Returns the microseconds from argument Returns the minute from the argument Return the month from the date passed Returns the name of the month Returns the current date and time Adds a period to a year-month Returns the number of months between periods Returns the quarter from a date argument Converts seconds to 'HH:MM:SS' format Returns the second (0-59) Converts a string to a date When invoked with three arguments a synonym for DATE_SUB() Subtracts times Returns the time at which the function executes Formats as time Returns the argument converted to seconds Extracts the time portion of the expression passed Subtracts time With a single argument this function returns the date or datetime expression. With two arguments, the sum of the arguments Adds an interval to a datetime expression Subtracts an interval from a datetime expression Returns the date argument converted to days Returns a UNIX timestamp Returns the current UTC date Returns the current UTC time Returns the current UTC date and time Returns the week number Returns the weekday index Returns the calendar week of the date (1-53) Returns the year Returns the year and week When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | ADDDATE('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr. mysql> SELECT ADDDATE('1998-01-02', 31); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime expression, while the expr2 is a time expression. mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002'); +---------------------------------------------------------+ | DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') | +---------------------------------------------------------+ | 1998-01-02 01:01:01.000001 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid. mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') | +---------------------------------------------------------+ | 2004-01-01 13:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') | +---------------------------------------------------------+ | 2004-01-01 22:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT CURDATE(); +---------------------------------------------------------+ | CURDATE() | +---------------------------------------------------------+ | 1997-12-15 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CURDATE() + 0; +---------------------------------------------------------+ | CURDATE() + 0 | +---------------------------------------------------------+ | 19971215 | +---------------------------------------------------------+ 1 row in set (0.00 sec) CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE() Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. mysql> SELECT CURTIME(); +---------------------------------------------------------+ | CURTIME() | +---------------------------------------------------------+ | 23:50:26 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CURTIME() + 0; +---------------------------------------------------------+ | CURTIME() + 0 | +---------------------------------------------------------+ | 235026 | +---------------------------------------------------------+ 1 row in set (0.00 sec) CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME(). CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW(). Extracts the date part of the date or datetime expression expr. mysql> SELECT DATE('2003-12-31 01:02:03'); +---------------------------------------------------------+ | DATE('2003-12-31 01:02:03') | +---------------------------------------------------------+ | 2003-12-31 | +---------------------------------------------------------+ 1 row in set (0.00 sec) DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation. mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30'); +---------------------------------------------------------+ | DATEDIFF('1997-12-31 23:59:59','1997-12-30') | +---------------------------------------------------------+ | 1 | +---------------------------------------------------------+ 1 row in set (0.00 sec) These functions perform date arithmetic. The date is a DATETIME or DATE value specifying the starting date. The expr is an expression specifying the interval value to be added or subtracted from the starting date. The expr is a string; it may start with a '-' for negative intervals. A unit is a keyword indicating the units in which the expression should be interpreted. The INTERVAL keyword and the unit specifier are not case sensitive. The following table shows the expected form of the expr argument for each unit value. The values QUARTER and WEEK are available from the MySQL 5.0.0. version. mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL '1:1' MINUTE_SECOND); +---------------------------------------------------------+ | DATE_ADD('1997-12-31 23:59:59', INTERVAL... | +---------------------------------------------------------+ | 1998-01-01 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR); +---------------------------------------------------------+ | DATE_ADD('1999-01-01', INTERVAL 1 HOUR) | +---------------------------------------------------------+ | 1999-01-01 01:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This command formats the date value as per the format string. The following specifiers may be used in the format string. The '%' character is required before the format specifier characters. %a Abbreviated weekday name (Sun..Sat) %b Abbreviated month name (Jan..Dec) %c Month, numeric (0..12) %D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .) %d Day of the month, numeric (00..31) %e Day of the month, numeric (0..31) %f Microseconds (000000..999999) %H Hour (00..23) %h Hour (01..12) %I Hour (01..12) %i Minutes, numeric (00..59) %j Day of year (001..366) %k Hour (0..23) %l Hour (1..12) %M Month name (January..December) %m Month, numeric (00..12) %p AM or PM %r Time, 12-hour (hh:mm:ss followed by AM or PM) %S Seconds (00..59) %s Seconds (00..59) %T Time, 24-hour (hh:mm:ss) %U Week (00..53), where Sunday is the first day of the week %u Week (00..53), where Monday is the first day of the week %V Week (01..53), where Sunday is the first day of the week; used with %X %v Week (01..53), where Monday is the first day of the week; used with %x %W Weekday name (Sunday..Saturday) %w Day of the week (0=Sunday..6=Saturday) %X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V %x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v %Y Year, numeric, four digits %y Year, numeric (two digits) %% A literal .%. character %x x, for any.x. not listed above mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') | +---------------------------------------------------------+ | Saturday October 1997 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00' -> '%H %k %I %r %T %S %w'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00....... | +---------------------------------------------------------+ | 22 22 10 10:23:00 PM 22:23:00 00 6 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This is similar to the DATE_ADD() function. The DAY() is a synonym for the DAYOFMONTH() function. Returns the name of the weekday for date. mysql> SELECT DAYNAME('1998-02-05'); +---------------------------------------------------------+ | DAYNAME('1998-02-05') | +---------------------------------------------------------+ | Thursday | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the day of the month for date, in the range 0 to 31. mysql> SELECT DAYOFMONTH('1998-02-03'); +---------------------------------------------------------+ | DAYOFMONTH('1998-02-03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values correspond to the ODBC standard. mysql> SELECT DAYOFWEEK('1998-02-03'); +---------------------------------------------------------+ |DAYOFWEEK('1998-02-03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the day of the year for date, in the range 1 to 366. mysql> SELECT DAYOFYEAR('1998-02-03'); +---------------------------------------------------------+ | DAYOFYEAR('1998-02-03') | +---------------------------------------------------------+ | 34 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic. mysql> SELECT EXTRACT(YEAR FROM '1999-07-02'); +---------------------------------------------------------+ | EXTRACT(YEAR FROM '1999-07-02') | +---------------------------------------------------------+ | 1999 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03'); +---------------------------------------------------------+ | EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03') | +---------------------------------------------------------+ | 199907 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Given a day number N, returns a DATE value. mysql> SELECT FROM_DAYS(729669); +---------------------------------------------------------+ | FROM_DAYS(729669) | +---------------------------------------------------------+ | 1997-10-07 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Note − Use FROM_DAYS() with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582). Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. The unix_timestamp argument is an internal timestamp values, which are produced by the UNIX_TIMESTAMP() function. If the format is given, the result is formatted according to the format string, which is used in the same way as is listed in the entry for the DATE_FORMAT() function. mysql> SELECT FROM_UNIXTIME(875996580); +---------------------------------------------------------+ | FROM_UNIXTIME(875996580) | +---------------------------------------------------------+ | 1997-10-04 22:23:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23. mysql> SELECT HOUR('10:05:03'); +---------------------------------------------------------+ | HOUR('10:05:03') | +---------------------------------------------------------+ | 10 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid. mysql> SELECT LAST_DAY('2003-02-05'); +---------------------------------------------------------+ | LAST_DAY('2003-02-05') | +---------------------------------------------------------+ | 2003-02-28 | +---------------------------------------------------------+ 1 row in set (0.00 sec) LOCALTIME and LOCALTIME() are synonyms for NOW(). LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW(). Returns a date, given year and day-of-year values. The dayofyear value must be greater than 0 or the result will be NULL. mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32); +---------------------------------------------------------+ | MAKEDATE(2001,31), MAKEDATE(2001,32) | +---------------------------------------------------------+ | '2001-01-31', '2001-02-01' | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns a time value calculated from the hour, minute and second arguments. mysql> SELECT MAKETIME(12,15,30); +---------------------------------------------------------+ | MAKETIME(12,15,30) | +---------------------------------------------------------+ | '12:15:30' | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the microseconds from the time or datetime expression (expr) as a number in the range from 0 to 999999. mysql> SELECT MICROSECOND('12:00:00.123456'); +---------------------------------------------------------+ | MICROSECOND('12:00:00.123456') | +---------------------------------------------------------+ | 123456 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the minute for time, in the range 0 to 59. mysql> SELECT MINUTE('98-02-03 10:05:03'); +---------------------------------------------------------+ | MINUTE('98-02-03 10:05:03') | +---------------------------------------------------------+ | 5 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the month for date, in the range 0 to 12. mysql> SELECT MONTH('1998-02-03') +---------------------------------------------------------+ | MONTH('1998-02-03') | +---------------------------------------------------------+ | 2 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the full name of the month for a date. mysql> SELECT MONTHNAME('1998-02-05'); +---------------------------------------------------------+ | MONTHNAME('1998-02-05') | +---------------------------------------------------------+ | February | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. This value is expressed in the current time zone. mysql> SELECT NOW(); +---------------------------------------------------------+ | NOW() | +---------------------------------------------------------+ | 1997-12-15 23:50:26 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value. mysql> SELECT PERIOD_ADD(9801,2); +---------------------------------------------------------+ | PERIOD_ADD(9801,2) | +---------------------------------------------------------+ | 199803 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the number of months between periods P1 and P2. These periods P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values. mysql> SELECT PERIOD_DIFF(9802,199703); +---------------------------------------------------------+ | PERIOD_DIFF(9802,199703) | +---------------------------------------------------------+ | 11 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the quarter of the year for date, in the range 1 to 4. mysql> SELECT QUARTER('98-04-01'); +---------------------------------------------------------+ | QUARTER('98-04-01') | +---------------------------------------------------------+ | 2 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the second for time, in the range 0 to 59. mysql> SELECT SECOND('10:05:03'); +---------------------------------------------------------+ | SECOND('10:05:03') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the seconds argument, converted to hours, minutes and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT SEC_TO_TIME(2378); +---------------------------------------------------------+ | SEC_TO_TIME(2378) | +---------------------------------------------------------+ | 00:39:38 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. The STR_TO_DATE() function returns a DATETIME value if the format string contains both date and time parts. Else, it returns a DATE or TIME value if the string contains only date or time parts. mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y'); +---------------------------------------------------------+ | STR_TO_DATE('04/31/2004', '%m/%d/%Y') | +---------------------------------------------------------+ | 2004-04-31 | +---------------------------------------------------------+ 1 row in set (0.00 sec) When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | DATE_SUB('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1997-12-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | SUBDATE('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1997-12-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time expression. mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999', -> '1 1:1:1.000002'); +---------------------------------------------------------+ | SUBTIME('1997-12-31 23:59:59.999999'... | +---------------------------------------------------------+ | 1997-12-30 22:58:58.999997 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT SYSDATE(); +---------------------------------------------------------+ | SYSDATE() | +---------------------------------------------------------+ | 2006-04-12 13:47:44 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Extracts the time part of the time or datetime expression expr and returns it as a string. mysql> SELECT TIME('2003-12-31 01:02:03'); +---------------------------------------------------------+ | TIME('2003-12-31 01:02:03') | +---------------------------------------------------------+ | 01:02:03 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1 and expr2 values are time or date-and-time expressions, but both must be of the same type. mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001', -> '1997-12-30 01:01:01.000002'); +---------------------------------------------------------+ | TIMEDIFF('1997-12-31 23:59:59.000001'..... | +---------------------------------------------------------+ | 46:58:57.999999 | +---------------------------------------------------------+ 1 row in set (0.00 sec) With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value. mysql> SELECT TIMESTAMP('2003-12-31'); +---------------------------------------------------------+ | TIMESTAMP('2003-12-31') | +---------------------------------------------------------+ | 2003-12-31 00:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values − FRAC_SECOND SECOND, MINUTE HOUR, DAY WEEK MONTH QUARTER or YEAR The unit value may be specified using one of the keywords as shown or with a prefix of SQL_TSI_. For example, DAY and SQL_TSI_DAY both are legal. mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02'); +---------------------------------------------------------+ | TIMESTAMPADD(MINUTE,1,'2003-01-02') | +---------------------------------------------------------+ | 2003-01-02 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2. The unit for the result is given by the unit argument. The legal values for the unit are the same as those listed in the description of the TIMESTAMPADD() function. mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01'); +---------------------------------------------------------+ | TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') | +---------------------------------------------------------+ | 3 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes and seconds. If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0 to 23. The other hour format specifiers produce the hour value modulo 12. mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l'); +---------------------------------------------------------+ | TIME_FORMAT('100:00:00', '%H %k %h %I %l') | +---------------------------------------------------------+ | 100 100 04 04 4 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the time argument converted to seconds. mysql> SELECT TIME_TO_SEC('22:23:00'); +---------------------------------------------------------+ | TIME_TO_SEC('22:23:00') | +---------------------------------------------------------+ | 80580 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Given a date, returns a day number (the number of days since year 0). mysql> SELECT TO_DAYS(950501); +---------------------------------------------------------+ | TO_DAYS(950501) | +---------------------------------------------------------+ | 728779 | +---------------------------------------------------------+ 1 row in set (0.00 sec) If called with no argument, this function returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD. mysql> SELECT UNIX_TIMESTAMP(); +---------------------------------------------------------+ | UNIX_TIMESTAMP() | +---------------------------------------------------------+ | 882226357 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00'); +---------------------------------------------------------+ | UNIX_TIMESTAMP('1997-10-04 22:23:00') | +---------------------------------------------------------+ | 875996580 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_DATE(), UTC_DATE() + 0; +---------------------------------------------------------+ | UTC_DATE(), UTC_DATE() + 0 | +---------------------------------------------------------+ | 2003-08-14, 20030814 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_TIME(), UTC_TIME() + 0; +---------------------------------------------------------+ | UTC_TIME(), UTC_TIME() + 0 | +---------------------------------------------------------+ | 18:07:53, 180753 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0; +---------------------------------------------------------+ | UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0 | +---------------------------------------------------------+ | 2003-08-14 18:08:04, 20030814180804 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on a Sunday or a Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used mysql> SELECT WEEK('1998-02-20'); +---------------------------------------------------------+ | WEEK('1998-02-20') | +---------------------------------------------------------+ | 7 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday). mysql> SELECT WEEKDAY('1998-02-03 22:23:00'); +---------------------------------------------------------+ | WEEKDAY('1998-02-03 22:23:00') | +---------------------------------------------------------+ | 1 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3). mysql> SELECT WEEKOFYEAR('1998-02-20'); +---------------------------------------------------------+ | WEEKOFYEAR('1998-02-20') | +---------------------------------------------------------+ | 8 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date. mysql> SELECT YEAR('98-02-03'); +---------------------------------------------------------+ | YEAR('98-02-03') | +---------------------------------------------------------+ | 1998 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Returns the year and the week for a date. The mode argument works exactly like the mode argument to the WEEK() function. The year in the result may be different from the year in the date argument for the first and the last week of the year. mysql> SELECT YEARWEEK('1987-01-01'); +---------------------------------------------------------+ | YEAR('98-02-03')YEARWEEK('1987-01-01') | +---------------------------------------------------------+ | 198653 | +---------------------------------------------------------+ 1 row in set (0.00 sec) Note − The week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2659, "s": 2453, "text": "The following table has a list of all the important Date and Time related functions available through SQL. There are various other functions supported by your RDBMS. The given list is based on MySQL RDBMS." }, { "code": null, "e": 2670, "s": 2659, "text": "Adds dates" }, { "code": null, "e": 2680, "s": 2670, "text": "Adds time" }, { "code": null, "e": 2718, "s": 2680, "text": "Converts from one timezone to another" }, { "code": null, "e": 2743, "s": 2718, "text": "Returns the current date" }, { "code": null, "e": 2766, "s": 2743, "text": "Synonyms for CURDATE()" }, { "code": null, "e": 2789, "s": 2766, "text": "Synonyms for CURTIME()" }, { "code": null, "e": 2808, "s": 2789, "text": "Synonyms for NOW()" }, { "code": null, "e": 2833, "s": 2808, "text": "Returns the current time" }, { "code": null, "e": 2848, "s": 2833, "text": "Adds two dates" }, { "code": null, "e": 2874, "s": 2848, "text": "Formats date as specified" }, { "code": null, "e": 2894, "s": 2874, "text": "Subtracts two dates" }, { "code": null, "e": 2950, "s": 2894, "text": "Extracts the date part of a date or datetime expression" }, { "code": null, "e": 2970, "s": 2950, "text": "Subtracts two dates" }, { "code": null, "e": 2995, "s": 2970, "text": "Synonym for DAYOFMONTH()" }, { "code": null, "e": 3027, "s": 2995, "text": "Returns the name of the weekday" }, { "code": null, "e": 3063, "s": 3027, "text": "Returns the day of the month (1-31)" }, { "code": null, "e": 3105, "s": 3063, "text": "Returns the weekday index of the argument" }, { "code": null, "e": 3141, "s": 3105, "text": "Returns the day of the year (1-366)" }, { "code": null, "e": 3165, "s": 3141, "text": "Extracts part of a date" }, { "code": null, "e": 3197, "s": 3165, "text": "Converts a day number to a date" }, { "code": null, "e": 3230, "s": 3197, "text": "Formats date as a UNIX timestamp" }, { "code": null, "e": 3248, "s": 3230, "text": "Extracts the hour" }, { "code": null, "e": 3299, "s": 3248, "text": "Returns the last day of the month for the argument" }, { "code": null, "e": 3317, "s": 3299, "text": "Synonym for NOW()" }, { "code": null, "e": 3335, "s": 3317, "text": "Synonym for NOW()" }, { "code": null, "e": 3380, "s": 3335, "text": "Creates a date from the year and day of year" }, { "code": null, "e": 3391, "s": 3380, "text": "MAKETIME()" }, { "code": null, "e": 3430, "s": 3391, "text": "Returns the microseconds from argument" }, { "code": null, "e": 3467, "s": 3430, "text": "Returns the minute from the argument" }, { "code": null, "e": 3505, "s": 3467, "text": "Return the month from the date passed" }, { "code": null, "e": 3535, "s": 3505, "text": "Returns the name of the month" }, { "code": null, "e": 3569, "s": 3535, "text": "Returns the current date and time" }, { "code": null, "e": 3599, "s": 3569, "text": "Adds a period to a year-month" }, { "code": null, "e": 3644, "s": 3599, "text": "Returns the number of months between periods" }, { "code": null, "e": 3685, "s": 3644, "text": "Returns the quarter from a date argument" }, { "code": null, "e": 3723, "s": 3685, "text": "Converts seconds to 'HH:MM:SS' format" }, { "code": null, "e": 3749, "s": 3723, "text": "Returns the second (0-59)" }, { "code": null, "e": 3777, "s": 3749, "text": "Converts a string to a date" }, { "code": null, "e": 3836, "s": 3777, "text": "When invoked with three arguments a synonym for DATE_SUB()" }, { "code": null, "e": 3852, "s": 3836, "text": "Subtracts times" }, { "code": null, "e": 3900, "s": 3852, "text": "Returns the time at which the function executes" }, { "code": null, "e": 3916, "s": 3900, "text": "Formats as time" }, { "code": null, "e": 3958, "s": 3916, "text": "Returns the argument converted to seconds" }, { "code": null, "e": 4009, "s": 3958, "text": "Extracts the time portion of the expression passed" }, { "code": null, "e": 4024, "s": 4009, "text": "Subtracts time" }, { "code": null, "e": 4147, "s": 4024, "text": "With a single argument this function returns the date or datetime expression. With two arguments, the sum of the arguments" }, { "code": null, "e": 4189, "s": 4147, "text": "Adds an interval to a datetime expression" }, { "code": null, "e": 4238, "s": 4189, "text": "Subtracts an interval from a datetime expression" }, { "code": null, "e": 4282, "s": 4238, "text": "Returns the date argument converted to days" }, { "code": null, "e": 4307, "s": 4282, "text": "Returns a UNIX timestamp" }, { "code": null, "e": 4336, "s": 4307, "text": "Returns the current UTC date" }, { "code": null, "e": 4365, "s": 4336, "text": "Returns the current UTC time" }, { "code": null, "e": 4403, "s": 4365, "text": "Returns the current UTC date and time" }, { "code": null, "e": 4427, "s": 4403, "text": "Returns the week number" }, { "code": null, "e": 4453, "s": 4427, "text": "Returns the weekday index" }, { "code": null, "e": 4498, "s": 4453, "text": "Returns the calendar week of the date (1-53)" }, { "code": null, "e": 4515, "s": 4498, "text": "Returns the year" }, { "code": null, "e": 4541, "s": 4515, "text": "Returns the year and week" }, { "code": null, "e": 4782, "s": 4541, "text": "When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD()." }, { "code": null, "e": 5540, "s": 4782, "text": "mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| ADDDATE('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5662, "s": 5540, "text": "When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr." }, { "code": null, "e": 6027, "s": 5662, "text": "mysql> SELECT ADDDATE('1998-01-02', 31);\n+---------------------------------------------------------+\n| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1998-02-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 6163, "s": 6027, "text": "ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime expression, while the expr2 is a time expression." }, { "code": null, "e": 6557, "s": 6163, "text": "mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002');\n+---------------------------------------------------------+\n| DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') |\n+---------------------------------------------------------+\n| 1998-01-02 01:01:01.000001 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 6749, "s": 6557, "text": "This converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid." }, { "code": null, "e": 7526, "s": 6749, "text": "mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');\n+---------------------------------------------------------+\n| CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') |\n+---------------------------------------------------------+\n| 2004-01-01 13:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');\n+---------------------------------------------------------+\n| CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') |\n+---------------------------------------------------------+\n| 2004-01-01 22:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 7677, "s": 7526, "text": "Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 8380, "s": 7677, "text": "mysql> SELECT CURDATE();\n+---------------------------------------------------------+\n| CURDATE() |\n+---------------------------------------------------------+\n| 1997-12-15 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CURDATE() + 0;\n+---------------------------------------------------------+\n| CURDATE() + 0 |\n+---------------------------------------------------------+\n| 19971215 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 8439, "s": 8380, "text": "CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE()" }, { "code": null, "e": 8635, "s": 8439, "text": "Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone." }, { "code": null, "e": 9338, "s": 8635, "text": "mysql> SELECT CURTIME();\n+---------------------------------------------------------+\n| CURTIME() |\n+---------------------------------------------------------+\n| 23:50:26 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT CURTIME() + 0;\n+---------------------------------------------------------+\n| CURTIME() + 0 |\n+---------------------------------------------------------+\n| 235026 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 9398, "s": 9338, "text": "CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME()." }, { "code": null, "e": 9464, "s": 9398, "text": "CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW()." }, { "code": null, "e": 9528, "s": 9464, "text": "Extracts the date part of the date or datetime expression expr." }, { "code": null, "e": 9895, "s": 9528, "text": "mysql> SELECT DATE('2003-12-31 01:02:03');\n+---------------------------------------------------------+\n| DATE('2003-12-31 01:02:03') |\n+---------------------------------------------------------+\n| 2003-12-31 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 10108, "s": 9895, "text": "DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation." }, { "code": null, "e": 10492, "s": 10108, "text": "mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');\n+---------------------------------------------------------+\n| DATEDIFF('1997-12-31 23:59:59','1997-12-30') |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 10776, "s": 10492, "text": "These functions perform date arithmetic. The date is a DATETIME or DATE value specifying the starting date. The expr is an expression specifying the interval value to be added or subtracted from the starting date. The expr is a string; it may start with a '-' for negative intervals." }, { "code": null, "e": 10864, "s": 10776, "text": "A unit is a keyword indicating the units in which the expression should be interpreted." }, { "code": null, "e": 10932, "s": 10864, "text": "The INTERVAL keyword and the unit specifier are not case sensitive." }, { "code": null, "e": 11018, "s": 10932, "text": "The following table shows the expected form of the expr argument for each unit value." }, { "code": null, "e": 11091, "s": 11018, "text": "The values QUARTER and WEEK are available from the MySQL 5.0.0. version." }, { "code": null, "e": 11879, "s": 11091, "text": "mysql> SELECT DATE_ADD('1997-12-31 23:59:59', \n -> INTERVAL '1:1' MINUTE_SECOND);\n+---------------------------------------------------------+\n| DATE_ADD('1997-12-31 23:59:59', INTERVAL... |\n+---------------------------------------------------------+\n| 1998-01-01 00:01:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR);\n+---------------------------------------------------------+\n| DATE_ADD('1999-01-01', INTERVAL 1 HOUR) |\n+---------------------------------------------------------+\n| 1999-01-01 01:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 11941, "s": 11879, "text": "This command formats the date value as per the format string." }, { "code": null, "e": 12070, "s": 11941, "text": "The following specifiers may be used in the format string. The '%' character is required before the format specifier characters." }, { "code": null, "e": 12073, "s": 12070, "text": "%a" }, { "code": null, "e": 12109, "s": 12073, "text": "Abbreviated weekday name (Sun..Sat)" }, { "code": null, "e": 12112, "s": 12109, "text": "%b" }, { "code": null, "e": 12146, "s": 12112, "text": "Abbreviated month name (Jan..Dec)" }, { "code": null, "e": 12149, "s": 12146, "text": "%c" }, { "code": null, "e": 12172, "s": 12149, "text": "Month, numeric (0..12)" }, { "code": null, "e": 12175, "s": 12172, "text": "%D" }, { "code": null, "e": 12236, "s": 12175, "text": "Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)" }, { "code": null, "e": 12239, "s": 12236, "text": "%d" }, { "code": null, "e": 12274, "s": 12239, "text": "Day of the month, numeric (00..31)" }, { "code": null, "e": 12277, "s": 12274, "text": "%e" }, { "code": null, "e": 12311, "s": 12277, "text": "Day of the month, numeric (0..31)" }, { "code": null, "e": 12314, "s": 12311, "text": "%f" }, { "code": null, "e": 12344, "s": 12314, "text": "Microseconds (000000..999999)" }, { "code": null, "e": 12347, "s": 12344, "text": "%H" }, { "code": null, "e": 12361, "s": 12347, "text": "Hour (00..23)" }, { "code": null, "e": 12364, "s": 12361, "text": "%h" }, { "code": null, "e": 12378, "s": 12364, "text": "Hour (01..12)" }, { "code": null, "e": 12381, "s": 12378, "text": "%I" }, { "code": null, "e": 12395, "s": 12381, "text": "Hour (01..12)" }, { "code": null, "e": 12398, "s": 12395, "text": "%i" }, { "code": null, "e": 12424, "s": 12398, "text": "Minutes, numeric (00..59)" }, { "code": null, "e": 12427, "s": 12424, "text": "%j" }, { "code": null, "e": 12450, "s": 12427, "text": "Day of year (001..366)" }, { "code": null, "e": 12453, "s": 12450, "text": "%k" }, { "code": null, "e": 12466, "s": 12453, "text": "Hour (0..23)" }, { "code": null, "e": 12469, "s": 12466, "text": "%l" }, { "code": null, "e": 12482, "s": 12469, "text": "Hour (1..12)" }, { "code": null, "e": 12485, "s": 12482, "text": "%M" }, { "code": null, "e": 12516, "s": 12485, "text": "Month name (January..December)" }, { "code": null, "e": 12519, "s": 12516, "text": "%m" }, { "code": null, "e": 12543, "s": 12519, "text": "Month, numeric (00..12)" }, { "code": null, "e": 12546, "s": 12543, "text": "%p" }, { "code": null, "e": 12555, "s": 12546, "text": "AM or PM" }, { "code": null, "e": 12558, "s": 12555, "text": "%r" }, { "code": null, "e": 12605, "s": 12558, "text": "Time, 12-hour (hh:mm:ss followed by AM or PM)" }, { "code": null, "e": 12608, "s": 12605, "text": "%S" }, { "code": null, "e": 12625, "s": 12608, "text": "Seconds (00..59)" }, { "code": null, "e": 12628, "s": 12625, "text": "%s" }, { "code": null, "e": 12645, "s": 12628, "text": "Seconds (00..59)" }, { "code": null, "e": 12648, "s": 12645, "text": "%T" }, { "code": null, "e": 12673, "s": 12648, "text": "Time, 24-hour (hh:mm:ss)" }, { "code": null, "e": 12676, "s": 12673, "text": "%U" }, { "code": null, "e": 12733, "s": 12676, "text": "Week (00..53), where Sunday is the first day of the week" }, { "code": null, "e": 12736, "s": 12733, "text": "%u" }, { "code": null, "e": 12793, "s": 12736, "text": "Week (00..53), where Monday is the first day of the week" }, { "code": null, "e": 12796, "s": 12793, "text": "%V" }, { "code": null, "e": 12867, "s": 12796, "text": "Week (01..53), where Sunday is the first day of the week; used with %X" }, { "code": null, "e": 12870, "s": 12867, "text": "%v" }, { "code": null, "e": 12941, "s": 12870, "text": "Week (01..53), where Monday is the first day of the week; used with %x" }, { "code": null, "e": 12944, "s": 12941, "text": "%W" }, { "code": null, "e": 12976, "s": 12944, "text": "Weekday name (Sunday..Saturday)" }, { "code": null, "e": 12979, "s": 12976, "text": "%w" }, { "code": null, "e": 13018, "s": 12979, "text": "Day of the week (0=Sunday..6=Saturday)" }, { "code": null, "e": 13021, "s": 13018, "text": "%X" }, { "code": null, "e": 13118, "s": 13021, "text": "Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V\n" }, { "code": null, "e": 13121, "s": 13118, "text": "%x" }, { "code": null, "e": 13219, "s": 13121, "text": "Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v\n" }, { "code": null, "e": 13222, "s": 13219, "text": "%Y" }, { "code": null, "e": 13249, "s": 13222, "text": "Year, numeric, four digits" }, { "code": null, "e": 13252, "s": 13249, "text": "%y" }, { "code": null, "e": 13279, "s": 13252, "text": "Year, numeric (two digits)" }, { "code": null, "e": 13282, "s": 13279, "text": "%%" }, { "code": null, "e": 13306, "s": 13282, "text": "A literal .%. character" }, { "code": null, "e": 13309, "s": 13306, "text": "%x" }, { "code": null, "e": 13340, "s": 13309, "text": "x, for any.x. not listed above" }, { "code": null, "e": 14130, "s": 13340, "text": "mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');\n+---------------------------------------------------------+\n| DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') |\n+---------------------------------------------------------+\n| Saturday October 1997 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT DATE_FORMAT('1997-10-04 22:23:00'\n -> '%H %k %I %r %T %S %w');\n+---------------------------------------------------------+\n| DATE_FORMAT('1997-10-04 22:23:00....... |\n+---------------------------------------------------------+\n| 22 22 10 10:23:00 PM 22:23:00 00 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 14174, "s": 14130, "text": "This is similar to the DATE_ADD() function." }, { "code": null, "e": 14228, "s": 14174, "text": "The DAY() is a synonym for the DAYOFMONTH() function." }, { "code": null, "e": 14270, "s": 14228, "text": "Returns the name of the weekday for date." }, { "code": null, "e": 14631, "s": 14270, "text": "mysql> SELECT DAYNAME('1998-02-05');\n+---------------------------------------------------------+\n| DAYNAME('1998-02-05') |\n+---------------------------------------------------------+\n| Thursday |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 14692, "s": 14631, "text": "Returns the day of the month for date, in the range 0 to 31." }, { "code": null, "e": 15056, "s": 14692, "text": "mysql> SELECT DAYOFMONTH('1998-02-03');\n+---------------------------------------------------------+\n| DAYOFMONTH('1998-02-03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 15186, "s": 15056, "text": "Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values correspond to the ODBC standard." }, { "code": null, "e": 15549, "s": 15186, "text": "mysql> SELECT DAYOFWEEK('1998-02-03');\n+---------------------------------------------------------+\n|DAYOFWEEK('1998-02-03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 15610, "s": 15549, "text": "Returns the day of the year for date, in the range 1 to 366." }, { "code": null, "e": 15973, "s": 15610, "text": "mysql> SELECT DAYOFYEAR('1998-02-03');\n+---------------------------------------------------------+\n| DAYOFYEAR('1998-02-03') |\n+---------------------------------------------------------+\n| 34 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 16137, "s": 15973, "text": "The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic." }, { "code": null, "e": 16895, "s": 16137, "text": "mysql> SELECT EXTRACT(YEAR FROM '1999-07-02');\n+---------------------------------------------------------+\n| EXTRACT(YEAR FROM '1999-07-02') |\n+---------------------------------------------------------+\n| 1999 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03');\n+---------------------------------------------------------+\n| EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03') |\n+---------------------------------------------------------+\n| 199907 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 16939, "s": 16895, "text": "Given a day number N, returns a DATE value." }, { "code": null, "e": 17296, "s": 16939, "text": "mysql> SELECT FROM_DAYS(729669);\n+---------------------------------------------------------+\n| FROM_DAYS(729669) |\n+---------------------------------------------------------+\n| 1997-10-07 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 17443, "s": 17296, "text": "Note − Use FROM_DAYS() with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582)." }, { "code": null, "e": 17802, "s": 17443, "text": "Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone. The unix_timestamp argument is an internal timestamp values, which are produced by the UNIX_TIMESTAMP() function." }, { "code": null, "e": 17970, "s": 17802, "text": "If the format is given, the result is formatted according to the format string, which is used in the same way as is listed in the entry for the DATE_FORMAT() function." }, { "code": null, "e": 18334, "s": 17970, "text": "mysql> SELECT FROM_UNIXTIME(875996580);\n+---------------------------------------------------------+\n| FROM_UNIXTIME(875996580) |\n+---------------------------------------------------------+\n| 1997-10-04 22:23:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 18528, "s": 18334, "text": "Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23." }, { "code": null, "e": 18884, "s": 18528, "text": "mysql> SELECT HOUR('10:05:03');\n+---------------------------------------------------------+\n| HOUR('10:05:03') |\n+---------------------------------------------------------+\n| 10 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 19023, "s": 18884, "text": "Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid." }, { "code": null, "e": 19385, "s": 19023, "text": "mysql> SELECT LAST_DAY('2003-02-05');\n+---------------------------------------------------------+\n| LAST_DAY('2003-02-05') |\n+---------------------------------------------------------+\n| 2003-02-28 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 19435, "s": 19385, "text": "LOCALTIME and LOCALTIME() are synonyms for NOW()." }, { "code": null, "e": 19495, "s": 19435, "text": "LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW()." }, { "code": null, "e": 19617, "s": 19495, "text": "Returns a date, given year and day-of-year values. The dayofyear value must be greater than 0 or the result will be NULL." }, { "code": null, "e": 19993, "s": 19617, "text": "mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32);\n+---------------------------------------------------------+\n| MAKEDATE(2001,31), MAKEDATE(2001,32) |\n+---------------------------------------------------------+\n| '2001-01-31', '2001-02-01' |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 20069, "s": 19993, "text": "Returns a time value calculated from the hour, minute and second arguments." }, { "code": null, "e": 20427, "s": 20069, "text": "mysql> SELECT MAKETIME(12,15,30);\n+---------------------------------------------------------+\n| MAKETIME(12,15,30) |\n+---------------------------------------------------------+\n| '12:15:30' |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 20539, "s": 20427, "text": "Returns the microseconds from the time or datetime expression (expr) as a number in the range from 0 to 999999." }, { "code": null, "e": 20909, "s": 20539, "text": "mysql> SELECT MICROSECOND('12:00:00.123456');\n+---------------------------------------------------------+\n| MICROSECOND('12:00:00.123456') |\n+---------------------------------------------------------+\n| 123456 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 20960, "s": 20909, "text": "Returns the minute for time, in the range 0 to 59." }, { "code": null, "e": 21327, "s": 20960, "text": "mysql> SELECT MINUTE('98-02-03 10:05:03');\n+---------------------------------------------------------+\n| MINUTE('98-02-03 10:05:03') |\n+---------------------------------------------------------+\n| 5 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 21377, "s": 21327, "text": "Returns the month for date, in the range 0 to 12." }, { "code": null, "e": 21735, "s": 21377, "text": "mysql> SELECT MONTH('1998-02-03')\n+---------------------------------------------------------+\n| MONTH('1998-02-03') |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 21782, "s": 21735, "text": "Returns the full name of the month for a date." }, { "code": null, "e": 22145, "s": 21782, "text": "mysql> SELECT MONTHNAME('1998-02-05');\n+---------------------------------------------------------+\n| MONTHNAME('1998-02-05') |\n+---------------------------------------------------------+\n| February |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 22365, "s": 22145, "text": "Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. This value is expressed in the current time zone." }, { "code": null, "e": 22710, "s": 22365, "text": "mysql> SELECT NOW();\n+---------------------------------------------------------+\n| NOW() |\n+---------------------------------------------------------+\n| 1997-12-15 23:50:26 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 22861, "s": 22710, "text": "Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value." }, { "code": null, "e": 23219, "s": 22861, "text": "mysql> SELECT PERIOD_ADD(9801,2);\n+---------------------------------------------------------+\n| PERIOD_ADD(9801,2) |\n+---------------------------------------------------------+\n| 199803 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 23401, "s": 23219, "text": "Returns the number of months between periods P1 and P2. These periods P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values." }, { "code": null, "e": 23765, "s": 23401, "text": "mysql> SELECT PERIOD_DIFF(9802,199703);\n+---------------------------------------------------------+\n| PERIOD_DIFF(9802,199703) |\n+---------------------------------------------------------+\n| 11 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 23828, "s": 23765, "text": "Returns the quarter of the year for date, in the range 1 to 4." }, { "code": null, "e": 24187, "s": 23828, "text": "mysql> SELECT QUARTER('98-04-01');\n+---------------------------------------------------------+\n| QUARTER('98-04-01') |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 24238, "s": 24187, "text": "Returns the second for time, in the range 0 to 59." }, { "code": null, "e": 24596, "s": 24238, "text": "mysql> SELECT SECOND('10:05:03');\n+---------------------------------------------------------+\n| SECOND('10:05:03') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 24784, "s": 24596, "text": "Returns the seconds argument, converted to hours, minutes and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 25141, "s": 24784, "text": "mysql> SELECT SEC_TO_TIME(2378);\n+---------------------------------------------------------+\n| SEC_TO_TIME(2378) |\n+---------------------------------------------------------+\n| 00:39:38 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 25436, "s": 25141, "text": "This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. The STR_TO_DATE() function returns a DATETIME value if the format string contains both date and time parts. Else, it returns a DATE or TIME value if the string contains only date or time parts." }, { "code": null, "e": 25813, "s": 25436, "text": "mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');\n+---------------------------------------------------------+\n| STR_TO_DATE('04/31/2004', '%m/%d/%Y') |\n+---------------------------------------------------------+\n| 2004-04-31 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 25994, "s": 25813, "text": "When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD()." }, { "code": null, "e": 26752, "s": 25994, "text": "mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| DATE_SUB('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1997-12-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY);\n+---------------------------------------------------------+\n| SUBDATE('1998-01-02', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 1997-12-02 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 26943, "s": 26752, "text": "The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time expression." }, { "code": null, "e": 27344, "s": 26943, "text": "mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999',\n -> '1 1:1:1.000002');\n+---------------------------------------------------------+\n| SUBTIME('1997-12-31 23:59:59.999999'... |\n+---------------------------------------------------------+\n| 1997-12-30 22:58:58.999997 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 27519, "s": 27344, "text": "Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 27868, "s": 27519, "text": "mysql> SELECT SYSDATE();\n+---------------------------------------------------------+\n| SYSDATE() |\n+---------------------------------------------------------+\n| 2006-04-12 13:47:44 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 27959, "s": 27868, "text": "Extracts the time part of the time or datetime expression expr and returns it as a string." }, { "code": null, "e": 28326, "s": 27959, "text": "mysql> SELECT TIME('2003-12-31 01:02:03');\n+---------------------------------------------------------+\n| TIME('2003-12-31 01:02:03') |\n+---------------------------------------------------------+\n| 01:02:03 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 28502, "s": 28326, "text": "The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1 and expr2 values are time or date-and-time expressions, but both must be of the same type." }, { "code": null, "e": 28916, "s": 28502, "text": "mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001',\n -> '1997-12-30 01:01:01.000002');\n+---------------------------------------------------------+\n| TIMEDIFF('1997-12-31 23:59:59.000001'..... |\n+---------------------------------------------------------+\n| 46:58:57.999999 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 29159, "s": 28916, "text": "With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value." }, { "code": null, "e": 29522, "s": 29159, "text": "mysql> SELECT TIMESTAMP('2003-12-31');\n+---------------------------------------------------------+\n| TIMESTAMP('2003-12-31') |\n+---------------------------------------------------------+\n| 2003-12-31 00:00:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 29722, "s": 29522, "text": "This function adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values −" }, { "code": null, "e": 29734, "s": 29722, "text": "FRAC_SECOND" }, { "code": null, "e": 29749, "s": 29734, "text": "SECOND, MINUTE" }, { "code": null, "e": 29759, "s": 29749, "text": "HOUR, DAY" }, { "code": null, "e": 29764, "s": 29759, "text": "WEEK" }, { "code": null, "e": 29770, "s": 29764, "text": "MONTH" }, { "code": null, "e": 29781, "s": 29770, "text": "QUARTER or" }, { "code": null, "e": 29786, "s": 29781, "text": "YEAR" }, { "code": null, "e": 29883, "s": 29786, "text": "The unit value may be specified using one of the keywords as shown or with a prefix of SQL_TSI_." }, { "code": null, "e": 29932, "s": 29883, "text": "For example, DAY and SQL_TSI_DAY both are legal." }, { "code": null, "e": 30307, "s": 29932, "text": "mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02');\n+---------------------------------------------------------+\n| TIMESTAMPADD(MINUTE,1,'2003-01-02') |\n+---------------------------------------------------------+\n| 2003-01-02 00:01:00 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 30579, "s": 30307, "text": "Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2. The unit for the result is given by the unit argument. The legal values for the unit are the same as those listed in the description of the TIMESTAMPADD() function." }, { "code": null, "e": 30965, "s": 30579, "text": "mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');\n+---------------------------------------------------------+\n| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |\n+---------------------------------------------------------+\n| 3 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 31109, "s": 30965, "text": "This function is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes and seconds." }, { "code": null, "e": 31334, "s": 31109, "text": "If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0 to 23. The other hour format specifiers produce the hour value modulo 12." }, { "code": null, "e": 31716, "s": 31334, "text": "mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');\n+---------------------------------------------------------+\n| TIME_FORMAT('100:00:00', '%H %k %h %I %l') |\n+---------------------------------------------------------+\n| 100 100 04 04 4 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 31764, "s": 31716, "text": "Returns the time argument converted to seconds." }, { "code": null, "e": 32127, "s": 31764, "text": "mysql> SELECT TIME_TO_SEC('22:23:00');\n+---------------------------------------------------------+\n| TIME_TO_SEC('22:23:00') |\n+---------------------------------------------------------+\n| 80580 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 32197, "s": 32127, "text": "Given a date, returns a day number (the number of days since year 0)." }, { "code": null, "e": 32552, "s": 32197, "text": "mysql> SELECT TO_DAYS(950501);\n+---------------------------------------------------------+\n| TO_DAYS(950501) |\n+---------------------------------------------------------+\n| 728779 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 32923, "s": 32552, "text": "If called with no argument, this function returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD." }, { "code": null, "e": 33657, "s": 32923, "text": "mysql> SELECT UNIX_TIMESTAMP();\n+---------------------------------------------------------+\n| UNIX_TIMESTAMP() |\n+---------------------------------------------------------+\n| 882226357 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');\n+---------------------------------------------------------+\n| UNIX_TIMESTAMP('1997-10-04 22:23:00') |\n+---------------------------------------------------------+\n| 875996580 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 33807, "s": 33657, "text": "Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 34173, "s": 33807, "text": "mysql> SELECT UTC_DATE(), UTC_DATE() + 0;\n+---------------------------------------------------------+\n| UTC_DATE(), UTC_DATE() + 0 |\n+---------------------------------------------------------+\n| 2003-08-14, 20030814 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 34319, "s": 34173, "text": "Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 34685, "s": 34319, "text": "mysql> SELECT UTC_TIME(), UTC_TIME() + 0;\n+---------------------------------------------------------+\n| UTC_TIME(), UTC_TIME() + 0 |\n+---------------------------------------------------------+\n| 18:07:53, 180753 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 34869, "s": 34685, "text": "Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a numeric context." }, { "code": null, "e": 35245, "s": 34869, "text": "mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;\n+---------------------------------------------------------+\n| UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0 |\n+---------------------------------------------------------+\n| 2003-08-14 18:08:04, 20030814180804 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 35571, "s": 35245, "text": "This function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on a Sunday or a Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used" }, { "code": null, "e": 35929, "s": 35571, "text": "mysql> SELECT WEEK('1998-02-20');\n+---------------------------------------------------------+\n| WEEK('1998-02-20') |\n+---------------------------------------------------------+\n| 7 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 36005, "s": 35929, "text": "Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday)." }, { "code": null, "e": 36375, "s": 36005, "text": "mysql> SELECT WEEKDAY('1998-02-03 22:23:00');\n+---------------------------------------------------------+\n| WEEKDAY('1998-02-03 22:23:00') |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 36529, "s": 36375, "text": "Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3)." }, { "code": null, "e": 36893, "s": 36529, "text": "mysql> SELECT WEEKOFYEAR('1998-02-20');\n+---------------------------------------------------------+\n| WEEKOFYEAR('1998-02-20') |\n+---------------------------------------------------------+\n| 8 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 36973, "s": 36893, "text": "Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date." }, { "code": null, "e": 37329, "s": 36973, "text": "mysql> SELECT YEAR('98-02-03');\n+---------------------------------------------------------+\n| YEAR('98-02-03') |\n+---------------------------------------------------------+\n| 1998 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 37570, "s": 37329, "text": "Returns the year and the week for a date. The mode argument works exactly like the mode argument to the WEEK() function. The year in the result may be different from the year in the date argument for the first and the last week of the year." }, { "code": null, "e": 37932, "s": 37570, "text": "mysql> SELECT YEARWEEK('1987-01-01');\n+---------------------------------------------------------+\n| YEAR('98-02-03')YEARWEEK('1987-01-01') |\n+---------------------------------------------------------+\n| 198653 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 38112, "s": 37932, "text": "Note − The week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year." }, { "code": null, "e": 38145, "s": 38112, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 38159, "s": 38145, "text": " Anadi Sharma" }, { "code": null, "e": 38192, "s": 38159, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 38206, "s": 38192, "text": " Anadi Sharma" }, { "code": null, "e": 38241, "s": 38206, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 38255, "s": 38241, "text": " Anadi Sharma" }, { "code": null, "e": 38288, "s": 38255, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 38310, "s": 38288, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 38345, "s": 38310, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 38399, "s": 38345, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 38432, "s": 38399, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 38460, "s": 38432, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 38467, "s": 38460, "text": " Print" }, { "code": null, "e": 38478, "s": 38467, "text": " Add Notes" } ]
Different ways for String to Integer Conversions in Java - GeeksforGeeks
29 May, 2019 Given a String in Java, the task is to convert this String into Integer. Examples: Input: str = "1234" Output: 1234 Input: str = "456" Output: 456 Convert using Integer.parseInt(String)The Integer class has a static method that returns an integer object representing the specified String parameter.Syntax :public static int parseInt(String str) throws NumberFormatException or public static int parseInt(String str, int radix) throws NumberFormatException Parameters:str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) to represent the sign of the number.radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method.Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs:For both the variants:String is null or of zero lengthThe value represented by the string is not a value of type intSpecifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1Example:class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.parseInt(str); System.out.println("Integer using " + "first variant of" + " praseInt = " + num1); int num2 = Integer.parseInt(str, 16); System.out.println("Integer using " + "second (radix) variant" + " of praseInt = " + num2); }}Output:Integer using first variant of praseInt = 1234 Integer using second (radix) variant of praseInt = 4660 Convert using Integer.valueOf(String)Syntax:public static Integer valueOf(String str) Parameters: This method accepts single parameter str of String type that is to be parsed.Return Value: The method returns an Integer object holding the value represented by the string argument.Example:class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.valueOf(str); System.out.println("Integer using" + " valueOf() = " + num1); }}Output:Integer using valueOf() = 1234 Convert using Integer.parseInt(String)The Integer class has a static method that returns an integer object representing the specified String parameter.Syntax :public static int parseInt(String str) throws NumberFormatException or public static int parseInt(String str, int radix) throws NumberFormatException Parameters:str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) to represent the sign of the number.radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method.Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs:For both the variants:String is null or of zero lengthThe value represented by the string is not a value of type intSpecifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1Example:class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.parseInt(str); System.out.println("Integer using " + "first variant of" + " praseInt = " + num1); int num2 = Integer.parseInt(str, 16); System.out.println("Integer using " + "second (radix) variant" + " of praseInt = " + num2); }}Output:Integer using first variant of praseInt = 1234 Integer using second (radix) variant of praseInt = 4660 public static int parseInt(String str) throws NumberFormatException or public static int parseInt(String str, int radix) throws NumberFormatException Parameters: str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) to represent the sign of the number. radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method. Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs: For both the variants: String is null or of zero length The value represented by the string is not a value of type int Specifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1 The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1 Example: class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.parseInt(str); System.out.println("Integer using " + "first variant of" + " praseInt = " + num1); int num2 = Integer.parseInt(str, 16); System.out.println("Integer using " + "second (radix) variant" + " of praseInt = " + num2); }} Integer using first variant of praseInt = 1234 Integer using second (radix) variant of praseInt = 4660 Convert using Integer.valueOf(String)Syntax:public static Integer valueOf(String str) Parameters: This method accepts single parameter str of String type that is to be parsed.Return Value: The method returns an Integer object holding the value represented by the string argument.Example:class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.valueOf(str); System.out.println("Integer using" + " valueOf() = " + num1); }}Output:Integer using valueOf() = 1234 Syntax: public static Integer valueOf(String str) Parameters: This method accepts single parameter str of String type that is to be parsed. Return Value: The method returns an Integer object holding the value represented by the string argument. Example: class GfG { public static void main(String args[]) { String str = "1234"; int num1 = Integer.valueOf(str); System.out.println("Integer using" + " valueOf() = " + num1); }} Integer using valueOf() = 1234 Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n29 May, 2019" }, { "code": null, "e": 24021, "s": 23948, "text": "Given a String in Java, the task is to convert this String into Integer." }, { "code": null, "e": 24031, "s": 24021, "text": "Examples:" }, { "code": null, "e": 24097, "s": 24031, "text": "Input: str = \"1234\"\nOutput: 1234\n\nInput: str = \"456\"\nOutput: 456\n" }, { "code": null, "e": 26562, "s": 24097, "text": "Convert using Integer.parseInt(String)The Integer class has a static method that returns an integer object representing the specified String parameter.Syntax :public static int parseInt(String str) throws NumberFormatException\nor\npublic static int parseInt(String str, int radix) throws NumberFormatException\nParameters:str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) to represent the sign of the number.radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method.Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs:For both the variants:String is null or of zero lengthThe value represented by the string is not a value of type intSpecifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) provided that the string is longer than length 1Example:class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.parseInt(str); System.out.println(\"Integer using \" + \"first variant of\" + \" praseInt = \" + num1); int num2 = Integer.parseInt(str, 16); System.out.println(\"Integer using \" + \"second (radix) variant\" + \" of praseInt = \" + num2); }}Output:Integer using first variant of praseInt = 1234\nInteger using second (radix) variant of praseInt = 4660\nConvert using Integer.valueOf(String)Syntax:public static Integer valueOf(String str)\nParameters: This method accepts single parameter str of String type that is to be parsed.Return Value: The method returns an Integer object holding the value represented by the string argument.Example:class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.valueOf(str); System.out.println(\"Integer using\" + \" valueOf() = \" + num1); }}Output:Integer using valueOf() = 1234\n" }, { "code": null, "e": 28447, "s": 26562, "text": "Convert using Integer.parseInt(String)The Integer class has a static method that returns an integer object representing the specified String parameter.Syntax :public static int parseInt(String str) throws NumberFormatException\nor\npublic static int parseInt(String str, int radix) throws NumberFormatException\nParameters:str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) to represent the sign of the number.radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method.Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs:For both the variants:String is null or of zero lengthThe value represented by the string is not a value of type intSpecifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) provided that the string is longer than length 1Example:class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.parseInt(str); System.out.println(\"Integer using \" + \"first variant of\" + \" praseInt = \" + num1); int num2 = Integer.parseInt(str, 16); System.out.println(\"Integer using \" + \"second (radix) variant\" + \" of praseInt = \" + num2); }}Output:Integer using first variant of praseInt = 1234\nInteger using second (radix) variant of praseInt = 4660\n" }, { "code": null, "e": 28598, "s": 28447, "text": "public static int parseInt(String str) throws NumberFormatException\nor\npublic static int parseInt(String str, int radix) throws NumberFormatException\n" }, { "code": null, "e": 28610, "s": 28598, "text": "Parameters:" }, { "code": null, "e": 28801, "s": 28610, "text": "str: A string which needs to be converted to the integer. It can also have the first character as a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) to represent the sign of the number." }, { "code": null, "e": 28926, "s": 28801, "text": "radix: The radix used while the string is being parsed. This parameter is only specific to the second variant of the method." }, { "code": null, "e": 29028, "s": 28926, "text": "Exceptions: NumberFormatException is thrown by this method if any of the following situations occurs:" }, { "code": null, "e": 29051, "s": 29028, "text": "For both the variants:" }, { "code": null, "e": 29084, "s": 29051, "text": "String is null or of zero length" }, { "code": null, "e": 29147, "s": 29084, "text": "The value represented by the string is not a value of type int" }, { "code": null, "e": 29536, "s": 29147, "text": "Specifically for the parseInt(String s, int radix) variant of the function:The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIXAny character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) provided that the string is longer than length 1" }, { "code": null, "e": 29640, "s": 29536, "text": "The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX" }, { "code": null, "e": 29851, "s": 29640, "text": "Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\\u002D’) or plus sign ‘+’ (‘\\u002B’) provided that the string is longer than length 1" }, { "code": null, "e": 29860, "s": 29851, "text": "Example:" }, { "code": "class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.parseInt(str); System.out.println(\"Integer using \" + \"first variant of\" + \" praseInt = \" + num1); int num2 = Integer.parseInt(str, 16); System.out.println(\"Integer using \" + \"second (radix) variant\" + \" of praseInt = \" + num2); }}", "e": 30388, "s": 29860, "text": null }, { "code": null, "e": 30492, "s": 30388, "text": "Integer using first variant of praseInt = 1234\nInteger using second (radix) variant of praseInt = 4660\n" }, { "code": null, "e": 31073, "s": 30492, "text": "Convert using Integer.valueOf(String)Syntax:public static Integer valueOf(String str)\nParameters: This method accepts single parameter str of String type that is to be parsed.Return Value: The method returns an Integer object holding the value represented by the string argument.Example:class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.valueOf(str); System.out.println(\"Integer using\" + \" valueOf() = \" + num1); }}Output:Integer using valueOf() = 1234\n" }, { "code": null, "e": 31081, "s": 31073, "text": "Syntax:" }, { "code": null, "e": 31124, "s": 31081, "text": "public static Integer valueOf(String str)\n" }, { "code": null, "e": 31214, "s": 31124, "text": "Parameters: This method accepts single parameter str of String type that is to be parsed." }, { "code": null, "e": 31319, "s": 31214, "text": "Return Value: The method returns an Integer object holding the value represented by the string argument." }, { "code": null, "e": 31328, "s": 31319, "text": "Example:" }, { "code": "class GfG { public static void main(String args[]) { String str = \"1234\"; int num1 = Integer.valueOf(str); System.out.println(\"Integer using\" + \" valueOf() = \" + num1); }}", "e": 31584, "s": 31328, "text": null }, { "code": null, "e": 31616, "s": 31584, "text": "Integer using valueOf() = 1234\n" }, { "code": null, "e": 31629, "s": 31616, "text": "Java-Strings" }, { "code": null, "e": 31634, "s": 31629, "text": "Java" }, { "code": null, "e": 31647, "s": 31634, "text": "Java-Strings" }, { "code": null, "e": 31652, "s": 31647, "text": "Java" }, { "code": null, "e": 31750, "s": 31652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31765, "s": 31750, "text": "Stream In Java" }, { "code": null, "e": 31811, "s": 31765, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31832, "s": 31811, "text": "Constructors in Java" }, { "code": null, "e": 31851, "s": 31832, "text": "Exceptions in Java" }, { "code": null, "e": 31881, "s": 31851, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31898, "s": 31881, "text": "Generics in Java" }, { "code": null, "e": 31941, "s": 31898, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 31970, "s": 31941, "text": "HashMap get() Method in Java" }, { "code": null, "e": 31991, "s": 31970, "text": "Introduction to Java" } ]
How can we set up a MySQL User account by using INSERT INTO statement?
For adding a new user to MySQL, we just need to add a new entry to the user table in the database mysql. To illustrate it we are using the following example − The following program is an example of adding a new user guest with SELECT, INSERT and UPDATE privileges with the password guest123; the SQL query is − root@host# mysql -u root -p Enter password:******* mysql> use mysql; Database changed mysql> INSERT INTO user (host, user, password,select_priv, insert_priv, update_priv) VALUES ('localhost', 'guest',PASSWORD('guest123'),'Y','Y’, 'Y'); Query OK, 1 row affected (0.20 sec) mysql> FLUSH PRIVILEGES; Query OK, 1 row affected (0.01 sec) mysql> SELECT host, user, password FROM user WHERE user = 'guest'; +-----------+---------+------------------+ | host | user | password | +-----------+---------+------------------+ | localhost | guest | 6f8c114b58f2ce9e | +-----------+---------+------------------+ 1 row in set (0.00 sec) When adding a new user, remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example, the password bypass is encrypted to 6f8c114b58f2ce9e. The FLUSH PRIVILEGES statement tells the server to reload the grant tables. If you don't use it, then you won't be able to connect to MySQL using the new user account at least until the server is rebooted.
[ { "code": null, "e": 1221, "s": 1062, "text": "For adding a new user to MySQL, we just need to add a new entry to the user table in the database mysql. To illustrate it we are using the following example −" }, { "code": null, "e": 1373, "s": 1221, "text": "The following program is an example of adding a new user guest with SELECT, INSERT and UPDATE privileges with the password guest123; the SQL query is −" }, { "code": null, "e": 2015, "s": 1373, "text": "root@host# mysql -u root -p\nEnter password:*******\nmysql> use mysql;\nDatabase changed\n\nmysql> INSERT INTO user (host, user, password,select_priv, insert_priv,\nupdate_priv) VALUES ('localhost', 'guest',PASSWORD('guest123'),'Y','Y’,\n'Y');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> FLUSH PRIVILEGES;\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> SELECT host, user, password FROM user WHERE user = 'guest';\n+-----------+---------+------------------+\n| host | user | password |\n+-----------+---------+------------------+\n| localhost | guest | 6f8c114b58f2ce9e |\n+-----------+---------+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2212, "s": 2015, "text": "When adding a new user, remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example, the password bypass is encrypted to 6f8c114b58f2ce9e." }, { "code": null, "e": 2418, "s": 2212, "text": "The FLUSH PRIVILEGES statement tells the server to reload the grant tables. If you don't use it, then you won't be able to connect to MySQL using the new user account at least until the server is rebooted." } ]
Java Assignment Operator Examples
The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program − Online Demo public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c += a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a ; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c /= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c <<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c &= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a ; System.out.println("c |= a = " + c ); } } This will produce the following result − c = a + b = 30 c += a = 40 c -= a = 30 c *= a = 300 c /= a = 1 c %= a = 5 c <<= 2 = 20 c >>= 2 = 5 c >>= 2 = 1 c &= a = 0 c ^= a = 10 c |= a = 10
[ { "code": null, "e": 1240, "s": 1062, "text": "The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program −" }, { "code": null, "e": 1252, "s": 1240, "text": "Online Demo" }, { "code": null, "e": 2170, "s": 1252, "text": "public class Test {\n public static void main(String args[]) {\n int a = 10;\n int b = 20;\n int c = 0;\n\n c = a + b;\n System.out.println(\"c = a + b = \" + c );\n\n c += a ;\n System.out.println(\"c += a = \" + c );\n\n c -= a ;\n System.out.println(\"c -= a = \" + c );\n\n c *= a ;\n System.out.println(\"c *= a = \" + c );\n\n a = 10;\n c = 15;\n c /= a ;\n System.out.println(\"c /= a = \" + c );\n\n a = 10;\n c = 15;\n c %= a ;\n System.out.println(\"c %= a = \" + c );\n\n c <<= 2 ;\n System.out.println(\"c <<= 2 = \" + c );\n\n c >>= 2 ;\n System.out.println(\"c >>= 2 = \" + c );\n\n c >>= 2 ;\n System.out.println(\"c >>= 2 = \" + c );\n\n c &= a ;\n System.out.println(\"c &= a = \" + c );\n\n c ^= a ;\n System.out.println(\"c ^= a = \" + c );\n\n c |= a ;\n System.out.println(\"c |= a = \" + c );\n }\n}" }, { "code": null, "e": 2211, "s": 2170, "text": "This will produce the following result −" }, { "code": null, "e": 2364, "s": 2211, "text": "c = a + b = 30\nc += a = 40\nc -= a = 30\nc *= a = 300\nc /= a = 1\nc %= a = 5\nc <<= 2 = 20\nc >>= 2 = 5\nc >>= 2 = 1\nc &= a = 0\nc ^= a = 10\nc |= a = 10" } ]
Difference between Java and PHP - GeeksforGeeks
10 Sep, 2020 Java is a very famous object-oriented programming language. It was developed by Sun Microsystems. It has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. It has a continuous contribution from industry experts, Java developers, and other open-source organizations. Example : Java // A Java program to print public class GFG { public static void main(String args[]) { System.out.println("Welcome to GFG"); } } Output: Welcome to GFG PHP is a server-side scripting language used mainly for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. Example: PHP <?php // Here echo command is// used to display contentecho "Welcome to GFG!"; ?> Output: Welcome to GFG! Difference between Java and PHP : JAVA PHP PHP-Misc Difference Between Java PHP Java PHP 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java 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": 26423, "s": 26395, "text": "\n10 Sep, 2020" }, { "code": null, "e": 26788, "s": 26423, "text": "Java is a very famous object-oriented programming language. It was developed by Sun Microsystems. It has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. It has a continuous contribution from industry experts, Java developers, and other open-source organizations. " }, { "code": null, "e": 26798, "s": 26788, "text": "Example :" }, { "code": null, "e": 26803, "s": 26798, "text": "Java" }, { "code": "// A Java program to print public class GFG { public static void main(String args[]) { System.out.println(\"Welcome to GFG\"); } }", "e": 26953, "s": 26803, "text": null }, { "code": null, "e": 26961, "s": 26953, "text": "Output:" }, { "code": null, "e": 26976, "s": 26961, "text": "Welcome to GFG" }, { "code": null, "e": 27307, "s": 26976, "text": "PHP is a server-side scripting language used mainly for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser." }, { "code": null, "e": 27316, "s": 27307, "text": "Example:" }, { "code": null, "e": 27320, "s": 27316, "text": "PHP" }, { "code": "<?php // Here echo command is// used to display contentecho \"Welcome to GFG!\"; ?> ", "e": 27405, "s": 27320, "text": null }, { "code": null, "e": 27413, "s": 27405, "text": "Output:" }, { "code": null, "e": 27429, "s": 27413, "text": "Welcome to GFG!" }, { "code": null, "e": 27463, "s": 27429, "text": "Difference between Java and PHP :" }, { "code": null, "e": 27468, "s": 27463, "text": "JAVA" }, { "code": null, "e": 27472, "s": 27468, "text": "PHP" }, { "code": null, "e": 27481, "s": 27472, "text": "PHP-Misc" }, { "code": null, "e": 27500, "s": 27481, "text": "Difference Between" }, { "code": null, "e": 27505, "s": 27500, "text": "Java" }, { "code": null, "e": 27509, "s": 27505, "text": "PHP" }, { "code": null, "e": 27514, "s": 27509, "text": "Java" }, { "code": null, "e": 27518, "s": 27514, "text": "PHP" }, { "code": null, "e": 27616, "s": 27518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27616, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27745, "s": 27677, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27803, "s": 27745, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27858, "s": 27803, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27924, "s": 27858, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 27939, "s": 27924, "text": "Arrays in Java" }, { "code": null, "e": 27983, "s": 27939, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28005, "s": 27983, "text": "For-each loop in Java" }, { "code": null, "e": 28056, "s": 28005, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Barabasi Albert Graph (for Scale Free Models) - GeeksforGeeks
15 Nov, 2021 The current article would deal with the concepts surrounding the complex networks using the python library Networkx. It is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. With NetworkX you can load and store networks in standard and nonstandard data formats, generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms, draw networks, and much more. The current article would deal with the algorithm for generating random scale free networks for using preferential attachment model. The reason of interest behind this model dates back to the 1990s when Albert Lazlo Barabasi and Reka Albert came out with the path breaking research describing the model followed by the scale free networks around the world. They suggested that several natural and human-made systems, including the Internet, the World Wide Web, citation networks, and some social networks are thought to be approximately scale-free networks.A scale-free network is a network whose degree distribution follows a power law, at least asymptotically. That is, the fraction P (k) of nodes in the network having k connections to other nodes goes for large values of k as Where is a parameter whose value is typically in the range 2 < < 3, although occasionally it may lie outside these bounds and c is a proportionality constant. The Barabási–Albert model is one of several proposed models that generate scale-free networks. It incorporates two important general concepts: growth and preferential attachment. Both growth and preferential attachment exist widely in real networks. Growth means that the number of nodes in the network increases over time.Preferential attachment means that the more connected a node is, the more likely it is to receive new links. Nodes with higher degree have stronger ability to grab links added to the network. Intuitively, the preferential attachment can be understood if we think in terms of social networks connecting people. Here a link from A to B means that person A "knows" or "is acquainted with" person B. Heavily linked nodes represent well-known people with lots of relations. When a newcomer enters the community, s/he is more likely to become acquainted with one of those more visible people rather than with a relative unknown. The BA model was proposed by assuming that in the World Wide Web, new pages link preferentially to hubs, i.e. very well-known sites such as Google, rather than to pages that hardly anyone knows. If someone selects a new page to link to by randomly choosing an existing link, the probability of selecting a particular page would be proportional to its degree. Following image will describe the BA Model graph with 50 nodes following the preferential attachment model. The above graph completely satisfies the logic of the rich getting richer and the poor getting poorer. Code:The following code is a part of the function which we will eventually implement using the networkx library. def barabasi_albert_graph(n, m, seed=None): """Returns a random graph according to the Barabási–Albert preferential Attachment model. A graph of ``n`` nodes is grown by attaching new nodes each with ``m`` Edges that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m : int Number of edges to attach from a new node to existing nodes seed : int, optional Seed for random number generator (default=None). Returns ------- G : Graph Raises ------ NetworkXError If ``m`` does not satisfy ``1 <= m < n``. if m < 1 or m >=n: raise nx.NetworkXError("Barabási–Albert network must have m >= 1" " and m < n, m = %d, n = %d" % (m, n)) if seed is not None: random.seed(seed) # Add m initial nodes (m0 in barabasi-speak) G=empty_graph(m) G.name="barabasi_albert_graph(%s,%s)"%(n,m) # Target nodes for new edges targets=list(range(m)) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes=[] # Start adding the other n-m nodes. The first node is m. source=m while source<n: # Add edges to m nodes from the source. G.add_edges_from(zip(*m,targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node "source" has m edges to add to the list. repeated_nodes.extend(*m) # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachement) targets = _random_subset(repeated_nodes,m) source += 1 return G The above code is a part of the networkx library which is used to handle the random graphs efficiently in python. One will have to install it before running the following code. >>> import networkx as nx>>> G= nx.barabasi_albert_graph(50,40)>>> nx.draw(G, with_labels=True) To display the above graph, I used the matplotlib library. We need to install it before the execution of the below codes. >>> import matplotlib.pyplot as plt>>> plt.show() So the final code seemed like: >>> import networkx as nx>>> import matplotlib.pyplot as plt >>> G= nx.barabasi_albert_graph(40,15)>>> nx.draw(G, with_labels=True)>>> plt.show() Output: BA model for 40 nodes Thus I would further like to describe more about the networkx library and it modules basically focusing on the centrality measure of a network (especially the scale free models). ReferencesYou can read more about the same at https://en.wikipedia.org/wiki/Barab%C3%A1si%E2%80%93Albert_model http://networkx.readthedocs.io/en/networkx-1.10/index.html.My Personal Notes arrow_drop_upSave . Advanced Data Structure Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Segment Tree | Set 1 (Sum of given range) Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 26387, "s": 26359, "text": "\n15 Nov, 2021" }, { "code": null, "e": 26899, "s": 26387, "text": "The current article would deal with the concepts surrounding the complex networks using the python library Networkx. It is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. With NetworkX you can load and store networks in standard and nonstandard data formats, generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms, draw networks, and much more." }, { "code": null, "e": 27680, "s": 26899, "text": "The current article would deal with the algorithm for generating random scale free networks for using preferential attachment model. The reason of interest behind this model dates back to the 1990s when Albert Lazlo Barabasi and Reka Albert came out with the path breaking research describing the model followed by the scale free networks around the world. They suggested that several natural and human-made systems, including the Internet, the World Wide Web, citation networks, and some social networks are thought to be approximately scale-free networks.A scale-free network is a network whose degree distribution follows a power law, at least asymptotically. That is, the fraction P (k) of nodes in the network having k connections to other nodes goes for large values of k as" }, { "code": null, "e": 27841, "s": 27680, "text": "Where is a parameter whose value is typically in the range 2 < < 3, although occasionally it may lie outside these bounds and c is a proportionality constant." }, { "code": null, "e": 29147, "s": 27841, "text": "The Barabási–Albert model is one of several proposed models that generate scale-free networks. It incorporates two important general concepts: growth and preferential attachment. Both growth and preferential attachment exist widely in real networks. Growth means that the number of nodes in the network increases over time.Preferential attachment means that the more connected a node is, the more likely it is to receive new links. Nodes with higher degree have stronger ability to grab links added to the network. Intuitively, the preferential attachment can be understood if we think in terms of social networks connecting people. Here a link from A to B means that person A \"knows\" or \"is acquainted with\" person B. Heavily linked nodes represent well-known people with lots of relations. When a newcomer enters the community, s/he is more likely to become acquainted with one of those more visible people rather than with a relative unknown. The BA model was proposed by assuming that in the World Wide Web, new pages link preferentially to hubs, i.e. very well-known sites such as Google, rather than to pages that hardly anyone knows. If someone selects a new page to link to by randomly choosing an existing link, the probability of selecting a particular page would be proportional to its degree." }, { "code": null, "e": 29255, "s": 29147, "text": "Following image will describe the BA Model graph with 50 nodes following the preferential attachment model." }, { "code": null, "e": 29358, "s": 29255, "text": "The above graph completely satisfies the logic of the rich getting richer and the poor getting poorer." }, { "code": null, "e": 29471, "s": 29358, "text": "Code:The following code is a part of the function which we will eventually implement using the networkx library." }, { "code": "def barabasi_albert_graph(n, m, seed=None): \"\"\"Returns a random graph according to the Barabási–Albert preferential Attachment model. A graph of ``n`` nodes is grown by attaching new nodes each with ``m`` Edges that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m : int Number of edges to attach from a new node to existing nodes seed : int, optional Seed for random number generator (default=None). Returns ------- G : Graph Raises ------ NetworkXError If ``m`` does not satisfy ``1 <= m < n``. if m < 1 or m >=n: raise nx.NetworkXError(\"Barabási–Albert network must have m >= 1\" \" and m < n, m = %d, n = %d\" % (m, n)) if seed is not None: random.seed(seed) # Add m initial nodes (m0 in barabasi-speak) G=empty_graph(m) G.name=\"barabasi_albert_graph(%s,%s)\"%(n,m) # Target nodes for new edges targets=list(range(m)) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes=[] # Start adding the other n-m nodes. The first node is m. source=m while source<n: # Add edges to m nodes from the source. G.add_edges_from(zip(*m,targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node \"source\" has m edges to add to the list. repeated_nodes.extend(*m) # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachement) targets = _random_subset(repeated_nodes,m) source += 1 return G", "e": 31203, "s": 29471, "text": null }, { "code": null, "e": 31380, "s": 31203, "text": "The above code is a part of the networkx library which is used to handle the random graphs efficiently in python. One will have to install it before running the following code." }, { "code": ">>> import networkx as nx>>> G= nx.barabasi_albert_graph(50,40)>>> nx.draw(G, with_labels=True)", "e": 31476, "s": 31380, "text": null }, { "code": null, "e": 31598, "s": 31476, "text": "To display the above graph, I used the matplotlib library. We need to install it before the execution of the below codes." }, { "code": ">>> import matplotlib.pyplot as plt>>> plt.show()", "e": 31648, "s": 31598, "text": null }, { "code": null, "e": 31679, "s": 31648, "text": "So the final code seemed like:" }, { "code": ">>> import networkx as nx>>> import matplotlib.pyplot as plt >>> G= nx.barabasi_albert_graph(40,15)>>> nx.draw(G, with_labels=True)>>> plt.show()", "e": 31826, "s": 31679, "text": null }, { "code": null, "e": 31834, "s": 31826, "text": "Output:" }, { "code": null, "e": 31856, "s": 31834, "text": "BA model for 40 nodes" }, { "code": null, "e": 32035, "s": 31856, "text": "Thus I would further like to describe more about the networkx library and it modules basically focusing on the centrality measure of a network (especially the scale free models)." }, { "code": null, "e": 32081, "s": 32035, "text": "ReferencesYou can read more about the same at" }, { "code": null, "e": 32146, "s": 32081, "text": "https://en.wikipedia.org/wiki/Barab%C3%A1si%E2%80%93Albert_model" }, { "code": null, "e": 32241, "s": 32146, "text": "http://networkx.readthedocs.io/en/networkx-1.10/index.html.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32243, "s": 32241, "text": "." }, { "code": null, "e": 32267, "s": 32243, "text": "Advanced Data Structure" }, { "code": null, "e": 32273, "s": 32267, "text": "Graph" }, { "code": null, "e": 32279, "s": 32273, "text": "Graph" }, { "code": null, "e": 32377, "s": 32279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32411, "s": 32377, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 32451, "s": 32411, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 32479, "s": 32451, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 32511, "s": 32479, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 32553, "s": 32511, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 32604, "s": 32553, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32662, "s": 32604, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32713, "s": 32662, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Life Expectancy vs Gross Domestic Product using Data Analytics! | by Dhruvil Shah | Towards Data Science
Data Analytics refers to data processing methods to improve productivity and business benefit. Data is derived from various sources and is cleaned and categorized to interpret different patterns of actions. Here, the relation between the terms GDP and Life Expectancy at Birth Year is analyzed with the help of the last 20 years data of six different countries. GDP: Gross Domestic Product (GDP) is the overall monetary or consumer value of all finished goods and services produced within the boundaries of a nation over a given period. It acts as a large measure of overall domestic output, as a detailed scorecard of the economic health of the country. GDP is measured in US dollars.Life Expectancy at Birth Year (LEABY): The word “Life Expectancy” refers to how many years a person may expect to live. By definition, life expectancy is based on an estimation of the average age at which members of a given demographic group will be at death. GDP: Gross Domestic Product (GDP) is the overall monetary or consumer value of all finished goods and services produced within the boundaries of a nation over a given period. It acts as a large measure of overall domestic output, as a detailed scorecard of the economic health of the country. GDP is measured in US dollars. Life Expectancy at Birth Year (LEABY): The word “Life Expectancy” refers to how many years a person may expect to live. By definition, life expectancy is based on an estimation of the average age at which members of a given demographic group will be at death. The data used in this project is gathered from the World Bank. This project aims to try and identify the relationship between the GDP and Life Expectancy of six countries namely, Australia, China, Germany, India, the United States of America, and Zimbabwe with the help of Data visualization. Find the code of this project here and connect with me on LinkedIn. Let’s get to the coding part. Violin plots help us to visualize and compare more than one distributions at a time. There are two symmetrical ‘KDE — Kernel Density Estimator — plots’ along the middle line. The ‘black thick line’ at the center shows the interquartile range while the lines that extend from it to the ends represent a 95% confidence interval. The white dot in the middle shows the median of the distribution. Learn more about violin plots here. Below is the code for creating the violin plots of each of the six countries. from matplotlib import pyplot as pltimport pandas as pdimport seaborn as snsdf = pd.read_csv("final.csv")fig = plt.subplots(figsize=(12, 7))sns.violinplot(data=df, x='Country', y='LEABY', fontsize='large', fontweight='bold')plt.savefig("violin.png",bbox_inches='tight') Output: We can see that variance is the highest in the data of Zimbabwe country and the lowest in the United States. Also, the median Life Expectancy is the largest in Australia and the lowest in Zimbabwe. A FacetGrid takes in a function and creates individual graphs for which you specify the arguments. Next, to see the correlation between GDP and LEABY, let’s see the facet grid of scatter graphs, mapping GDP as a function of Life Expectancy by country. Below are the matplotlib scatter plots for the plot (LEABY vs GDP). g = sns.FacetGrid(df, col='Year', hue='Country', col_wrap=4, size=2)g = (g.map(plt.scatter, 'GDP', 'LEABY', edgecolor="w").add_legend()) Scatter plots are easy to interpret. We can notice the changes over the last 20 years in the countries from the plot above. China and the United States are the countries that have moved most along the x-axis i.e. GDP has increased over the years while Zimbabwe has moved most along the y-axis i.e. life expectancy there has increased over time. Further, Life expectancy in Australia and the United States seems to be constant for the last 20 years. Furthermore, a great way to visualize a variable over time is by using a line plot. Now, instead of the scatter plots if we use line plots for GDP and Life expectancy individually we could more easily see the changes over time. Below is the FacetGrid of line graphs mapping GDP by country. g3 = sns.FacetGrid(df, col="Country", col_wrap=3, size=4)g3 = (g3.map(plt.plot, "Year", "GDP").add_legend()) United States of America has the highest GDP among these countries and it steadily seems to be increasing over the years. As we can see that the GDP in China has drastically increased in the past 10 years, it is interesting to know what happened in China that made this sudden change? There are many reasons behind that, which you can find in the below article. www.weforum.org Now let’s look at a similar plot as above for LEABY. Below is the FacetGrid of line graphs mapping Life expectancy by country. g3 = sns.FacetGrid(df, col="Country", col_wrap=3, size=4)g3 = (g3.map(plt.plot, "Year", "LEABY").add_legend()) It is from 2010–2015 when there is a huge change in the Life expectancy of these six countries. The United States has had the least change in life expectancy over time, could this be the outcome of having high GDP? But then there is the case of Australia where the GDP is lower compared to other ones’, but the life expectancy is still almost equal to that of the United States. It seems that the relation between GDP and Life expectancy is not that simple. “It’s pretty surprising,” says Adriana Lleras-Muney, a professor of economics at the Los Angeles University of California. “We know that people live longer in rich countries than people in poor countries. There is a strong relationship between GDP and life expectancy which indicates that more income is better. And yet, when the economy is doing well, when it is rising higher than normal, we find that more people are dying.” That is to say, becoming rich has great benefits. But the method of being wealthy, it sounds risky. To conclude, the economists agree that, when the economic performance of a country — its GDP — is higher than anticipated, mortality rates are often higher than expected. The relationship is evident but the impact size is small. Adults are about 1 percent more likely to die in a year when GDP is about 5 percent above average — which is a decent boom. Read the below article for a better understanding of the relation between GDP and Life expectancy.
[ { "code": null, "e": 534, "s": 172, "text": "Data Analytics refers to data processing methods to improve productivity and business benefit. Data is derived from various sources and is cleaned and categorized to interpret different patterns of actions. Here, the relation between the terms GDP and Life Expectancy at Birth Year is analyzed with the help of the last 20 years data of six different countries." }, { "code": null, "e": 1117, "s": 534, "text": "GDP: Gross Domestic Product (GDP) is the overall monetary or consumer value of all finished goods and services produced within the boundaries of a nation over a given period. It acts as a large measure of overall domestic output, as a detailed scorecard of the economic health of the country. GDP is measured in US dollars.Life Expectancy at Birth Year (LEABY): The word “Life Expectancy” refers to how many years a person may expect to live. By definition, life expectancy is based on an estimation of the average age at which members of a given demographic group will be at death." }, { "code": null, "e": 1441, "s": 1117, "text": "GDP: Gross Domestic Product (GDP) is the overall monetary or consumer value of all finished goods and services produced within the boundaries of a nation over a given period. It acts as a large measure of overall domestic output, as a detailed scorecard of the economic health of the country. GDP is measured in US dollars." }, { "code": null, "e": 1701, "s": 1441, "text": "Life Expectancy at Birth Year (LEABY): The word “Life Expectancy” refers to how many years a person may expect to live. By definition, life expectancy is based on an estimation of the average age at which members of a given demographic group will be at death." }, { "code": null, "e": 1994, "s": 1701, "text": "The data used in this project is gathered from the World Bank. This project aims to try and identify the relationship between the GDP and Life Expectancy of six countries namely, Australia, China, Germany, India, the United States of America, and Zimbabwe with the help of Data visualization." }, { "code": null, "e": 2092, "s": 1994, "text": "Find the code of this project here and connect with me on LinkedIn. Let’s get to the coding part." }, { "code": null, "e": 2521, "s": 2092, "text": "Violin plots help us to visualize and compare more than one distributions at a time. There are two symmetrical ‘KDE — Kernel Density Estimator — plots’ along the middle line. The ‘black thick line’ at the center shows the interquartile range while the lines that extend from it to the ends represent a 95% confidence interval. The white dot in the middle shows the median of the distribution. Learn more about violin plots here." }, { "code": null, "e": 2599, "s": 2521, "text": "Below is the code for creating the violin plots of each of the six countries." }, { "code": null, "e": 2869, "s": 2599, "text": "from matplotlib import pyplot as pltimport pandas as pdimport seaborn as snsdf = pd.read_csv(\"final.csv\")fig = plt.subplots(figsize=(12, 7))sns.violinplot(data=df, x='Country', y='LEABY', fontsize='large', fontweight='bold')plt.savefig(\"violin.png\",bbox_inches='tight')" }, { "code": null, "e": 2877, "s": 2869, "text": "Output:" }, { "code": null, "e": 3075, "s": 2877, "text": "We can see that variance is the highest in the data of Zimbabwe country and the lowest in the United States. Also, the median Life Expectancy is the largest in Australia and the lowest in Zimbabwe." }, { "code": null, "e": 3174, "s": 3075, "text": "A FacetGrid takes in a function and creates individual graphs for which you specify the arguments." }, { "code": null, "e": 3395, "s": 3174, "text": "Next, to see the correlation between GDP and LEABY, let’s see the facet grid of scatter graphs, mapping GDP as a function of Life Expectancy by country. Below are the matplotlib scatter plots for the plot (LEABY vs GDP)." }, { "code": null, "e": 3532, "s": 3395, "text": "g = sns.FacetGrid(df, col='Year', hue='Country', col_wrap=4, size=2)g = (g.map(plt.scatter, 'GDP', 'LEABY', edgecolor=\"w\").add_legend())" }, { "code": null, "e": 3981, "s": 3532, "text": "Scatter plots are easy to interpret. We can notice the changes over the last 20 years in the countries from the plot above. China and the United States are the countries that have moved most along the x-axis i.e. GDP has increased over the years while Zimbabwe has moved most along the y-axis i.e. life expectancy there has increased over time. Further, Life expectancy in Australia and the United States seems to be constant for the last 20 years." }, { "code": null, "e": 4271, "s": 3981, "text": "Furthermore, a great way to visualize a variable over time is by using a line plot. Now, instead of the scatter plots if we use line plots for GDP and Life expectancy individually we could more easily see the changes over time. Below is the FacetGrid of line graphs mapping GDP by country." }, { "code": null, "e": 4380, "s": 4271, "text": "g3 = sns.FacetGrid(df, col=\"Country\", col_wrap=3, size=4)g3 = (g3.map(plt.plot, \"Year\", \"GDP\").add_legend())" }, { "code": null, "e": 4742, "s": 4380, "text": "United States of America has the highest GDP among these countries and it steadily seems to be increasing over the years. As we can see that the GDP in China has drastically increased in the past 10 years, it is interesting to know what happened in China that made this sudden change? There are many reasons behind that, which you can find in the below article." }, { "code": null, "e": 4758, "s": 4742, "text": "www.weforum.org" }, { "code": null, "e": 4885, "s": 4758, "text": "Now let’s look at a similar plot as above for LEABY. Below is the FacetGrid of line graphs mapping Life expectancy by country." }, { "code": null, "e": 4996, "s": 4885, "text": "g3 = sns.FacetGrid(df, col=\"Country\", col_wrap=3, size=4)g3 = (g3.map(plt.plot, \"Year\", \"LEABY\").add_legend())" }, { "code": null, "e": 5454, "s": 4996, "text": "It is from 2010–2015 when there is a huge change in the Life expectancy of these six countries. The United States has had the least change in life expectancy over time, could this be the outcome of having high GDP? But then there is the case of Australia where the GDP is lower compared to other ones’, but the life expectancy is still almost equal to that of the United States. It seems that the relation between GDP and Life expectancy is not that simple." }, { "code": null, "e": 5982, "s": 5454, "text": "“It’s pretty surprising,” says Adriana Lleras-Muney, a professor of economics at the Los Angeles University of California. “We know that people live longer in rich countries than people in poor countries. There is a strong relationship between GDP and life expectancy which indicates that more income is better. And yet, when the economy is doing well, when it is rising higher than normal, we find that more people are dying.” That is to say, becoming rich has great benefits. But the method of being wealthy, it sounds risky." } ]
Anonymous Functions in Scala - GeeksforGeeks
26 Feb, 2019 In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.Syntax: (z:Int, y:Int)=> z*y Or (_:Int)*(_Int) In the above first syntax, => is known as a transformer. The transformer is used to transform the parameter-list of the left-hand side of the symbol into a new result using the expression present on the right-hand side. In the above second syntax, _ character is known as a wildcard is a shorthand way to represent a parameter who appears only once in the anonymous function. When a function literal is instantiated in an object is known as a function value. Or in other words, when an anonymous function is assigned to a variable then we can invoke that variable like a function call. We can define multiple arguments in the anonymous function. Example 1: // Scala program to illustrate the anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // with multiple parameters Assign // anonymous functions to variables var myfc1 = (str1:String, str2:String) => str1 + str2 // An anonymous function is created // using _ wildcard instead of // variable name because str1 and // str2 variable appear only once var myfc2 = (_:String) + (_:String) // Here, the variable invoke like a function call println(myfc1("Geeks", "12Geeks")) println(myfc2("Geeks", "forGeeks")) }} Output: Geeks12Geeks GeeksforGeeks We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function.Example 2: // Scala program to illustrate anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // without parameter var myfun1 = () => {"Welcome to GeeksforGeeks...!!"} println(myfun1()) // A function which contain anonymous // function as a parameter def myfunction(fun:(String, String)=> String) = { fun("Dog", "Cat") } // Explicit type declaration of anonymous // function in another function val f1 = myfunction((str1: String, str2: String) => str1 + str2) // Shorthand declaration using wildcard val f2 = myfunction(_ + _) println(f1) println(f2) }} Output: Welcome to GeeksforGeeks...!! DogCat DogCat Scala Scala-Method 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 Scala | reduce() Function Scala List filter() method with example String concatenation in Scala Scala Tutorial – Learn Scala with Step By Step Guide Type Casting in Scala Scala List contains() method with example Scala String replace() method with example
[ { "code": null, "e": 24818, "s": 24790, "text": "\n26 Feb, 2019" }, { "code": null, "e": 25092, "s": 24818, "text": "In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.Syntax:" }, { "code": null, "e": 25131, "s": 25092, "text": "(z:Int, y:Int)=> z*y\nOr\n(_:Int)*(_Int)" }, { "code": null, "e": 25351, "s": 25131, "text": "In the above first syntax, => is known as a transformer. The transformer is used to transform the parameter-list of the left-hand side of the symbol into a new result using the expression present on the right-hand side." }, { "code": null, "e": 25507, "s": 25351, "text": "In the above second syntax, _ character is known as a wildcard is a shorthand way to represent a parameter who appears only once in the anonymous function." }, { "code": null, "e": 25777, "s": 25507, "text": "When a function literal is instantiated in an object is known as a function value. Or in other words, when an anonymous function is assigned to a variable then we can invoke that variable like a function call. We can define multiple arguments in the anonymous function." }, { "code": null, "e": 25788, "s": 25777, "text": "Example 1:" }, { "code": "// Scala program to illustrate the anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // with multiple parameters Assign // anonymous functions to variables var myfc1 = (str1:String, str2:String) => str1 + str2 // An anonymous function is created // using _ wildcard instead of // variable name because str1 and // str2 variable appear only once var myfc2 = (_:String) + (_:String) // Here, the variable invoke like a function call println(myfc1(\"Geeks\", \"12Geeks\")) println(myfc2(\"Geeks\", \"forGeeks\")) }}", "e": 26465, "s": 25788, "text": null }, { "code": null, "e": 26473, "s": 26465, "text": "Output:" }, { "code": null, "e": 26501, "s": 26473, "text": "Geeks12Geeks\nGeeksforGeeks\n" }, { "code": null, "e": 26671, "s": 26503, "text": "We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function.Example 2:" }, { "code": "// Scala program to illustrate anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // without parameter var myfun1 = () => {\"Welcome to GeeksforGeeks...!!\"} println(myfun1()) // A function which contain anonymous // function as a parameter def myfunction(fun:(String, String)=> String) = { fun(\"Dog\", \"Cat\") } // Explicit type declaration of anonymous // function in another function val f1 = myfunction((str1: String, str2: String) => str1 + str2) // Shorthand declaration using wildcard val f2 = myfunction(_ + _) println(f1) println(f2) }}", "e": 27452, "s": 26671, "text": null }, { "code": null, "e": 27460, "s": 27452, "text": "Output:" }, { "code": null, "e": 27505, "s": 27460, "text": "Welcome to GeeksforGeeks...!!\nDogCat\nDogCat\n" }, { "code": null, "e": 27511, "s": 27505, "text": "Scala" }, { "code": null, "e": 27524, "s": 27511, "text": "Scala-Method" }, { "code": null, "e": 27530, "s": 27524, "text": "Scala" }, { "code": null, "e": 27628, "s": 27530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27646, "s": 27628, "text": "For Loop in Scala" }, { "code": null, "e": 27667, "s": 27646, "text": "Scala | map() method" }, { "code": null, "e": 27690, "s": 27667, "text": "Scala | flatMap Method" }, { "code": null, "e": 27716, "s": 27690, "text": "Scala | reduce() Function" }, { "code": null, "e": 27756, "s": 27716, "text": "Scala List filter() method with example" }, { "code": null, "e": 27786, "s": 27756, "text": "String concatenation in Scala" }, { "code": null, "e": 27839, "s": 27786, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 27861, "s": 27839, "text": "Type Casting in Scala" }, { "code": null, "e": 27903, "s": 27861, "text": "Scala List contains() method with example" } ]
Python - How to Count the NaN Occurrences in a Column in Pandas Dataframe?
To count the NaN occurrences in a column, use the isna(). Use the sum() to add the values and find the count. At first, let us import the required libraries with their respective aliases − import pandas as pd import numpy as np Create a DataFrame. We have set the NaN values using the Numpy np.inf in “Units_Sold” column − dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN] }) Count NaN values from column "Units_Sold" − dataFrame["Units_Sold"].isna().sum() Following is the code − import pandas as pd import numpy as np # creating dataframe dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN] }) print("Dataframe...\n",dataFrame) # count NaN values from column "Units_Sol" count = dataFrame["Units_Sold"].isna().sum() print("\nCount of NaN values in column Units_Sold...\n",count) This will produce the following output − Dataframe... Car Cubic_Capacity Reg_Price Units_Sold 0 BMW 2000 7000 100.0 1 Lexus 1800 1500 NaN 2 Tesla 1500 5000 150.0 3 Mustang 2500 8000 NaN 4 Mercedes 2200 9000 200.0 5 Jaguar 3000 6000 NaN Count of NaN values in column Units_Sold... 3
[ { "code": null, "e": 1172, "s": 1062, "text": "To count the NaN occurrences in a column, use the isna(). Use the sum() to add the values and find the count." }, { "code": null, "e": 1251, "s": 1172, "text": "At first, let us import the required libraries with their respective aliases −" }, { "code": null, "e": 1290, "s": 1251, "text": "import pandas as pd\nimport numpy as np" }, { "code": null, "e": 1385, "s": 1290, "text": "Create a DataFrame. We have set the NaN values using the Numpy np.inf in “Units_Sold” column −" }, { "code": null, "e": 1640, "s": 1385, "text": "dataFrame = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, np.NaN, 150, np.NaN, 200, np.NaN]\n})" }, { "code": null, "e": 1684, "s": 1640, "text": "Count NaN values from column \"Units_Sold\" −" }, { "code": null, "e": 1722, "s": 1684, "text": "dataFrame[\"Units_Sold\"].isna().sum()\n" }, { "code": null, "e": 1746, "s": 1722, "text": "Following is the code −" }, { "code": null, "e": 2250, "s": 1746, "text": "import pandas as pd\nimport numpy as np\n\n# creating dataframe\ndataFrame = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, np.NaN, 150, np.NaN, 200, np.NaN]\n})\n\nprint(\"Dataframe...\\n\",dataFrame)\n\n# count NaN values from column \"Units_Sol\"\ncount = dataFrame[\"Units_Sold\"].isna().sum()\n\nprint(\"\\nCount of NaN values in column Units_Sold...\\n\",count)" }, { "code": null, "e": 2291, "s": 2250, "text": "This will produce the following output −" }, { "code": null, "e": 2729, "s": 2291, "text": "Dataframe...\n Car Cubic_Capacity Reg_Price Units_Sold\n0 BMW 2000 7000 100.0\n1 Lexus 1800 1500 NaN\n2 Tesla 1500 5000 150.0\n3 Mustang 2500 8000 NaN\n4 Mercedes 2200 9000 200.0\n5 Jaguar 3000 6000 NaN\n\nCount of NaN values in column Units_Sold...\n3" } ]
Python Pandas - Create a subset by choosing specific values from columns based on indexes
To create a subset by choosing specific values from columns based on indexes, use the iloc() method. Let us first import the pandas library import pandas as pd Create a Pandas DataFrame with Product records. We have 3 columns in it dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) Creating a subset with 2 columns and 1st 2 rows using iloc( print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2] Following is the complete code import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame print"\nDisplaying a subset:\n",dataFrame['Product'] # creating a subset with 2 columns and 1st 2 rows using iloc() print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2] This will produce the following output DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 ChromeCast 2 1000 1200 Speaker 3 900 1500 Earphone Displaying a subset: 0 SmartTV 1 ChromeCast 2 Speaker 3 Earphone Name: Product, dtype: object Displaying a subset using iloc() = Closing_Stock Opening_Stock 0 200 300 1 500 700
[ { "code": null, "e": 1202, "s": 1062, "text": "To create a subset by choosing specific values from columns based on indexes, use the iloc() method. Let us first import the pandas library" }, { "code": null, "e": 1222, "s": 1202, "text": "import pandas as pd" }, { "code": null, "e": 1294, "s": 1222, "text": "Create a Pandas DataFrame with Product records. We have 3 columns in it" }, { "code": null, "e": 1462, "s": 1294, "text": "dataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"],\n\"Opening_Stock\": [300, 700, 1200, 1500],\"Closing_Stock\": [200, 500, 1000, 900]})" }, { "code": null, "e": 1522, "s": 1462, "text": "Creating a subset with 2 columns and 1st 2 rows using iloc(" }, { "code": null, "e": 1595, "s": 1522, "text": "print\"\\nDisplaying a subset using iloc() = \\n\",dataFrame.iloc[0:2, 0:2]\n" }, { "code": null, "e": 1626, "s": 1595, "text": "Following is the complete code" }, { "code": null, "e": 2038, "s": 1626, "text": "import pandas as pd\n\ndataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"],\n\"Opening_Stock\": [300, 700, 1200, 1500],\"Closing_Stock\": [200, 500, 1000, 900]})\n\nprint\"DataFrame...\\n\",dataFrame\n\nprint\"\\nDisplaying a subset:\\n\",dataFrame['Product']\n\n# creating a subset with 2 columns and 1st 2 rows using iloc()\nprint\"\\nDisplaying a subset using iloc() = \\n\",dataFrame.iloc[0:2, 0:2]" }, { "code": null, "e": 2077, "s": 2038, "text": "This will produce the following output" }, { "code": null, "e": 2555, "s": 2077, "text": "DataFrame...\n Closing_Stock Opening_Stock Product\n0 200 300 SmartTV\n1 500 700 ChromeCast\n2 1000 1200 Speaker\n3 900 1500 Earphone\n\nDisplaying a subset:\n0 SmartTV\n1 ChromeCast\n2 Speaker\n3 Earphone\nName: Product, dtype: object\n\nDisplaying a subset using iloc() =\n Closing_Stock Opening_Stock\n0 200 300\n1 500 700" } ]
Matplotlib.axes.Axes.invert_yaxis() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.invert_yaxis() function in axes module of matplotlib library is used to invert the y-axis. Syntax: Axes.invert_yaxis(self) Parameters: This method does not accepts any parameters. Returns:This method does not returns any value. Below examples illustrate the matplotlib.axes.Axes.invert_yaxis() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis() \Example', fontsize = 14, fontweight ='bold')plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x]) fig, ax = plt.subplots()ax.plot(yy)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis()\ Example', fontsize = 14, fontweight ='bold')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24699, "s": 24671, "text": "\n19 Apr, 2020" }, { "code": null, "e": 24999, "s": 24699, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 25099, "s": 24999, "text": "The Axes.invert_yaxis() function in axes module of matplotlib library is used to invert the y-axis." }, { "code": null, "e": 25131, "s": 25099, "text": "Syntax: Axes.invert_yaxis(self)" }, { "code": null, "e": 25188, "s": 25131, "text": "Parameters: This method does not accepts any parameters." }, { "code": null, "e": 25236, "s": 25188, "text": "Returns:This method does not returns any value." }, { "code": null, "e": 25331, "s": 25236, "text": "Below examples illustrate the matplotlib.axes.Axes.invert_yaxis() function in matplotlib.axes:" }, { "code": null, "e": 25342, "s": 25331, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis() \\Example', fontsize = 14, fontweight ='bold')plt.show()", "e": 25690, "s": 25342, "text": null }, { "code": null, "e": 25698, "s": 25690, "text": "Output:" }, { "code": null, "e": 25709, "s": 25698, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x]) fig, ax = plt.subplots()ax.plot(yy)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis()\\ Example', fontsize = 14, fontweight ='bold')plt.show()", "e": 26049, "s": 25709, "text": null }, { "code": null, "e": 26057, "s": 26049, "text": "Output:" }, { "code": null, "e": 26075, "s": 26057, "text": "Python-matplotlib" }, { "code": null, "e": 26082, "s": 26075, "text": "Python" }, { "code": null, "e": 26180, "s": 26082, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26189, "s": 26180, "text": "Comments" }, { "code": null, "e": 26202, "s": 26189, "text": "Old Comments" }, { "code": null, "e": 26220, "s": 26202, "text": "Python Dictionary" }, { "code": null, "e": 26255, "s": 26220, "text": "Read a file line by line in Python" }, { "code": null, "e": 26277, "s": 26255, "text": "Enumerate() in Python" }, { "code": null, "e": 26309, "s": 26277, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26339, "s": 26309, "text": "Iterate over a list in Python" }, { "code": null, "e": 26381, "s": 26339, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26424, "s": 26381, "text": "Python program to convert a list to string" }, { "code": null, "e": 26468, "s": 26424, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26493, "s": 26468, "text": "sum() function in Python" } ]
Dictionary keys() Method in Java with Examples - GeeksforGeeks
27 Dec, 2018 The keys() method of Dictionary class in Java is used to get the enumeration of the keys present in the dictionary. Syntax: Enumeration enu = DICTIONARY.keys() Parameters: The method does not take any parameters. Return value: The method returns an enumeration of the keys of the Dictionary. Below programs are used to illustrate the working of the java.util.Dictionary.keys() method:Program 1: // Java code to illustrate the keys() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting elements into the Dictionary dict.put(10, "Geeks"); dict.put(15, "4"); dict.put(20, "Geeks"); dict.put(25, "Welcomes"); dict.put(30, "You"); // Displaying the Dictionary System.out.println("The Dictionary is: " + dict); // Creating an empty enumeration to store Enumeration enu = dict.keys(); System.out.println("The enumeration of keys are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} The Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} The enumeration of keys are: 10 20 30 15 25 Program 2: // Java code to illustrate the keys() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting elements into the table dict.put("Geeks", 10); dict.put("4", 15); dict.put("Geeks", 20); dict.put("Welcomes", 25); dict.put("You", 30); // Displaying the Dictionary System.out.println("The Dictionary is: " + dict); // Creating an empty enumeration to store Enumeration enu = dict.keys(); System.out.println("The enumeration of keys are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} The Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20} The enumeration of keys are: You Welcomes 4 Geeks Java - util package Java-Collections Java-Dictionary Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n27 Dec, 2018" }, { "code": null, "e": 24064, "s": 23948, "text": "The keys() method of Dictionary class in Java is used to get the enumeration of the keys present in the dictionary." }, { "code": null, "e": 24072, "s": 24064, "text": "Syntax:" }, { "code": null, "e": 24108, "s": 24072, "text": "Enumeration enu = DICTIONARY.keys()" }, { "code": null, "e": 24161, "s": 24108, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 24240, "s": 24161, "text": "Return value: The method returns an enumeration of the keys of the Dictionary." }, { "code": null, "e": 24343, "s": 24240, "text": "Below programs are used to illustrate the working of the java.util.Dictionary.keys() method:Program 1:" }, { "code": "// Java code to illustrate the keys() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting elements into the Dictionary dict.put(10, \"Geeks\"); dict.put(15, \"4\"); dict.put(20, \"Geeks\"); dict.put(25, \"Welcomes\"); dict.put(30, \"You\"); // Displaying the Dictionary System.out.println(\"The Dictionary is: \" + dict); // Creating an empty enumeration to store Enumeration enu = dict.keys(); System.out.println(\"The enumeration of keys are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 25200, "s": 24343, "text": null }, { "code": null, "e": 25312, "s": 25200, "text": "The Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe enumeration of keys are:\n10\n20\n30\n15\n25\n" }, { "code": null, "e": 25323, "s": 25312, "text": "Program 2:" }, { "code": "// Java code to illustrate the keys() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting elements into the table dict.put(\"Geeks\", 10); dict.put(\"4\", 15); dict.put(\"Geeks\", 20); dict.put(\"Welcomes\", 25); dict.put(\"You\", 30); // Displaying the Dictionary System.out.println(\"The Dictionary is: \" + dict); // Creating an empty enumeration to store Enumeration enu = dict.keys(); System.out.println(\"The enumeration of keys are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 26175, "s": 25323, "text": null }, { "code": null, "e": 26283, "s": 26175, "text": "The Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe enumeration of keys are:\nYou\nWelcomes\n4\nGeeks\n" }, { "code": null, "e": 26303, "s": 26283, "text": "Java - util package" }, { "code": null, "e": 26320, "s": 26303, "text": "Java-Collections" }, { "code": null, "e": 26336, "s": 26320, "text": "Java-Dictionary" }, { "code": null, "e": 26351, "s": 26336, "text": "Java-Functions" }, { "code": null, "e": 26356, "s": 26351, "text": "Java" }, { "code": null, "e": 26361, "s": 26356, "text": "Java" }, { "code": null, "e": 26378, "s": 26361, "text": "Java-Collections" }, { "code": null, "e": 26476, "s": 26378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26491, "s": 26476, "text": "Stream In Java" }, { "code": null, "e": 26537, "s": 26491, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26558, "s": 26537, "text": "Constructors in Java" }, { "code": null, "e": 26577, "s": 26558, "text": "Exceptions in Java" }, { "code": null, "e": 26607, "s": 26577, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26624, "s": 26607, "text": "Generics in Java" }, { "code": null, "e": 26667, "s": 26624, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26696, "s": 26667, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26717, "s": 26696, "text": "Introduction to Java" } ]
Java new Keyword
❮ Java Keywords Create an object called "myObj" and print the value of x: public class Main { int x = 5; public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } } Try it Yourself » The new keyword creates new objects. Read more about objects in our Java Classes/Objects Tutorial. ❮ Java Keywords We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 76, "s": 18, "text": "Create an object called \"myObj\" and print the value of x:" }, { "code": null, "e": 222, "s": 76, "text": "public class Main {\n int x = 5;\n\n public static void main(String[] args) {\n Main myObj = new Main();\n System.out.println(myObj.x);\n }\n}\n" }, { "code": null, "e": 242, "s": 222, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 279, "s": 242, "text": "The new keyword creates new objects." }, { "code": null, "e": 341, "s": 279, "text": "Read more about objects in our Java Classes/Objects Tutorial." }, { "code": null, "e": 359, "s": 341, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 392, "s": 359, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 434, "s": 392, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 541, "s": 434, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 560, "s": 541, "text": "help@w3schools.com" } ]
Find the largest and second largest value in a Linked List - GeeksforGeeks
18 Jun, 2021 Given a Linked List, the task is to find the largest and second largest value in a Linked List.Example: Input: LL = 10 -> 15 -> 5 -> 20 -> 7 -> 9 Output: Largest = 20 Second Largest = 15Input: LL = 0 -> 5 -> 52 -> 21 Output: Largest = 52 Second Largest = 21 Approach: Store the maximum of first two nodes in a variable max.Store the minimum of first two nodes in a variable second_max.Iterate over the remaining linked list. For each node: If current node value is greater than max, then set second_max as max and max as current node’s value.Else if current node value is greater than second_max, then set second_max as current node’s value. Store the maximum of first two nodes in a variable max. Store the minimum of first two nodes in a variable second_max. Iterate over the remaining linked list. For each node: If current node value is greater than max, then set second_max as max and max as current node’s value.Else if current node value is greater than second_max, then set second_max as current node’s value. If current node value is greater than max, then set second_max as max and max as current node’s value. Else if current node value is greater than second_max, then set second_max as current node’s value. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the largest and// second largest element in a Linked List #include <bits/stdc++.h>using namespace std; // Link list nodestruct Node { int data; struct Node* next;}; // Function to push the node at the// beginning of the linked listvoid 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;} // Function to print the largest// and second largest elementvoid findLargestAndSecondLargest(struct Node* head){ // initialise max and second max using // first two nodes of linked list int val1 = head->data, val2 = head->next->data, max = std::max(val1, val2), second_max = std::min(val1, val2); // move the head pointer to 3rd node head = head->next->next; // iterate over rest of linked list while (head != NULL) { if (head->data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head->data; } else if (head->data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head->data; } // move the head pointer to next node head = head->next; } // Print the largest // and second largest value cout << "Largest = " << max << endl; cout << "Second Largest = " << second_max << endl;} // Driver codeint main(){ struct Node* head = NULL; push(&head, 20); push(&head, 5); push(&head, 15); push(&head, 10); push(&head, 7); push(&head, 6); push(&head, 11); push(&head, 9); findLargestAndSecondLargest(head); return 0;} // Java program to find the largest and// second largest element in a Linked Listclass GFG{ // Link list nodestatic class Node { int data; Node next; }; // Function to push the node at the// beginning of the linked liststatic Node 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; return head_ref;} // Function to print the largest// and second largest elementstatic void findLargestAndSecondLargest(Node head){ // initialise max and second max using // first two nodes of linked list int val1 = head.data, val2 = head.next.data, max = Math.max(val1, val2), second_max = Math.min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value System.out.print("Largest = " + max +"\n"); System.out.print("Second Largest = " + second_max +"\n");} // Driver codepublic static void main(String[] args){ Node head = null; head = push(head, 20); head = push(head, 5); head = push(head, 15); head = push(head, 10); head = push(head, 7); head = push(head, 6); head = push(head, 11); head = push(head, 9); findLargestAndSecondLargest(head);}} // This code is contributed by Rajput-Ji # Python3 program to find the largest and# second largest element in a Linked List# Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at the # beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Function to find the max and # second largest value from the list def findLargestAndSecondLargest(self): # Take a Head to iterate list Head = self.head # Initialize max and second_max # using first two nodes of the list val1 = Head.data val2 = Head.next.data Max = max(val1, val2) second_max = min(val1, val2) # Move the Head to third node Head = Head.next.next # Iterate over rest of linked list while(Head != None): # If current node value is # greater then Max then if(Head.data > Max): # Set the current max to second_max # and current node value to max second_max = Max Max = Head.data # Else if current node value is # greater then second_max value elif(Head.data > second_max): # Then current node value # to second_max second_max = Head.data # Move the head to next node Head = Head.next # Print the largest and second largest values print("Largest = ", Max) print("Second Largest = ", second_max) # Driver codeif __name__ == '__main__': # Initialising the linked list head = LinkedList() # Pushing the values in list head.push(20) head.push(5) head.push(15) head.push(10) head.push(7) head.push(6) head.push(11) head.push(9) # Calling the function to print # largest and second largest values. head.findLargestAndSecondLargest() # This code is contributed by Amit Mangal. // C# program to find the largest and// second largest element in a Linked Listusing System; class GFG{ // Link list nodeclass Node { public int data; public Node next; }; // Function to push the node at the// beginning of the linked liststatic Node 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; return head_ref;} // Function to print the largest// and second largest elementstatic void findLargestAndSecondLargest(Node head){ // initialise max and second max using // first two nodes of linked list int val1 = head.data, val2 = head.next.data, max = Math.Max(val1, val2), second_max = Math.Min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value Console.Write("Largest = " + max +"\n"); Console.Write("Second Largest = " + second_max +"\n");} // Driver codepublic static void Main(String[] args){ Node head = null; head = push(head, 20); head = push(head, 5); head = push(head, 15); head = push(head, 10); head = push(head, 7); head = push(head, 6); head = push(head, 11); head = push(head, 9); findLargestAndSecondLargest(head);}} // This code is contributed by Princi Singh <script> // Javascript program to find the largest and// second largest element in a Linked List // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }}; // Function to push the node at the// beginning of the linked listfunction 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;} // Function to print the largest// and second largest elementfunction findLargestAndSecondLargest(head){ // initialise max and second max using // first two nodes of linked list var val1 = head.data, val2 = head.next.data, max = Math.max(val1, val2), second_max = Math.min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value document.write( "Largest = " + max + "<br>"); document.write( "Second Largest = " + second_max + "<br>");} // Driver codevar head = null;head = push(head, 20);head = push(head, 5);head = push(head, 15);head = push(head, 10);head = push(head, 7);head = push(head, 6);head = push(head, 11);head = push(head, 9);findLargestAndSecondLargest(head); // This code is contributed by noob2000.</script> Largest = 20 Second Largest = 15 Performance Analysis: Time Complexity: In the above approach, as we are iterating over the linked list only once, so the time complexity is O(N). Auxiliary Space Complexity: In the above approach, we are not using any extra space apart from a few constant size variables, so Auxiliary space complexity is O(1). Rajput-Ji princi singh amit_mangal_ noob2000 Linked List School Programming Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Linked List vs Array Detect loop in a linked list Merge two sorted linked lists Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24794, "s": 24766, "text": "\n18 Jun, 2021" }, { "code": null, "e": 24900, "s": 24794, "text": "Given a Linked List, the task is to find the largest and second largest value in a Linked List.Example: " }, { "code": null, "e": 25056, "s": 24900, "text": "Input: LL = 10 -> 15 -> 5 -> 20 -> 7 -> 9 Output: Largest = 20 Second Largest = 15Input: LL = 0 -> 5 -> 52 -> 21 Output: Largest = 52 Second Largest = 21 " }, { "code": null, "e": 25070, "s": 25058, "text": "Approach: " }, { "code": null, "e": 25444, "s": 25070, "text": "Store the maximum of first two nodes in a variable max.Store the minimum of first two nodes in a variable second_max.Iterate over the remaining linked list. For each node: If current node value is greater than max, then set second_max as max and max as current node’s value.Else if current node value is greater than second_max, then set second_max as current node’s value." }, { "code": null, "e": 25500, "s": 25444, "text": "Store the maximum of first two nodes in a variable max." }, { "code": null, "e": 25563, "s": 25500, "text": "Store the minimum of first two nodes in a variable second_max." }, { "code": null, "e": 25820, "s": 25563, "text": "Iterate over the remaining linked list. For each node: If current node value is greater than max, then set second_max as max and max as current node’s value.Else if current node value is greater than second_max, then set second_max as current node’s value." }, { "code": null, "e": 25923, "s": 25820, "text": "If current node value is greater than max, then set second_max as max and max as current node’s value." }, { "code": null, "e": 26023, "s": 25923, "text": "Else if current node value is greater than second_max, then set second_max as current node’s value." }, { "code": null, "e": 26076, "s": 26023, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26080, "s": 26076, "text": "C++" }, { "code": null, "e": 26085, "s": 26080, "text": "Java" }, { "code": null, "e": 26093, "s": 26085, "text": "Python3" }, { "code": null, "e": 26096, "s": 26093, "text": "C#" }, { "code": null, "e": 26107, "s": 26096, "text": "Javascript" }, { "code": "// C++ program to find the largest and// second largest element in a Linked List #include <bits/stdc++.h>using namespace std; // Link list nodestruct Node { int data; struct Node* next;}; // Function to push the node at the// beginning of the linked listvoid 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;} // Function to print the largest// and second largest elementvoid findLargestAndSecondLargest(struct Node* head){ // initialise max and second max using // first two nodes of linked list int val1 = head->data, val2 = head->next->data, max = std::max(val1, val2), second_max = std::min(val1, val2); // move the head pointer to 3rd node head = head->next->next; // iterate over rest of linked list while (head != NULL) { if (head->data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head->data; } else if (head->data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head->data; } // move the head pointer to next node head = head->next; } // Print the largest // and second largest value cout << \"Largest = \" << max << endl; cout << \"Second Largest = \" << second_max << endl;} // Driver codeint main(){ struct Node* head = NULL; push(&head, 20); push(&head, 5); push(&head, 15); push(&head, 10); push(&head, 7); push(&head, 6); push(&head, 11); push(&head, 9); findLargestAndSecondLargest(head); return 0;}", "e": 28064, "s": 26107, "text": null }, { "code": "// Java program to find the largest and// second largest element in a Linked Listclass GFG{ // Link list nodestatic class Node { int data; Node next; }; // Function to push the node at the// beginning of the linked liststatic Node 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; return head_ref;} // Function to print the largest// and second largest elementstatic void findLargestAndSecondLargest(Node head){ // initialise max and second max using // first two nodes of linked list int val1 = head.data, val2 = head.next.data, max = Math.max(val1, val2), second_max = Math.min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value System.out.print(\"Largest = \" + max +\"\\n\"); System.out.print(\"Second Largest = \" + second_max +\"\\n\");} // Driver codepublic static void main(String[] args){ Node head = null; head = push(head, 20); head = push(head, 5); head = push(head, 15); head = push(head, 10); head = push(head, 7); head = push(head, 6); head = push(head, 11); head = push(head, 9); findLargestAndSecondLargest(head);}} // This code is contributed by Rajput-Ji", "e": 30058, "s": 28064, "text": null }, { "code": "# Python3 program to find the largest and# second largest element in a Linked List# Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at the # beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Function to find the max and # second largest value from the list def findLargestAndSecondLargest(self): # Take a Head to iterate list Head = self.head # Initialize max and second_max # using first two nodes of the list val1 = Head.data val2 = Head.next.data Max = max(val1, val2) second_max = min(val1, val2) # Move the Head to third node Head = Head.next.next # Iterate over rest of linked list while(Head != None): # If current node value is # greater then Max then if(Head.data > Max): # Set the current max to second_max # and current node value to max second_max = Max Max = Head.data # Else if current node value is # greater then second_max value elif(Head.data > second_max): # Then current node value # to second_max second_max = Head.data # Move the head to next node Head = Head.next # Print the largest and second largest values print(\"Largest = \", Max) print(\"Second Largest = \", second_max) # Driver codeif __name__ == '__main__': # Initialising the linked list head = LinkedList() # Pushing the values in list head.push(20) head.push(5) head.push(15) head.push(10) head.push(7) head.push(6) head.push(11) head.push(9) # Calling the function to print # largest and second largest values. head.findLargestAndSecondLargest() # This code is contributed by Amit Mangal.", "e": 32538, "s": 30058, "text": null }, { "code": "// C# program to find the largest and// second largest element in a Linked Listusing System; class GFG{ // Link list nodeclass Node { public int data; public Node next; }; // Function to push the node at the// beginning of the linked liststatic Node 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; return head_ref;} // Function to print the largest// and second largest elementstatic void findLargestAndSecondLargest(Node head){ // initialise max and second max using // first two nodes of linked list int val1 = head.data, val2 = head.next.data, max = Math.Max(val1, val2), second_max = Math.Min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value Console.Write(\"Largest = \" + max +\"\\n\"); Console.Write(\"Second Largest = \" + second_max +\"\\n\");} // Driver codepublic static void Main(String[] args){ Node head = null; head = push(head, 20); head = push(head, 5); head = push(head, 15); head = push(head, 10); head = push(head, 7); head = push(head, 6); head = push(head, 11); head = push(head, 9); findLargestAndSecondLargest(head);}} // This code is contributed by Princi Singh", "e": 34563, "s": 32538, "text": null }, { "code": "<script> // Javascript program to find the largest and// second largest element in a Linked List // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }}; // Function to push the node at the// beginning of the linked listfunction 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;} // Function to print the largest// and second largest elementfunction findLargestAndSecondLargest(head){ // initialise max and second max using // first two nodes of linked list var val1 = head.data, val2 = head.next.data, max = Math.max(val1, val2), second_max = Math.min(val1, val2); // move the head pointer to 3rd node head = head.next.next; // iterate over rest of linked list while (head != null) { if (head.data > max) { // If current node value is greater // than max, then set second_max as // current max value and max as // current node value second_max = max; max = head.data; } else if (head.data > second_max) { // else if current node value is // greater than second_max, set // second_max as node value second_max = head.data; } // move the head pointer to next node head = head.next; } // Print the largest // and second largest value document.write( \"Largest = \" + max + \"<br>\"); document.write( \"Second Largest = \" + second_max + \"<br>\");} // Driver codevar head = null;head = push(head, 20);head = push(head, 5);head = push(head, 15);head = push(head, 10);head = push(head, 7);head = push(head, 6);head = push(head, 11);head = push(head, 9);findLargestAndSecondLargest(head); // This code is contributed by noob2000.</script>", "e": 36484, "s": 34563, "text": null }, { "code": null, "e": 36517, "s": 36484, "text": "Largest = 20\nSecond Largest = 15" }, { "code": null, "e": 36543, "s": 36519, "text": "Performance Analysis: " }, { "code": null, "e": 36667, "s": 36543, "text": "Time Complexity: In the above approach, as we are iterating over the linked list only once, so the time complexity is O(N)." }, { "code": null, "e": 36832, "s": 36667, "text": "Auxiliary Space Complexity: In the above approach, we are not using any extra space apart from a few constant size variables, so Auxiliary space complexity is O(1)." }, { "code": null, "e": 36844, "s": 36834, "text": "Rajput-Ji" }, { "code": null, "e": 36857, "s": 36844, "text": "princi singh" }, { "code": null, "e": 36870, "s": 36857, "text": "amit_mangal_" }, { "code": null, "e": 36879, "s": 36870, "text": "noob2000" }, { "code": null, "e": 36891, "s": 36879, "text": "Linked List" }, { "code": null, "e": 36910, "s": 36891, "text": "School Programming" }, { "code": null, "e": 36922, "s": 36910, "text": "Linked List" }, { "code": null, "e": 37020, "s": 36922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37039, "s": 37020, "text": "LinkedList in Java" }, { "code": null, "e": 37095, "s": 37039, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 37116, "s": 37095, "text": "Linked List vs Array" }, { "code": null, "e": 37145, "s": 37116, "text": "Detect loop in a linked list" }, { "code": null, "e": 37175, "s": 37145, "text": "Merge two sorted linked lists" }, { "code": null, "e": 37193, "s": 37175, "text": "Python Dictionary" }, { "code": null, "e": 37209, "s": 37193, "text": "Arrays in C/C++" }, { "code": null, "e": 37228, "s": 37209, "text": "Inheritance in C++" }, { "code": null, "e": 37253, "s": 37228, "text": "Reverse a string in Java" } ]
C# | Get or set the element at specified index in Collection<T> - GeeksforGeeks
01 Feb, 2019 Collection<T>.Item[Int32] property is used to get or set the element at the specified index. Syntax: public T this[int index] { get; set; } Here, index is the zero-based index of the element to get or set. Return Value: The element at the specified index. Exception: This method will give ArgumentOutOfRangeException if the index is less than zero or index is equal to or greater than Count. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to get or set the// element at the specified indexusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } // Get the element at index 2 Console.WriteLine("Element at index 2 is : " + myColl[2]); // Get the element at index 3 Console.WriteLine("Element at index 3 is : " + myColl[3]); // Set the element at index 3 myColl[3] = "GFG"; // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } }} Output: A B C D E Element at index 2 is : C Element at index 3 is : D A B C GFG E Example 2: // C# code to get or set the// element at the specified indexusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } // Get the element at index -1 // This should raise "ArgumentOutOfRangeException" // as the index is less than 0 Console.WriteLine("Element at index -1 is : " + myColl[-1]); // Set the element at index 2 myColl[2] = 10; // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Note: Collection<T> accepts null as a valid value for reference types and allows duplicate elements. This property provides the ability to access a specific element in the collection by using the syntax : myCollection[index]. Retrieving the value of this property is an O(1) operation. Setting the property is also an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.item?view=netframework-4.7.2 CSharp-Collection-Class CSharp-Collections.ObjectModel-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24395, "s": 24302, "text": "Collection<T>.Item[Int32] property is used to get or set the element at the specified index." }, { "code": null, "e": 24403, "s": 24395, "text": "Syntax:" }, { "code": null, "e": 24443, "s": 24403, "text": "public T this[int index] { get; set; }\n" }, { "code": null, "e": 24509, "s": 24443, "text": "Here, index is the zero-based index of the element to get or set." }, { "code": null, "e": 24559, "s": 24509, "text": "Return Value: The element at the specified index." }, { "code": null, "e": 24695, "s": 24559, "text": "Exception: This method will give ArgumentOutOfRangeException if the index is less than zero or index is equal to or greater than Count." }, { "code": null, "e": 24775, "s": 24695, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 24786, "s": 24775, "text": "Example 1:" }, { "code": "// C# code to get or set the// element at the specified indexusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } // Get the element at index 2 Console.WriteLine(\"Element at index 2 is : \" + myColl[2]); // Get the element at index 3 Console.WriteLine(\"Element at index 3 is : \" + myColl[3]); // Set the element at index 3 myColl[3] = \"GFG\"; // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } }}", "e": 25824, "s": 24786, "text": null }, { "code": null, "e": 25832, "s": 25824, "text": "Output:" }, { "code": null, "e": 25907, "s": 25832, "text": "A\nB\nC\nD\nE\nElement at index 2 is : C\nElement at index 3 is : D\nA\nB\nC\nGFG\nE\n" }, { "code": null, "e": 25918, "s": 25907, "text": "Example 2:" }, { "code": "// C# code to get or set the// element at the specified indexusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } // Get the element at index -1 // This should raise \"ArgumentOutOfRangeException\" // as the index is less than 0 Console.WriteLine(\"Element at index -1 is : \" + myColl[-1]); // Set the element at index 2 myColl[2] = 10; // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } }}", "e": 26892, "s": 25918, "text": null }, { "code": null, "e": 26907, "s": 26892, "text": "Runtime Error:" }, { "code": null, "e": 27071, "s": 26907, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index" }, { "code": null, "e": 27077, "s": 27071, "text": "Note:" }, { "code": null, "e": 27172, "s": 27077, "text": "Collection<T> accepts null as a valid value for reference types and allows duplicate elements." }, { "code": null, "e": 27297, "s": 27172, "text": "This property provides the ability to access a specific element in the collection by using the syntax : myCollection[index]." }, { "code": null, "e": 27357, "s": 27297, "text": "Retrieving the value of this property is an O(1) operation." }, { "code": null, "e": 27405, "s": 27357, "text": "Setting the property is also an O(1) operation." }, { "code": null, "e": 27416, "s": 27405, "text": "Reference:" }, { "code": null, "e": 27533, "s": 27416, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.item?view=netframework-4.7.2" }, { "code": null, "e": 27557, "s": 27533, "text": "CSharp-Collection-Class" }, { "code": null, "e": 27598, "s": 27557, "text": "CSharp-Collections.ObjectModel-Namespace" }, { "code": null, "e": 27601, "s": 27598, "text": "C#" }, { "code": null, "e": 27699, "s": 27601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27717, "s": 27699, "text": "Destructors in C#" }, { "code": null, "e": 27740, "s": 27717, "text": "Extension Method in C#" }, { "code": null, "e": 27768, "s": 27740, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27808, "s": 27768, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27851, "s": 27808, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27873, "s": 27851, "text": "Partial Classes in C#" }, { "code": null, "e": 27890, "s": 27873, "text": "C# | Inheritance" }, { "code": null, "e": 27906, "s": 27890, "text": "C# | List Class" }, { "code": null, "e": 27956, "s": 27906, "text": "Difference between Hashtable and Dictionary in C#" } ]
How to select data from a table using SQL | by Kate Marie Lewis | Towards Data Science
Whilst self isolating at home, my friends and I have decided to work together as a group learning data science. We have had one lesson so far and I have been so pleased by how enthusiastic the group is. By asking questions, my friends helped me to be clearer in my explanations and assisted each other learning. Hopefully, we can maintain this momentum and keep developing new data science skills together. If you would like to join us in learning data science during this global pandemic, please feel free to follow along. You may like to go back to the previous lesson so that you can start from the beginning. Otherwise, if you are interested specifically in learning how to select data from tables using SQL then you have come to the right place. In the previous lesson we learned how to create a table and to put some data into it using SQL. This was done using the CREATE TABLE and INSERT INTO keywords. For a bit of fun, we used the children’s show Bluey in the example. Now that we know how to create a table of data from our first lesson, let’s learn how to access it. Using the SQL keyword SELECT you can access all the data in your table, specific columns or a specific number of records. We will go through each of these three scenarios in this lesson. In addition, we will practice how to select data without including duplicate values using the SELECT DISTINCT keyword. In contrast to the children’s show used as an example in the previous lesson, this week we will use The Walking Dead. Certainly not one for the kids 😉 In the first season of The Walking Dead, there were some good guys and some bad guys and some others in between. But what we want to find out the top 5 characters who are the deadliest of them all. To figure out who is the best at killing we need to figure out what criteria we want to use. The characters in The Walking Dead have dispatched many ‘walkers’, but quite a lot of them have also killed several humans. We will define the deadliest characters as the one that has killed the most zombies. Then if there is a tie for zombie kills, the person who has killed the most humans will be hailed as the deadliest character out of the two. We have a table that contains information about characters from The Walking Dead that we will use to solve our problem. The dataset is primarily from this article. I changed some of the numbers slightly to illustrate one of the points of the lesson. So now we need to work out how to select the correct data from the table to find out who is the deadliest. Like we saw in the first lesson, you can use an asterisk to indicate that you want to select all the data in the table. All of the available columns in the table will be returned when the query is run. SELECT *FROM name_of_table; This is one of the simplest queries that you can write. Indentation does not do anything in SQL. I just do it to make my code easier to read. Generally speaking, you should conform to the indentation rules set forth in your organisation’s style guide. However, we don’t have a style guide so you can organise your code whichever way pleases you. It is important to know that in other coding languages like Python indentations are functional. If you do not use the correct indentations in Python your code will throw an error. If you want to select only specific columns from a larger table you can list the names of the columns that you want to be returned from the query. SELECT name_column_one, name_column_two, name_column_fiveFROM name_of_table; This is very useful, particularly for very wide datasets where there are many more columns than can be easily visualised in the resulting table. For example if you were looking at census data but are only interested in a few of the many available columns, it is much easier to see the values you want if you only select those columns of interest. Question 1: Can you tell how many columns are in the above table? The keyword LIMIT can be used to select a specific number of records. When LIMIT is used, only the specified number of records are returned starting from the top of the table. This is particularly helpful if you have your data in a particular order. If you would like to order your data by a column of interest you can use the ORDER BY keyword. ORDER BY is put after the FROM statement. To use ORDER BY, you need to specify which column(s) you want to use to dictate the order the data is returned in. You may also decide if you want it to be ordered in an ascending or descending order by using ASC or DESC respectively. SELECT *FROM name_of_table ORDER BY name_column_one DESCLIMIT 10; The code above will select all of the columns from the table and will return the top 10 records. This is after they have been put in descending ordered according to the values in column one. The syntax to SELECT and SELECT DISTINCT is the same. The difference will be in the results it returns. SELECT DISTINCT name_column_oneFROM name_of_table; SELECT DISTINCT returns only the different values from the columns selected and so all duplicates are removed. That is easy to understand if you are only selecting one column. However you can also use SELECT DISTINCT to select unique combinations of columns. SELECT DISTINCT name_column_one, name_column_fiveFROM name_of_table; So using the code above, you would get distinct combinations of the values in column one and column five. Even if there are duplicate values in column one, if there are different values for column five in those same rows, both rows would be returned. go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently) In the left hand box put the CREATE TABLE and INSERT INTO queries below CREATE TABLE walking_dead( first_name varchar(255), last_name varchar(255), hair_colour varchar(255), walker_kills int(255), human_kills int(255), number_of_hands int(255));INSERT INTO walking_dead (first_name, last_name, hair_colour, walker_kills, human_kills, number_of_hands)VALUES ('Maggie', 'Greene', 'brown', 64, 5, 2), ('Carol', 'Peletier', 'grey', 57, 27, 2), ('Merle', 'Dixon', 'dark blonde', 20, 6, 1), ('Tyreese', 'Williams', 'black', 59, 0, 2), ('Morgan', 'Jones', 'black', 40, 3, 2), ('Glenn', 'Rhee', 'black', 185, 5, 2), ('Michonne', '', 'black', 141, 10, 2), ('Andrea', 'Harrison', 'blonde', 39, 0, 2), ('Sasha', 'Williams', 'black', 73, 4, 2), ('Abraham', 'Ford', 'red', 49, 4, 2), ('Shane', 'Walsh', 'brown', 28, 3, 2), ('Daryl', 'Dixon', 'brown', 185, 22, 2), ('Rick', 'Grimes', 'brown', 216, 35, 2), ('Philip “The Governor”', 'Blake', 'brown', 26, 30, 2); 3. Click the build schema button 4. In the right hand box put your queries 5. Run the query below and see if it returns what you would expect it to: SELECT hair_colour, number_of_handsFROM walking_deadORDER BY hair_colour ASC, number_of_hands DESC; Hint: Notice the order that the columns are arranged in and that there are duplicate values in the results 6. Run the query below and see if it returns what you would expect it to: SELECT DISTINCT hair_colour, number_of_handsFROM walking_deadORDER BY hair_colour ASC, number_of_hands DESC; Hint: Notice how adding the DISTINCT keyword changes the results that get returned 7. Run the query below and see if it returns what you would expect it to: SELECT first_name, human_killsFROM walking_deadORDER BY human_kills DESCLIMIT 10; Hint: Notice the order and number of records returned. 8. Run the query below and see if it returns what you would expect it to: SELECT first_name, human_killsFROM walking_deadORDER BY first_name ASCLIMIT 10; Hint: Notice the difference in results returned compared with the previous query. Exercise 1: Write a query to select all the data from this table Exercise 2: Write a query to create a list of all the different family names in the dataset Exercise 3: Write a query to create a list of all the different family name, hair colour combinations in this dataset Exercise 4: Select the full name, walker_kills and human_kills of the top 5 most deadly characters. This is based on the criteria that zombie kills are most important, followed by human kills. There is at least one big fan of The Walking Dead in our study group. She was thrilled to get a zombie based lesson 😜 Some members of the group are running a little behind our initially planned timeline and are still working on this lesson. But what can you do when it is school holidays and you have three kids home to take care of? Or if you are working on getting your company and employees through this financial downturn. The women working with me to learn data science have plenty of other things going on in their lives so I totally understand that they can sometimes get in the way. Having said that, everyone still seems enthusiastic to complete this lesson when they can. My mates who have been able to complete the lesson this week have done really well. They seem to be grasping the basics of selecting from tables really well. I can’t wait to see how they go when we move onto some of the slightly more complex SQL methods. In the next lesson, we will focus on filtering data. There are lots of different ways to filter tables in SQL, but we will focus on learning to use the keywords WHERE, AND, OR, LIKE, IN, BETWEEN and NOT. In addition to data, my other passion is painting. You can find my wildlife art at www.katemarielewis.com
[ { "code": null, "e": 579, "s": 172, "text": "Whilst self isolating at home, my friends and I have decided to work together as a group learning data science. We have had one lesson so far and I have been so pleased by how enthusiastic the group is. By asking questions, my friends helped me to be clearer in my explanations and assisted each other learning. Hopefully, we can maintain this momentum and keep developing new data science skills together." }, { "code": null, "e": 923, "s": 579, "text": "If you would like to join us in learning data science during this global pandemic, please feel free to follow along. You may like to go back to the previous lesson so that you can start from the beginning. Otherwise, if you are interested specifically in learning how to select data from tables using SQL then you have come to the right place." }, { "code": null, "e": 1150, "s": 923, "text": "In the previous lesson we learned how to create a table and to put some data into it using SQL. This was done using the CREATE TABLE and INSERT INTO keywords. For a bit of fun, we used the children’s show Bluey in the example." }, { "code": null, "e": 1250, "s": 1150, "text": "Now that we know how to create a table of data from our first lesson, let’s learn how to access it." }, { "code": null, "e": 1556, "s": 1250, "text": "Using the SQL keyword SELECT you can access all the data in your table, specific columns or a specific number of records. We will go through each of these three scenarios in this lesson. In addition, we will practice how to select data without including duplicate values using the SELECT DISTINCT keyword." }, { "code": null, "e": 1707, "s": 1556, "text": "In contrast to the children’s show used as an example in the previous lesson, this week we will use The Walking Dead. Certainly not one for the kids 😉" }, { "code": null, "e": 1905, "s": 1707, "text": "In the first season of The Walking Dead, there were some good guys and some bad guys and some others in between. But what we want to find out the top 5 characters who are the deadliest of them all." }, { "code": null, "e": 2122, "s": 1905, "text": "To figure out who is the best at killing we need to figure out what criteria we want to use. The characters in The Walking Dead have dispatched many ‘walkers’, but quite a lot of them have also killed several humans." }, { "code": null, "e": 2348, "s": 2122, "text": "We will define the deadliest characters as the one that has killed the most zombies. Then if there is a tie for zombie kills, the person who has killed the most humans will be hailed as the deadliest character out of the two." }, { "code": null, "e": 2598, "s": 2348, "text": "We have a table that contains information about characters from The Walking Dead that we will use to solve our problem. The dataset is primarily from this article. I changed some of the numbers slightly to illustrate one of the points of the lesson." }, { "code": null, "e": 2705, "s": 2598, "text": "So now we need to work out how to select the correct data from the table to find out who is the deadliest." }, { "code": null, "e": 2907, "s": 2705, "text": "Like we saw in the first lesson, you can use an asterisk to indicate that you want to select all the data in the table. All of the available columns in the table will be returned when the query is run." }, { "code": null, "e": 2942, "s": 2907, "text": "SELECT *FROM name_of_table;" }, { "code": null, "e": 2998, "s": 2942, "text": "This is one of the simplest queries that you can write." }, { "code": null, "e": 3468, "s": 2998, "text": "Indentation does not do anything in SQL. I just do it to make my code easier to read. Generally speaking, you should conform to the indentation rules set forth in your organisation’s style guide. However, we don’t have a style guide so you can organise your code whichever way pleases you. It is important to know that in other coding languages like Python indentations are functional. If you do not use the correct indentations in Python your code will throw an error." }, { "code": null, "e": 3615, "s": 3468, "text": "If you want to select only specific columns from a larger table you can list the names of the columns that you want to be returned from the query." }, { "code": null, "e": 3707, "s": 3615, "text": "SELECT name_column_one, name_column_two, name_column_fiveFROM name_of_table;" }, { "code": null, "e": 4054, "s": 3707, "text": "This is very useful, particularly for very wide datasets where there are many more columns than can be easily visualised in the resulting table. For example if you were looking at census data but are only interested in a few of the many available columns, it is much easier to see the values you want if you only select those columns of interest." }, { "code": null, "e": 4120, "s": 4054, "text": "Question 1: Can you tell how many columns are in the above table?" }, { "code": null, "e": 4370, "s": 4120, "text": "The keyword LIMIT can be used to select a specific number of records. When LIMIT is used, only the specified number of records are returned starting from the top of the table. This is particularly helpful if you have your data in a particular order." }, { "code": null, "e": 4622, "s": 4370, "text": "If you would like to order your data by a column of interest you can use the ORDER BY keyword. ORDER BY is put after the FROM statement. To use ORDER BY, you need to specify which column(s) you want to use to dictate the order the data is returned in." }, { "code": null, "e": 4742, "s": 4622, "text": "You may also decide if you want it to be ordered in an ascending or descending order by using ASC or DESC respectively." }, { "code": null, "e": 4818, "s": 4742, "text": "SELECT *FROM name_of_table ORDER BY name_column_one DESCLIMIT 10;" }, { "code": null, "e": 5009, "s": 4818, "text": "The code above will select all of the columns from the table and will return the top 10 records. This is after they have been put in descending ordered according to the values in column one." }, { "code": null, "e": 5113, "s": 5009, "text": "The syntax to SELECT and SELECT DISTINCT is the same. The difference will be in the results it returns." }, { "code": null, "e": 5170, "s": 5113, "text": "SELECT DISTINCT name_column_oneFROM name_of_table;" }, { "code": null, "e": 5429, "s": 5170, "text": "SELECT DISTINCT returns only the different values from the columns selected and so all duplicates are removed. That is easy to understand if you are only selecting one column. However you can also use SELECT DISTINCT to select unique combinations of columns." }, { "code": null, "e": 5507, "s": 5429, "text": "SELECT DISTINCT name_column_one, name_column_fiveFROM name_of_table;" }, { "code": null, "e": 5758, "s": 5507, "text": "So using the code above, you would get distinct combinations of the values in column one and column five. Even if there are duplicate values in column one, if there are different values for column five in those same rows, both rows would be returned." }, { "code": null, "e": 5959, "s": 5758, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 6089, "s": 5959, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)" }, { "code": null, "e": 6161, "s": 6089, "text": "In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 7097, "s": 6161, "text": "CREATE TABLE walking_dead( first_name varchar(255), last_name varchar(255), hair_colour varchar(255), walker_kills int(255), human_kills int(255), number_of_hands int(255));INSERT INTO walking_dead (first_name, last_name, hair_colour, walker_kills, human_kills, number_of_hands)VALUES ('Maggie', 'Greene', 'brown', 64, 5, 2), ('Carol', 'Peletier', 'grey', 57, 27, 2), ('Merle', 'Dixon', 'dark blonde', 20, 6, 1), ('Tyreese', 'Williams', 'black', 59, 0, 2), ('Morgan', 'Jones', 'black', 40, 3, 2), ('Glenn', 'Rhee', 'black', 185, 5, 2), ('Michonne', '', 'black', 141, 10, 2), ('Andrea', 'Harrison', 'blonde', 39, 0, 2), ('Sasha', 'Williams', 'black', 73, 4, 2), ('Abraham', 'Ford', 'red', 49, 4, 2), ('Shane', 'Walsh', 'brown', 28, 3, 2), ('Daryl', 'Dixon', 'brown', 185, 22, 2), ('Rick', 'Grimes', 'brown', 216, 35, 2), ('Philip “The Governor”', 'Blake', 'brown', 26, 30, 2);" }, { "code": null, "e": 7130, "s": 7097, "text": "3. Click the build schema button" }, { "code": null, "e": 7172, "s": 7130, "text": "4. In the right hand box put your queries" }, { "code": null, "e": 7246, "s": 7172, "text": "5. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 7359, "s": 7246, "text": "SELECT hair_colour, number_of_handsFROM walking_deadORDER BY hair_colour ASC, number_of_hands DESC;" }, { "code": null, "e": 7466, "s": 7359, "text": "Hint: Notice the order that the columns are arranged in and that there are duplicate values in the results" }, { "code": null, "e": 7540, "s": 7466, "text": "6. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 7662, "s": 7540, "text": "SELECT DISTINCT hair_colour, number_of_handsFROM walking_deadORDER BY hair_colour ASC, number_of_hands DESC;" }, { "code": null, "e": 7745, "s": 7662, "text": "Hint: Notice how adding the DISTINCT keyword changes the results that get returned" }, { "code": null, "e": 7819, "s": 7745, "text": "7. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 7914, "s": 7819, "text": "SELECT first_name, human_killsFROM walking_deadORDER BY human_kills DESCLIMIT 10;" }, { "code": null, "e": 7969, "s": 7914, "text": "Hint: Notice the order and number of records returned." }, { "code": null, "e": 8043, "s": 7969, "text": "8. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 8136, "s": 8043, "text": "SELECT first_name, human_killsFROM walking_deadORDER BY first_name ASCLIMIT 10;" }, { "code": null, "e": 8218, "s": 8136, "text": "Hint: Notice the difference in results returned compared with the previous query." }, { "code": null, "e": 8283, "s": 8218, "text": "Exercise 1: Write a query to select all the data from this table" }, { "code": null, "e": 8375, "s": 8283, "text": "Exercise 2: Write a query to create a list of all the different family names in the dataset" }, { "code": null, "e": 8493, "s": 8375, "text": "Exercise 3: Write a query to create a list of all the different family name, hair colour combinations in this dataset" }, { "code": null, "e": 8686, "s": 8493, "text": "Exercise 4: Select the full name, walker_kills and human_kills of the top 5 most deadly characters. This is based on the criteria that zombie kills are most important, followed by human kills." }, { "code": null, "e": 8804, "s": 8686, "text": "There is at least one big fan of The Walking Dead in our study group. She was thrilled to get a zombie based lesson 😜" }, { "code": null, "e": 9277, "s": 8804, "text": "Some members of the group are running a little behind our initially planned timeline and are still working on this lesson. But what can you do when it is school holidays and you have three kids home to take care of? Or if you are working on getting your company and employees through this financial downturn. The women working with me to learn data science have plenty of other things going on in their lives so I totally understand that they can sometimes get in the way." }, { "code": null, "e": 9623, "s": 9277, "text": "Having said that, everyone still seems enthusiastic to complete this lesson when they can. My mates who have been able to complete the lesson this week have done really well. They seem to be grasping the basics of selecting from tables really well. I can’t wait to see how they go when we move onto some of the slightly more complex SQL methods." }, { "code": null, "e": 9827, "s": 9623, "text": "In the next lesson, we will focus on filtering data. There are lots of different ways to filter tables in SQL, but we will focus on learning to use the keywords WHERE, AND, OR, LIKE, IN, BETWEEN and NOT." } ]
List of tuples to dictionary conversion in Python
In this article, we are going to learn how to convert the list of tuples into a dictionary. Converting a list of tuples into a dictionary is a straightforward thing. Follow the below steps to complete the code. Initialize the list with tuples. Use the dict to convert given list of tuples into a dictionary. Print the resultant dictionary. Let's see the code. # initializing the list tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)] # converting to dict result = dict(tuples) # printing the result print(result) If you run the above code, you will get the following result. {'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5} Let's add value as list in the resultant dictionary using setdefault() method. Follow the below steps to complete the code. Initialize the list with tuples. Iterate over the list of tuples. Set default value for the key and append the value. Print the result. Let's see the code. # initializing the list tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)] # result result = {} # iterating over the tuples lists for (key, value) in tuples: # setting the default value as list([]) # appending the current value result.setdefault(key, []).append(value) # printing the list print(result) If you run the above code, you will get the following result. {'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]} If you have any queries in the article, mention them in the comment section.
[ { "code": null, "e": 1228, "s": 1062, "text": "In this article, we are going to learn how to convert the list of tuples into a dictionary. Converting a list of tuples into a dictionary is a straightforward thing." }, { "code": null, "e": 1273, "s": 1228, "text": "Follow the below steps to complete the code." }, { "code": null, "e": 1306, "s": 1273, "text": "Initialize the list with tuples." }, { "code": null, "e": 1370, "s": 1306, "text": "Use the dict to convert given list of tuples into a dictionary." }, { "code": null, "e": 1402, "s": 1370, "text": "Print the resultant dictionary." }, { "code": null, "e": 1422, "s": 1402, "text": "Let's see the code." }, { "code": null, "e": 1607, "s": 1422, "text": "# initializing the list\ntuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]\n\n# converting to dict\nresult = dict(tuples)\n\n# printing the result\nprint(result)" }, { "code": null, "e": 1669, "s": 1607, "text": "If you run the above code, you will get the following result." }, { "code": null, "e": 1731, "s": 1669, "text": "{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}\n" }, { "code": null, "e": 1810, "s": 1731, "text": "Let's add value as list in the resultant dictionary using setdefault() method." }, { "code": null, "e": 1855, "s": 1810, "text": "Follow the below steps to complete the code." }, { "code": null, "e": 1888, "s": 1855, "text": "Initialize the list with tuples." }, { "code": null, "e": 1921, "s": 1888, "text": "Iterate over the list of tuples." }, { "code": null, "e": 1973, "s": 1921, "text": "Set default value for the key and append the value." }, { "code": null, "e": 1991, "s": 1973, "text": "Print the result." }, { "code": null, "e": 2011, "s": 1991, "text": "Let's see the code." }, { "code": null, "e": 2355, "s": 2011, "text": "# initializing the list\ntuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]\n\n# result\nresult = {}\n\n# iterating over the tuples lists\nfor (key, value) in tuples:\n # setting the default value as list([])\n # appending the current value\n result.setdefault(key, []).append(value)\n\n# printing the list\nprint(result)" }, { "code": null, "e": 2417, "s": 2355, "text": "If you run the above code, you will get the following result." }, { "code": null, "e": 2489, "s": 2417, "text": "{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}\n" }, { "code": null, "e": 2566, "s": 2489, "text": "If you have any queries in the article, mention them in the comment section." } ]
MATLAB - Scalar Multiplication of Vectors
When you multiply a vector by a number, this is called the scalar multiplication. Scalar multiplication produces a new vector of same type with each element of the original vector multiplied by the number. Create a script file with the following code − v = [ 12 34 10 8]; m = 5 * v When you run the file, it displays the following result − m = 60 170 50 40 Please note that you can perform all scalar operations on vectors. For example, you can add, subtract and divide a vector with a scalar quantity. 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2347, "s": 2141, "text": "When you multiply a vector by a number, this is called the scalar multiplication. Scalar multiplication produces a new vector of same type with each element of the original vector multiplied by the number." }, { "code": null, "e": 2394, "s": 2347, "text": "Create a script file with the following code −" }, { "code": null, "e": 2423, "s": 2394, "text": "v = [ 12 34 10 8];\nm = 5 * v" }, { "code": null, "e": 2481, "s": 2423, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2510, "s": 2481, "text": "m =\n 60 170 50 40\n" }, { "code": null, "e": 2656, "s": 2510, "text": "Please note that you can perform all scalar operations on vectors. For example, you can add, subtract and divide a vector with a scalar quantity." }, { "code": null, "e": 2689, "s": 2656, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2702, "s": 2689, "text": " Nouman Azam" }, { "code": null, "e": 2737, "s": 2702, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2750, "s": 2737, "text": " Nouman Azam" }, { "code": null, "e": 2783, "s": 2750, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2792, "s": 2783, "text": " Sanjeev" }, { "code": null, "e": 2825, "s": 2792, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2841, "s": 2825, "text": " TELCOMA Global" }, { "code": null, "e": 2874, "s": 2841, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2890, "s": 2874, "text": " TELCOMA Global" }, { "code": null, "e": 2923, "s": 2890, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 2940, "s": 2923, "text": " Phinite Academy" }, { "code": null, "e": 2947, "s": 2940, "text": " Print" }, { "code": null, "e": 2958, "s": 2947, "text": " Add Notes" } ]
Serialize Python dictionary to XML - GeeksforGeeks
30 Nov, 2021 XML is a markup language that is designed to transport data. It was made while keeping it self descriptive in mind. Syntax of XML is similar to HTML other than the fact that the tags in XML aren’t pre-defined. This allows for data to be stored between custom tags where the tag contains details about the data and the data is stored in between the opening and closing tags. Note: You can read more about XML here: XML | Basics and XML | Syntax Currently, there are two major modules that allow to serialize Python dictionary to XML. They are dict2xmlDicttoxml dict2xml Dicttoxml For a quick conversion of Python Dictionary to XML, you can use dict2xml. Install it using: $ pip install dict2xml Now suppose you have a Dictionary named data in Python which you want to convert to XML Python3 # Converting Python Dictionary to XMLfrom dict2xml import dict2xml data = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dict2xml(data)print(xml) Output: <a>2</a> <b> <c>as</c> <f>True</f> </b> <d>7</d> Wrapping around a root element and custom indenting Suppose you want to wrap the answer around a root element and add indent of 3 spaces. Python3 # Converting Python Dictionary to XML# with a root elemtntfrom dict2xml import dict2xml data = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dict2xml(data, wrap ='root', indent =" ")print(xml) Output: <root> <a>2</a> <b> <c>as</c> <f>True</f> </b> <d>7</d> </root> Dict2xml is good but it doesn’t have many options to specify how I want my XML to be formatted or to add attributes in tags. dicttoxml can be used for these purposes. It also works perfectly on Dict-like and Iterable Objects. Install it via terminal or command prompt by typing: $ pip install dicttoxml or $ easy_install dicttoxml Python3 # Using dicttoxml for converting Python# Dictionary to XMLfrom dicttoxml import dicttoxml # Data to be parseddata = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dicttoxml(data)print(xml) Output: b'<?xml version=”1.0′′ encoding=”UTF-8′′ ?><root><a type=”int”>2</a><b type=”dict”><c type=”str”>as</c><f type=”bool”>True</f></b><d type=”int”>7</d></root>’ Pretty Format the output Lets pretty format the text so that we can read it clearly. Python already has an inbuilt package for this! Python3 # Pretty printing XML after parsing# it from dictionaryfrom xml.dom.minidom import parseStringfrom dicttoxml import dicttoxml # Data to be parseddata = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dicttoxml(data)dom = parseString(xml) print(dom.toprettyxml()) Output: <?xml version="1.0" ?> <root> <a type="int">2</a> <b type="dict"> <c type="str">as</c> <f type="bool">True</f> </b> <d type="int">7</d> </root> Removing Type Attributes You might notice that the tags now contain attributes like type=”int”/”dict”/”str” which can be turned off using attr_type=False Python3 # Removing Type Attribute from parsed XMLfrom xml.dom.minidom import parseString # attr_type = False is used# to remove type attributesxml = dicttoxml(data, attr_type = False) print(parseString(xml).toprettyxml()) Output: <?xml version="1.0" ?> <root> <a>2</a> <b> <c>as</c> <f>True</f> </b> <d>7</d> </root> Saving XML to a file At times you might need to save XML to a file which can be done as follows Python3 # Converting Python Dictionary to# XML and saving to a filefrom dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Variable name of Dictionary is dataxml = dicttoxml(data) # Obtain decode string by decode()# functionxml_decode = xml.decode() xmlfile = open("dict.xml", "w")xmlfile.write(xml_decode)xmlfile.close() Output: Define custom Item names If you don’t want item elements in a list to be called ‘item’, you can specify the element name using a function that takes the parent element name (i.e. the list name) as an argument. Python3 # Defining custom names for listsfrom dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Dictionary to be convertedobj = {'mylist': [u'foo', u'bar', u'baz'], 'mydict': { 'foo': u'bar', 'baz': 1}, 'ok': True} # custom function for defining# item namesmy_item_func = lambda x: 'list_item'xml = dicttoxml(obj, item_func = my_item_func) # Pretty formating XMLxml_format = parseString(xml).toprettyxml() print(xml_format) Output: <?xml version="1.0" ?> <root> <mylist type="list"> <list_item type="str">foo</list_item> <list_item type="str">bar</list_item> <list_item type="str">baz</list_item> </mylist> <mydict type="dict"> <foo type="str">bar</foo> <baz type="int">1</baz> </mydict> <ok type="bool">True</ok> </root> The benefit of taking the parent element name as an argument is that you can write the function to do something with it. Let’s say you have an object with some lists of specific items: Python3 # Using parent name in dictionary# as tag name in xml from dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Dictionary to be converteddata = { 'month':['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] } # Here x is the parent, you can chose# to do some processing or use a part# of the parent name for tag namemy_item_func = lambda x: x+'s'xml = dicttoxml(data, item_func = my_item_func) print(parseString(xml).toprettyxml()) Output: <?xml version="1.0" ?> <root> <month type="list"> <months type="str">Jan</months> <months type="str">Feb</months> <months type="str">Mar</months> <months type="str">Apr</months> <months type="str">May</months> <months type="str">Jun</months> <months type="str">Jul</months> <months type="str">Aug</months> <months type="str">Sep</months> <months type="str">Oct</months> <months type="str">Nov</months> <months type="str">Dec</months> </month> </root> Akanksha_Rai sagar0719kumar singghakshay python-modules python-utility Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24854, "s": 24826, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25228, "s": 24854, "text": "XML is a markup language that is designed to transport data. It was made while keeping it self descriptive in mind. Syntax of XML is similar to HTML other than the fact that the tags in XML aren’t pre-defined. This allows for data to be stored between custom tags where the tag contains details about the data and the data is stored in between the opening and closing tags." }, { "code": null, "e": 25298, "s": 25228, "text": "Note: You can read more about XML here: XML | Basics and XML | Syntax" }, { "code": null, "e": 25397, "s": 25298, "text": "Currently, there are two major modules that allow to serialize Python dictionary to XML. They are " }, { "code": null, "e": 25415, "s": 25397, "text": "dict2xmlDicttoxml" }, { "code": null, "e": 25424, "s": 25415, "text": "dict2xml" }, { "code": null, "e": 25434, "s": 25424, "text": "Dicttoxml" }, { "code": null, "e": 25528, "s": 25434, "text": "For a quick conversion of Python Dictionary to XML, you can use dict2xml. Install it using: " }, { "code": null, "e": 25551, "s": 25528, "text": "$ pip install dict2xml" }, { "code": null, "e": 25641, "s": 25551, "text": "Now suppose you have a Dictionary named data in Python which you want to convert to XML " }, { "code": null, "e": 25649, "s": 25641, "text": "Python3" }, { "code": "# Converting Python Dictionary to XMLfrom dict2xml import dict2xml data = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dict2xml(data)print(xml)", "e": 25853, "s": 25649, "text": null }, { "code": null, "e": 25861, "s": 25853, "text": "Output:" }, { "code": null, "e": 25914, "s": 25861, "text": "<a>2</a>\n<b>\n <c>as</c>\n <f>True</f>\n</b>\n<d>7</d>" }, { "code": null, "e": 26053, "s": 25914, "text": "Wrapping around a root element and custom indenting Suppose you want to wrap the answer around a root element and add indent of 3 spaces. " }, { "code": null, "e": 26061, "s": 26053, "text": "Python3" }, { "code": "# Converting Python Dictionary to XML# with a root elemtntfrom dict2xml import dict2xml data = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dict2xml(data, wrap ='root', indent =\" \")print(xml)", "e": 26315, "s": 26061, "text": null }, { "code": null, "e": 26324, "s": 26315, "text": "Output: " }, { "code": null, "e": 26412, "s": 26324, "text": "<root>\n <a>2</a>\n <b>\n <c>as</c>\n <f>True</f>\n </b>\n <d>7</d>\n</root>" }, { "code": null, "e": 26693, "s": 26412, "text": "Dict2xml is good but it doesn’t have many options to specify how I want my XML to be formatted or to add attributes in tags. dicttoxml can be used for these purposes. It also works perfectly on Dict-like and Iterable Objects. Install it via terminal or command prompt by typing: " }, { "code": null, "e": 26719, "s": 26693, "text": " $ pip install dicttoxml " }, { "code": null, "e": 26724, "s": 26719, "text": "or " }, { "code": null, "e": 26752, "s": 26724, "text": " $ easy_install dicttoxml " }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": "# Using dicttoxml for converting Python# Dictionary to XMLfrom dicttoxml import dicttoxml # Data to be parseddata = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dicttoxml(data)print(xml)", "e": 27008, "s": 26760, "text": null }, { "code": null, "e": 27016, "s": 27008, "text": "Output:" }, { "code": null, "e": 27174, "s": 27016, "text": "b'<?xml version=”1.0′′ encoding=”UTF-8′′ ?><root><a type=”int”>2</a><b type=”dict”><c type=”str”>as</c><f type=”bool”>True</f></b><d type=”int”>7</d></root>’" }, { "code": null, "e": 27308, "s": 27174, "text": "Pretty Format the output Lets pretty format the text so that we can read it clearly. Python already has an inbuilt package for this! " }, { "code": null, "e": 27316, "s": 27308, "text": "Python3" }, { "code": "# Pretty printing XML after parsing# it from dictionaryfrom xml.dom.minidom import parseStringfrom dicttoxml import dicttoxml # Data to be parseddata = {'a': 2, 'b': { 'c': 'as', 'f': True}, 'd': 7, } xml = dicttoxml(data)dom = parseString(xml) print(dom.toprettyxml())", "e": 27636, "s": 27316, "text": null }, { "code": null, "e": 27645, "s": 27636, "text": "Output: " }, { "code": null, "e": 27821, "s": 27645, "text": "<?xml version=\"1.0\" ?>\n<root>\n <a type=\"int\">2</a>\n <b type=\"dict\">\n <c type=\"str\">as</c>\n <f type=\"bool\">True</f>\n </b>\n <d type=\"int\">7</d>\n</root>" }, { "code": null, "e": 27976, "s": 27821, "text": "Removing Type Attributes You might notice that the tags now contain attributes like type=”int”/”dict”/”str” which can be turned off using attr_type=False " }, { "code": null, "e": 27984, "s": 27976, "text": "Python3" }, { "code": "# Removing Type Attribute from parsed XMLfrom xml.dom.minidom import parseString # attr_type = False is used# to remove type attributesxml = dicttoxml(data, attr_type = False) print(parseString(xml).toprettyxml())", "e": 28198, "s": 27984, "text": null }, { "code": null, "e": 28207, "s": 28198, "text": "Output: " }, { "code": null, "e": 28326, "s": 28207, "text": "<?xml version=\"1.0\" ?>\n<root>\n <a>2</a>\n <b>\n <c>as</c>\n <f>True</f>\n </b>\n <d>7</d>\n</root>" }, { "code": null, "e": 28422, "s": 28326, "text": "Saving XML to a file At times you might need to save XML to a file which can be done as follows" }, { "code": null, "e": 28430, "s": 28422, "text": "Python3" }, { "code": "# Converting Python Dictionary to# XML and saving to a filefrom dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Variable name of Dictionary is dataxml = dicttoxml(data) # Obtain decode string by decode()# functionxml_decode = xml.decode() xmlfile = open(\"dict.xml\", \"w\")xmlfile.write(xml_decode)xmlfile.close()", "e": 28762, "s": 28430, "text": null }, { "code": null, "e": 28771, "s": 28762, "text": "Output: " }, { "code": null, "e": 28982, "s": 28771, "text": "Define custom Item names If you don’t want item elements in a list to be called ‘item’, you can specify the element name using a function that takes the parent element name (i.e. the list name) as an argument. " }, { "code": null, "e": 28990, "s": 28982, "text": "Python3" }, { "code": "# Defining custom names for listsfrom dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Dictionary to be convertedobj = {'mylist': [u'foo', u'bar', u'baz'], 'mydict': { 'foo': u'bar', 'baz': 1}, 'ok': True} # custom function for defining# item namesmy_item_func = lambda x: 'list_item'xml = dicttoxml(obj, item_func = my_item_func) # Pretty formating XMLxml_format = parseString(xml).toprettyxml() print(xml_format)", "e": 29471, "s": 28990, "text": null }, { "code": null, "e": 29480, "s": 29471, "text": "Output: " }, { "code": null, "e": 29830, "s": 29480, "text": "<?xml version=\"1.0\" ?>\n<root>\n <mylist type=\"list\">\n <list_item type=\"str\">foo</list_item>\n <list_item type=\"str\">bar</list_item>\n <list_item type=\"str\">baz</list_item>\n </mylist>\n <mydict type=\"dict\">\n <foo type=\"str\">bar</foo>\n <baz type=\"int\">1</baz>\n </mydict>\n <ok type=\"bool\">True</ok>\n</root>" }, { "code": null, "e": 30016, "s": 29830, "text": "The benefit of taking the parent element name as an argument is that you can write the function to do something with it. Let’s say you have an object with some lists of specific items: " }, { "code": null, "e": 30024, "s": 30016, "text": "Python3" }, { "code": "# Using parent name in dictionary# as tag name in xml from dicttoxml import dicttoxmlfrom xml.dom.minidom import parseString # Dictionary to be converteddata = { 'month':['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] } # Here x is the parent, you can chose# to do some processing or use a part# of the parent name for tag namemy_item_func = lambda x: x+'s'xml = dicttoxml(data, item_func = my_item_func) print(parseString(xml).toprettyxml())", "e": 30573, "s": 30024, "text": null }, { "code": null, "e": 30582, "s": 30573, "text": "Output: " }, { "code": null, "e": 31137, "s": 30582, "text": "<?xml version=\"1.0\" ?>\n<root>\n <month type=\"list\">\n <months type=\"str\">Jan</months>\n <months type=\"str\">Feb</months>\n <months type=\"str\">Mar</months>\n <months type=\"str\">Apr</months>\n <months type=\"str\">May</months>\n <months type=\"str\">Jun</months>\n <months type=\"str\">Jul</months>\n <months type=\"str\">Aug</months>\n <months type=\"str\">Sep</months>\n <months type=\"str\">Oct</months>\n <months type=\"str\">Nov</months>\n <months type=\"str\">Dec</months>\n </month>\n</root>" }, { "code": null, "e": 31152, "s": 31139, "text": "Akanksha_Rai" }, { "code": null, "e": 31167, "s": 31152, "text": "sagar0719kumar" }, { "code": null, "e": 31180, "s": 31167, "text": "singghakshay" }, { "code": null, "e": 31195, "s": 31180, "text": "python-modules" }, { "code": null, "e": 31210, "s": 31195, "text": "python-utility" }, { "code": null, "e": 31217, "s": 31210, "text": "Python" }, { "code": null, "e": 31233, "s": 31217, "text": "Write From Home" }, { "code": null, "e": 31331, "s": 31233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31349, "s": 31331, "text": "Python Dictionary" }, { "code": null, "e": 31384, "s": 31349, "text": "Read a file line by line in Python" }, { "code": null, "e": 31406, "s": 31384, "text": "Enumerate() in Python" }, { "code": null, "e": 31438, "s": 31406, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31468, "s": 31438, "text": "Iterate over a list in Python" }, { "code": null, "e": 31504, "s": 31468, "text": "Convert integer to string in Python" }, { "code": null, "e": 31540, "s": 31504, "text": "Convert string to integer in Python" }, { "code": null, "e": 31556, "s": 31540, "text": "Python infinity" }, { "code": null, "e": 31617, "s": 31556, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Knowing The General Modeling Framework is a Must For All Data Scientists | by Robert Wood | Towards Data Science
When it comes to building statistical models, we do so with the purpose of understanding or approximating some aspect of our world. The concept of the general modeling framework lends well to breaking down the purposes and approaches that we might take to generate said understanding. Take a look at the general modeling framework as depicted by the below formula: y = f(x) + e y: the outcome variable/whatever we’re trying to better understand x: the independent variable(s) or whatever we’re using to explain y f(): the function that when applied to x approximates the value of y e: the error or distance between our explanation of Y through our function of X in comparison to actual Y. Eg: everything we can’t explain through our f(X) A couple of key takeaways here. What makes up y, is our understanding of y as a function of x with error sprinkled on top. Our effort to identify that function is what modeling is all about. If you’ve heard about signal & noise, the function is the signal, the sign, the indicator and the noise is the error, the variation, etc. Let’s run through two purposes or approaches you can leverage in conjunction with this framework to guide your modeling process. As far as the modeling mechanics, much of it will remain the same. The core difference here being the philosophy that’s guiding your process. When it comes to modeling for explanation, the driving force is that we’re trying to understand which variables potentially cause an outcome or relate to it. With that as the preface, let’s jump into some exploratory data analysis that would kick off our process of modeling for explanation. Once we have come to an understanding of F Once you have teased out an interpretation of the function (of X), you can apply it to other data (another X) to generate predictions. while the EDA we engage in will be largely the same, the intent/use will likely be different. Again, this difference is highlighted by the intent to generate predictions using this historic relationship between X & Y. When modeling for prediction, we still find ourselves in the predicament of not knowing the function or error, which we still need to separate and understand. The bigger thing is that when modeling for explanation we care a lot about the form of our function, whereas when modeling for prediction we don’t so much.... what we care about in that case is whether or not our predictions are accurate, hence the name.. modeling for prediction. Whether modeling for explanation or prediction, we still will go through the process of exploratory data analysis. This process will give us the right information to guide our direction to understand the function of X. Let’s kick our process off with exploratory data analysis (or EDA as we call it in the biz ;) ). The intention of EDA is that we precede our modeling process with a series of activities that lend to better understanding each of the independent and dependent variables we seek to model and at a high level how they may relate to one another. I have pulled down a house prices dataset from kaggle. You can find that here: https://www.kaggle.com/shree1992/housedata/data We will typically kick this process off with a series of functions that give us a quick perspective into the data. Both glimpse and str will give you a view of the fields, their datatypes, the dimensions, & samples. glimpse(housing) str(housing) We will now look at head to get a look at the first several rows of our dataset. head(housing) We’ll load up ggplot2 and make a histogram to look at a few of these variables library(ggplot2)ggplot(housing, aes(x = bathrooms)) + geom_histogram(binwidth = 1) With geom_histogram we can see the count of homes that fall into each numeric category. We can see the greatest number of homes has 2.5 bathrooms. Let’s do the same thing for a few more variables for example’s sake. Below you’ll see the distribution of square feet. We can see a slightly right skewed distribution. Let’s visualize home price. As you can see it’s a bit right skewed due to homes at some of those extreme prices. One thing to keep in mind when visualizing distributions and there is skew is visualizing the log10 distribution of the variable. The beauty of taking the log is that it preserves the order of values. Let’s take a quick look! We saw the square foot living distribution had some right skew, so let’s visualize that. housing %>% mutate(sqft_living_log = log10(sqft_living))%>% ggplot(aes(x = sqft_living_log)) + geom_histogram() As we can see above, we have a normally distributed log value for square footage. This makes it easier to compare some of these lower values with those that exist along the greater extremes of the right tail. Lets walk through a similar process now with multiple variables involved. This will allow us to get an idea of how these variables relate to one another. We’ll kick it off first with a scatter of sqft & price. housing %>% ggplot(aes(x = sqft_living, y = price)) + geom_point() These two variables have a linear relationship and correlate at .43 Now we know that both of these variables are right skewed, let’s visualize them again after converting them to their log10 selves. housing %>% mutate(sqft_living_log = log10(sqft_living), price_log = log10(price))%>% ggplot(aes(x = sqft_living_log, y = price_log)) + geom_point() Now that we’ve gone through some EDA, let’s revisit the idea of modeling for explanation. The purpose is to understand which factors explain y, or as it relates to the housing data, how variables (sqft, # of bathrooms, etc.) might explain y. When it comes to modeling for prediction, our purpose would be to approximate housing prices. We don’t necessarily care what variables contribute to our function nor what are function really consists of... all we really care about is how well our model approximates reality. A good example here, would be Zillow & their zestimate. They absolutely care about the accuracy of the outcome that their current model is spitting out. When modeling, something to keep in mind is that we aren’t going to understand how error is generated... the purpose here is to derive the function by making an assessment of the relationship between X & Y. That function as we called out earlier is the signal, thus modeling is the process we take to separate signal & noise. Hopefully this introduction to the general modeling framework sheds some light on how you think about modeling. Happy data science-ing!
[ { "code": null, "e": 304, "s": 172, "text": "When it comes to building statistical models, we do so with the purpose of understanding or approximating some aspect of our world." }, { "code": null, "e": 457, "s": 304, "text": "The concept of the general modeling framework lends well to breaking down the purposes and approaches that we might take to generate said understanding." }, { "code": null, "e": 537, "s": 457, "text": "Take a look at the general modeling framework as depicted by the below formula:" }, { "code": null, "e": 550, "s": 537, "text": "y = f(x) + e" }, { "code": null, "e": 617, "s": 550, "text": "y: the outcome variable/whatever we’re trying to better understand" }, { "code": null, "e": 685, "s": 617, "text": "x: the independent variable(s) or whatever we’re using to explain y" }, { "code": null, "e": 754, "s": 685, "text": "f(): the function that when applied to x approximates the value of y" }, { "code": null, "e": 910, "s": 754, "text": "e: the error or distance between our explanation of Y through our function of X in comparison to actual Y. Eg: everything we can’t explain through our f(X)" }, { "code": null, "e": 1239, "s": 910, "text": "A couple of key takeaways here. What makes up y, is our understanding of y as a function of x with error sprinkled on top. Our effort to identify that function is what modeling is all about. If you’ve heard about signal & noise, the function is the signal, the sign, the indicator and the noise is the error, the variation, etc." }, { "code": null, "e": 1368, "s": 1239, "text": "Let’s run through two purposes or approaches you can leverage in conjunction with this framework to guide your modeling process." }, { "code": null, "e": 1510, "s": 1368, "text": "As far as the modeling mechanics, much of it will remain the same. The core difference here being the philosophy that’s guiding your process." }, { "code": null, "e": 1668, "s": 1510, "text": "When it comes to modeling for explanation, the driving force is that we’re trying to understand which variables potentially cause an outcome or relate to it." }, { "code": null, "e": 1802, "s": 1668, "text": "With that as the preface, let’s jump into some exploratory data analysis that would kick off our process of modeling for explanation." }, { "code": null, "e": 1980, "s": 1802, "text": "Once we have come to an understanding of F Once you have teased out an interpretation of the function (of X), you can apply it to other data (another X) to generate predictions." }, { "code": null, "e": 2198, "s": 1980, "text": "while the EDA we engage in will be largely the same, the intent/use will likely be different. Again, this difference is highlighted by the intent to generate predictions using this historic relationship between X & Y." }, { "code": null, "e": 2357, "s": 2198, "text": "When modeling for prediction, we still find ourselves in the predicament of not knowing the function or error, which we still need to separate and understand." }, { "code": null, "e": 2638, "s": 2357, "text": "The bigger thing is that when modeling for explanation we care a lot about the form of our function, whereas when modeling for prediction we don’t so much.... what we care about in that case is whether or not our predictions are accurate, hence the name.. modeling for prediction." }, { "code": null, "e": 2857, "s": 2638, "text": "Whether modeling for explanation or prediction, we still will go through the process of exploratory data analysis. This process will give us the right information to guide our direction to understand the function of X." }, { "code": null, "e": 3198, "s": 2857, "text": "Let’s kick our process off with exploratory data analysis (or EDA as we call it in the biz ;) ). The intention of EDA is that we precede our modeling process with a series of activities that lend to better understanding each of the independent and dependent variables we seek to model and at a high level how they may relate to one another." }, { "code": null, "e": 3325, "s": 3198, "text": "I have pulled down a house prices dataset from kaggle. You can find that here: https://www.kaggle.com/shree1992/housedata/data" }, { "code": null, "e": 3440, "s": 3325, "text": "We will typically kick this process off with a series of functions that give us a quick perspective into the data." }, { "code": null, "e": 3541, "s": 3440, "text": "Both glimpse and str will give you a view of the fields, their datatypes, the dimensions, & samples." }, { "code": null, "e": 3558, "s": 3541, "text": "glimpse(housing)" }, { "code": null, "e": 3571, "s": 3558, "text": "str(housing)" }, { "code": null, "e": 3652, "s": 3571, "text": "We will now look at head to get a look at the first several rows of our dataset." }, { "code": null, "e": 3666, "s": 3652, "text": "head(housing)" }, { "code": null, "e": 3745, "s": 3666, "text": "We’ll load up ggplot2 and make a histogram to look at a few of these variables" }, { "code": null, "e": 3829, "s": 3745, "text": "library(ggplot2)ggplot(housing, aes(x = bathrooms)) + geom_histogram(binwidth = 1)" }, { "code": null, "e": 3976, "s": 3829, "text": "With geom_histogram we can see the count of homes that fall into each numeric category. We can see the greatest number of homes has 2.5 bathrooms." }, { "code": null, "e": 4045, "s": 3976, "text": "Let’s do the same thing for a few more variables for example’s sake." }, { "code": null, "e": 4095, "s": 4045, "text": "Below you’ll see the distribution of square feet." }, { "code": null, "e": 4144, "s": 4095, "text": "We can see a slightly right skewed distribution." }, { "code": null, "e": 4172, "s": 4144, "text": "Let’s visualize home price." }, { "code": null, "e": 4257, "s": 4172, "text": "As you can see it’s a bit right skewed due to homes at some of those extreme prices." }, { "code": null, "e": 4387, "s": 4257, "text": "One thing to keep in mind when visualizing distributions and there is skew is visualizing the log10 distribution of the variable." }, { "code": null, "e": 4458, "s": 4387, "text": "The beauty of taking the log is that it preserves the order of values." }, { "code": null, "e": 4483, "s": 4458, "text": "Let’s take a quick look!" }, { "code": null, "e": 4572, "s": 4483, "text": "We saw the square foot living distribution had some right skew, so let’s visualize that." }, { "code": null, "e": 4687, "s": 4572, "text": "housing %>% mutate(sqft_living_log = log10(sqft_living))%>% ggplot(aes(x = sqft_living_log)) + geom_histogram()" }, { "code": null, "e": 4896, "s": 4687, "text": "As we can see above, we have a normally distributed log value for square footage. This makes it easier to compare some of these lower values with those that exist along the greater extremes of the right tail." }, { "code": null, "e": 5050, "s": 4896, "text": "Lets walk through a similar process now with multiple variables involved. This will allow us to get an idea of how these variables relate to one another." }, { "code": null, "e": 5106, "s": 5050, "text": "We’ll kick it off first with a scatter of sqft & price." }, { "code": null, "e": 5175, "s": 5106, "text": "housing %>% ggplot(aes(x = sqft_living, y = price)) + geom_point()" }, { "code": null, "e": 5243, "s": 5175, "text": "These two variables have a linear relationship and correlate at .43" }, { "code": null, "e": 5374, "s": 5243, "text": "Now we know that both of these variables are right skewed, let’s visualize them again after converting them to their log10 selves." }, { "code": null, "e": 5534, "s": 5374, "text": "housing %>% mutate(sqft_living_log = log10(sqft_living), price_log = log10(price))%>% ggplot(aes(x = sqft_living_log, y = price_log)) + geom_point()" }, { "code": null, "e": 5776, "s": 5534, "text": "Now that we’ve gone through some EDA, let’s revisit the idea of modeling for explanation. The purpose is to understand which factors explain y, or as it relates to the housing data, how variables (sqft, # of bathrooms, etc.) might explain y." }, { "code": null, "e": 6204, "s": 5776, "text": "When it comes to modeling for prediction, our purpose would be to approximate housing prices. We don’t necessarily care what variables contribute to our function nor what are function really consists of... all we really care about is how well our model approximates reality. A good example here, would be Zillow & their zestimate. They absolutely care about the accuracy of the outcome that their current model is spitting out." }, { "code": null, "e": 6530, "s": 6204, "text": "When modeling, something to keep in mind is that we aren’t going to understand how error is generated... the purpose here is to derive the function by making an assessment of the relationship between X & Y. That function as we called out earlier is the signal, thus modeling is the process we take to separate signal & noise." }, { "code": null, "e": 6642, "s": 6530, "text": "Hopefully this introduction to the general modeling framework sheds some light on how you think about modeling." } ]
jQuery | Selectors and Event Methods - GeeksforGeeks
12 Feb, 2019 jQuery is a powerful JavaScript library. It is more powerful than the JavaScript. The codes of jQuery are more precise, shorter and simpler than the standard JavaScript codes. It can perform a variety of functions.In this article, we will learn about jQuery selectors, jQuery Event methods and some useful methods. jQuery selectors:jQuery selectors are used to select the HTML element(s) and allows you to manipulate the HTML element(s) in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. All selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses: $("selector-name")Elements Selector :The elements selector selects the element on the basis of its name.Example :In this example, when the user clicks on button, the <h1> element gets hidden.Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $("h1").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:Id Selector :The id selector selects the element on the basis of its id.Example :In this example, when the user double clicks on button, the element with id = “gfg” gets hidden.Code:-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p id="gfg">Welcome to Geeks for Geeks !</p> <p id="GFG">Computer Science Portal </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").dblclick(function() { $("#gfg").hide(); }); </script></body> </html>Output:Before double clicking on Hide button:After double clicking on Hide button:Class Selector :The class selector selects the element on the basis of its class.Example :In this example, when the user clicks on button, the element with class = “GFG” gets hidden.Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p class="gfg">Welcome to Geeks for Geeks !</p> <p class="GFG">Explore More about GfG </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $(".GFG").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:jQuery Event methods:Event refers to the actions performed by the site visitor during their interactivity with the website (or webpage).There can be various types of events such asUser clicks on the button.User moves mouse pointer over an image.User pressed any key from keyboard, etc.Some of the events methods are givenMethod NameDescriptionclick()The click() method contains an function for event handling which gets invoked when the user clicks on the particular HTML element.dblclick()The dblclick() method contains an function for event handling which gets invoked when the user double clicks on the particular HTML element.mouseenter()The mouseenter() method contains an function for event handling which gets invoked when mouse pointer enters the particular HTML element.mouseleave()The mouseleave() method contains an function for event handling which gets invoked when mouse pointer is removed from the particular HTML element which was selected earlier.mousedown()The mousedown() method contains an function for event handling which gets invoked when mouse left, right or middle button is pressed while the mouse pointer is over the HTML element.mouseup()The mouseup() method contains an function for event handling which gets invoked when mouse left, right or middle button is released while the mouse pointer is over the HTML element.hover()The hover() method contains an function for event handling which gets invoked when mouse pointer enter and leaves the HTML element. It is a combination of mouseenter() and mouseleave() methods.Get and Set Methods:jQuery has various methods to get the value of an attribute and set the attribute to specific value.There methods are powerful enough to the change the website content and its style. Some of them are:text() – This method is used get or set the text content of selected HTML element.html() – This method is used get or set the content of selected elements (including HTML elements).val() – This method is used get or set the value of various form fields in the webpage.attr() – This method is used get or set the value of various various attributes in the webpage.css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id="e1">Welcome.</p> <p id="e2">Learn and Explore</p> <p> <input type="text" id="e3" value="jQuery is powerful!" /> </p> <p id="e4" align="left">Geeks for Geeks</p> <p> <div id="e5"></div> </p> <button id="gfg1">Change Text</button> <button id="gfg2">Change HTML</button> <button id="gfg3">Change Value</button> <button id="gfg4">Change Alignment</button> <button id="gfg5">Change Shape</button> <script type="text/javascript"> $("#gfg1").click(function() { $("#e1").text("Geeks for Geeks"); }); $("#gfg2").click(function() { $("#e2").html("<b>Enrich your Knowledge.</b>"); }); $("#gfg3").click(function() { $("#e3").val("jQuery at Geeks for Geeks"); }); $("#gfg4").click(function() { $("#e4").attr("align", "center"); }); $("#gfg5").click(function() { $("#e5").css("border-radius", "50px"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes arrow_drop_upSave $("selector-name") Elements Selector :The elements selector selects the element on the basis of its name.Example :In this example, when the user clicks on button, the <h1> element gets hidden.Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $("h1").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $("h1").hide(); }); </script></body> </html> Output:Before clicking on Hide button:After clicking on Hide button: Id Selector :The id selector selects the element on the basis of its id.Example :In this example, when the user double clicks on button, the element with id = “gfg” gets hidden.Code:-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p id="gfg">Welcome to Geeks for Geeks !</p> <p id="GFG">Computer Science Portal </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").dblclick(function() { $("#gfg").hide(); }); </script></body> </html>Output:Before double clicking on Hide button:After double clicking on Hide button: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p id="gfg">Welcome to Geeks for Geeks !</p> <p id="GFG">Computer Science Portal </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").dblclick(function() { $("#gfg").hide(); }); </script></body> </html> Output:Before double clicking on Hide button:After double clicking on Hide button: Class Selector :The class selector selects the element on the basis of its class.Example :In this example, when the user clicks on button, the element with class = “GFG” gets hidden.Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p class="gfg">Welcome to Geeks for Geeks !</p> <p class="GFG">Explore More about GfG </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $(".GFG").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <p class="gfg">Welcome to Geeks for Geeks !</p> <p class="GFG">Explore More about GfG </p> <br/> <button>Hide</button> <script type="text/javascript"> $("button").click(function() { $(".GFG").hide(); }); </script></body> </html> Output:Before clicking on Hide button:After clicking on Hide button: User clicks on the button.User moves mouse pointer over an image.User pressed any key from keyboard, etc. User clicks on the button. User moves mouse pointer over an image. User pressed any key from keyboard, etc. Some of the events methods are given text() – This method is used get or set the text content of selected HTML element.html() – This method is used get or set the content of selected elements (including HTML elements).val() – This method is used get or set the value of various form fields in the webpage.attr() – This method is used get or set the value of various various attributes in the webpage.css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id="e1">Welcome.</p> <p id="e2">Learn and Explore</p> <p> <input type="text" id="e3" value="jQuery is powerful!" /> </p> <p id="e4" align="left">Geeks for Geeks</p> <p> <div id="e5"></div> </p> <button id="gfg1">Change Text</button> <button id="gfg2">Change HTML</button> <button id="gfg3">Change Value</button> <button id="gfg4">Change Alignment</button> <button id="gfg5">Change Shape</button> <script type="text/javascript"> $("#gfg1").click(function() { $("#e1").text("Geeks for Geeks"); }); $("#gfg2").click(function() { $("#e2").html("<b>Enrich your Knowledge.</b>"); }); $("#gfg3").click(function() { $("#e3").val("jQuery at Geeks for Geeks"); }); $("#gfg4").click(function() { $("#e4").attr("align", "center"); }); $("#gfg5").click(function() { $("#e5").css("border-radius", "50px"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes arrow_drop_upSave text() – This method is used get or set the text content of selected HTML element. html() – This method is used get or set the content of selected elements (including HTML elements). val() – This method is used get or set the value of various form fields in the webpage. attr() – This method is used get or set the value of various various attributes in the webpage. css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id="e1">Welcome.</p> <p id="e2">Learn and Explore</p> <p> <input type="text" id="e3" value="jQuery is powerful!" /> </p> <p id="e4" align="left">Geeks for Geeks</p> <p> <div id="e5"></div> </p> <button id="gfg1">Change Text</button> <button id="gfg2">Change HTML</button> <button id="gfg3">Change Value</button> <button id="gfg4">Change Alignment</button> <button id="gfg5">Change Shape</button> <script type="text/javascript"> $("#gfg1").click(function() { $("#e1").text("Geeks for Geeks"); }); $("#gfg2").click(function() { $("#e2").html("<b>Enrich your Knowledge.</b>"); }); $("#gfg3").click(function() { $("#e3").val("jQuery at Geeks for Geeks"); }); $("#gfg4").click(function() { $("#e4").attr("align", "center"); }); $("#gfg5").click(function() { $("#e5").css("border-radius", "50px"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes arrow_drop_upSave Example :Code :-<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id="e1">Welcome.</p> <p id="e2">Learn and Explore</p> <p> <input type="text" id="e3" value="jQuery is powerful!" /> </p> <p id="e4" align="left">Geeks for Geeks</p> <p> <div id="e5"></div> </p> <button id="gfg1">Change Text</button> <button id="gfg2">Change HTML</button> <button id="gfg3">Change Value</button> <button id="gfg4">Change Alignment</button> <button id="gfg5">Change Shape</button> <script type="text/javascript"> $("#gfg1").click(function() { $("#e1").text("Geeks for Geeks"); }); $("#gfg2").click(function() { $("#e2").html("<b>Enrich your Knowledge.</b>"); }); $("#gfg3").click(function() { $("#e3").val("jQuery at Geeks for Geeks"); }); $("#gfg4").click(function() { $("#e4").attr("align", "center"); }); $("#gfg5").click(function() { $("#e5").css("border-radius", "50px"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id="e1">Welcome.</p> <p id="e2">Learn and Explore</p> <p> <input type="text" id="e3" value="jQuery is powerful!" /> </p> <p id="e4" align="left">Geeks for Geeks</p> <p> <div id="e5"></div> </p> <button id="gfg1">Change Text</button> <button id="gfg2">Change HTML</button> <button id="gfg3">Change Value</button> <button id="gfg4">Change Alignment</button> <button id="gfg5">Change Shape</button> <script type="text/javascript"> $("#gfg1").click(function() { $("#e1").text("Geeks for Geeks"); }); $("#gfg2").click(function() { $("#e2").html("<b>Enrich your Knowledge.</b>"); }); $("#gfg3").click(function() { $("#e3").val("jQuery at Geeks for Geeks"); }); $("#gfg4").click(function() { $("#e4").attr("align", "center"); }); $("#gfg5").click(function() { $("#e5").css("border-radius", "50px"); }); </script></body> </html> Output:Before clicking on buttons:After clicking on buttons: jQuery-Basics JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 40747, "s": 40719, "text": "\n12 Feb, 2019" }, { "code": null, "e": 41062, "s": 40747, "text": "jQuery is a powerful JavaScript library. It is more powerful than the JavaScript. The codes of jQuery are more precise, shorter and simpler than the standard JavaScript codes. It can perform a variety of functions.In this article, we will learn about jQuery selectors, jQuery Event methods and some useful methods." }, { "code": null, "e": 47073, "s": 41062, "text": "jQuery selectors:jQuery selectors are used to select the HTML element(s) and allows you to manipulate the HTML element(s) in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. All selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses: $(\"selector-name\")Elements Selector :The elements selector selects the element on the basis of its name.Example :In this example, when the user clicks on button, the <h1> element gets hidden.Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\"h1\").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:Id Selector :The id selector selects the element on the basis of its id.Example :In this example, when the user double clicks on button, the element with id = “gfg” gets hidden.Code:-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p id=\"gfg\">Welcome to Geeks for Geeks !</p> <p id=\"GFG\">Computer Science Portal </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").dblclick(function() { $(\"#gfg\").hide(); }); </script></body> </html>Output:Before double clicking on Hide button:After double clicking on Hide button:Class Selector :The class selector selects the element on the basis of its class.Example :In this example, when the user clicks on button, the element with class = “GFG” gets hidden.Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p class=\"gfg\">Welcome to Geeks for Geeks !</p> <p class=\"GFG\">Explore More about GfG </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\".GFG\").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:jQuery Event methods:Event refers to the actions performed by the site visitor during their interactivity with the website (or webpage).There can be various types of events such asUser clicks on the button.User moves mouse pointer over an image.User pressed any key from keyboard, etc.Some of the events methods are givenMethod NameDescriptionclick()The click() method contains an function for event handling which gets invoked when the user clicks on the particular HTML element.dblclick()The dblclick() method contains an function for event handling which gets invoked when the user double clicks on the particular HTML element.mouseenter()The mouseenter() method contains an function for event handling which gets invoked when mouse pointer enters the particular HTML element.mouseleave()The mouseleave() method contains an function for event handling which gets invoked when mouse pointer is removed from the particular HTML element which was selected earlier.mousedown()The mousedown() method contains an function for event handling which gets invoked when mouse left, right or middle button is pressed while the mouse pointer is over the HTML element.mouseup()The mouseup() method contains an function for event handling which gets invoked when mouse left, right or middle button is released while the mouse pointer is over the HTML element.hover()The hover() method contains an function for event handling which gets invoked when mouse pointer enter and leaves the HTML element. It is a combination of mouseenter() and mouseleave() methods.Get and Set Methods:jQuery has various methods to get the value of an attribute and set the attribute to specific value.There methods are powerful enough to the change the website content and its style. Some of them are:text() – This method is used get or set the text content of selected HTML element.html() – This method is used get or set the content of selected elements (including HTML elements).val() – This method is used get or set the value of various form fields in the webpage.attr() – This method is used get or set the value of various various attributes in the webpage.css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id=\"e1\">Welcome.</p> <p id=\"e2\">Learn and Explore</p> <p> <input type=\"text\" id=\"e3\" value=\"jQuery is powerful!\" /> </p> <p id=\"e4\" align=\"left\">Geeks for Geeks</p> <p> <div id=\"e5\"></div> </p> <button id=\"gfg1\">Change Text</button> <button id=\"gfg2\">Change HTML</button> <button id=\"gfg3\">Change Value</button> <button id=\"gfg4\">Change Alignment</button> <button id=\"gfg5\">Change Shape</button> <script type=\"text/javascript\"> $(\"#gfg1\").click(function() { $(\"#e1\").text(\"Geeks for Geeks\"); }); $(\"#gfg2\").click(function() { $(\"#e2\").html(\"<b>Enrich your Knowledge.</b>\"); }); $(\"#gfg3\").click(function() { $(\"#e3\").val(\"jQuery at Geeks for Geeks\"); }); $(\"#gfg4\").click(function() { $(\"#e4\").attr(\"align\", \"center\"); }); $(\"#gfg5\").click(function() { $(\"#e5\").css(\"border-radius\", \"50px\"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 47093, "s": 47073, "text": " $(\"selector-name\")" }, { "code": null, "e": 47737, "s": 47093, "text": "Elements Selector :The elements selector selects the element on the basis of its name.Example :In this example, when the user clicks on button, the <h1> element gets hidden.Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\"h1\").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <h1>Welcome to Geeks for Geeks !</h1> <h2>This is Web Technology section </h2> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\"h1\").hide(); }); </script></body> </html>", "e": 48133, "s": 47737, "text": null }, { "code": null, "e": 48202, "s": 48133, "text": "Output:Before clicking on Hide button:After clicking on Hide button:" }, { "code": null, "e": 48875, "s": 48202, "text": "Id Selector :The id selector selects the element on the basis of its id.Example :In this example, when the user double clicks on button, the element with id = “gfg” gets hidden.Code:-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p id=\"gfg\">Welcome to Geeks for Geeks !</p> <p id=\"GFG\">Computer Science Portal </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").dblclick(function() { $(\"#gfg\").hide(); }); </script></body> </html>Output:Before double clicking on Hide button:After double clicking on Hide button:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p id=\"gfg\">Welcome to Geeks for Geeks !</p> <p id=\"GFG\">Computer Science Portal </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").dblclick(function() { $(\"#gfg\").hide(); }); </script></body> </html>", "e": 49283, "s": 48875, "text": null }, { "code": null, "e": 49366, "s": 49283, "text": "Output:Before double clicking on Hide button:After double clicking on Hide button:" }, { "code": null, "e": 50033, "s": 49366, "text": "Class Selector :The class selector selects the element on the basis of its class.Example :In this example, when the user clicks on button, the element with class = “GFG” gets hidden.Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p class=\"gfg\">Welcome to Geeks for Geeks !</p> <p class=\"GFG\">Explore More about GfG </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\".GFG\").hide(); }); </script></body> </html>Output:Before clicking on Hide button:After clicking on Hide button:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></head> <body> <p class=\"gfg\">Welcome to Geeks for Geeks !</p> <p class=\"GFG\">Explore More about GfG </p> <br/> <button>Hide</button> <script type=\"text/javascript\"> $(\"button\").click(function() { $(\".GFG\").hide(); }); </script></body> </html>", "e": 50443, "s": 50033, "text": null }, { "code": null, "e": 50512, "s": 50443, "text": "Output:Before clicking on Hide button:After clicking on Hide button:" }, { "code": null, "e": 50618, "s": 50512, "text": "User clicks on the button.User moves mouse pointer over an image.User pressed any key from keyboard, etc." }, { "code": null, "e": 50645, "s": 50618, "text": "User clicks on the button." }, { "code": null, "e": 50685, "s": 50645, "text": "User moves mouse pointer over an image." }, { "code": null, "e": 50726, "s": 50685, "text": "User pressed any key from keyboard, etc." }, { "code": null, "e": 50763, "s": 50726, "text": "Some of the events methods are given" }, { "code": null, "e": 52648, "s": 50763, "text": "text() – This method is used get or set the text content of selected HTML element.html() – This method is used get or set the content of selected elements (including HTML elements).val() – This method is used get or set the value of various form fields in the webpage.attr() – This method is used get or set the value of various various attributes in the webpage.css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id=\"e1\">Welcome.</p> <p id=\"e2\">Learn and Explore</p> <p> <input type=\"text\" id=\"e3\" value=\"jQuery is powerful!\" /> </p> <p id=\"e4\" align=\"left\">Geeks for Geeks</p> <p> <div id=\"e5\"></div> </p> <button id=\"gfg1\">Change Text</button> <button id=\"gfg2\">Change HTML</button> <button id=\"gfg3\">Change Value</button> <button id=\"gfg4\">Change Alignment</button> <button id=\"gfg5\">Change Shape</button> <script type=\"text/javascript\"> $(\"#gfg1\").click(function() { $(\"#e1\").text(\"Geeks for Geeks\"); }); $(\"#gfg2\").click(function() { $(\"#e2\").html(\"<b>Enrich your Knowledge.</b>\"); }); $(\"#gfg3\").click(function() { $(\"#e3\").val(\"jQuery at Geeks for Geeks\"); }); $(\"#gfg4\").click(function() { $(\"#e4\").attr(\"align\", \"center\"); }); $(\"#gfg5\").click(function() { $(\"#e5\").css(\"border-radius\", \"50px\"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 52731, "s": 52648, "text": "text() – This method is used get or set the text content of selected HTML element." }, { "code": null, "e": 52831, "s": 52731, "text": "html() – This method is used get or set the content of selected elements (including HTML elements)." }, { "code": null, "e": 52919, "s": 52831, "text": "val() – This method is used get or set the value of various form fields in the webpage." }, { "code": null, "e": 53015, "s": 52919, "text": "attr() – This method is used get or set the value of various various attributes in the webpage." }, { "code": null, "e": 54537, "s": 53015, "text": "css() – This method is used get or set the value of various CSS properties in the webpage.Example :Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id=\"e1\">Welcome.</p> <p id=\"e2\">Learn and Explore</p> <p> <input type=\"text\" id=\"e3\" value=\"jQuery is powerful!\" /> </p> <p id=\"e4\" align=\"left\">Geeks for Geeks</p> <p> <div id=\"e5\"></div> </p> <button id=\"gfg1\">Change Text</button> <button id=\"gfg2\">Change HTML</button> <button id=\"gfg3\">Change Value</button> <button id=\"gfg4\">Change Alignment</button> <button id=\"gfg5\">Change Shape</button> <script type=\"text/javascript\"> $(\"#gfg1\").click(function() { $(\"#e1\").text(\"Geeks for Geeks\"); }); $(\"#gfg2\").click(function() { $(\"#e2\").html(\"<b>Enrich your Knowledge.</b>\"); }); $(\"#gfg3\").click(function() { $(\"#e3\").val(\"jQuery at Geeks for Geeks\"); }); $(\"#gfg4\").click(function() { $(\"#e4\").attr(\"align\", \"center\"); }); $(\"#gfg5\").click(function() { $(\"#e5\").css(\"border-radius\", \"50px\"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 55934, "s": 54537, "text": "Example :Code :-<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id=\"e1\">Welcome.</p> <p id=\"e2\">Learn and Explore</p> <p> <input type=\"text\" id=\"e3\" value=\"jQuery is powerful!\" /> </p> <p id=\"e4\" align=\"left\">Geeks for Geeks</p> <p> <div id=\"e5\"></div> </p> <button id=\"gfg1\">Change Text</button> <button id=\"gfg2\">Change HTML</button> <button id=\"gfg3\">Change Value</button> <button id=\"gfg4\">Change Alignment</button> <button id=\"gfg5\">Change Shape</button> <script type=\"text/javascript\"> $(\"#gfg1\").click(function() { $(\"#e1\").text(\"Geeks for Geeks\"); }); $(\"#gfg2\").click(function() { $(\"#e2\").html(\"<b>Enrich your Knowledge.</b>\"); }); $(\"#gfg3\").click(function() { $(\"#e3\").val(\"jQuery at Geeks for Geeks\"); }); $(\"#gfg4\").click(function() { $(\"#e4\").attr(\"align\", \"center\"); }); $(\"#gfg5\").click(function() { $(\"#e5\").css(\"border-radius\", \"50px\"); }); </script></body> </html>Output:Before clicking on buttons:After clicking on buttons:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> #e5 { width: 100px; height: 100px; border-radius: 0px; background-color: aqua; } </style></head> <body> <p id=\"e1\">Welcome.</p> <p id=\"e2\">Learn and Explore</p> <p> <input type=\"text\" id=\"e3\" value=\"jQuery is powerful!\" /> </p> <p id=\"e4\" align=\"left\">Geeks for Geeks</p> <p> <div id=\"e5\"></div> </p> <button id=\"gfg1\">Change Text</button> <button id=\"gfg2\">Change HTML</button> <button id=\"gfg3\">Change Value</button> <button id=\"gfg4\">Change Alignment</button> <button id=\"gfg5\">Change Shape</button> <script type=\"text/javascript\"> $(\"#gfg1\").click(function() { $(\"#e1\").text(\"Geeks for Geeks\"); }); $(\"#gfg2\").click(function() { $(\"#e2\").html(\"<b>Enrich your Knowledge.</b>\"); }); $(\"#gfg3\").click(function() { $(\"#e3\").val(\"jQuery at Geeks for Geeks\"); }); $(\"#gfg4\").click(function() { $(\"#e4\").attr(\"align\", \"center\"); }); $(\"#gfg5\").click(function() { $(\"#e5\").css(\"border-radius\", \"50px\"); }); </script></body> </html>", "e": 57255, "s": 55934, "text": null }, { "code": null, "e": 57316, "s": 57255, "text": "Output:Before clicking on buttons:After clicking on buttons:" }, { "code": null, "e": 57330, "s": 57316, "text": "jQuery-Basics" }, { "code": null, "e": 57341, "s": 57330, "text": "JavaScript" }, { "code": null, "e": 57348, "s": 57341, "text": "JQuery" }, { "code": null, "e": 57446, "s": 57348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57491, "s": 57446, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 57552, "s": 57491, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 57621, "s": 57552, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 57693, "s": 57621, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 57745, "s": 57693, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 57791, "s": 57745, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 57854, "s": 57791, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 57883, "s": 57854, "text": "Form validation using jQuery" }, { "code": null, "e": 57960, "s": 57883, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Computer Programming - Numbers
Every programming language provides support for manipulating different types of numbers such as simple whole integers and floating point numbers. C, Java, and Python categorize these numbers in several categories based on their nature. Let's go back and check the data types chapter, where we listed down the core data types related to numbers − These data types are called primitive data types and you can use these data types to build more data types, which are called user-defined data types. We have seen various mathematical and logical operations on numbers during a discussion on operators. So we know how to add numbers, subtract numbers, divide numbers, etc. First let's see how to print various types of numbers available in C programming language − #include <stdio.h> int main() { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374; printf( "s: %d\n", s); printf( "i: %d\n", i); printf( "l: %ld\n", l); printf( "f: %.3f\n", f); printf( "d: %.3f\n", d); } Rest of the coding is very obvious, but we used %.3f to print float and double, which indicates the number of digits after the decimal to be printed. When the above program is executed, it produces the following result − s: 10 i: 1000 l: 1000000 f: 230.470 d: 30949.374 The following table lists down various useful built-in mathematical functions available in C programming language which can be used for various important mathematical calculations. For example, if you want to calculate the square root of a number, for example, 2304, then you have a built-in function available to calculate the square root. double cos(double); This function takes an angle (as a double) and returns the cosine. double sin(double); This function takes an angle (as a double) and returns the sine. double tan(double); This function takes an angle (as a double) and returns the tangent. double log(double); This function takes a number and returns the natural log of that number. double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it to. double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return the length of the hypotenuse. double sqrt(double); You pass this function a number and it returns its square root. int abs(int); This function returns the absolute value of an integer that is passed to it. double fabs(double); This function returns the absolute value of any decimal number passed to it. double floor(double); Finds the integer which is less than or equal to the argument passed to it. Following is a simple example to show a few mathematical operations. To utilize these functions, you need to include the math header file <math.h> in your program in the same way you included stdio.h − #include <stdio.h> #include <math.h> int main() { short s; int i; long l; float f; double d; printf( "sin(s): %f\n", sin(10)); printf( "abs(i): %f\n", abs(1000)); printf( "floor(f): %f\n", floor(230.47)); printf( "sqrt(l): %f\n", sqrt(1000000)); printf( "pow(d, 2): %f\n", pow(2.374, 2)); } When the above program is executed, it produces the following result − sin(s): -0.544021 abs(i): -0.544021 floor(f): 230.000000 sqrt(l): 1000.000000 pow(d, 2): 5.635876 Besides the above usage, you will use numbers in loop counting, flag representation, true or false values in C programming. Following is the equivalent program written in Java. Java provides almost all the numeric data types available in C programming. You can try to execute the following program to see the output, which is identical to the result generated by the above C example. public class DemoJava { public static void main(String []args) { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000L; f = 230.47f; d = 30949.374; System.out.format( "s: %d\n", s); System.out.format( "i: %d\n", i); System.out.format( "l: %d\n", l); System.out.format( "f: %f\n", f); System.out.format( "d: %f\n", d); } } When the above program is executed, it produces the following result − s: 10 i: 1000 l: 1000000 f: 230.470001 d: 30949.374000 Java also provides a full range of built-in functions for mathematical calculation and you can use them in the same way as you did in C programming. Python is a little different from C and Java; it categorizes numbers in int, long, float and complex. Here are some examples of numbers in Python − Following is the equivalent program written in Python − s = 10 i = 1000 l = 1000000 f = 230.47 d = 30949.374 print "s: ", s print "i: ", i print "l: ", l print "f: ", f print "d: ", d When the above program is executed, it produces the following result − s: 10 i: 1000 l: 1000000 f: 230.47 d: 30949.374 Python also provides a full range of built-in functions for mathematical calculations and you can use them in the same way you have used them in C programming. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2376, "s": 2140, "text": "Every programming language provides support for manipulating different types of numbers such as simple whole integers and floating point numbers. C, Java, and Python categorize these numbers in several categories based on their nature." }, { "code": null, "e": 2486, "s": 2376, "text": "Let's go back and check the data types chapter, where we listed down the core data types related to numbers −" }, { "code": null, "e": 2636, "s": 2486, "text": "These data types are called primitive data types and you can use these data types to build more data types, which are called user-defined data types." }, { "code": null, "e": 2808, "s": 2636, "text": "We have seen various mathematical and logical operations on numbers during a discussion on operators. So we know how to add numbers, subtract numbers, divide numbers, etc." }, { "code": null, "e": 2900, "s": 2808, "text": "First let's see how to print various types of numbers available in C programming language −" }, { "code": null, "e": 3210, "s": 2900, "text": "#include <stdio.h>\n\nint main() {\n short s;\n int i;\n long l;\n float f;\n double d;\n\n s = 10;\n i = 1000;\n l = 1000000;\n f = 230.47;\n d = 30949.374;\n\n printf( \"s: %d\\n\", s);\n printf( \"i: %d\\n\", i);\n printf( \"l: %ld\\n\", l);\n printf( \"f: %.3f\\n\", f);\n printf( \"d: %.3f\\n\", d);\n}" }, { "code": null, "e": 3431, "s": 3210, "text": "Rest of the coding is very obvious, but we used %.3f to print float and double, which indicates the number of digits after the decimal to be printed. When the above program is executed, it produces the following result −" }, { "code": null, "e": 3481, "s": 3431, "text": "s: 10\ni: 1000\nl: 1000000\nf: 230.470\nd: 30949.374\n" }, { "code": null, "e": 3662, "s": 3481, "text": "The following table lists down various useful built-in mathematical functions available in C programming language which can be used for various important mathematical calculations." }, { "code": null, "e": 3822, "s": 3662, "text": "For example, if you want to calculate the square root of a number, for example, 2304, then you have a built-in function available to calculate the square root." }, { "code": null, "e": 3842, "s": 3822, "text": "double cos(double);" }, { "code": null, "e": 3909, "s": 3842, "text": "This function takes an angle (as a double) and returns the cosine." }, { "code": null, "e": 3929, "s": 3909, "text": "double sin(double);" }, { "code": null, "e": 3994, "s": 3929, "text": "This function takes an angle (as a double) and returns the sine." }, { "code": null, "e": 4014, "s": 3994, "text": "double tan(double);" }, { "code": null, "e": 4082, "s": 4014, "text": "This function takes an angle (as a double) and returns the tangent." }, { "code": null, "e": 4102, "s": 4082, "text": "double log(double);" }, { "code": null, "e": 4175, "s": 4102, "text": "This function takes a number and returns the natural log of that number." }, { "code": null, "e": 4203, "s": 4175, "text": "double pow(double, double);" }, { "code": null, "e": 4296, "s": 4203, "text": "The first is a number you wish to raise and the second is the power you wish to raise it to." }, { "code": null, "e": 4326, "s": 4296, "text": "double hypot(double, double);" }, { "code": null, "e": 4442, "s": 4326, "text": "If you pass this function the length of two sides of a right triangle, it will return the length of the hypotenuse." }, { "code": null, "e": 4463, "s": 4442, "text": "double sqrt(double);" }, { "code": null, "e": 4527, "s": 4463, "text": "You pass this function a number and it returns its square root." }, { "code": null, "e": 4541, "s": 4527, "text": "int abs(int);" }, { "code": null, "e": 4618, "s": 4541, "text": "This function returns the absolute value of an integer that is passed to it." }, { "code": null, "e": 4639, "s": 4618, "text": "double fabs(double);" }, { "code": null, "e": 4716, "s": 4639, "text": "This function returns the absolute value of any decimal number passed to it." }, { "code": null, "e": 4738, "s": 4716, "text": "double floor(double);" }, { "code": null, "e": 4814, "s": 4738, "text": "Finds the integer which is less than or equal to the argument passed to it." }, { "code": null, "e": 5016, "s": 4814, "text": "Following is a simple example to show a few mathematical operations. To utilize these functions, you need to include the math header file <math.h> in your program in the same way you included stdio.h −" }, { "code": null, "e": 5346, "s": 5016, "text": "#include <stdio.h>\n#include <math.h>\n\nint main() {\n short s;\n int i;\n long l;\n float f;\n double d;\n\n printf( \"sin(s): %f\\n\", sin(10));\n printf( \"abs(i): %f\\n\", abs(1000));\n printf( \"floor(f): %f\\n\", floor(230.47));\n printf( \"sqrt(l): %f\\n\", sqrt(1000000));\n printf( \"pow(d, 2): %f\\n\", pow(2.374, 2));\n}" }, { "code": null, "e": 5417, "s": 5346, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 5516, "s": 5417, "text": "sin(s): -0.544021\nabs(i): -0.544021\nfloor(f): 230.000000\nsqrt(l): 1000.000000\npow(d, 2): 5.635876\n" }, { "code": null, "e": 5640, "s": 5516, "text": "Besides the above usage, you will use numbers in loop counting, flag representation, true or false values in C programming." }, { "code": null, "e": 5769, "s": 5640, "text": "Following is the equivalent program written in Java. Java provides almost all the numeric data types available in C programming." }, { "code": null, "e": 5900, "s": 5769, "text": "You can try to execute the following program to see the output, which is identical to the result generated by the above C example." }, { "code": null, "e": 6347, "s": 5900, "text": "public class DemoJava {\n public static void main(String []args) {\n short s;\n int i;\n long l;\n float f;\n double d;\n\n s = 10;\n i = 1000;\n l = 1000000L;\n f = 230.47f;\n d = 30949.374;\n\n System.out.format( \"s: %d\\n\", s);\n System.out.format( \"i: %d\\n\", i);\n System.out.format( \"l: %d\\n\", l);\n System.out.format( \"f: %f\\n\", f);\n System.out.format( \"d: %f\\n\", d);\n }\n}" }, { "code": null, "e": 6418, "s": 6347, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 6474, "s": 6418, "text": "s: 10\ni: 1000\nl: 1000000\nf: 230.470001\nd: 30949.374000\n" }, { "code": null, "e": 6623, "s": 6474, "text": "Java also provides a full range of built-in functions for mathematical calculation and you can use them in the same way as you did in C programming." }, { "code": null, "e": 6771, "s": 6623, "text": "Python is a little different from C and Java; it categorizes numbers in int, long, float and complex. Here are some examples of numbers in Python −" }, { "code": null, "e": 6827, "s": 6771, "text": "Following is the equivalent program written in Python −" }, { "code": null, "e": 6956, "s": 6827, "text": "s = 10\ni = 1000\nl = 1000000\nf = 230.47\nd = 30949.374\n\nprint \"s: \", s\nprint \"i: \", i\nprint \"l: \", l\nprint \"f: \", f\nprint \"d: \", d" }, { "code": null, "e": 7027, "s": 6956, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 7081, "s": 7027, "text": "s: 10\ni: 1000\nl: 1000000\nf: 230.47\nd: 30949.374\n" }, { "code": null, "e": 7241, "s": 7081, "text": "Python also provides a full range of built-in functions for mathematical calculations and you can use them in the same way you have used them in C programming." }, { "code": null, "e": 7278, "s": 7241, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 7297, "s": 7278, "text": " Arnab Chakraborty" }, { "code": null, "e": 7331, "s": 7297, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 7350, "s": 7331, "text": " Arnab Chakraborty" }, { "code": null, "e": 7383, "s": 7350, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 7402, "s": 7383, "text": " Arnab Chakraborty" }, { "code": null, "e": 7437, "s": 7402, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7445, "s": 7437, "text": " Shweta" }, { "code": null, "e": 7478, "s": 7445, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7495, "s": 7478, "text": " Abhilash Nelson" }, { "code": null, "e": 7528, "s": 7495, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 7550, "s": 7528, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7557, "s": 7550, "text": " Print" }, { "code": null, "e": 7568, "s": 7557, "text": " Add Notes" } ]
Python 3 - Number max() Method
The max() method returns the largest of its arguments i.e. the value closest to positive infinity. Following is the syntax for max() method − max( x, y, z, .... ) x − This is a numeric expression. x − This is a numeric expression. y − This is also a numeric expression. y − This is also a numeric expression. z − This is also a numeric expression. z − This is also a numeric expression. This method returns the largest of its arguments. The following example shows the usage of the max() method. #!/usr/bin/python3 print ("max(80, 100, 1000) : ", max(80, 100, 1000)) print ("max(-20, 100, 400) : ", max(-20, 100, 400)) print ("max(-80, -20, -10) : ", max(-80, -20, -10)) print ("max(0, 100, -400) : ", max(0, 100, -400)) When we run the above program, it produces the following result − max(80, 100, 1000) : 1000 max(-20, 100, 400) : 400 max(-80, -20, -10) : -10 max(0, 100, -400) : 100 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": 2439, "s": 2340, "text": "The max() method returns the largest of its arguments i.e. the value closest to positive infinity." }, { "code": null, "e": 2482, "s": 2439, "text": "Following is the syntax for max() method −" }, { "code": null, "e": 2504, "s": 2482, "text": "max( x, y, z, .... )\n" }, { "code": null, "e": 2538, "s": 2504, "text": "x − This is a numeric expression." }, { "code": null, "e": 2572, "s": 2538, "text": "x − This is a numeric expression." }, { "code": null, "e": 2611, "s": 2572, "text": "y − This is also a numeric expression." }, { "code": null, "e": 2650, "s": 2611, "text": "y − This is also a numeric expression." }, { "code": null, "e": 2689, "s": 2650, "text": "z − This is also a numeric expression." }, { "code": null, "e": 2728, "s": 2689, "text": "z − This is also a numeric expression." }, { "code": null, "e": 2778, "s": 2728, "text": "This method returns the largest of its arguments." }, { "code": null, "e": 2837, "s": 2778, "text": "The following example shows the usage of the max() method." }, { "code": null, "e": 3063, "s": 2837, "text": "#!/usr/bin/python3\n\nprint (\"max(80, 100, 1000) : \", max(80, 100, 1000))\nprint (\"max(-20, 100, 400) : \", max(-20, 100, 400))\nprint (\"max(-80, -20, -10) : \", max(-80, -20, -10))\nprint (\"max(0, 100, -400) : \", max(0, 100, -400))" }, { "code": null, "e": 3129, "s": 3063, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3230, "s": 3129, "text": "max(80, 100, 1000) : 1000\nmax(-20, 100, 400) : 400\nmax(-80, -20, -10) : -10\nmax(0, 100, -400) : 100\n" }, { "code": null, "e": 3267, "s": 3230, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3283, "s": 3267, "text": " Malhar Lathkar" }, { "code": null, "e": 3316, "s": 3283, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3335, "s": 3316, "text": " Arnab Chakraborty" }, { "code": null, "e": 3370, "s": 3335, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3392, "s": 3370, "text": " In28Minutes Official" }, { "code": null, "e": 3426, "s": 3392, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3454, "s": 3426, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3489, "s": 3454, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3503, "s": 3489, "text": " Lets Kode It" }, { "code": null, "e": 3536, "s": 3503, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3553, "s": 3536, "text": " Abhilash Nelson" }, { "code": null, "e": 3560, "s": 3553, "text": " Print" }, { "code": null, "e": 3571, "s": 3560, "text": " Add Notes" } ]
How to check if a vector contains given value in R ? - GeeksforGeeks
05 Apr, 2021 We can check if a vector contains a given value using the %in% operator. For this, we have to create a vector with some values. And we have to read input from the user for what value to be checked. Or we can assign some value to a variable explicitly. Using the %in% operator with the below-given syntax we can find the element we are looking for. Syntax : value_to_be_checked %in% vector The above operation only returns a boolean value that is true or false. Steps – Create vector Set value to be searched Using the given syntax, search for the element in the vector If found print true Else false Example 1 : R vec1 = c(1,2,3,4,5) a = 1 a %in% vec1 Output : TRUE Example 2 : R vec1 = c("karthik", "nikhil", "sravan") a = "karthik" a %in% vec1 Output : TRUE Example 3 : R vec1 = c("karthik", "nikhil", "sravan") a = "krishna" a %in% vec1 Output : FALSE Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26597, "s": 26569, "text": "\n05 Apr, 2021" }, { "code": null, "e": 26945, "s": 26597, "text": "We can check if a vector contains a given value using the %in% operator. For this, we have to create a vector with some values. And we have to read input from the user for what value to be checked. Or we can assign some value to a variable explicitly. Using the %in% operator with the below-given syntax we can find the element we are looking for." }, { "code": null, "e": 26954, "s": 26945, "text": "Syntax :" }, { "code": null, "e": 26986, "s": 26954, "text": "value_to_be_checked %in% vector" }, { "code": null, "e": 27058, "s": 26986, "text": "The above operation only returns a boolean value that is true or false." }, { "code": null, "e": 27066, "s": 27058, "text": "Steps –" }, { "code": null, "e": 27080, "s": 27066, "text": "Create vector" }, { "code": null, "e": 27105, "s": 27080, "text": "Set value to be searched" }, { "code": null, "e": 27166, "s": 27105, "text": "Using the given syntax, search for the element in the vector" }, { "code": null, "e": 27186, "s": 27166, "text": "If found print true" }, { "code": null, "e": 27197, "s": 27186, "text": "Else false" }, { "code": null, "e": 27209, "s": 27197, "text": "Example 1 :" }, { "code": null, "e": 27211, "s": 27209, "text": "R" }, { "code": "vec1 = c(1,2,3,4,5) a = 1 a %in% vec1", "e": 27252, "s": 27211, "text": null }, { "code": null, "e": 27261, "s": 27252, "text": "Output :" }, { "code": null, "e": 27266, "s": 27261, "text": "TRUE" }, { "code": null, "e": 27278, "s": 27266, "text": "Example 2 :" }, { "code": null, "e": 27280, "s": 27278, "text": "R" }, { "code": "vec1 = c(\"karthik\", \"nikhil\", \"sravan\") a = \"karthik\" a %in% vec1", "e": 27350, "s": 27280, "text": null }, { "code": null, "e": 27359, "s": 27350, "text": "Output :" }, { "code": null, "e": 27364, "s": 27359, "text": "TRUE" }, { "code": null, "e": 27376, "s": 27364, "text": "Example 3 :" }, { "code": null, "e": 27378, "s": 27376, "text": "R" }, { "code": "vec1 = c(\"karthik\", \"nikhil\", \"sravan\") a = \"krishna\" a %in% vec1", "e": 27448, "s": 27378, "text": null }, { "code": null, "e": 27457, "s": 27448, "text": "Output :" }, { "code": null, "e": 27463, "s": 27457, "text": "FALSE" }, { "code": null, "e": 27470, "s": 27463, "text": "Picked" }, { "code": null, "e": 27488, "s": 27470, "text": "R Vector-Programs" }, { "code": null, "e": 27498, "s": 27488, "text": "R-Vectors" }, { "code": null, "e": 27509, "s": 27498, "text": "R Language" }, { "code": null, "e": 27520, "s": 27509, "text": "R Programs" }, { "code": null, "e": 27618, "s": 27520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27670, "s": 27618, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27705, "s": 27670, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27763, "s": 27705, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27801, "s": 27763, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27844, "s": 27801, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27902, "s": 27844, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27945, "s": 27902, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27994, "s": 27945, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28044, "s": 27994, "text": "How to filter R dataframe by multiple conditions?" } ]
JavaScript String substr() Method - GeeksforGeeks
06 Oct, 2021 Below is the example of the String substr() Method. Example: JavaScript <script>function func() { var str = 'Geeks for Geeks'; var sub_str = str.substr(6); document.write(sub_str);}func();</script> Output: for Geeks str.substr() method returns the specified number of characters from the specified index from the given string.Syntax: str.substr(start , length) start: It defines the starting index from where the substring is to be extracted from the base string. length: It defines the number of characters to be extracted starting from the start in the given string. If the second argument to the function is undefined then all the characters from the start till the end of the length are extracted. Return value: This method returns a string that is the part of the given string. If the length is 0 or negative value then it returns an empty string.Examples for the above method are provided below:Example 1: var str = 'It is a great day.' print(str.substr(5)); Output: a great day. In this example the method substr() creates a substring starting from index 5 till the end of the string.Example 2: var str = 'It is a great day.' print(str.substr(5,6)); Output: a gre In this example the method substr() extracts the substring starting at index 5 and length of string is 6.Example 3: var str = 'It is a great day.' print(str.substr(5,-7)); Output: In this example since the length of the string to be extracted is negative therefore the method returns an empty string.Codes for the above method are provided below:Program 1: JavaScript <script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5); document.write(sub_str);} func();</script> Output: a great day. Program 2: JavaScript <script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5,6); document.write(sub_str);} func();</script> Output: a gre Program 3: JavaScript <script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5,-7); document.write(sub_str);}func();</script> Output: 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. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26175, "s": 26147, "text": "\n06 Oct, 2021" }, { "code": null, "e": 26229, "s": 26175, "text": "Below is the example of the String substr() Method. " }, { "code": null, "e": 26240, "s": 26229, "text": "Example: " }, { "code": null, "e": 26251, "s": 26240, "text": "JavaScript" }, { "code": "<script>function func() { var str = 'Geeks for Geeks'; var sub_str = str.substr(6); document.write(sub_str);}func();</script>", "e": 26386, "s": 26251, "text": null }, { "code": null, "e": 26396, "s": 26386, "text": "Output: " }, { "code": null, "e": 26406, "s": 26396, "text": "for Geeks" }, { "code": null, "e": 26526, "s": 26406, "text": "str.substr() method returns the specified number of characters from the specified index from the given string.Syntax: " }, { "code": null, "e": 26553, "s": 26526, "text": "str.substr(start , length)" }, { "code": null, "e": 26658, "s": 26555, "text": "start: It defines the starting index from where the substring is to be extracted from the base string." }, { "code": null, "e": 26896, "s": 26658, "text": "length: It defines the number of characters to be extracted starting from the start in the given string. If the second argument to the function is undefined then all the characters from the start till the end of the length are extracted." }, { "code": null, "e": 27108, "s": 26896, "text": "Return value: This method returns a string that is the part of the given string. If the length is 0 or negative value then it returns an empty string.Examples for the above method are provided below:Example 1: " }, { "code": null, "e": 27161, "s": 27108, "text": "var str = 'It is a great day.'\nprint(str.substr(5));" }, { "code": null, "e": 27171, "s": 27161, "text": "Output: " }, { "code": null, "e": 27185, "s": 27171, "text": " a great day." }, { "code": null, "e": 27303, "s": 27185, "text": "In this example the method substr() creates a substring starting from index 5 till the end of the string.Example 2: " }, { "code": null, "e": 27358, "s": 27303, "text": "var str = 'It is a great day.'\nprint(str.substr(5,6));" }, { "code": null, "e": 27368, "s": 27358, "text": "Output: " }, { "code": null, "e": 27375, "s": 27368, "text": " a gre" }, { "code": null, "e": 27493, "s": 27375, "text": "In this example the method substr() extracts the substring starting at index 5 and length of string is 6.Example 3: " }, { "code": null, "e": 27549, "s": 27493, "text": "var str = 'It is a great day.'\nprint(str.substr(5,-7));" }, { "code": null, "e": 27559, "s": 27549, "text": "Output: " }, { "code": null, "e": 27739, "s": 27561, "text": "In this example since the length of the string to be extracted is negative therefore the method returns an empty string.Codes for the above method are provided below:Program 1: " }, { "code": null, "e": 27750, "s": 27739, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5); document.write(sub_str);} func();</script>", "e": 27958, "s": 27750, "text": null }, { "code": null, "e": 27968, "s": 27958, "text": "Output: " }, { "code": null, "e": 27982, "s": 27968, "text": " a great day." }, { "code": null, "e": 27994, "s": 27982, "text": "Program 2: " }, { "code": null, "e": 28005, "s": 27994, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5,6); document.write(sub_str);} func();</script>", "e": 28216, "s": 28005, "text": null }, { "code": null, "e": 28226, "s": 28216, "text": "Output: " }, { "code": null, "e": 28233, "s": 28226, "text": " a gre" }, { "code": null, "e": 28245, "s": 28233, "text": "Program 3: " }, { "code": null, "e": 28256, "s": 28245, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.'; var sub_str = str.substr(5,-7); document.write(sub_str);}func();</script>", "e": 28467, "s": 28256, "text": null }, { "code": null, "e": 28477, "s": 28467, "text": "Output: " }, { "code": null, "e": 28500, "s": 28481, "text": "Supported Browser:" }, { "code": null, "e": 28519, "s": 28500, "text": "Chrome 1 and above" }, { "code": null, "e": 28537, "s": 28519, "text": "Edge 12 and above" }, { "code": null, "e": 28557, "s": 28537, "text": "Firefox 1 and above" }, { "code": null, "e": 28587, "s": 28557, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 28605, "s": 28587, "text": "Opera 3 and above" }, { "code": null, "e": 28624, "s": 28605, "text": "Safari 1 and above" }, { "code": null, "e": 28636, "s": 28624, "text": "ysachin2314" }, { "code": null, "e": 28655, "s": 28636, "text": "JavaScript-Methods" }, { "code": null, "e": 28673, "s": 28655, "text": "javascript-string" }, { "code": null, "e": 28684, "s": 28673, "text": "JavaScript" }, { "code": null, "e": 28701, "s": 28684, "text": "Web Technologies" }, { "code": null, "e": 28799, "s": 28701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28839, "s": 28799, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28884, "s": 28839, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28945, "s": 28884, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29017, "s": 28945, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29058, "s": 29017, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29098, "s": 29058, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29131, "s": 29098, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29176, "s": 29131, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29219, "s": 29176, "text": "How to fetch data from an API in ReactJS ?" } ]
How to draw a rounded Rectangle on HTML Canvas?
To draw a rectangle in HTML, use the canvas element. With canvas, use the rect() method to draw a rectangle. But, for creating a rounded rectangle, using the rect() method won’t work. We will be using the lineTo() and quadraticCurveTo() method to create a rounded rectangle. This is how you can create a canvas in HTML5 − You can learn how to create a rounded rectangle in canvas <!DOCTYPE HTML> <html> <head> <title>HTML5 Canvas Tag</title> </head> <body> <canvas id="newCanvas" width="300" height="150"></canvas> <script> var canvas = document.getElementById('newCanvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 10); ctx.lineTo(80, 10); ctx.quadraticCurveTo(90, 10, 90, 20); ctx.lineTo(90, 80); ctx.quadraticCurveTo(90, 90, 80, 90); ctx.lineTo(20, 90); ctx.quadraticCurveTo(10, 90, 10, 80); ctx.lineTo(10, 20); ctx.quadraticCurveTo(10, 10, 20, 10); ctx.stroke(); </script> </body> </html>
[ { "code": null, "e": 1337, "s": 1062, "text": "To draw a rectangle in HTML, use the canvas element. With canvas, use the rect() method to draw a rectangle. But, for creating a rounded rectangle, using the rect() method won’t work. We will be using the lineTo() and quadraticCurveTo() method to create a rounded rectangle." }, { "code": null, "e": 1384, "s": 1337, "text": "This is how you can create a canvas in HTML5 −" }, { "code": null, "e": 1442, "s": 1384, "text": "You can learn how to create a rounded rectangle in canvas" }, { "code": null, "e": 2134, "s": 1442, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n <title>HTML5 Canvas Tag</title>\n </head>\n <body>\n <canvas id=\"newCanvas\" width=\"300\" height=\"150\"></canvas>\n <script>\n var canvas = document.getElementById('newCanvas');\n var ctx = canvas.getContext('2d');\n ctx.beginPath();\n ctx.moveTo(20, 10);\n ctx.lineTo(80, 10);\n ctx.quadraticCurveTo(90, 10, 90, 20);\n ctx.lineTo(90, 80);\n ctx.quadraticCurveTo(90, 90, 80, 90);\n ctx.lineTo(20, 90);\n ctx.quadraticCurveTo(10, 90, 10, 80);\n ctx.lineTo(10, 20);\n ctx.quadraticCurveTo(10, 10, 20, 10);\n ctx.stroke();\n </script>\n </body>\n</html>" } ]
Output of Java Programs | Set 36 (do-while loop) - GeeksforGeeks
18 Jun, 2020 Prerequisite : while loop in Java 1. What will be the output for the following program? class Test {public static void main(String[] args) { do while (true) System.out.println("HELLO"); while (false); }} Options:1. HELLO2. Compile time error3. HELLO (infinitely)4. No Output The answer is option (3) Explanation: Think the above example like this do while(true) System.out.println("HELLO"); while(false); This is the simple do-while loop. As we know that in while loop without curly braces we can take only one statement which should not be declarative. Here, HELLO is that one statement of while loop which is without curly braces. Here the inner while loop always gives true and the program output will HELLO infinitely. 2. What will be the output for the following program? class Test {public static void main(String[] args) { do System.out.println("FRIENDS"); while (true); System.out.println("ENEMY"); }} Options:1. Compile time error2. FRIENDS3. No output4. ENEMY The answer is option (1) Explanation: Here while loop always give true and it will print FRIENDS infinitely and did not give change to print ENEMY. Which gives compile time error saying prog.java:8: error: unreachable statement System.out.println("ENEMY"); 3. What will be the output for the following program? class Test {public static void main(String[] args) { int x = 1, y = 2; do System.out.println("FRIENDS"); while (x < y); System.out.println("ENEMY"); }} Options:1. FRIENDS2. ENEMY3. No Output4. FRIENDS (Infinitely) The answer is option (4) Explanation: Here at the compile time compiler thinks that x and y both are variables and its value can be changed and that will gives false to the while loop. Which gives the chance to print ENEMY that’s why compiler did not throw any compile time error. 4. What will be the output for the following program? class Test {public static void main(String[] args) { do while (true) ; System.out.println("HELLO"); }} Options:1 HELLO2 HELLO (Infinitely)3 Error: Unreachable statement4 Error: ; expected The answer is option (4) Explanation: In the above example there is a syntax error of do-while loop. As we all know that without curly braces we can take a statement which cannot be declarative but if we are not specifying any statement and not mentioning any curly braces then compiler will give an error saying Error: ; expected. 5. What will be the output for the following program? class Test {public static void main(String[] args) { do { System.out.print(1); do { System.out.print(2); } while (false); } while (false); }} Options:1. 122. 213. 14. 2 The answer is option (1) Explanation: In the above example, nesting in a do while will work under nesting process. First inner do-while loop will be executed after that the outer one. 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. Akanksha_Rai Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to copy a string in C/C++ Output of C++ programs | Set 34 (File Handling) Output of C++ programs | Set 50 Output of Java program | Set 28 Output of Python Program | Set 1 Runtime Errors Output of Java Program | Set 20 (Inheritance) Output of C Programs | Set 2 How to show full column content in a PySpark Dataframe ? C++ Programming Multiple Choice Questions
[ { "code": null, "e": 25905, "s": 25877, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25939, "s": 25905, "text": "Prerequisite : while loop in Java" }, { "code": null, "e": 25993, "s": 25939, "text": "1. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { do while (true) System.out.println(\"HELLO\"); while (false); }}", "e": 26158, "s": 25993, "text": null }, { "code": null, "e": 26229, "s": 26158, "text": "Options:1. HELLO2. Compile time error3. HELLO (infinitely)4. No Output" }, { "code": null, "e": 26254, "s": 26229, "text": "The answer is option (3)" }, { "code": null, "e": 26301, "s": 26254, "text": "Explanation: Think the above example like this" }, { "code": null, "e": 26378, "s": 26301, "text": "do \n while(true)\n System.out.println(\"HELLO\");\nwhile(false);" }, { "code": null, "e": 26696, "s": 26378, "text": "This is the simple do-while loop. As we know that in while loop without curly braces we can take only one statement which should not be declarative. Here, HELLO is that one statement of while loop which is without curly braces. Here the inner while loop always gives true and the program output will HELLO infinitely." }, { "code": null, "e": 26750, "s": 26696, "text": "2. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { do System.out.println(\"FRIENDS\"); while (true); System.out.println(\"ENEMY\"); }}", "e": 26924, "s": 26750, "text": null }, { "code": null, "e": 26984, "s": 26924, "text": "Options:1. Compile time error2. FRIENDS3. No output4. ENEMY" }, { "code": null, "e": 27009, "s": 26984, "text": "The answer is option (1)" }, { "code": null, "e": 27170, "s": 27009, "text": "Explanation: Here while loop always give true and it will print FRIENDS infinitely and did not give change to print ENEMY. Which gives compile time error saying" }, { "code": null, "e": 27249, "s": 27170, "text": "prog.java:8: error: unreachable statement\n System.out.println(\"ENEMY\");" }, { "code": null, "e": 27303, "s": 27249, "text": "3. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { int x = 1, y = 2; do System.out.println(\"FRIENDS\"); while (x < y); System.out.println(\"ENEMY\"); }}", "e": 27503, "s": 27303, "text": null }, { "code": null, "e": 27565, "s": 27503, "text": "Options:1. FRIENDS2. ENEMY3. No Output4. FRIENDS (Infinitely)" }, { "code": null, "e": 27591, "s": 27565, "text": " The answer is option (4)" }, { "code": null, "e": 27847, "s": 27591, "text": "Explanation: Here at the compile time compiler thinks that x and y both are variables and its value can be changed and that will gives false to the while loop. Which gives the chance to print ENEMY that’s why compiler did not throw any compile time error." }, { "code": null, "e": 27901, "s": 27847, "text": "4. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { do while (true) ; System.out.println(\"HELLO\"); }}", "e": 28053, "s": 27901, "text": null }, { "code": null, "e": 28138, "s": 28053, "text": "Options:1 HELLO2 HELLO (Infinitely)3 Error: Unreachable statement4 Error: ; expected" }, { "code": null, "e": 28164, "s": 28138, "text": " The answer is option (4)" }, { "code": null, "e": 28471, "s": 28164, "text": "Explanation: In the above example there is a syntax error of do-while loop. As we all know that without curly braces we can take a statement which cannot be declarative but if we are not specifying any statement and not mentioning any curly braces then compiler will give an error saying Error: ; expected." }, { "code": null, "e": 28525, "s": 28471, "text": "5. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { do { System.out.print(1); do { System.out.print(2); } while (false); } while (false); }}", "e": 28741, "s": 28525, "text": null }, { "code": null, "e": 28768, "s": 28741, "text": "Options:1. 122. 213. 14. 2" }, { "code": null, "e": 28793, "s": 28768, "text": "The answer is option (1)" }, { "code": null, "e": 28952, "s": 28793, "text": "Explanation: In the above example, nesting in a do while will work under nesting process. First inner do-while loop will be executed after that the outer one." }, { "code": null, "e": 29258, "s": 28952, "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": 29383, "s": 29258, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29396, "s": 29383, "text": "Akanksha_Rai" }, { "code": null, "e": 29408, "s": 29396, "text": "Java-Output" }, { "code": null, "e": 29423, "s": 29408, "text": "Program Output" }, { "code": null, "e": 29521, "s": 29423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29562, "s": 29521, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 29610, "s": 29562, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 29642, "s": 29610, "text": "Output of C++ programs | Set 50" }, { "code": null, "e": 29674, "s": 29642, "text": "Output of Java program | Set 28" }, { "code": null, "e": 29707, "s": 29674, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 29722, "s": 29707, "text": "Runtime Errors" }, { "code": null, "e": 29768, "s": 29722, "text": "Output of Java Program | Set 20 (Inheritance)" }, { "code": null, "e": 29797, "s": 29768, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 29854, "s": 29797, "text": "How to show full column content in a PySpark Dataframe ?" } ]
Does it make sense to use “LIMIT 1” in a query “SELECT 1 ...”?
Yes, you can use LIMIT 1 with SELECT1. Suppose, you are using SELECT 1 and your table has billions of records. In this case, it will print 1 billion times. The syntax of SELECT 1 is as follows − SELECT 1 FROM yourTableName; Suppose, you are using LIMIT 1 and your table has billions of records. This case, it will print 1 only once. The syntax of SELECT 1 with LIMIT 1 is as follows − SELECT 1 FROM yourTableName LIMIT 1; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table Select1AndLimit1Demo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> ); Query OK, 0 rows affected (1.99 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into Select1AndLimit1Demo(Name) values('John'); Query OK, 1 row affected (0.21 sec) mysql> insert into Select1AndLimit1Demo(Name) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into Select1AndLimit1Demo(Name) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into Select1AndLimit1Demo(Name) values('Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into Select1AndLimit1Demo(Name) values('David'); Query OK, 1 row affected (0.14 sec) mysql> insert into Select1AndLimit1Demo(Name) values('Mike'); Query OK, 1 row affected (0.20 sec) mysql> insert into Select1AndLimit1Demo(Name) values('Maxwell'); Query OK, 1 row affected (0.11 sec) Display all records from the table using a select statement. The query is as follows − mysql> select *from Select1AndLimit1Demo; +----+---------+ | Id | Name | +----+---------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Bob | | 5 | David | | 6 | Mike | | 7 | Maxwell | +----+---------+ 7 rows in set (0.00 sec) Here is the case of SELECT 1. The query is as follows − mysql> select 1 from Select1AndLimit1Demo; +---+ | 1 | +---+ | 1 | | 1 | | 1 | | 1 | | 1 | | 1 | | 1 | +---+ 7 rows in set (0.00 sec) Above, we have a table with 7 records. Therefore, the output is 7 times 1. Let us now see the case of SELECT 1 with LIMIT 1. The query is as follows − mysql> select 1 from Select1AndLimit1Demo limit 1; The following is the output displaying the value 1 only once − +---+ | 1 | +---+ | 1 | +---+ 1 row in set (0.00 sec) Above, our table has 7 records. We are getting 1 times 1 because we have used LIMIT 1.
[ { "code": null, "e": 1101, "s": 1062, "text": "Yes, you can use LIMIT 1 with SELECT1." }, { "code": null, "e": 1218, "s": 1101, "text": "Suppose, you are using SELECT 1 and your table has billions of records. In this case, it will print 1 billion times." }, { "code": null, "e": 1257, "s": 1218, "text": "The syntax of SELECT 1 is as follows −" }, { "code": null, "e": 1286, "s": 1257, "text": "SELECT 1 FROM yourTableName;" }, { "code": null, "e": 1395, "s": 1286, "text": "Suppose, you are using LIMIT 1 and your table has billions of records. This case, it will print 1 only once." }, { "code": null, "e": 1447, "s": 1395, "text": "The syntax of SELECT 1 with LIMIT 1 is as follows −" }, { "code": null, "e": 1484, "s": 1447, "text": "SELECT 1 FROM yourTableName LIMIT 1;" }, { "code": null, "e": 1583, "s": 1484, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1751, "s": 1583, "text": "mysql> create table Select1AndLimit1Demo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (1.99 sec)" }, { "code": null, "e": 1832, "s": 1751, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2521, "s": 1832, "text": "mysql> insert into Select1AndLimit1Demo(Name) values('John');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('Carol');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('Sam');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('Bob');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('David');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('Mike');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into Select1AndLimit1Demo(Name) values('Maxwell');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2608, "s": 2521, "text": "Display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 2650, "s": 2608, "text": "mysql> select *from Select1AndLimit1Demo;" }, { "code": null, "e": 2862, "s": 2650, "text": "+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Sam |\n| 4 | Bob |\n| 5 | David |\n| 6 | Mike |\n| 7 | Maxwell |\n+----+---------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2918, "s": 2862, "text": "Here is the case of SELECT 1. The query is as follows −" }, { "code": null, "e": 2961, "s": 2918, "text": "mysql> select 1 from Select1AndLimit1Demo;" }, { "code": null, "e": 3052, "s": 2961, "text": "+---+\n| 1 |\n+---+\n| 1 |\n| 1 |\n| 1 |\n| 1 |\n| 1 |\n| 1 |\n| 1 |\n+---+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3127, "s": 3052, "text": "Above, we have a table with 7 records. Therefore, the output is 7 times 1." }, { "code": null, "e": 3203, "s": 3127, "text": "Let us now see the case of SELECT 1 with LIMIT 1. The query is as follows −" }, { "code": null, "e": 3254, "s": 3203, "text": "mysql> select 1 from Select1AndLimit1Demo limit 1;" }, { "code": null, "e": 3317, "s": 3254, "text": "The following is the output displaying the value 1 only once −" }, { "code": null, "e": 3371, "s": 3317, "text": "+---+\n| 1 |\n+---+\n| 1 |\n+---+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3458, "s": 3371, "text": "Above, our table has 7 records. We are getting 1 times 1 because we have used LIMIT 1." } ]
Check if a linked list is Circular Linked List - GeeksforGeeks
07 Jul, 2021 Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it is not NULL-terminated and all nodes are connected in the form of a cycle. Below is an example of a circular linked list. An empty linked list is considered as circular.Note that this problem is different from cycle detection problem, here all nodes have to be part of cycle. The idea is to store head of the linked list and traverse it. If we reach NULL, linked list is not circular. If reach head again, linked list is circular. C++ Java Python3 C# Javascript // C++ program to check if linked list is circular#include<bits/stdc++.h>using namespace std; /* Link list Node */struct Node{ int data; struct Node* next;}; /* This function returns true if given linked list is circular, else false. */bool isCircular(struct Node *head){ // An empty linked list is circular if (head == NULL) return true; // Next of head struct Node *node = head->next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != NULL && node != head) node = node->next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.Node *newNode(int data){ struct Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); isCircular(head)? cout << "Yes\n" : cout << "No\n" ; // Making linked list circular head->next->next->next->next = head; isCircular(head)? cout << "Yes\n" : cout << "No\n" ; return 0;} // Java program to check if// linked list is circularimport java.util.*; class GFG{ /* Link list Node */static class Node{ int data; Node next;} /*This function returns true if given linkedlist is circular, else false. */static boolean isCircular( Node head){ // An empty linked list is circular if (head == null) return true; // Next of head Node node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} /* Driver code*/public static void main(String args[]){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); System.out.print(isCircular(head)? "Yes\n" : "No\n" ); // Making linked list circular head.next.next.next.next = head; System.out.print(isCircular(head)? "Yes\n" : "No\n" ); }} // This code contributed by Arnab Kundu # A simple Python program to check if a linked list is circular # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None def Circular(head): if head==None: return True # Next of head node = head.next i = 0 # This loop would stop in both cases (1) If # Circular (2) Not circular while((node is not None) and (node is not head)): i = i + 1 node = node.next return(node==head) # Code execution starts hereif __name__=='__main__': llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) fourth = Node(4) llist.head.next = second; second.next = third; third.next = fourth if (Circular(llist.head)): print('Yes') else: print('No') fourth.next = llist.head if (Circular(llist.head)): print('Yes') else: print('No') # This code is contributed by Sanket Badhe // C# program to check if// linked list is circularusing System;public class GFG{ /* Link list Node */public class Node{ public int data; public Node next;} /*This function returns true if given linkedlist is circular, else false. */static bool isCircular( Node head){ // An empty linked list is circular if (head == null) return true; // Next of head Node node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} /* Driver code*/public static void Main(String []args){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); Console.Write(isCircular(head)? "Yes\n" : "No\n" ); // Making linked list circular head.next.next.next.next = head; Console.Write(isCircular(head)? "Yes\n" : "No\n" ); }}// This code has been contributed by 29AjayKumar <script>// javascript program to check if// linked list is circular /* Link list Node */class Node { constructor(val) { this.data = val; this.next = null; }} /* * This function returns true if given linked list is circular, else false. */ function isCircular( head) { // An empty linked list is circular if (head == null) return true; // Next of head node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head); } // Utility function to create a new node. function newNode(data) { temp = new Node(); temp.data = data; temp.next = null; return temp; } /* Driver code */ /* Start with the empty list */ head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); document.write(isCircular(head) ? "Yes<br/>" : "No<br/>"); // Making linked list circular head.next.next.next.next = head; document.write(isCircular(head) ? "Yes<br/>" : "No<br/>"); // This code contributed by gauravrajput1</script> Output : No Yes YouTubeGeeksforGeeks507K subscribersCheck if a linked list is Circular Linked List | 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 / 5:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ce2rnhkNLzU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above andrew1234 29AjayKumar Sanket Badhe Mk raghav nidhi_biet ayushbhardwaj5588 GauravRajput1 circular linked list MAQ Software Microsoft SAP Labs Linked List Microsoft MAQ Software SAP Labs Linked List circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion) Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list Implement a stack using singly linked list Queue - Linked List Implementation Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications)
[ { "code": null, "e": 25863, "s": 25835, "text": "\n07 Jul, 2021" }, { "code": null, "e": 26097, "s": 25863, "text": "Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it is not NULL-terminated and all nodes are connected in the form of a cycle. Below is an example of a circular linked list. " }, { "code": null, "e": 26252, "s": 26097, "text": "An empty linked list is considered as circular.Note that this problem is different from cycle detection problem, here all nodes have to be part of cycle. " }, { "code": null, "e": 26409, "s": 26252, "text": "The idea is to store head of the linked list and traverse it. If we reach NULL, linked list is not circular. If reach head again, linked list is circular. " }, { "code": null, "e": 26413, "s": 26409, "text": "C++" }, { "code": null, "e": 26418, "s": 26413, "text": "Java" }, { "code": null, "e": 26426, "s": 26418, "text": "Python3" }, { "code": null, "e": 26429, "s": 26426, "text": "C#" }, { "code": null, "e": 26440, "s": 26429, "text": "Javascript" }, { "code": "// C++ program to check if linked list is circular#include<bits/stdc++.h>using namespace std; /* Link list Node */struct Node{ int data; struct Node* next;}; /* This function returns true if given linked list is circular, else false. */bool isCircular(struct Node *head){ // An empty linked list is circular if (head == NULL) return true; // Next of head struct Node *node = head->next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != NULL && node != head) node = node->next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.Node *newNode(int data){ struct Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); isCircular(head)? cout << \"Yes\\n\" : cout << \"No\\n\" ; // Making linked list circular head->next->next->next->next = head; isCircular(head)? cout << \"Yes\\n\" : cout << \"No\\n\" ; return 0;}", "e": 27718, "s": 26440, "text": null }, { "code": "// Java program to check if// linked list is circularimport java.util.*; class GFG{ /* Link list Node */static class Node{ int data; Node next;} /*This function returns true if given linkedlist is circular, else false. */static boolean isCircular( Node head){ // An empty linked list is circular if (head == null) return true; // Next of head Node node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} /* Driver code*/public static void main(String args[]){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); System.out.print(isCircular(head)? \"Yes\\n\" : \"No\\n\" ); // Making linked list circular head.next.next.next.next = head; System.out.print(isCircular(head)? \"Yes\\n\" : \"No\\n\" ); }} // This code contributed by Arnab Kundu", "e": 28980, "s": 27718, "text": null }, { "code": "# A simple Python program to check if a linked list is circular # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None def Circular(head): if head==None: return True # Next of head node = head.next i = 0 # This loop would stop in both cases (1) If # Circular (2) Not circular while((node is not None) and (node is not head)): i = i + 1 node = node.next return(node==head) # Code execution starts hereif __name__=='__main__': llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) fourth = Node(4) llist.head.next = second; second.next = third; third.next = fourth if (Circular(llist.head)): print('Yes') else: print('No') fourth.next = llist.head if (Circular(llist.head)): print('Yes') else: print('No') # This code is contributed by Sanket Badhe", "e": 30181, "s": 28980, "text": null }, { "code": "// C# program to check if// linked list is circularusing System;public class GFG{ /* Link list Node */public class Node{ public int data; public Node next;} /*This function returns true if given linkedlist is circular, else false. */static bool isCircular( Node head){ // An empty linked list is circular if (head == null) return true; // Next of head Node node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head);} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} /* Driver code*/public static void Main(String []args){ /* Start with the empty list */ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); Console.Write(isCircular(head)? \"Yes\\n\" : \"No\\n\" ); // Making linked list circular head.next.next.next.next = head; Console.Write(isCircular(head)? \"Yes\\n\" : \"No\\n\" ); }}// This code has been contributed by 29AjayKumar", "e": 31454, "s": 30181, "text": null }, { "code": "<script>// javascript program to check if// linked list is circular /* Link list Node */class Node { constructor(val) { this.data = val; this.next = null; }} /* * This function returns true if given linked list is circular, else false. */ function isCircular( head) { // An empty linked list is circular if (head == null) return true; // Next of head node = head.next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != null && node != head) node = node.next; // If loop stopped because of circular // condition return (node == head); } // Utility function to create a new node. function newNode(data) { temp = new Node(); temp.data = data; temp.next = null; return temp; } /* Driver code */ /* Start with the empty list */ head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); document.write(isCircular(head) ? \"Yes<br/>\" : \"No<br/>\"); // Making linked list circular head.next.next.next.next = head; document.write(isCircular(head) ? \"Yes<br/>\" : \"No<br/>\"); // This code contributed by gauravrajput1</script>", "e": 32809, "s": 31454, "text": null }, { "code": null, "e": 32819, "s": 32809, "text": "Output : " }, { "code": null, "e": 32826, "s": 32819, "text": "No\nYes" }, { "code": null, "e": 33671, "s": 32826, "text": "YouTubeGeeksforGeeks507K subscribersCheck if a linked list is Circular Linked List | 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 / 5:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ce2rnhkNLzU\" 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": 34102, "s": 33671, "text": "?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34115, "s": 34104, "text": "andrew1234" }, { "code": null, "e": 34127, "s": 34115, "text": "29AjayKumar" }, { "code": null, "e": 34140, "s": 34127, "text": "Sanket Badhe" }, { "code": null, "e": 34150, "s": 34140, "text": "Mk raghav" }, { "code": null, "e": 34161, "s": 34150, "text": "nidhi_biet" }, { "code": null, "e": 34179, "s": 34161, "text": "ayushbhardwaj5588" }, { "code": null, "e": 34193, "s": 34179, "text": "GauravRajput1" }, { "code": null, "e": 34214, "s": 34193, "text": "circular linked list" }, { "code": null, "e": 34227, "s": 34214, "text": "MAQ Software" }, { "code": null, "e": 34237, "s": 34227, "text": "Microsoft" }, { "code": null, "e": 34246, "s": 34237, "text": "SAP Labs" }, { "code": null, "e": 34258, "s": 34246, "text": "Linked List" }, { "code": null, "e": 34268, "s": 34258, "text": "Microsoft" }, { "code": null, "e": 34281, "s": 34268, "text": "MAQ Software" }, { "code": null, "e": 34290, "s": 34281, "text": "SAP Labs" }, { "code": null, "e": 34302, "s": 34290, "text": "Linked List" }, { "code": null, "e": 34323, "s": 34302, "text": "circular linked list" }, { "code": null, "e": 34421, "s": 34323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34440, "s": 34421, "text": "LinkedList in Java" }, { "code": null, "e": 34461, "s": 34440, "text": "Linked List vs Array" }, { "code": null, "e": 34517, "s": 34461, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 34546, "s": 34517, "text": "Detect loop in a linked list" }, { "code": null, "e": 34576, "s": 34546, "text": "Merge two sorted linked lists" }, { "code": null, "e": 34615, "s": 34576, "text": "Find the middle of a given linked list" }, { "code": null, "e": 34658, "s": 34615, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 34693, "s": 34658, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 34740, "s": 34693, "text": "Implementing a Linked List in Java using Class" } ]
Perl | Opening and Reading a File - GeeksforGeeks
26 Feb, 2019 A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Open function is used to open a new file or an existing file. Syntax: open FILEHANDLE, VAR Here FILEHANDLE is the handle returned by the open function and VAR is the expression having file name and mode of opening the file.The table given below shows the modes in which file can be opened and access to various operations. Once a FILEHANDLE is assigned a file, various operations like reading, writing and appending can be done. There are a number of different ways of reading a file. Using a File Handle Operator Using getc function Using read function The FileHandle OperatorThe main method of reading the information from an open filehandle is using the operator < >. When < > operator is used in a list context, it returns a list of lines from the specified filehandle. The example below reads one line from the file and stores it in the scalar.Let the content of file “GFG.txt” is as given below:GeeksforGeeks Hello Geek Geek a revolution Geeks are the best Example: GFG.pl# Opening the file open(fh, "GFG.txt") or die "File '$filename' can't be opened"; # Reading First line from the file$firstline = <fh>;print "$firstline\n";Output : Let the content of file “GFG.txt” is as given below: GeeksforGeeks Hello Geek Geek a revolution Geeks are the best Example: GFG.pl # Opening the file open(fh, "GFG.txt") or die "File '$filename' can't be opened"; # Reading First line from the file$firstline = <fh>;print "$firstline\n"; Output : getc FunctionThe getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specifiedSyntax: getc FILEHANDLE# Opening the file open(fh, "GFG.txt") or die "File '$filename' can't be opened"; # Reading First char from the file$firstchar = getc(fh);print "$firstchar\n";Output:If there was an error or the filehandle is at end of the file, then it returns undef. Syntax: getc FILEHANDLE # Opening the file open(fh, "GFG.txt") or die "File '$filename' can't be opened"; # Reading First char from the file$firstchar = getc(fh);print "$firstchar\n"; Output: If there was an error or the filehandle is at end of the file, then it returns undef. read FunctionThe read function is used to read binary data from a file using filehandle.Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTHHere, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error. Reading Multiple line at a time The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF).Example: File.pl# Opening the fileopen(FH, "GFG.txt")or die "Sorry!! couldn't open";print "Reading file \n"; # Reading the file till FH reaches EOFwhile(<FH>){ # Printing one line at a time print $_;}close;Output : Exception Handling in Files There are two ways in which Exception can be handledThrow an exception if file cannot be openedGive a warning if file cannot be opened and continue runningThrow an ExceptionWhen filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example :# Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die "Couldn't Open file $filename";Output:The above code prints an error if file not found and exits from the code.Give a warningWhen filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example :# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn "Couldn't Open a file $filename";}Output:My Personal Notes arrow_drop_upSave Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTH Here, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error. The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF). Example: File.pl # Opening the fileopen(FH, "GFG.txt")or die "Sorry!! couldn't open";print "Reading file \n"; # Reading the file till FH reaches EOFwhile(<FH>){ # Printing one line at a time print $_;}close; Output : There are two ways in which Exception can be handled Throw an exception if file cannot be opened Give a warning if file cannot be opened and continue running Throw an ExceptionWhen filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example :# Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die "Couldn't Open file $filename";Output:The above code prints an error if file not found and exits from the code. # Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die "Couldn't Open file $filename"; Output: The above code prints an error if file not found and exits from the code. Give a warningWhen filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example :# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn "Couldn't Open a file $filename";}Output:My Personal Notes arrow_drop_upSave # Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn "Couldn't Open a file $filename";} Output: Perl-files Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | split() Function Perl | push() Function Perl | exists() Function Perl | length() Function Perl | chomp() Function Perl | grep() Function Perl | Regex Cheat Sheet Perl | sleep() Function Perl | Removing leading and trailing white spaces (trim) Perl Tutorial - Learn Perl With Examples
[ { "code": null, "e": 25200, "s": 25172, "text": "\n26 Feb, 2019" }, { "code": null, "e": 25499, "s": 25200, "text": "A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. " }, { "code": null, "e": 25562, "s": 25499, "text": " Open function is used to open a new file or an existing file." }, { "code": null, "e": 25591, "s": 25562, "text": "Syntax: open FILEHANDLE, VAR" }, { "code": null, "e": 25823, "s": 25591, "text": "Here FILEHANDLE is the handle returned by the open function and VAR is the expression having file name and mode of opening the file.The table given below shows the modes in which file can be opened and access to various operations." }, { "code": null, "e": 25988, "s": 25825, "text": " Once a FILEHANDLE is assigned a file, various operations like reading, writing and appending can be done. There are a number of different ways of reading a file." }, { "code": null, "e": 26017, "s": 25988, "text": "Using a File Handle Operator" }, { "code": null, "e": 26037, "s": 26017, "text": "Using getc function" }, { "code": null, "e": 26057, "s": 26037, "text": "Using read function" }, { "code": null, "e": 26646, "s": 26057, "text": "The FileHandle OperatorThe main method of reading the information from an open filehandle is using the operator < >. When < > operator is used in a list context, it returns a list of lines from the specified filehandle. The example below reads one line from the file and stores it in the scalar.Let the content of file “GFG.txt” is as given below:GeeksforGeeks\nHello Geek\nGeek a revolution\nGeeks are the best\nExample: GFG.pl# Opening the file open(fh, \"GFG.txt\") or die \"File '$filename' can't be opened\"; # Reading First line from the file$firstline = <fh>;print \"$firstline\\n\";Output :" }, { "code": null, "e": 26699, "s": 26646, "text": "Let the content of file “GFG.txt” is as given below:" }, { "code": null, "e": 26762, "s": 26699, "text": "GeeksforGeeks\nHello Geek\nGeek a revolution\nGeeks are the best\n" }, { "code": null, "e": 26778, "s": 26762, "text": "Example: GFG.pl" }, { "code": "# Opening the file open(fh, \"GFG.txt\") or die \"File '$filename' can't be opened\"; # Reading First line from the file$firstline = <fh>;print \"$firstline\\n\";", "e": 26935, "s": 26778, "text": null }, { "code": null, "e": 26944, "s": 26935, "text": "Output :" }, { "code": null, "e": 27339, "s": 26944, "text": "getc FunctionThe getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specifiedSyntax: getc FILEHANDLE# Opening the file open(fh, \"GFG.txt\") or die \"File '$filename' can't be opened\"; # Reading First char from the file$firstchar = getc(fh);print \"$firstchar\\n\";Output:If there was an error or the filehandle is at end of the file, then it returns undef." }, { "code": null, "e": 27363, "s": 27339, "text": "Syntax: getc FILEHANDLE" }, { "code": "# Opening the file open(fh, \"GFG.txt\") or die \"File '$filename' can't be opened\"; # Reading First char from the file$firstchar = getc(fh);print \"$firstchar\\n\";", "e": 27525, "s": 27363, "text": null }, { "code": null, "e": 27533, "s": 27525, "text": "Output:" }, { "code": null, "e": 27619, "s": 27533, "text": "If there was an error or the filehandle is at end of the file, then it returns undef." }, { "code": null, "e": 29473, "s": 27619, "text": "read FunctionThe read function is used to read binary data from a file using filehandle.Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTHHere, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error. Reading Multiple line at a time The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF).Example: File.pl# Opening the fileopen(FH, \"GFG.txt\")or die \"Sorry!! couldn't open\";print \"Reading file \\n\"; # Reading the file till FH reaches EOFwhile(<FH>){ # Printing one line at a time print $_;}close;Output : Exception Handling in Files There are two ways in which Exception can be handledThrow an exception if file cannot be openedGive a warning if file cannot be opened and continue runningThrow an ExceptionWhen filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example :# Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die \"Couldn't Open file $filename\";Output:The above code prints an error if file not found and exits from the code.Give a warningWhen filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example :# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn \"Couldn't Open a file $filename\";}Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29550, "s": 29473, "text": "Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTH" }, { "code": null, "e": 29868, "s": 29550, "text": "Here, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error." }, { "code": null, "e": 29979, "s": 29870, "text": " The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF)." }, { "code": null, "e": 29996, "s": 29979, "text": "Example: File.pl" }, { "code": "# Opening the fileopen(FH, \"GFG.txt\")or die \"Sorry!! couldn't open\";print \"Reading file \\n\"; # Reading the file till FH reaches EOFwhile(<FH>){ # Printing one line at a time print $_;}close;", "e": 30194, "s": 29996, "text": null }, { "code": null, "e": 30204, "s": 30194, "text": "Output : " }, { "code": null, "e": 30258, "s": 30204, "text": " There are two ways in which Exception can be handled" }, { "code": null, "e": 30302, "s": 30258, "text": "Throw an exception if file cannot be opened" }, { "code": null, "e": 30363, "s": 30302, "text": "Give a warning if file cannot be opened and continue running" }, { "code": null, "e": 30769, "s": 30363, "text": "Throw an ExceptionWhen filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example :# Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die \"Couldn't Open file $filename\";Output:The above code prints an error if file not found and exits from the code." }, { "code": "# Initializing filename $filename = 'GFG1.txt'; # Prints an error and exits if file not foundopen(fh, '<', $filename) or die \"Couldn't Open file $filename\";", "e": 30927, "s": 30769, "text": null }, { "code": null, "e": 30935, "s": 30927, "text": "Output:" }, { "code": null, "e": 31009, "s": 30935, "text": "The above code prints an error if file not found and exits from the code." }, { "code": null, "e": 31432, "s": 31009, "text": "Give a warningWhen filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example :# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn \"Couldn't Open a file $filename\";}Output:My Personal Notes\narrow_drop_upSave" }, { "code": "# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){ while(<fh>) { print $_; }} # Executes if file not foundelse{ warn \"Couldn't Open a file $filename\";}", "e": 31662, "s": 31432, "text": null }, { "code": null, "e": 31670, "s": 31662, "text": "Output:" }, { "code": null, "e": 31681, "s": 31670, "text": "Perl-files" }, { "code": null, "e": 31688, "s": 31681, "text": "Picked" }, { "code": null, "e": 31693, "s": 31688, "text": "Perl" }, { "code": null, "e": 31698, "s": 31693, "text": "Perl" }, { "code": null, "e": 31796, "s": 31698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31805, "s": 31796, "text": "Comments" }, { "code": null, "e": 31818, "s": 31805, "text": "Old Comments" }, { "code": null, "e": 31842, "s": 31818, "text": "Perl | split() Function" }, { "code": null, "e": 31865, "s": 31842, "text": "Perl | push() Function" }, { "code": null, "e": 31890, "s": 31865, "text": "Perl | exists() Function" }, { "code": null, "e": 31915, "s": 31890, "text": "Perl | length() Function" }, { "code": null, "e": 31939, "s": 31915, "text": "Perl | chomp() Function" }, { "code": null, "e": 31962, "s": 31939, "text": "Perl | grep() Function" }, { "code": null, "e": 31987, "s": 31962, "text": "Perl | Regex Cheat Sheet" }, { "code": null, "e": 32011, "s": 31987, "text": "Perl | sleep() Function" }, { "code": null, "e": 32068, "s": 32011, "text": "Perl | Removing leading and trailing white spaces (trim)" } ]
How to convert Dictionary to Hashtable in PowerShell?
Like any other data type conversion in PowerShell, we can convert Dictionary to hashtable in a similar way. We have a below Dictionary for the example called $CityData. Key Value --- ----- India 91 Austria 43 Its datatype is Dictionary, PS C:\> $citydata.GetType() | ft -AutoSize IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Dictionary`2 System.Object To convert it to the hashtable, $hash = [Hashtable]$citydata Or $hash = [System.Collections.Hashtable]$CityData Datatype: PS C:\> $hash | ft -AutoSize Name Value ---- ----- Austria 43 India 91
[ { "code": null, "e": 1232, "s": 1062, "text": "Like any other data type conversion in PowerShell, we can convert Dictionary to hashtable in a similar way. We have a below Dictionary for the example called $CityData." }, { "code": null, "e": 1288, "s": 1232, "text": "Key Value\n--- -----\nIndia 91\nAustria 43" }, { "code": null, "e": 1316, "s": 1288, "text": "Its datatype is Dictionary," }, { "code": null, "e": 1359, "s": 1316, "text": "PS C:\\> $citydata.GetType() | ft -AutoSize" }, { "code": null, "e": 1484, "s": 1359, "text": "IsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True Dictionary`2 System.Object" }, { "code": null, "e": 1516, "s": 1484, "text": "To convert it to the hashtable," }, { "code": null, "e": 1545, "s": 1516, "text": "$hash = [Hashtable]$citydata" }, { "code": null, "e": 1548, "s": 1545, "text": "Or" }, { "code": null, "e": 1596, "s": 1548, "text": "$hash = [System.Collections.Hashtable]$CityData" }, { "code": null, "e": 1606, "s": 1596, "text": "Datatype:" }, { "code": null, "e": 1635, "s": 1606, "text": "PS C:\\> $hash | ft -AutoSize" }, { "code": null, "e": 1685, "s": 1635, "text": "Name Value\n---- -----\nAustria 43\nIndia 91" } ]
How to create and populate two-dimension Java array?
A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns − Live Demo public class Creating2DArray { public static void main(String args[]) { int[][] myArray = new int[3][3]; myArray[0][0] = 21; myArray[0][1] = 22; myArray[0][2] = 23; myArray[1][0] = 24; myArray[1][1] = 25; myArray[1][2] = 26; myArray[2][0] = 27; myArray[2][1] = 28; myArray[2][2] = 29; for(int i=0; i<myArray.length; i++ ) { for(int j=0;j<myArray.length; j++) { System.out.println(myArray[i][j]); } } } } 21 22 23 24 25 26 27 28 29
[ { "code": null, "e": 1239, "s": 1062, "text": "A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns −" }, { "code": null, "e": 1250, "s": 1239, "text": " Live Demo" }, { "code": null, "e": 1656, "s": 1250, "text": "public class Creating2DArray {\n\npublic static void main(String args[]) {\nint[][] myArray = new int[3][3];\nmyArray[0][0] = 21;\nmyArray[0][1] = 22;\nmyArray[0][2] = 23;\nmyArray[1][0] = 24;\nmyArray[1][1] = 25;\nmyArray[1][2] = 26;\nmyArray[2][0] = 27;\nmyArray[2][1] = 28;\nmyArray[2][2] = 29;\n\nfor(int i=0; i<myArray.length; i++ ) {\nfor(int j=0;j<myArray.length; j++) {\nSystem.out.println(myArray[i][j]);\n}\n}\n}\n}" }, { "code": null, "e": 1683, "s": 1656, "text": "21\n22\n23\n24\n25\n26\n27\n28\n29" } ]
ML - Support Vector Machine(SVM)
Support vector machines (SVMs) are powerful yet flexible supervised machine learning algorithms which are used both for classification and regression. But generally, they are used in classification problems. In 1960s, SVMs were first introduced but later they got refined in 1990. SVMs have their unique way of implementation as compared to other machine learning algorithms. Lately, they are extremely popular because of their ability to handle multiple continuous and categorical variables. An SVM model is basically a representation of different classes in a hyperplane in multidimensional space. The hyperplane will be generated in an iterative manner by SVM so that the error can be minimized. The goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH). The followings are important concepts in SVM − Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points. Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points. Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes. Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes. Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin. Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin. The main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) and it can be done in the following two steps − First, SVM will generate hyperplanes iteratively that segregates the classes in best way. First, SVM will generate hyperplanes iteratively that segregates the classes in best way. Then, it will choose the hyperplane that separates the classes correctly. Then, it will choose the hyperplane that separates the classes correctly. For implementing SVM in Python − We will start with the standard libraries import as follows − For implementing SVM in Python − We will start with the standard libraries import as follows − In practice, SVM algorithm is implemented with kernel that transforms an input data space into the required form. SVM uses a technique called the kernel trick in which kernel takes a low dimensional input space and transforms it into a higher dimensional space. In simple words, kernel converts non-separable problems into separable problems by adding more dimensions to it. It makes SVM more powerful, flexible and accurate. The following are some of the types of kernels used by SVM. It can be used as a dot product between any two observations. The formula of linear kernel is as below − K(x,xi)=sum(x∗xi) From the above formula, we can see that the product between two vectors say x & xi is the sum of the multiplication of each pair of input values. It is more generalized form of linear kernel and distinguish curved or nonlinear input space. Following is the formula for polynomial kernel − k(X,Xi)=1+sum(X∗Xi)^d Here d is the degree of polynomial, which we need to specify manually in the learning algorithm. RBF kernel, mostly used in SVM classification, maps input space in indefinite dimensional space. Following formula explains it mathematically − K(x,xi)=exp(−gamma∗sum(x−xi^2)) Here, gamma ranges from 0 to 1. We need to manually specify it in the learning algorithm. A good default value of gamma is 0.1. As we implemented SVM for linearly separable data, we can implement it in Python for the data that is not linearly separable. It can be done by using kernels. The following is an example for creating an SVM classifier by using kernels. We will be using iris dataset from scikit-learn − We will start by importing following packages − import pandas as pd import numpy as np from sklearn import svm, datasets import matplotlib.pyplot as plt Now, we need to load the input data − iris = datasets.load_iris() From this dataset, we are taking first two features as follows − X = iris.data[:, :2] y = iris.target Next, we will plot the SVM boundaries with original data as follows − x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 h = (x_max / x_min)/100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) X_plot = np.c_[xx.ravel(), yy.ravel()] Now, we need to provide the value of regularization parameter as follows − C = 1.0 Next, SVM classifier object can be created as follows − Svc_classifier = svm.SVC(kernel='linear', C=C).fit(X, y) Z = svc_classifier.predict(X_plot) Z = Z.reshape(xx.shape) plt.figure(figsize=(15, 5)) plt.subplot(121) plt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.title('Support Vector Classifier with linear kernel') Output Text(0.5, 1.0, 'Support Vector Classifier with linear kernel') For creating SVM classifier with rbf kernel, we can change the kernel to rbf as follows − Svc_classifier = svm.SVC(kernel = 'rbf', gamma =‘auto’,C = C).fit(X, y) Z = svc_classifier.predict(X_plot) Z = Z.reshape(xx.shape) plt.figure(figsize=(15, 5)) plt.subplot(121) plt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3) plt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.title('Support Vector Classifier with rbf kernel') Output Text(0.5, 1.0, 'Support Vector Classifier with rbf kernel') We put the value of gamma to ‘auto’ but you can provide its value between 0 to 1 also. Pros of SVM classifiers SVM classifiers offers great accuracy and work well with high dimensional space. SVM classifiers basically use a subset of training points hence in result uses very less memory. Cons of SVM classifiers They have high training time hence in practice not suitable for large datasets. Another disadvantage is that SVM classifiers do not work well with overlapping classes. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2797, "s": 2304, "text": "Support vector machines (SVMs) are powerful yet flexible supervised machine learning algorithms which are used both for classification and regression. But generally, they are used in classification problems. In 1960s, SVMs were first introduced but later they got refined in 1990. SVMs have their unique way of implementation as compared to other machine learning algorithms. Lately, they are extremely popular because of their ability to handle multiple continuous and categorical variables." }, { "code": null, "e": 3103, "s": 2797, "text": "An SVM model is basically a representation of different classes in a hyperplane in multidimensional space. The hyperplane will be generated in an iterative manner by SVM so that the error can be minimized. The goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH)." }, { "code": null, "e": 3150, "s": 3103, "text": "The followings are important concepts in SVM −" }, { "code": null, "e": 3309, "s": 3150, "text": "Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points." }, { "code": null, "e": 3468, "s": 3309, "text": "Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points." }, { "code": null, "e": 3617, "s": 3468, "text": "Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes." }, { "code": null, "e": 3766, "s": 3617, "text": "Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes." }, { "code": null, "e": 4051, "s": 3766, "text": "Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin." }, { "code": null, "e": 4336, "s": 4051, "text": "Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin." }, { "code": null, "e": 4488, "s": 4336, "text": "The main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) and it can be done in the following two steps −" }, { "code": null, "e": 4578, "s": 4488, "text": "First, SVM will generate hyperplanes iteratively that segregates the classes in best way." }, { "code": null, "e": 4668, "s": 4578, "text": "First, SVM will generate hyperplanes iteratively that segregates the classes in best way." }, { "code": null, "e": 4742, "s": 4668, "text": "Then, it will choose the hyperplane that separates the classes correctly." }, { "code": null, "e": 4816, "s": 4742, "text": "Then, it will choose the hyperplane that separates the classes correctly." }, { "code": null, "e": 4911, "s": 4816, "text": "For implementing SVM in Python − We will start with the standard libraries import as follows −" }, { "code": null, "e": 5006, "s": 4911, "text": "For implementing SVM in Python − We will start with the standard libraries import as follows −" }, { "code": null, "e": 5492, "s": 5006, "text": "In practice, SVM algorithm is implemented with kernel that transforms an input data space into the required form. SVM uses a technique called the kernel trick in which kernel takes a low dimensional input space and transforms it into a higher dimensional space. In simple words, kernel converts non-separable problems into separable problems by adding more dimensions to it. It makes SVM more powerful, flexible and accurate. The following are some of the types of kernels used by SVM." }, { "code": null, "e": 5597, "s": 5492, "text": "It can be used as a dot product between any two observations. The formula of linear kernel is as below −" }, { "code": null, "e": 5615, "s": 5597, "text": "K(x,xi)=sum(x∗xi)" }, { "code": null, "e": 5761, "s": 5615, "text": "From the above formula, we can see that the product between two vectors say x & xi is the sum of the multiplication of each pair of input values." }, { "code": null, "e": 5904, "s": 5761, "text": "It is more generalized form of linear kernel and distinguish curved or nonlinear input space. Following is the formula for polynomial kernel −" }, { "code": null, "e": 5926, "s": 5904, "text": "k(X,Xi)=1+sum(X∗Xi)^d" }, { "code": null, "e": 6023, "s": 5926, "text": "Here d is the degree of polynomial, which we need to specify manually in the learning algorithm." }, { "code": null, "e": 6167, "s": 6023, "text": "RBF kernel, mostly used in SVM classification, maps input space in indefinite dimensional space. Following formula explains it mathematically −" }, { "code": null, "e": 6199, "s": 6167, "text": "K(x,xi)=exp(−gamma∗sum(x−xi^2))" }, { "code": null, "e": 6327, "s": 6199, "text": "Here, gamma ranges from 0 to 1. We need to manually specify it in the learning algorithm. A good default value of gamma is 0.1." }, { "code": null, "e": 6486, "s": 6327, "text": "As we implemented SVM for linearly separable data, we can implement it in Python for the data that is not linearly separable. It can be done by using kernels." }, { "code": null, "e": 6613, "s": 6486, "text": "The following is an example for creating an SVM classifier by using kernels. We will be using iris dataset from scikit-learn −" }, { "code": null, "e": 6661, "s": 6613, "text": "We will start by importing following packages −" }, { "code": null, "e": 6766, "s": 6661, "text": "import pandas as pd\nimport numpy as np\nfrom sklearn import svm, datasets\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 6804, "s": 6766, "text": "Now, we need to load the input data −" }, { "code": null, "e": 6833, "s": 6804, "text": "iris = datasets.load_iris()\n" }, { "code": null, "e": 6898, "s": 6833, "text": "From this dataset, we are taking first two features as follows −" }, { "code": null, "e": 6936, "s": 6898, "text": "X = iris.data[:, :2]\ny = iris.target\n" }, { "code": null, "e": 7006, "s": 6936, "text": "Next, we will plot the SVM boundaries with original data as follows −" }, { "code": null, "e": 7250, "s": 7006, "text": "x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nh = (x_max / x_min)/100\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\nX_plot = np.c_[xx.ravel(), yy.ravel()]" }, { "code": null, "e": 7325, "s": 7250, "text": "Now, we need to provide the value of regularization parameter as follows −" }, { "code": null, "e": 7334, "s": 7325, "text": "C = 1.0\n" }, { "code": null, "e": 7390, "s": 7334, "text": "Next, SVM classifier object can be created as follows −" }, { "code": null, "e": 7447, "s": 7390, "text": "Svc_classifier = svm.SVC(kernel='linear', C=C).fit(X, y)" }, { "code": null, "e": 7798, "s": 7447, "text": "Z = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize=(15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('Support Vector Classifier with linear kernel')" }, { "code": null, "e": 7805, "s": 7798, "text": "Output" }, { "code": null, "e": 7869, "s": 7805, "text": "Text(0.5, 1.0, 'Support Vector Classifier with linear kernel')\n" }, { "code": null, "e": 7959, "s": 7869, "text": "For creating SVM classifier with rbf kernel, we can change the kernel to rbf as follows −" }, { "code": null, "e": 8387, "s": 7959, "text": "Svc_classifier = svm.SVC(kernel = 'rbf', gamma =‘auto’,C = C).fit(X, y)\nZ = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize=(15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3)\nplt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('Support Vector Classifier with rbf kernel')" }, { "code": null, "e": 8394, "s": 8387, "text": "Output" }, { "code": null, "e": 8455, "s": 8394, "text": "Text(0.5, 1.0, 'Support Vector Classifier with rbf kernel')\n" }, { "code": null, "e": 8542, "s": 8455, "text": "We put the value of gamma to ‘auto’ but you can provide its value between 0 to 1 also." }, { "code": null, "e": 8566, "s": 8542, "text": "Pros of SVM classifiers" }, { "code": null, "e": 8744, "s": 8566, "text": "SVM classifiers offers great accuracy and work well with high dimensional space. SVM classifiers basically use a subset of training points hence in result uses very less memory." }, { "code": null, "e": 8768, "s": 8744, "text": "Cons of SVM classifiers" }, { "code": null, "e": 8936, "s": 8768, "text": "They have high training time hence in practice not suitable for large datasets. Another disadvantage is that SVM classifiers do not work well with overlapping classes." }, { "code": null, "e": 8973, "s": 8936, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 8996, "s": 8973, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 9032, "s": 8996, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 9060, "s": 9032, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9094, "s": 9060, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 9111, "s": 9094, "text": " Abhilash Nelson" }, { "code": null, "e": 9144, "s": 9111, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9166, "s": 9144, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9199, "s": 9166, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 9221, "s": 9199, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9254, "s": 9221, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 9276, "s": 9254, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9283, "s": 9276, "text": " Print" }, { "code": null, "e": 9294, "s": 9283, "text": " Add Notes" } ]
Addressing Modes - GeeksforGeeks
04 Sep, 2019 Addressing Modes– The term addressing modes refers to the way in which the operand of an instruction is specified. The addressing mode specifies a rule for interpreting or modifying the address field of the instruction before the operand is actually executed. Addressing modes for 8086 instructions are divided into two categories: 1) Addressing modes for data 2) Addressing modes for branch The 8086 memory addressing modes provide flexible access to memory, allowing you to easily access variables, arrays, records, pointers, and other complex data types. The key to good assembly language programming is the proper use of memory addressing modes. An assembly language program instruction consists of two parts The memory address of an operand consists of two components: IMPORTANT TERMS Starting address of memory segment. Effective address or Offset: An offset is determined by adding any combination of three address elements: displacement, base and index.Displacement: It is an 8 bit or 16 bit immediate value given in the instruction.Base: Contents of base register, BX or BP.Index: Content of index register SI or DI. Displacement: It is an 8 bit or 16 bit immediate value given in the instruction. Base: Contents of base register, BX or BP. Index: Content of index register SI or DI. According to different ways of specifying an operand by 8086 microprocessor, different addressing modes are used by 8086. Addressing modes used by 8086 microprocessor are discussed below: Implied mode:: In implied addressing the operand is specified in the instruction itself. In this mode the data is 8 bits or 16 bits long and data is the part of instruction.Zero address instruction are designed with implied addressing mode.Example: CLC (used to reset Carry flag to 0) Example: CLC (used to reset Carry flag to 0) Immediate addressing mode (symbol #):In this mode data is present in address field of instruction .Designed like one address instruction format.Note:Limitation in the immediate mode is that the range of constants are restricted by size of address field.Example: MOV AL, 35H (move the data 35H into AL register) Example: MOV AL, 35H (move the data 35H into AL register) Register mode: In register addressing the operand is placed in one of 8 bit or 16 bit general purpose registers. The data is in the register that is specified by the instruction.Here one register reference is required to access the data.Example: MOV AX,CX (move the contents of CX register to AX register) Example: MOV AX,CX (move the contents of CX register to AX register) Register Indirect mode: In this addressing the operand’s offset is placed in any one of the registers BX,BP,SI,DI as specified in the instruction. The effective address of the data is in the base register or an index register that is specified by the instruction.Here two register reference is required to access the data.The 8086 CPUs let you access memory indirectly through a register using the register indirect addressing modes.MOV AX, [BX](move the contents of memory location s addressed by the register BX to the register AX) MOV AX, [BX](move the contents of memory location s addressed by the register BX to the register AX) Auto Indexed (increment mode): Effective address of the operand is the contents of a register specified in the instruction. After accessing the operand, the contents of this register are automatically incremented to point to the next consecutive memory location.(R1)+.Here one register reference,one memory reference and one ALU operation is required to access the data.Example:Add R1, (R2)+ // OR R1 = R1 +M[R2] R2 = R2 + d Useful for stepping through arrays in a loop. R2 – start of array d – size of an element Add R1, (R2)+ // OR R1 = R1 +M[R2] R2 = R2 + d Useful for stepping through arrays in a loop. R2 – start of array d – size of an element Auto indexed ( decrement mode): Effective address of the operand is the contents of a register specified in the instruction. Before accessing the operand, the contents of this register are automatically decremented to point to the previous consecutive memory location. –(R1)Here one register reference,one memory reference and one ALU operation is required to access the data.Example:Add R1,-(R2) //OR R2 = R2-d R1 = R1 + M[R2] Auto decrement mode is same as auto increment mode. Both can also be used to implement a stack as push and pop . Auto increment and Auto decrement modes are useful for implementing “Last-In-First-Out” data structures. Example: Add R1,-(R2) //OR R2 = R2-d R1 = R1 + M[R2] Auto decrement mode is same as auto increment mode. Both can also be used to implement a stack as push and pop . Auto increment and Auto decrement modes are useful for implementing “Last-In-First-Out” data structures. Direct addressing/ Absolute addressing Mode (symbol [ ]): The operand’s offset is given in the instruction as an 8 bit or 16 bit displacement element. In this addressing mode the 16 bit effective address of the data is the part of the instruction.Here only one memory reference operation is required to access the data.Example:ADD AL,[0301] //add the contents of offset address 0301 to AL Example:ADD AL,[0301] //add the contents of offset address 0301 to AL Indirect addressing Mode (symbol @ or () ):In this mode address field of instruction contains the address of effective address.Here two references are required.1st reference to get effective address.2nd reference to access the data.Based on the availability of Effective address, Indirect mode is of two kind:Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data.Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data. Based on the availability of Effective address, Indirect mode is of two kind: Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data.Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data. Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data. Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data. Indexed addressing mode: The operand’s offset is the sum of the content of an index register SI or DI and an 8 bit or 16 bit displacement.Example:MOV AX, [SI +05] Example:MOV AX, [SI +05] Based Indexed Addressing: The operand’s offset is sum of the content of a base register BX or BP and an index register SI or DI.Example: ADD AX, [BX+SI] Based on Transfer of control, addressing modes are:PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value PC= PC + Relative value.Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value. PC= Base register + Relative value. Note:PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes.Advantages of Addressing ModesTo give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation.To reduce the number bits in the addressing field of the Instruction.Sample GATE QuestionMatch each of the high level language statements given on the left hand side with the most natural addressing mode from those listed on the right hand side.1. A[1] = B[J]; a. Indirect addressing 2. while [*A++]; b. Indexed addressing 3. int temp = *x; c. Autoincrement(A) (1, c), (2, b), (3, a)(B) (1, a), (2, c), (3, b)(C) (1, b), (2, c), (3, a)(D) (1, a), (2, b), (3, c)Answer: (C)Explanation:List 1 List 2 1) A[1] = B[J]; b) Index addressing Here indexing is used 2) while [*A++]; c) auto increment The memory locations are automatically incremented 3) int temp = *x; a) Indirect addressing Here temp is assigned the value of int type stored at the address contained in XHence (C) is correct solution.This article is contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Example: ADD AX, [BX+SI] Based on Transfer of control, addressing modes are: PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value PC= PC + Relative value. EA= PC + Address field value PC= PC + Relative value. Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value. PC= Base register + Relative value. Note:PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes. EA= Base register + Address field value. PC= Base register + Relative value. Note: PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes. PC relative nad based register both addressing modes are suitable for program relocation at runtime. Based register addressing mode is best suitable to write position independent codes. Advantages of Addressing Modes To give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation.To reduce the number bits in the addressing field of the Instruction. To give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation. To reduce the number bits in the addressing field of the Instruction. Sample GATE Question Match each of the high level language statements given on the left hand side with the most natural addressing mode from those listed on the right hand side. 1. A[1] = B[J]; a. Indirect addressing 2. while [*A++]; b. Indexed addressing 3. int temp = *x; c. Autoincrement (A) (1, c), (2, b), (3, a)(B) (1, a), (2, c), (3, b)(C) (1, b), (2, c), (3, a)(D) (1, a), (2, b), (3, c) Answer: (C) Explanation: List 1 List 2 1) A[1] = B[J]; b) Index addressing Here indexing is used 2) while [*A++]; c) auto increment The memory locations are automatically incremented 3) int temp = *x; a) Indirect addressing Here temp is assigned the value of int type stored at the address contained in X Hence (C) is correct solution. This article is contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. VaibhavRai3 dt_kanha hiteshjangidit19 Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Decimal to Binary Conversion Logical and Physical Address in Operating System Addressing modes in 8085 microprocessor Architecture of 8085 microprocessor Difference between Von Neumann and Harvard Architecture Interrupts Computer Organization | Booth's Algorithm 8085 program to add two 8 bit numbers Program for Binary To Decimal Conversion IEEE Standard 754 Floating Point Numbers
[ { "code": null, "e": 27462, "s": 27434, "text": "\n04 Sep, 2019" }, { "code": null, "e": 27722, "s": 27462, "text": "Addressing Modes– The term addressing modes refers to the way in which the operand of an instruction is specified. The addressing mode specifies a rule for interpreting or modifying the address field of the instruction before the operand is actually executed." }, { "code": null, "e": 27794, "s": 27722, "text": "Addressing modes for 8086 instructions are divided into two categories:" }, { "code": null, "e": 27823, "s": 27794, "text": "1) Addressing modes for data" }, { "code": null, "e": 27854, "s": 27823, "text": "2) Addressing modes for branch" }, { "code": null, "e": 28113, "s": 27854, "text": "The 8086 memory addressing modes provide flexible access to memory, allowing you to easily access variables, arrays, records, pointers, and other complex data types. The key to good assembly language programming is the proper use of memory addressing modes." }, { "code": null, "e": 28176, "s": 28113, "text": "An assembly language program instruction consists of two parts" }, { "code": null, "e": 28238, "s": 28176, "text": "The memory address of an operand consists of two components: " }, { "code": null, "e": 28254, "s": 28238, "text": "IMPORTANT TERMS" }, { "code": null, "e": 28290, "s": 28254, "text": "Starting address of memory segment." }, { "code": null, "e": 28590, "s": 28290, "text": "Effective address or Offset: An offset is determined by adding any combination of three address elements: displacement, base and index.Displacement: It is an 8 bit or 16 bit immediate value given in the instruction.Base: Contents of base register, BX or BP.Index: Content of index register SI or DI." }, { "code": null, "e": 28671, "s": 28590, "text": "Displacement: It is an 8 bit or 16 bit immediate value given in the instruction." }, { "code": null, "e": 28714, "s": 28671, "text": "Base: Contents of base register, BX or BP." }, { "code": null, "e": 28757, "s": 28714, "text": "Index: Content of index register SI or DI." }, { "code": null, "e": 28879, "s": 28757, "text": "According to different ways of specifying an operand by 8086 microprocessor, different addressing modes are used by 8086." }, { "code": null, "e": 28945, "s": 28879, "text": "Addressing modes used by 8086 microprocessor are discussed below:" }, { "code": null, "e": 29231, "s": 28945, "text": "Implied mode:: In implied addressing the operand is specified in the instruction itself. In this mode the data is 8 bits or 16 bits long and data is the part of instruction.Zero address instruction are designed with implied addressing mode.Example: CLC (used to reset Carry flag to 0)" }, { "code": null, "e": 29277, "s": 29231, "text": "Example: CLC (used to reset Carry flag to 0)" }, { "code": null, "e": 29589, "s": 29277, "text": "Immediate addressing mode (symbol #):In this mode data is present in address field of instruction .Designed like one address instruction format.Note:Limitation in the immediate mode is that the range of constants are restricted by size of address field.Example: MOV AL, 35H (move the data 35H into AL register)" }, { "code": null, "e": 29648, "s": 29589, "text": "Example: MOV AL, 35H (move the data 35H into AL register)" }, { "code": null, "e": 29954, "s": 29648, "text": "Register mode: In register addressing the operand is placed in one of 8 bit or 16 bit general purpose registers. The data is in the register that is specified by the instruction.Here one register reference is required to access the data.Example: MOV AX,CX (move the contents of CX register to AX register)" }, { "code": null, "e": 30023, "s": 29954, "text": "Example: MOV AX,CX (move the contents of CX register to AX register)" }, { "code": null, "e": 30558, "s": 30023, "text": "Register Indirect mode: In this addressing the operand’s offset is placed in any one of the registers BX,BP,SI,DI as specified in the instruction. The effective address of the data is in the base register or an index register that is specified by the instruction.Here two register reference is required to access the data.The 8086 CPUs let you access memory indirectly through a register using the register indirect addressing modes.MOV AX, [BX](move the contents of memory location s \naddressed by the register BX to the register AX)" }, { "code": null, "e": 30660, "s": 30558, "text": "MOV AX, [BX](move the contents of memory location s \naddressed by the register BX to the register AX)" }, { "code": null, "e": 31175, "s": 30660, "text": "Auto Indexed (increment mode): Effective address of the operand is the contents of a register specified in the instruction. After accessing the operand, the contents of this register are automatically incremented to point to the next consecutive memory location.(R1)+.Here one register reference,one memory reference and one ALU operation is required to access the data.Example:Add R1, (R2)+ // OR\nR1 = R1 +M[R2]\nR2 = R2 + d Useful for stepping through arrays in a loop. R2 – start of array d – size of an element" }, { "code": null, "e": 31224, "s": 31175, "text": "Add R1, (R2)+ // OR\nR1 = R1 +M[R2]\nR2 = R2 + d " }, { "code": null, "e": 31313, "s": 31224, "text": "Useful for stepping through arrays in a loop. R2 – start of array d – size of an element" }, { "code": null, "e": 31962, "s": 31313, "text": "Auto indexed ( decrement mode): Effective address of the operand is the contents of a register specified in the instruction. Before accessing the operand, the contents of this register are automatically decremented to point to the previous consecutive memory location. –(R1)Here one register reference,one memory reference and one ALU operation is required to access the data.Example:Add R1,-(R2) //OR\nR2 = R2-d\nR1 = R1 + M[R2] Auto decrement mode is same as auto increment mode. Both can also be used to implement a stack as push and pop . Auto increment and Auto decrement modes are useful for implementing “Last-In-First-Out” data structures." }, { "code": null, "e": 31971, "s": 31962, "text": "Example:" }, { "code": null, "e": 32018, "s": 31971, "text": "Add R1,-(R2) //OR\nR2 = R2-d\nR1 = R1 + M[R2] " }, { "code": null, "e": 32237, "s": 32018, "text": "Auto decrement mode is same as auto increment mode. Both can also be used to implement a stack as push and pop . Auto increment and Auto decrement modes are useful for implementing “Last-In-First-Out” data structures." }, { "code": null, "e": 32628, "s": 32237, "text": "Direct addressing/ Absolute addressing Mode (symbol [ ]): The operand’s offset is given in the instruction as an 8 bit or 16 bit displacement element. In this addressing mode the 16 bit effective address of the data is the part of the instruction.Here only one memory reference operation is required to access the data.Example:ADD AL,[0301] //add the contents of offset address 0301 to AL" }, { "code": null, "e": 32700, "s": 32628, "text": "Example:ADD AL,[0301] //add the contents of offset address 0301 to AL" }, { "code": null, "e": 33462, "s": 32700, "text": "Indirect addressing Mode (symbol @ or () ):In this mode address field of instruction contains the address of effective address.Here two references are required.1st reference to get effective address.2nd reference to access the data.Based on the availability of Effective address, Indirect mode is of two kind:Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data.Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data." }, { "code": null, "e": 33540, "s": 33462, "text": "Based on the availability of Effective address, Indirect mode is of two kind:" }, { "code": null, "e": 33993, "s": 33540, "text": "Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data.Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data." }, { "code": null, "e": 34233, "s": 33993, "text": "Register Indirect:In this mode effective address is in the register, and corresponding register name will be maintained in the address field of an instruction.Here one register reference,one memory reference is required to access the data." }, { "code": null, "e": 34447, "s": 34233, "text": "Memory Indirect:In this mode effective address is in the memory, and corresponding memory address will be maintained in the address field of an instruction.Here two memory reference is required to access the data." }, { "code": null, "e": 34611, "s": 34447, "text": "Indexed addressing mode: The operand’s offset is the sum of the content of an index register SI or DI and an 8 bit or 16 bit displacement.Example:MOV AX, [SI +05] " }, { "code": null, "e": 34637, "s": 34611, "text": "Example:MOV AX, [SI +05] " }, { "code": null, "e": 36733, "s": 34637, "text": " Based Indexed Addressing: The operand’s offset is sum of the content of a base register BX or BP and an index register SI or DI.Example: ADD AX, [BX+SI] Based on Transfer of control, addressing modes are:PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value\nPC= PC + Relative value.Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value.\nPC= Base register + Relative value.\nNote:PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes.Advantages of Addressing ModesTo give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation.To reduce the number bits in the addressing field of the Instruction.Sample GATE QuestionMatch each of the high level language statements given on the left hand side with the most natural addressing mode from those listed on the right hand side.1. A[1] = B[J]; a. Indirect addressing\n2. while [*A++]; b. Indexed addressing\n3. int temp = *x; c. Autoincrement(A) (1, c), (2, b), (3, a)(B) (1, a), (2, c), (3, b)(C) (1, b), (2, c), (3, a)(D) (1, a), (2, b), (3, c)Answer: (C)Explanation:List 1 List 2\n1) A[1] = B[J]; b) Index addressing \nHere indexing is used\n\n2) while [*A++]; c) auto increment\nThe memory locations are automatically incremented\n\n3) int temp = *x; a) Indirect addressing\nHere temp is assigned the value of int type stored\nat the address contained in XHence (C) is correct solution.This article is contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36759, "s": 36733, "text": "Example: ADD AX, [BX+SI] " }, { "code": null, "e": 36811, "s": 36759, "text": "Based on Transfer of control, addressing modes are:" }, { "code": null, "e": 37050, "s": 36811, "text": "PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value\nPC= PC + Relative value." }, { "code": null, "e": 37104, "s": 37050, "text": "EA= PC + Address field value\nPC= PC + Relative value." }, { "code": null, "e": 37582, "s": 37104, "text": "Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value.\nPC= Base register + Relative value.\nNote:PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes." }, { "code": null, "e": 37660, "s": 37582, "text": "EA= Base register + Address field value.\nPC= Base register + Relative value.\n" }, { "code": null, "e": 37666, "s": 37660, "text": "Note:" }, { "code": null, "e": 37851, "s": 37666, "text": "PC relative nad based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes." }, { "code": null, "e": 37952, "s": 37851, "text": "PC relative nad based register both addressing modes are suitable for program relocation at runtime." }, { "code": null, "e": 38037, "s": 37952, "text": "Based register addressing mode is best suitable to write position independent codes." }, { "code": null, "e": 38068, "s": 38037, "text": "Advantages of Addressing Modes" }, { "code": null, "e": 38258, "s": 38068, "text": "To give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation.To reduce the number bits in the addressing field of the Instruction." }, { "code": null, "e": 38379, "s": 38258, "text": "To give programmers to facilities such as Pointers, counters for loop controls, indexing of data and program relocation." }, { "code": null, "e": 38449, "s": 38379, "text": "To reduce the number bits in the addressing field of the Instruction." }, { "code": null, "e": 38470, "s": 38449, "text": "Sample GATE Question" }, { "code": null, "e": 38627, "s": 38470, "text": "Match each of the high level language statements given on the left hand side with the most natural addressing mode from those listed on the right hand side." }, { "code": null, "e": 38762, "s": 38627, "text": "1. A[1] = B[J]; a. Indirect addressing\n2. while [*A++]; b. Indexed addressing\n3. int temp = *x; c. Autoincrement" }, { "code": null, "e": 38867, "s": 38762, "text": "(A) (1, c), (2, b), (3, a)(B) (1, a), (2, c), (3, b)(C) (1, b), (2, c), (3, a)(D) (1, a), (2, b), (3, c)" }, { "code": null, "e": 38879, "s": 38867, "text": "Answer: (C)" }, { "code": null, "e": 38892, "s": 38879, "text": "Explanation:" }, { "code": null, "e": 39213, "s": 38892, "text": "List 1 List 2\n1) A[1] = B[J]; b) Index addressing \nHere indexing is used\n\n2) while [*A++]; c) auto increment\nThe memory locations are automatically incremented\n\n3) int temp = *x; a) Indirect addressing\nHere temp is assigned the value of int type stored\nat the address contained in X" }, { "code": null, "e": 39244, "s": 39213, "text": "Hence (C) is correct solution." }, { "code": null, "e": 39414, "s": 39244, "text": "This article is contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 39426, "s": 39414, "text": "VaibhavRai3" }, { "code": null, "e": 39435, "s": 39426, "text": "dt_kanha" }, { "code": null, "e": 39452, "s": 39435, "text": "hiteshjangidit19" }, { "code": null, "e": 39489, "s": 39452, "text": "Computer Organization & Architecture" }, { "code": null, "e": 39587, "s": 39489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39628, "s": 39587, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 39677, "s": 39628, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 39717, "s": 39677, "text": "Addressing modes in 8085 microprocessor" }, { "code": null, "e": 39753, "s": 39717, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 39809, "s": 39753, "text": "Difference between Von Neumann and Harvard Architecture" }, { "code": null, "e": 39820, "s": 39809, "text": "Interrupts" }, { "code": null, "e": 39862, "s": 39820, "text": "Computer Organization | Booth's Algorithm" }, { "code": null, "e": 39900, "s": 39862, "text": "8085 program to add two 8 bit numbers" }, { "code": null, "e": 39941, "s": 39900, "text": "Program for Binary To Decimal Conversion" } ]
How to Get Started With Facebook’s Detectron2 | by Rob | Towards Data Science
Among many different techniques for object detection, Facebook came up with its model: Detectron2. This model, similarly to Yolo models, is able to draw bounding boxes around objects and inference with a panoptic segmentation model, in other words, instead of drawing a box around an object it “wraps” the object bounding its real borders (Think of it as the smart snipping tool from photoshop.) The purpose of this guide is to show how to easily implement a pretrained Detectron2 model, able to recognize objects represented by the classes from the COCO (Common Object in COntext) dataset. This guide is meant to provide a starting point for a beginner in computer vision, it aims at explaining what are the first steps to implement a pre-trained model, and its final goal is to spike your interest into learning more, and arranging your thoughts in this overwhelming field. I provide a Google Colab Notebook that you can clone and use as you wish or you can follow up and code along! To get started its core dependencies must be installed: PyTorch Cython Detectron2 OpenCV Those tasks can take several minutes, and since you need a GPU to run this notebook, I advise you to clone my Colab notebook and write everything from Google Colab, this will also help you become more confident with command line snippets and file management in the cloud! !pip install -U torch==1.4+cu100 torchvision==0.5+cu100 -f https://download.pytorch.org/whl/torch_stable.html!pip install cython pyyaml==5.1!pip install -U ‘git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'!git clone https://github.com/facebookresearch/detectron2 detectron2_repo!pip install -e detectron2_repo#!pip install opencv-python Google Colab already comes with OpenCV Once those dependencies are installed you will most probably need to restart your runtime/kernel. Now we need to import some libraries we will need to import, process and infers predictions, among those libraries we have ...... Since I am using Google Colab, the function cv2.imshow() is not available, and I need to use a "patched" version of it if you are running this notebook on your local machine to get rid of it. # import some common librariesimport numpy as npimport cv2import randomfrom google.colab.patches import cv2_imshow # On your local machine you don’t need it.# import some common detectron2 utilitiesfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalog In this guide I am using an image from my google drive, you can mount your Google Drive and use an image of your choice: from google.colab import drivedrive.mount(‘/content/drive’) Let’s now get a picture for which we want to run our model: im = cv2.imread(“./drive/My Drive/turin.png”)cv2_imshow(im) Once our image is loaded, we need to load our model and a little bit of configuration. First, we load the configurations from Detectron, and then we apply to it a custom configuration coming from COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml. Then the threshold is set, hence the sensitivity of the model while detecting objects (play with these parameters!). The next step consists of loading the checkpoints relative to this model, in other words, the model itself in .pklformat. The next step consists in instantiating the model itself, think like the same you do in scikit-learn when for example you want to make a regression: reg = LinearRegression() reg.fit(X, y) reg.predict(X_test) However, instead of passing to our predictor an array X_train we pass our image, which corresponds as well in an array (a 3D array to be precise: one axis for the width, another for the height and the last one representing the colors of the image). The reason we are using a pre-trained model, instead of training our model can be explained by the first two lines from the description file detectron2/MODEL_ZOO: “This file documents a large collection of baselines trained with detectron2 in Sep-Oct, 2019. All numbers were obtained on Big Basin servers with 8 NVIDIA V100 GPUs & NVLink. The software in use was PyTorch 1.3, CUDA 9.2, cuDNN 7.4.2 or 7.6.3.”. However, of course, you can use a baseline model to further train it to recognize a specific object, this process is known as Transfer Learning. cfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file(“COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml”))cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this modelcfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(“COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml”)predictor = DefaultPredictor(cfg)outputs = predictor(im) If we inspect the outputs generated by the model we are presented with a massive dictionary (please, refer to the Colab Notebook), this dictionary contains, the number of objects detected (num_instances), info about the image and the coordinates of the image where the box should be drawn, together with the labels (pred_classes) for each box (instance). Let's take a look at the first box: [1314.3333, 485.8268, 1345.7896, 539.3832] There are 4 values, each of them representing respectively x, y and width, and height of the rectangle. (Sometimes, in OpenCV, when iterating over things such as detected object you do a loop like: for x, y, w, h in ...) Now we can visualize the image along with the boxes showing predicted objects in the image, to achieve this we must use a specific object that let us merge the predictions with the original image, this object is called Visualizer, once instantiated the Visualizer with our image and the metadata, we can call the draw_instance_predictions method with the outputs as argument: v = Visualizer(im, MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.5) # Scaling the image 1.5 times, for big images consider a value below 0v = v.draw_instance_predictions(outputs[“instances”].to(“cpu”))cv2_imshow(v.get_image()) Computer vision is a field which behind the obstacles one can have at learning it, also has some entry barriers: often it is difficult to have access to specific hardware, a model can take hours to train, and our small laptops can often freeze, hence it is hard to follow the “classical” trial and error learning path that maybe we followed while experimenting with some machine learning algorithms while cracking scikit-learn! Since (hopefully) you have now a basic idea of the workflow, from how to import an image to how to display it, as long as how to load a model from detectron2 library, the next step could be trying to retrain it, using (I suggest) some cloud providers, it can be Google Colab, Paperspace Gradient, Azure Notebooks or anything else. Another good forward step could be to try implementing the Detectron2 “rival” Yolo, and maybe implement it in an iOS app using CoreMLtools.
[ { "code": null, "e": 567, "s": 171, "text": "Among many different techniques for object detection, Facebook came up with its model: Detectron2. This model, similarly to Yolo models, is able to draw bounding boxes around objects and inference with a panoptic segmentation model, in other words, instead of drawing a box around an object it “wraps” the object bounding its real borders (Think of it as the smart snipping tool from photoshop.)" }, { "code": null, "e": 1157, "s": 567, "text": "The purpose of this guide is to show how to easily implement a pretrained Detectron2 model, able to recognize objects represented by the classes from the COCO (Common Object in COntext) dataset. This guide is meant to provide a starting point for a beginner in computer vision, it aims at explaining what are the first steps to implement a pre-trained model, and its final goal is to spike your interest into learning more, and arranging your thoughts in this overwhelming field. I provide a Google Colab Notebook that you can clone and use as you wish or you can follow up and code along!" }, { "code": null, "e": 1213, "s": 1157, "text": "To get started its core dependencies must be installed:" }, { "code": null, "e": 1221, "s": 1213, "text": "PyTorch" }, { "code": null, "e": 1228, "s": 1221, "text": "Cython" }, { "code": null, "e": 1239, "s": 1228, "text": "Detectron2" }, { "code": null, "e": 1246, "s": 1239, "text": "OpenCV" }, { "code": null, "e": 1518, "s": 1246, "text": "Those tasks can take several minutes, and since you need a GPU to run this notebook, I advise you to clone my Colab notebook and write everything from Google Colab, this will also help you become more confident with command line snippets and file management in the cloud!" }, { "code": null, "e": 1916, "s": 1518, "text": "!pip install -U torch==1.4+cu100 torchvision==0.5+cu100 -f https://download.pytorch.org/whl/torch_stable.html!pip install cython pyyaml==5.1!pip install -U ‘git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'!git clone https://github.com/facebookresearch/detectron2 detectron2_repo!pip install -e detectron2_repo#!pip install opencv-python Google Colab already comes with OpenCV" }, { "code": null, "e": 2144, "s": 1916, "text": "Once those dependencies are installed you will most probably need to restart your runtime/kernel. Now we need to import some libraries we will need to import, process and infers predictions, among those libraries we have ......" }, { "code": null, "e": 2336, "s": 2144, "text": "Since I am using Google Colab, the function cv2.imshow() is not available, and I need to use a \"patched\" version of it if you are running this notebook on your local machine to get rid of it." }, { "code": null, "e": 2743, "s": 2336, "text": "# import some common librariesimport numpy as npimport cv2import randomfrom google.colab.patches import cv2_imshow # On your local machine you don’t need it.# import some common detectron2 utilitiesfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalog" }, { "code": null, "e": 2864, "s": 2743, "text": "In this guide I am using an image from my google drive, you can mount your Google Drive and use an image of your choice:" }, { "code": null, "e": 2924, "s": 2864, "text": "from google.colab import drivedrive.mount(‘/content/drive’)" }, { "code": null, "e": 2984, "s": 2924, "text": "Let’s now get a picture for which we want to run our model:" }, { "code": null, "e": 3044, "s": 2984, "text": "im = cv2.imread(“./drive/My Drive/turin.png”)cv2_imshow(im)" }, { "code": null, "e": 3682, "s": 3044, "text": "Once our image is loaded, we need to load our model and a little bit of configuration. First, we load the configurations from Detectron, and then we apply to it a custom configuration coming from COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml. Then the threshold is set, hence the sensitivity of the model while detecting objects (play with these parameters!). The next step consists of loading the checkpoints relative to this model, in other words, the model itself in .pklformat. The next step consists in instantiating the model itself, think like the same you do in scikit-learn when for example you want to make a regression:" }, { "code": null, "e": 3990, "s": 3682, "text": "reg = LinearRegression() reg.fit(X, y) reg.predict(X_test) However, instead of passing to our predictor an array X_train we pass our image, which corresponds as well in an array (a 3D array to be precise: one axis for the width, another for the height and the last one representing the colors of the image)." }, { "code": null, "e": 4153, "s": 3990, "text": "The reason we are using a pre-trained model, instead of training our model can be explained by the first two lines from the description file detectron2/MODEL_ZOO:" }, { "code": null, "e": 4400, "s": 4153, "text": "“This file documents a large collection of baselines trained with detectron2 in Sep-Oct, 2019. All numbers were obtained on Big Basin servers with 8 NVIDIA V100 GPUs & NVLink. The software in use was PyTorch 1.3, CUDA 9.2, cuDNN 7.4.2 or 7.6.3.”." }, { "code": null, "e": 4545, "s": 4400, "text": "However, of course, you can use a baseline model to further train it to recognize a specific object, this process is known as Transfer Learning." }, { "code": null, "e": 4897, "s": 4545, "text": "cfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file(“COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml”))cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this modelcfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(“COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml”)predictor = DefaultPredictor(cfg)outputs = predictor(im)" }, { "code": null, "e": 5288, "s": 4897, "text": "If we inspect the outputs generated by the model we are presented with a massive dictionary (please, refer to the Colab Notebook), this dictionary contains, the number of objects detected (num_instances), info about the image and the coordinates of the image where the box should be drawn, together with the labels (pred_classes) for each box (instance). Let's take a look at the first box:" }, { "code": null, "e": 5331, "s": 5288, "text": "[1314.3333, 485.8268, 1345.7896, 539.3832]" }, { "code": null, "e": 5552, "s": 5331, "text": "There are 4 values, each of them representing respectively x, y and width, and height of the rectangle. (Sometimes, in OpenCV, when iterating over things such as detected object you do a loop like: for x, y, w, h in ...)" }, { "code": null, "e": 5928, "s": 5552, "text": "Now we can visualize the image along with the boxes showing predicted objects in the image, to achieve this we must use a specific object that let us merge the predictions with the original image, this object is called Visualizer, once instantiated the Visualizer with our image and the metadata, we can call the draw_instance_predictions method with the outputs as argument:" }, { "code": null, "e": 6161, "s": 5928, "text": "v = Visualizer(im, MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.5) # Scaling the image 1.5 times, for big images consider a value below 0v = v.draw_instance_predictions(outputs[“instances”].to(“cpu”))cv2_imshow(v.get_image())" }, { "code": null, "e": 6589, "s": 6161, "text": "Computer vision is a field which behind the obstacles one can have at learning it, also has some entry barriers: often it is difficult to have access to specific hardware, a model can take hours to train, and our small laptops can often freeze, hence it is hard to follow the “classical” trial and error learning path that maybe we followed while experimenting with some machine learning algorithms while cracking scikit-learn!" } ]
How to do Logistic Regression in R | by Michaelino Mervisiano | Towards Data Science
Introduction Logistic regression is one of the most popular forms of the generalized linear model. It comes in handy if you want to predict a binary outcome from a set of continuous and/or categorical predictor variables. In this article, I will discuss an overview on how to use Logistic Regression in R with an example dataset. We will use infidelity data as our example dataset, known as Fair’s Affairs, which is based on a cross-sectional survey conducted by Psychology Today in 1969 and is described in Greene (2003) and Fair (1978). This data contains 9 variables collected on 601 respondents which hold information such as how often they have affairs during the past years, as well as their age, gender, education, years married, have children (yes/no), how religious they are (on a 5-point scale from 1=anti to 5=very), occupation (7-point classification), and a self-rating on happiness toward their marriage (from 1=very unhappy to 5=very happy). The figure below shows a few observations to give you an overview of the data. Applying Logistic Regression, we can find which factors contributed the most to infidelity. Then, you can use the model to check which one between you and your partner that more likely to have an affair or not 😜 But, before that, we will run through some descriptive statistics with the code below to get a better understanding of our data. # How to do Logistic Regression in R# Created by Michaelino Mervisiano> install.packages("AER")> library("AER")> data(Affairs, package="AER")> View(Affairs)> summary(Affairs) affairs gender age yearsmarried children Min. : 0.0 female:315 Min. :17.50 Min. : 0.125 no :171 1st Qu: 0.0 male :286 1st Qu:27.00 1st Qu: 4.000 yes:430 Median : 0.0 Median :32.00 Median : 7.000 Mean : 1.456 Mean :32.49 Mean : 8.178 3rd Qu.: 0.0 3rd Qu.:37.00 3rd Qu.:15.000 Max. :12.0 Max. :57.00 Max. :15.000 religiousness education occupation rating Min. :1 Min. : 9.0 Min. :1.0 Min. :1.000 1st Qu:2 1st Qu:14.0 1st Qu:3.0 1st Qu:3.000 Median :3 Median :16.0 Median :5.0 Median :4.000 Mean :3.116 Mean :16.17 Mean :4.195 Mean :3.932 3rd Qu.:4 3rd Qu.:18.0 3rd Qu.:6.0 3rd Qu.:5.000 Max. :5 Max. :20.0 Max. :7.0 Max. :5.000>table(Affairs$affairs) 0 1 2 3 7 12 451 34 17 19 42 38 From the summary above, we can see that there are 286 male respondents (representing 48% of the overall respondents), 430 respondents had children (representing 72% of the overall respondents), and average age for our respondents was 32.5 years old. In addition, we find that 451 respondents claimed not engaging in an affair in the past year. It means 25% of our respondents has an affair with the largest number reported was 12. In conclusion, we can say that 6% of respondents has 1 affair per month 😏. As we are interested in the binary outcome for our response variable (had an affair/didn’t have an affair). We can transform affairs into abinary variable called ynaffair with the following code. > Affairs$ynaffair[Affairs$affairs > 0] <- 1> Affairs$ynaffair[Affairs$affairs == 0] <- 0> Affairs$ynaffair <- factor(Affairs$ynaffair,levels=c(0,1), labels=c("No","Yes"))> table(Affairs$ynaffair)No Yes451 150 Fit the model with Logistic Regression Now, we can execute the logistic regression to measure the relationship between response variable (affair) and explanatory variables (age, gender, education, occupation, children, self-rating, etc) in R. > fit.full <- glm(ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation +rating, data=Affairs, family=binomial())> summary(fit.full)Deviance Residuals: Min 1Q Median 3Q Max-1.571 -0.750 -0.569 -0.254 2.519Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) 1.3773 0.8878 1.55 0.12081gendermale 0.2803 0.2391 1.17 0.24108age -0.0443 0.0182 -2.43 0.01530 *yearsmarried 0.0948 0.0322 2.94 0.00326 **childrenyes 0.3977 0.2915 1.36 0.17251religiousness -0.3247 0.0898 -3.62 0.00030 ***education 0.0211 0.0505 0.42 0.67685occupation 0.0309 0.0718 0.43 0.66663rating -0.4685 0.0909 -5.15 2.6e-07 ***---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1(Dispersion parameter for binomial family taken to be 1) Null deviance: 675.38 on 600 degrees of freedomResidual deviance: 609.51 on 592 degrees of freedomAIC: 627.5Number of Fisher Scoring iterations: 4 If we observe the Pr(>|z|) or p-values for the regression coefficients, then we find that gender, presence of children, education, and occupation do not have a significant contribution to our response variable. Therefore, we can try to fit a second model by including only significant variables such as age, years married, religiousness, and rating to fit the data instead. > fit.reduced <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, data=Affairs, family=binomial())> summary(fit.reduced)Deviance Residuals: Min 1Q Median 3Q Max-1.628 -0.755 -0.570 -0.262 2.400Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) 1.9308 0.6103 3.16 0.00156 **age -0.0353 0.0174 -2.03 0.04213 *yearsmarried 0.1006 0.0292 3.44 0.00057 ***religiousness -0.3290 0.0895 -3.68 0.00023 ***rating -0.4614 0.0888 -5.19 2.1e-07 ***---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1(Dispersion parameter for binomial family taken to be 1) Null deviance: 675.38 on 600 degrees of freedomResidual deviance: 615.36 on 596 degrees of freedomAIC: 625.4Number of Fisher Scoring iterations: 4 For the second model, we can see that p-values for each regression coefficient is statistically significant. Then, we may run chi-square test with anova function in R to compared between first and second model. We will see which model that explain our response variable better. > anova(fit.reduced, fit.full, test="Chisq") Analysis of Deviance Table Model 1: ynaffair ~ age + yearsmarried + religiousness + rating Model 2: ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation + rating Resid.Df Resid.Dev Df Deviance P(>|Chi|) 1 596 615 2 592 610 4 5.85 0.21 The output above displays nonsignificant chi-square value with p-values= 0.21. It means that the second model with only four predictors fits as well as the full model with nine predictors. It supports our initial belief that gender, children, education, and occupation don’t add any contribution to predict infidelity (our response variable). Thus, we will continue the analysis with the second model as it is easier to do our interpretations on the simpler model. Interpret the model parameters Based on the regression coefficients from the second model, we are seeing that the odds of having affairs increase with years married and decrease with age, religiousness, and happiness self-rating. We can observe it based on the positive or negative sign from each regression coefficient. In conclusion, we might say the longer you are married, then the more likely you will have an affair. On the other hand, the happier you are in the marriage, then the less likely you will have an affair. > coef(fit.reduced) (Intercept) age yearsmarried religiousness rating 1.931 -0.035 0.101 -0.329 -0.461 Next, we want to know the impact value of each of these variables towards affair. First, we need to remember that logistic regression modeled the response variable to log(odds) that Y = 1. It implies the regression coefficients allow the change in log(odds) in the return for a unit change in the predictor variable, holding all other predictor variables constant. Since log(odds) are hard to interpret, we will transform it by exponentiating the outcome as follow > exp(coef(fit.reduced)) (Intercept) age yearsmarried religiousness rating 6.895 0.965 1.106 0.720 0.630 We observe that the odds of having affair are increased by a factor of 1.106 for a one-year increase in years married (holding age, religiousness, and happiness rating constant). On the contrary, the odds of having affair are multiplied by a factor of 0.965 for every year increase in age. It means the chance of having an affair drop by -3.5% every time someone gets older. Furthermore, the change in the odds of the higher value on the response variable for an n unit change in a predictor variable is exp(βj)^n. Then, a 15-year increase would increase the odds by a factor of 1.10615≈4.5, holding the other predictor variables constant. Predict the outcome using new data In this section, we are using the model that we built to predict the outcome for the new data. The first step, we will make a new data containing the values of predictor variables we’re interested in. The second step, we will apply the predict() function in R to estimate the probabilities of the outcome event following the values from the new data. Consider new data below where we have 5 new respondents with different self-rating, holding other variables set to the average of overall data. Then, we apply the prediction function to get the probabilities of having affair for these new respondents. > newdata1 <- data.frame(rating=c(1,2,3,4,5),age=mean(Affairs$age), yearsmarried=mean(Affairs$yearsmarried), religiousness=mean(Affairs$religiousness))> newdata1 rating age yearsmarried religiousness1 1 32.5 8.18 3.122 2 32.5 8.18 3.123 3 32.5 8.18 3.124 4 32.5 8.18 3.125 5 32.5 8.18 3.12> newdata1$prob <- predict(fit.reduced, newdata=newdata1, type="response")> newdata1 rating age yearsmarried religiousness prob1 1 32.5 8.18 3.12 0.5302 2 32.5 8.18 3.12 0.4163 3 32.5 8.18 3.12 0.3104 4 32.5 8.18 3.12 0.2205 5 32.5 8.18 3.12 0.151 Clearly, we notice that chance of having affair declining from 0.53 when marriage is rated 1=”very unhappy” to 0.15 when the marriage is rated 5=”very happy” (holding other predictor variables constant). It indicates the unhappy couple are three times more likely to have an affair compared to the happy one. Let’s create another new data to observe the impact of age toward infidelity > newdata2 <- data.frame(rating=mean(Affairs$rating), age=(17,27,37,47, 57), yearsmarried=mean(Affairs$yearsmarried), religiousness=mean(Affairs$religiousness))> newdata2 rating age yearsmarried religiousness1 3.93 17 8.18 3.122 3.93 27 8.18 3.123 3.93 37 8.18 3.124 3.93 47 8.18 3.125 3.93 57 8.18 3.12> newdata2$prob <- predict(fit.reduced, newdata=newdata2, type="response")> newdata2 rating age yearsmarried religiousness prob1 3.93 17 8.18 3.12 0.3352 3.93 27 8.18 3.12 0.2623 3.93 37 8.18 3.12 0.1994 3.93 47 8.18 3.12 0.1495 3.93 57 8.18 3.12 0.109 Here, we see that as age increases from 17 to 57, the probability of having affair declining from 0.34 to 0.11, holding the other variables constant. If you are interested to explore the impact of other predictor variables or to predict other new data, then you can use this approach to analyze it further. Evaluate overdispersion In logistic regression, we need to check the expected variance for data drawn from a binomial distribution σ2 = nπ(1 − π), where n is the number of observations and π is the probability of belonging to the Y = 1 group. Overdispersion occurs when data admit more variability than expected under the assumed distribution. If overdispersion is present in a dataset, the estimated standard errors and test statistics the overall goodness-of-fit will be distorted and adjustments must be made. One of the solutions, we need to use the quasibinomial distribution rather than the binomial distribution for glm() function in R. There are two ways to verify if we have an overdispersion issue or not: The first method, we can check overdispersion by dividing the residual deviance with the residual degrees of freedom of our binomial model. If the ratio considerably larger than 1, then it indicates that we have an overdispersion issue. Calculating this ratio using our data example, we find that the ratio is close to 1. It means no overdispersion problem on our model. > deviance(fit.reduced)/df.residual(fit.reduced) [1] 1.032 The second method, we are using two models fit to check overdispersion. Basically, we will fit the logistic regression using two different models using different distributions. Then, we check if there’s a statistical evidence that the expected variance of the two models is significantly different. > fit <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, family = binomial(), data = Affairs)> fit.od <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, family = quasibinomial(), data = Affairs)> pchisq(summary(fit.od)$dispersion * fit$df.residual, fit$df.residual, lower = F)[1] 0.34 We find that p-value =0.34 is clearly not significant (p > 0.05), strengthening our belief that overdispersion isn’t a problem on our model I hope you find this article is useful and kindly share it with others
[ { "code": null, "e": 184, "s": 171, "text": "Introduction" }, { "code": null, "e": 501, "s": 184, "text": "Logistic regression is one of the most popular forms of the generalized linear model. It comes in handy if you want to predict a binary outcome from a set of continuous and/or categorical predictor variables. In this article, I will discuss an overview on how to use Logistic Regression in R with an example dataset." }, { "code": null, "e": 1207, "s": 501, "text": "We will use infidelity data as our example dataset, known as Fair’s Affairs, which is based on a cross-sectional survey conducted by Psychology Today in 1969 and is described in Greene (2003) and Fair (1978). This data contains 9 variables collected on 601 respondents which hold information such as how often they have affairs during the past years, as well as their age, gender, education, years married, have children (yes/no), how religious they are (on a 5-point scale from 1=anti to 5=very), occupation (7-point classification), and a self-rating on happiness toward their marriage (from 1=very unhappy to 5=very happy). The figure below shows a few observations to give you an overview of the data." }, { "code": null, "e": 1419, "s": 1207, "text": "Applying Logistic Regression, we can find which factors contributed the most to infidelity. Then, you can use the model to check which one between you and your partner that more likely to have an affair or not 😜" }, { "code": null, "e": 1548, "s": 1419, "text": "But, before that, we will run through some descriptive statistics with the code below to get a better understanding of our data." }, { "code": null, "e": 2591, "s": 1548, "text": "# How to do Logistic Regression in R# Created by Michaelino Mervisiano> install.packages(\"AER\")> library(\"AER\")> data(Affairs, package=\"AER\")> View(Affairs)> summary(Affairs) affairs gender age yearsmarried children Min. : 0.0 female:315 Min. :17.50 Min. : 0.125 no :171 1st Qu: 0.0 male :286 1st Qu:27.00 1st Qu: 4.000 yes:430 Median : 0.0 Median :32.00 Median : 7.000 Mean : 1.456 Mean :32.49 Mean : 8.178 3rd Qu.: 0.0 3rd Qu.:37.00 3rd Qu.:15.000 Max. :12.0 Max. :57.00 Max. :15.000 religiousness education occupation rating Min. :1 Min. : 9.0 Min. :1.0 Min. :1.000 1st Qu:2 1st Qu:14.0 1st Qu:3.0 1st Qu:3.000 Median :3 Median :16.0 Median :5.0 Median :4.000 Mean :3.116 Mean :16.17 Mean :4.195 Mean :3.932 3rd Qu.:4 3rd Qu.:18.0 3rd Qu.:6.0 3rd Qu.:5.000 Max. :5 Max. :20.0 Max. :7.0 Max. :5.000>table(Affairs$affairs) 0 1 2 3 7 12 451 34 17 19 42 38" }, { "code": null, "e": 3097, "s": 2591, "text": "From the summary above, we can see that there are 286 male respondents (representing 48% of the overall respondents), 430 respondents had children (representing 72% of the overall respondents), and average age for our respondents was 32.5 years old. In addition, we find that 451 respondents claimed not engaging in an affair in the past year. It means 25% of our respondents has an affair with the largest number reported was 12. In conclusion, we can say that 6% of respondents has 1 affair per month 😏." }, { "code": null, "e": 3293, "s": 3097, "text": "As we are interested in the binary outcome for our response variable (had an affair/didn’t have an affair). We can transform affairs into abinary variable called ynaffair with the following code." }, { "code": null, "e": 3507, "s": 3293, "text": "> Affairs$ynaffair[Affairs$affairs > 0] <- 1> Affairs$ynaffair[Affairs$affairs == 0] <- 0> Affairs$ynaffair <- factor(Affairs$ynaffair,levels=c(0,1), labels=c(\"No\",\"Yes\"))> table(Affairs$ynaffair)No Yes451 150" }, { "code": null, "e": 3546, "s": 3507, "text": "Fit the model with Logistic Regression" }, { "code": null, "e": 3750, "s": 3546, "text": "Now, we can execute the logistic regression to measure the relationship between response variable (affair) and explanatory variables (age, gender, education, occupation, children, self-rating, etc) in R." }, { "code": null, "e": 4861, "s": 3750, "text": "> fit.full <- glm(ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation +rating, data=Affairs, family=binomial())> summary(fit.full)Deviance Residuals: Min 1Q Median 3Q Max-1.571 -0.750 -0.569 -0.254 2.519Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) 1.3773 0.8878 1.55 0.12081gendermale 0.2803 0.2391 1.17 0.24108age -0.0443 0.0182 -2.43 0.01530 *yearsmarried 0.0948 0.0322 2.94 0.00326 **childrenyes 0.3977 0.2915 1.36 0.17251religiousness -0.3247 0.0898 -3.62 0.00030 ***education 0.0211 0.0505 0.42 0.67685occupation 0.0309 0.0718 0.43 0.66663rating -0.4685 0.0909 -5.15 2.6e-07 ***---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1(Dispersion parameter for binomial family taken to be 1) Null deviance: 675.38 on 600 degrees of freedomResidual deviance: 609.51 on 592 degrees of freedomAIC: 627.5Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 5235, "s": 4861, "text": "If we observe the Pr(>|z|) or p-values for the regression coefficients, then we find that gender, presence of children, education, and occupation do not have a significant contribution to our response variable. Therefore, we can try to fit a second model by including only significant variables such as age, years married, religiousness, and rating to fit the data instead." }, { "code": null, "e": 6096, "s": 5235, "text": "> fit.reduced <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, data=Affairs, family=binomial())> summary(fit.reduced)Deviance Residuals: Min 1Q Median 3Q Max-1.628 -0.755 -0.570 -0.262 2.400Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) 1.9308 0.6103 3.16 0.00156 **age -0.0353 0.0174 -2.03 0.04213 *yearsmarried 0.1006 0.0292 3.44 0.00057 ***religiousness -0.3290 0.0895 -3.68 0.00023 ***rating -0.4614 0.0888 -5.19 2.1e-07 ***---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1(Dispersion parameter for binomial family taken to be 1) Null deviance: 675.38 on 600 degrees of freedomResidual deviance: 615.36 on 596 degrees of freedomAIC: 625.4Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 6374, "s": 6096, "text": "For the second model, we can see that p-values for each regression coefficient is statistically significant. Then, we may run chi-square test with anova function in R to compared between first and second model. We will see which model that explain our response variable better." }, { "code": null, "e": 6746, "s": 6374, "text": "> anova(fit.reduced, fit.full, test=\"Chisq\") Analysis of Deviance Table Model 1: ynaffair ~ age + yearsmarried + religiousness + rating Model 2: ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation + rating Resid.Df Resid.Dev Df Deviance P(>|Chi|) 1 596 615 2 592 610 4 5.85 0.21" }, { "code": null, "e": 7211, "s": 6746, "text": "The output above displays nonsignificant chi-square value with p-values= 0.21. It means that the second model with only four predictors fits as well as the full model with nine predictors. It supports our initial belief that gender, children, education, and occupation don’t add any contribution to predict infidelity (our response variable). Thus, we will continue the analysis with the second model as it is easier to do our interpretations on the simpler model." }, { "code": null, "e": 7242, "s": 7211, "text": "Interpret the model parameters" }, { "code": null, "e": 7736, "s": 7242, "text": "Based on the regression coefficients from the second model, we are seeing that the odds of having affairs increase with years married and decrease with age, religiousness, and happiness self-rating. We can observe it based on the positive or negative sign from each regression coefficient. In conclusion, we might say the longer you are married, then the more likely you will have an affair. On the other hand, the happier you are in the marriage, then the less likely you will have an affair." }, { "code": null, "e": 7869, "s": 7736, "text": "> coef(fit.reduced) (Intercept) age yearsmarried religiousness rating 1.931 -0.035 0.101 -0.329 -0.461" }, { "code": null, "e": 8234, "s": 7869, "text": "Next, we want to know the impact value of each of these variables towards affair. First, we need to remember that logistic regression modeled the response variable to log(odds) that Y = 1. It implies the regression coefficients allow the change in log(odds) in the return for a unit change in the predictor variable, holding all other predictor variables constant." }, { "code": null, "e": 8334, "s": 8234, "text": "Since log(odds) are hard to interpret, we will transform it by exponentiating the outcome as follow" }, { "code": null, "e": 8475, "s": 8334, "text": "> exp(coef(fit.reduced)) (Intercept) age yearsmarried religiousness rating 6.895 0.965 1.106 0.720 0.630" }, { "code": null, "e": 8850, "s": 8475, "text": "We observe that the odds of having affair are increased by a factor of 1.106 for a one-year increase in years married (holding age, religiousness, and happiness rating constant). On the contrary, the odds of having affair are multiplied by a factor of 0.965 for every year increase in age. It means the chance of having an affair drop by -3.5% every time someone gets older." }, { "code": null, "e": 9115, "s": 8850, "text": "Furthermore, the change in the odds of the higher value on the response variable for an n unit change in a predictor variable is exp(βj)^n. Then, a 15-year increase would increase the odds by a factor of 1.10615≈4.5, holding the other predictor variables constant." }, { "code": null, "e": 9150, "s": 9115, "text": "Predict the outcome using new data" }, { "code": null, "e": 9501, "s": 9150, "text": "In this section, we are using the model that we built to predict the outcome for the new data. The first step, we will make a new data containing the values of predictor variables we’re interested in. The second step, we will apply the predict() function in R to estimate the probabilities of the outcome event following the values from the new data." }, { "code": null, "e": 9753, "s": 9501, "text": "Consider new data below where we have 5 new respondents with different self-rating, holding other variables set to the average of overall data. Then, we apply the prediction function to get the probabilities of having affair for these new respondents." }, { "code": null, "e": 10630, "s": 9753, "text": "> newdata1 <- data.frame(rating=c(1,2,3,4,5),age=mean(Affairs$age), yearsmarried=mean(Affairs$yearsmarried), religiousness=mean(Affairs$religiousness))> newdata1 rating age yearsmarried religiousness1 1 32.5 8.18 3.122 2 32.5 8.18 3.123 3 32.5 8.18 3.124 4 32.5 8.18 3.125 5 32.5 8.18 3.12> newdata1$prob <- predict(fit.reduced, newdata=newdata1, type=\"response\")> newdata1 rating age yearsmarried religiousness prob1 1 32.5 8.18 3.12 0.5302 2 32.5 8.18 3.12 0.4163 3 32.5 8.18 3.12 0.3104 4 32.5 8.18 3.12 0.2205 5 32.5 8.18 3.12 0.151" }, { "code": null, "e": 10939, "s": 10630, "text": "Clearly, we notice that chance of having affair declining from 0.53 when marriage is rated 1=”very unhappy” to 0.15 when the marriage is rated 5=”very happy” (holding other predictor variables constant). It indicates the unhappy couple are three times more likely to have an affair compared to the happy one." }, { "code": null, "e": 11016, "s": 10939, "text": "Let’s create another new data to observe the impact of age toward infidelity" }, { "code": null, "e": 11885, "s": 11016, "text": "> newdata2 <- data.frame(rating=mean(Affairs$rating), age=(17,27,37,47, 57), yearsmarried=mean(Affairs$yearsmarried), religiousness=mean(Affairs$religiousness))> newdata2 rating age yearsmarried religiousness1 3.93 17 8.18 3.122 3.93 27 8.18 3.123 3.93 37 8.18 3.124 3.93 47 8.18 3.125 3.93 57 8.18 3.12> newdata2$prob <- predict(fit.reduced, newdata=newdata2, type=\"response\")> newdata2 rating age yearsmarried religiousness prob1 3.93 17 8.18 3.12 0.3352 3.93 27 8.18 3.12 0.2623 3.93 37 8.18 3.12 0.1994 3.93 47 8.18 3.12 0.1495 3.93 57 8.18 3.12 0.109" }, { "code": null, "e": 12192, "s": 11885, "text": "Here, we see that as age increases from 17 to 57, the probability of having affair declining from 0.34 to 0.11, holding the other variables constant. If you are interested to explore the impact of other predictor variables or to predict other new data, then you can use this approach to analyze it further." }, { "code": null, "e": 12216, "s": 12192, "text": "Evaluate overdispersion" }, { "code": null, "e": 12435, "s": 12216, "text": "In logistic regression, we need to check the expected variance for data drawn from a binomial distribution σ2 = nπ(1 − π), where n is the number of observations and π is the probability of belonging to the Y = 1 group." }, { "code": null, "e": 12836, "s": 12435, "text": "Overdispersion occurs when data admit more variability than expected under the assumed distribution. If overdispersion is present in a dataset, the estimated standard errors and test statistics the overall goodness-of-fit will be distorted and adjustments must be made. One of the solutions, we need to use the quasibinomial distribution rather than the binomial distribution for glm() function in R." }, { "code": null, "e": 12908, "s": 12836, "text": "There are two ways to verify if we have an overdispersion issue or not:" }, { "code": null, "e": 13048, "s": 12908, "text": "The first method, we can check overdispersion by dividing the residual deviance with the residual degrees of freedom of our binomial model." }, { "code": null, "e": 13279, "s": 13048, "text": "If the ratio considerably larger than 1, then it indicates that we have an overdispersion issue. Calculating this ratio using our data example, we find that the ratio is close to 1. It means no overdispersion problem on our model." }, { "code": null, "e": 13339, "s": 13279, "text": "> deviance(fit.reduced)/df.residual(fit.reduced) [1] 1.032" }, { "code": null, "e": 13638, "s": 13339, "text": "The second method, we are using two models fit to check overdispersion. Basically, we will fit the logistic regression using two different models using different distributions. Then, we check if there’s a statistical evidence that the expected variance of the two models is significantly different." }, { "code": null, "e": 13975, "s": 13638, "text": "> fit <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, family = binomial(), data = Affairs)> fit.od <- glm(ynaffair ~ age + yearsmarried + religiousness + rating, family = quasibinomial(), data = Affairs)> pchisq(summary(fit.od)$dispersion * fit$df.residual, fit$df.residual, lower = F)[1] 0.34" }, { "code": null, "e": 14115, "s": 13975, "text": "We find that p-value =0.34 is clearly not significant (p > 0.05), strengthening our belief that overdispersion isn’t a problem on our model" } ]
Automorphic Number - GeeksforGeeks
11 Mar, 2022 Given a number N, the task is to check whether the number is Automorphic number or not. A number is called Automorphic number if and only if its square ends in the same digits as the number itself.Examples : Input : N = 76 Output : Automorphic Explanation: As 76*76 = 5776 Input : N = 25 Output : Automorphic As 25*25 = 625 Input : N = 7 Output : Not Automorphic As 7*7 = 49 1. Store the square of given number. 2. Loop until N becomes 0 as we have to match all digits with its square. i) Check if (n%10 == sq%10) i.e. last digit of number = last digit of square or not a) if not equal, return false. ii) Otherwise continue i.e. reduce number and square i.e. n = n/10 and sq = sq/10; 3- Return true if all digits matched. C++ Java Python3 C# PHP Javascript // C++ program to check if a number is Automorphic#include <iostream>using namespace std; // Function to check Automorphic numberbool isAutomorphic(int N){ // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit of N doesn't // match with its square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true;} // Driver codeint main(){ int N = 5; isAutomorphic(N) ? cout << "Automorphic" : cout << "Not Automorphic"; return 0;} // Java program to check if a number is Automorphicclass Test { // Function to check Automorphic number static boolean isAutomorphic(int N) { // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit of N doesn't // match with its square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true; } // Driver method public static void main(String[] args) { int N = 5; System.out.println(isAutomorphic(N) ? "Automorphic" : "Not Automorphic"); }} # Python program to check if a number is Automorphic # Function to check Automorphic numberdef isAutomorphic(N) : # Store the square sq = N * N # Start Comparing digits while (N > 0) : # Return false, if any digit of N doesn't # match with its square's digits from last if (N % 10 != sq % 10) : return False # Reduce N and square N //= 10 sq //= 10 return True # Driver codeN = 5if isAutomorphic(N) : print ("Automorphic")else : print ("Not Automorphic") # This Code is contributed by Nikita Tiwari. // C# program to check if a// number is Automorphicusing System; class GFG { // Function to check Automorphic number static bool isAutomorphic(int N) { // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit // of N doesn't match with its // square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true; } // Driver Code public static void Main() { int N = 5; Console.Write(isAutomorphic(N) ? "Automorphic" : "Not Automorphic"); }} // This code is Contributed by Nitin Mittal. <?php// PHP program to check if// a number is Automorphic // Function to check// Automorphic numberfunction isAutomorphic($N){ // Store the square $sq = $N * $N; // Start Comparing digits while ($N > 0) { // Return false, if any // digit of N doesn't // match with its square's // digits from last if ($N % 10 != $sq % 10) return -1; // Reduce N and square $N /= 10; $sq /= 10; } return 1;} // Driver code$N = 5; $geeks = isAutomorphic($N) ? "Automorphic" : "Not Automorphic"; echo $geeks; // This code is contributed by ajit?> <script> // Javascript program to check if// a number is Automorphic // Function to check// Automorphic numberfunction isAutomorphic(N){ // Store the square let sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any // digit of N doesn't // match with its square's // digits from last if (N % 10 != sq % 10) return -1; // Reduce N and square N /= 10; sq /= 10; } return 1;} // Driver codelet N = 5; let geeks = isAutomorphic(N) ? "Automorphic" : "Not Automorphic"; document.write(geeks); // This code is contributed by _saurabh_jaiswal</script> Output : Automorphic YouTubeGeeksforGeeks507K subscribersAutomorphic number | 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 / 3:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=U7RpbcsbUIE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Sahil Chhabra. 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 jit_t _saurabh_jaiswal amartyaghoshgfg simmytarika5 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ Program for factorial of a number The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Program for Decimal to Binary Conversion Program to find sum of elements in a given array
[ { "code": null, "e": 26274, "s": 26246, "text": "\n11 Mar, 2022" }, { "code": null, "e": 26484, "s": 26274, "text": "Given a number N, the task is to check whether the number is Automorphic number or not. A number is called Automorphic number if and only if its square ends in the same digits as the number itself.Examples : " }, { "code": null, "e": 26656, "s": 26484, "text": "Input : N = 76 \nOutput : Automorphic\nExplanation: As 76*76 = 5776\n\nInput : N = 25\nOutput : Automorphic\nAs 25*25 = 625\n\nInput : N = 7\nOutput : Not Automorphic\nAs 7*7 = 49" }, { "code": null, "e": 27044, "s": 26660, "text": "1. Store the square of given number.\n2. Loop until N becomes 0 as we have to match \n all digits with its square.\n i) Check if (n%10 == sq%10) i.e. last digit \n of number = last digit of square or not\n a) if not equal, return false.\n ii) Otherwise continue i.e. reduce number and \n square i.e. n = n/10 and sq = sq/10;\n3- Return true if all digits matched." }, { "code": null, "e": 27050, "s": 27046, "text": "C++" }, { "code": null, "e": 27055, "s": 27050, "text": "Java" }, { "code": null, "e": 27063, "s": 27055, "text": "Python3" }, { "code": null, "e": 27066, "s": 27063, "text": "C#" }, { "code": null, "e": 27070, "s": 27066, "text": "PHP" }, { "code": null, "e": 27081, "s": 27070, "text": "Javascript" }, { "code": "// C++ program to check if a number is Automorphic#include <iostream>using namespace std; // Function to check Automorphic numberbool isAutomorphic(int N){ // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit of N doesn't // match with its square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true;} // Driver codeint main(){ int N = 5; isAutomorphic(N) ? cout << \"Automorphic\" : cout << \"Not Automorphic\"; return 0;}", "e": 27720, "s": 27081, "text": null }, { "code": "// Java program to check if a number is Automorphicclass Test { // Function to check Automorphic number static boolean isAutomorphic(int N) { // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit of N doesn't // match with its square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true; } // Driver method public static void main(String[] args) { int N = 5; System.out.println(isAutomorphic(N) ? \"Automorphic\" : \"Not Automorphic\"); }}", "e": 28435, "s": 27720, "text": null }, { "code": "# Python program to check if a number is Automorphic # Function to check Automorphic numberdef isAutomorphic(N) : # Store the square sq = N * N # Start Comparing digits while (N > 0) : # Return false, if any digit of N doesn't # match with its square's digits from last if (N % 10 != sq % 10) : return False # Reduce N and square N //= 10 sq //= 10 return True # Driver codeN = 5if isAutomorphic(N) : print (\"Automorphic\")else : print (\"Not Automorphic\") # This Code is contributed by Nikita Tiwari.", "e": 29032, "s": 28435, "text": null }, { "code": "// C# program to check if a// number is Automorphicusing System; class GFG { // Function to check Automorphic number static bool isAutomorphic(int N) { // Store the square int sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any digit // of N doesn't match with its // square's digits from last if (N % 10 != sq % 10) return false; // Reduce N and square N /= 10; sq /= 10; } return true; } // Driver Code public static void Main() { int N = 5; Console.Write(isAutomorphic(N) ? \"Automorphic\" : \"Not Automorphic\"); }} // This code is Contributed by Nitin Mittal.", "e": 29798, "s": 29032, "text": null }, { "code": "<?php// PHP program to check if// a number is Automorphic // Function to check// Automorphic numberfunction isAutomorphic($N){ // Store the square $sq = $N * $N; // Start Comparing digits while ($N > 0) { // Return false, if any // digit of N doesn't // match with its square's // digits from last if ($N % 10 != $sq % 10) return -1; // Reduce N and square $N /= 10; $sq /= 10; } return 1;} // Driver code$N = 5; $geeks = isAutomorphic($N) ? \"Automorphic\" : \"Not Automorphic\"; echo $geeks; // This code is contributed by ajit?>", "e": 30441, "s": 29798, "text": null }, { "code": "<script> // Javascript program to check if// a number is Automorphic // Function to check// Automorphic numberfunction isAutomorphic(N){ // Store the square let sq = N * N; // Start Comparing digits while (N > 0) { // Return false, if any // digit of N doesn't // match with its square's // digits from last if (N % 10 != sq % 10) return -1; // Reduce N and square N /= 10; sq /= 10; } return 1;} // Driver codelet N = 5; let geeks = isAutomorphic(N) ? \"Automorphic\" : \"Not Automorphic\"; document.write(geeks); // This code is contributed by _saurabh_jaiswal</script>", "e": 31138, "s": 30441, "text": null }, { "code": null, "e": 31149, "s": 31138, "text": "Output : " }, { "code": null, "e": 31161, "s": 31149, "text": "Automorphic" }, { "code": null, "e": 31980, "s": 31163, "text": "YouTubeGeeksforGeeks507K subscribersAutomorphic number | 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 / 3:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=U7RpbcsbUIE\" 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": 32402, "s": 31980, "text": "This article is contributed by Sahil Chhabra. 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": 32415, "s": 32402, "text": "nitin mittal" }, { "code": null, "e": 32421, "s": 32415, "text": "jit_t" }, { "code": null, "e": 32438, "s": 32421, "text": "_saurabh_jaiswal" }, { "code": null, "e": 32454, "s": 32438, "text": "amartyaghoshgfg" }, { "code": null, "e": 32467, "s": 32454, "text": "simmytarika5" }, { "code": null, "e": 32481, "s": 32467, "text": "number-digits" }, { "code": null, "e": 32494, "s": 32481, "text": "Mathematical" }, { "code": null, "e": 32507, "s": 32494, "text": "Mathematical" }, { "code": null, "e": 32605, "s": 32507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32629, "s": 32605, "text": "Merge two sorted arrays" }, { "code": null, "e": 32672, "s": 32629, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32686, "s": 32672, "text": "Prime Numbers" }, { "code": null, "e": 32759, "s": 32686, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32780, "s": 32759, "text": "Operators in C / C++" }, { "code": null, "e": 32814, "s": 32780, "text": "Program for factorial of a number" }, { "code": null, "e": 32857, "s": 32814, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32910, "s": 32857, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 32951, "s": 32910, "text": "Program for Decimal to Binary Conversion" } ]
Predicting Future Stock Market Trends with Python & Machine Learning | by Lucas Rea | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. With the recent volatility of the stock market due to the COVID-19 pandemic, I thought it was a good idea to try and utilize machine learning to predict the near-future trends of the stock market. I’m fairly new to machine learning, and this is my first Medium article so I thought this would be a good project to start off with and showcase. This article tackles different topics concerning data science, namely; data collection and cleaning, feature engineering, as well as the creation of machine learning models to make predictions. Note: I previously had the look-ahead bias in my code for this article, which produced some extremely good results (suspiciously good). However they were misleading, and I now aim to try and fix that with cross-validation. Author’s disclaimer: This project is not financial or investment advice. It is not a guarantee that it will provide the correct results most of the time. Therefore you should be very careful and not use this as a primary source of trading insight. You can find all the code on a jupyter notebook on my github: github.com To begin, we include all of the libraries used for this project. I used the yfinance API to gather all of the historical stock market data. It’s taken directly from the yahoo finance website, so it’s very reliable data. We then define some constants that used in data retrieval and data processing. The list with the indicator symbols is useful to help use produce more features for our model. Here’s a link where you can find the actual names of some of these features. github.com Now we pull our historical data from yfinance. We don’t have many features to work with — not particularly useful unless we find a way to normalize them at least or derive more features from them. We see that our data above is rough and contains lots of spikes for a time series. It isn’t very smooth and can be difficult for the model to extract trends from. To reduce the appearance of this we want to exponentially smooth our data before we compute the technical indicators. We can see that the data is much more smoothed. Having many peaks and troughs can make it hard to approximate, or be difficult to extract tends when computing the technical indicators. It can throw the model off. Now it’s time to compute our technical indicators. As stated above, I use the finta library in combination with python’s built in eval function to quickly compute all the indicators in the INDICATORS list. I also compute some ema’s at different average lengths in addition to a normalized volume value. I remove the columns like ‘Open’, ‘High’, ‘Low’, and ‘Adj Close’ because we can get a good enough approximation with our ema’s in addition to the indicators. Volume has been proven to have a correlation with price fluctuations, which is why I normalized it. Index(['close', 'RSI', 'MACD', 'SIGNAL', '14 period STOCH %K','MFV', '14 period ATR', 'MOM', '14 period MFI', 'ROC', 'OBV_x', 'OBV_y', '20 period CCI', '14 period EMV', 'VIm', 'VIp', 'ema50', 'ema21', 'ema14', 'ema5', 'normVol'], dtype='object') Right before we gather our predictions, I decided to keep a small bit of data to predict future values with. This line captures 5 rows corresponding to the 5 days of the week on July 27th. live_pred_data = data.iloc[-16:-11] Now comes one of the most important part of this project — computing the truth values. Without these, we wouldn’t even be able to train a machine learning model to make predictions. How do we obtain truth value? Well it’s quite intuitive. If we want to know when a stock will increase or decrease (to make a million dollars hopefully!) we would just need to look into the future and observe the price to determine if we should buy or sell right now. Well, with all this historical data, that’s exactly what we can do. Going back to the table where we initially pulled our data, if we want to know the buy (1) or sell (0) decision on the day of 1993–03–29 (where the closing price was 11.4375), we just need to look X days ahead to see if the price is higher or lower than that on 1993–03–29. So if we look 1 day ahead, we see that the price increased to 11.5. So the truth value on 1993–03–29 would be a buy (1). Since this is also the last step of data processing, we remove all of the NaN value that our indicators and prediction generated, as well as removing the ‘close’ column. Because we used Pandas’ shift() function, we lose about 15 rows from the end of the dataset (which is why I captured the week of July 27th before this step). Right before we train our model we must split up the data into a train set and test set. However, due to the nature of time-series’, we need to handle this part carefully. If we randomize our train-test set, we could encounter a look-ahead bias which is not good for predicting the stock market. It’s caused when you train your model on data it would’ve already seen. To prevent this we are going to be training the model using a different technique called cross-validation. The image below illustrates how we are going to partition our data and test the accuracy of the model. First, we’re going to use multiple classifiers to create an ensemble model. The goal here is to combine the predictions of several models to try and improve on predictability. For each sub-model, we’re also going to use a feature from Sklearn, GridSearchCV, to optimize each model for the best possible results. First we create the random forest model. Then the KNN model. And now finally we create the voting classifier Once we set up our models, we can put it together with the cross-validation. We start by writing some code that will allow us to iterate over our data with many evenly sized chunks. Printing out the indices of our dataframe, we have successfully partitioned our data like in the sliding window image. 10 5020 6030 7040 8050 9060 100...6820 68606830 6870 Now we add in the code that will split the partitions into train and test sets. It’s very important to set shuffle=False in the train_test_split function —it’s how you avoid the look-ahead bias. Finally we incorporate our models. A sample run of this looks like... the results are exaggerated. rf prediction is [1. 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1.]knn prediction is [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]ensemble prediction is [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]truth values are [1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1.]0.9166666666666666 0.9166666666666666 0.9166666666666666 And then the final results gives us RF Accuracy = 0.6732649071358748KNN Accuracy = 0.67460899315738Ensemble Accuracy = 0.6925708699902248 We can see that we gain slightly more accuracy by using ensemble modelling. Compared to not using cross-validation, the resulting accuracy is much less. However this is a more correct way of going about this problem... and about a 70% accuracy isn’t bad either! For the next step we’re going to predict how the S&P500 will behave with our predictive model. I’m writing this article on the weekend of August 17th. So to see if this model can produce accurate results, I’m going to use the closing data from this week as the ‘truth’ values for the prediction. Since this model is tuned to have a 15 day window, we need to feed in the input data with the days in the week of July 27th. July 27th -> August 17th July 28th -> August 18th July 29th -> August 19th July 30th -> August 20th July 31st -> August 21st We saved the week we’re going to use in live_pred_data. live_pred_data.head() Here are the five main days we are going to generate a prediction for. Looks like the models predicts that the price will increase for each day. Lets validate our prediction with the actual results. del(live_pred_data['close'])prediction = ensemble_model.predict(live_pred_data)print(prediction)[1. 1. 1. 1. 1.] Results July 27th : $ 322.78 — August 17th : $ 337.91 July 28th : $ 321.74 — August 18th : $ 338.64 July 29th : $ 323.93 — August 19th : $ 337.23 July 30th : $ 323.95 — August 20th : $ 338.28 July 31st : $ 325.62 — August 21st : $ 339.48 As we can see from the actual results, we can confirm that the model was correct in all of its predictions. However there are many factors that go into determining the stock price, so to say that the model will produce similar results every time is naive. However, during relatively normal periods of time (without major panic that causes volatility in the stock market), the model should be able to produce good results. To summarize what we’ve done in this project, We’ve collected data to be used in analysis and feature creation.We’ve used pandas to compute many model features and produce clean data to help us in machine learning. Created predictions or truth values using pandas.Utilized cross-validation to avoid the look-ahead bias. Trained many machine learning models and then combined them using ensemble learning to produce higher prediction accuracy.Ensured our predictions were accurate with real world data. We’ve collected data to be used in analysis and feature creation. We’ve used pandas to compute many model features and produce clean data to help us in machine learning. Created predictions or truth values using pandas. Utilized cross-validation to avoid the look-ahead bias. Trained many machine learning models and then combined them using ensemble learning to produce higher prediction accuracy. Ensured our predictions were accurate with real world data. I’ve learned a lot about data science and machine learning through this project, and I hope you did too. Being my first article, I’d love any form of feedback to help improve my skills as a programmer and data scientist. Thanks for reading :)
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 815, "s": 472, "text": "With the recent volatility of the stock market due to the COVID-19 pandemic, I thought it was a good idea to try and utilize machine learning to predict the near-future trends of the stock market. I’m fairly new to machine learning, and this is my first Medium article so I thought this would be a good project to start off with and showcase." }, { "code": null, "e": 1009, "s": 815, "text": "This article tackles different topics concerning data science, namely; data collection and cleaning, feature engineering, as well as the creation of machine learning models to make predictions." }, { "code": null, "e": 1232, "s": 1009, "text": "Note: I previously had the look-ahead bias in my code for this article, which produced some extremely good results (suspiciously good). However they were misleading, and I now aim to try and fix that with cross-validation." }, { "code": null, "e": 1480, "s": 1232, "text": "Author’s disclaimer: This project is not financial or investment advice. It is not a guarantee that it will provide the correct results most of the time. Therefore you should be very careful and not use this as a primary source of trading insight." }, { "code": null, "e": 1542, "s": 1480, "text": "You can find all the code on a jupyter notebook on my github:" }, { "code": null, "e": 1553, "s": 1542, "text": "github.com" }, { "code": null, "e": 1773, "s": 1553, "text": "To begin, we include all of the libraries used for this project. I used the yfinance API to gather all of the historical stock market data. It’s taken directly from the yahoo finance website, so it’s very reliable data." }, { "code": null, "e": 1947, "s": 1773, "text": "We then define some constants that used in data retrieval and data processing. The list with the indicator symbols is useful to help use produce more features for our model." }, { "code": null, "e": 2024, "s": 1947, "text": "Here’s a link where you can find the actual names of some of these features." }, { "code": null, "e": 2035, "s": 2024, "text": "github.com" }, { "code": null, "e": 2232, "s": 2035, "text": "Now we pull our historical data from yfinance. We don’t have many features to work with — not particularly useful unless we find a way to normalize them at least or derive more features from them." }, { "code": null, "e": 2513, "s": 2232, "text": "We see that our data above is rough and contains lots of spikes for a time series. It isn’t very smooth and can be difficult for the model to extract trends from. To reduce the appearance of this we want to exponentially smooth our data before we compute the technical indicators." }, { "code": null, "e": 2726, "s": 2513, "text": "We can see that the data is much more smoothed. Having many peaks and troughs can make it hard to approximate, or be difficult to extract tends when computing the technical indicators. It can throw the model off." }, { "code": null, "e": 3029, "s": 2726, "text": "Now it’s time to compute our technical indicators. As stated above, I use the finta library in combination with python’s built in eval function to quickly compute all the indicators in the INDICATORS list. I also compute some ema’s at different average lengths in addition to a normalized volume value." }, { "code": null, "e": 3287, "s": 3029, "text": "I remove the columns like ‘Open’, ‘High’, ‘Low’, and ‘Adj Close’ because we can get a good enough approximation with our ema’s in addition to the indicators. Volume has been proven to have a correlation with price fluctuations, which is why I normalized it." }, { "code": null, "e": 3533, "s": 3287, "text": "Index(['close', 'RSI', 'MACD', 'SIGNAL', '14 period STOCH %K','MFV', '14 period ATR', 'MOM', '14 period MFI', 'ROC', 'OBV_x', 'OBV_y', '20 period CCI', '14 period EMV', 'VIm', 'VIp', 'ema50', 'ema21', 'ema14', 'ema5', 'normVol'], dtype='object')" }, { "code": null, "e": 3722, "s": 3533, "text": "Right before we gather our predictions, I decided to keep a small bit of data to predict future values with. This line captures 5 rows corresponding to the 5 days of the week on July 27th." }, { "code": null, "e": 3758, "s": 3722, "text": "live_pred_data = data.iloc[-16:-11]" }, { "code": null, "e": 3940, "s": 3758, "text": "Now comes one of the most important part of this project — computing the truth values. Without these, we wouldn’t even be able to train a machine learning model to make predictions." }, { "code": null, "e": 4276, "s": 3940, "text": "How do we obtain truth value? Well it’s quite intuitive. If we want to know when a stock will increase or decrease (to make a million dollars hopefully!) we would just need to look into the future and observe the price to determine if we should buy or sell right now. Well, with all this historical data, that’s exactly what we can do." }, { "code": null, "e": 4671, "s": 4276, "text": "Going back to the table where we initially pulled our data, if we want to know the buy (1) or sell (0) decision on the day of 1993–03–29 (where the closing price was 11.4375), we just need to look X days ahead to see if the price is higher or lower than that on 1993–03–29. So if we look 1 day ahead, we see that the price increased to 11.5. So the truth value on 1993–03–29 would be a buy (1)." }, { "code": null, "e": 4841, "s": 4671, "text": "Since this is also the last step of data processing, we remove all of the NaN value that our indicators and prediction generated, as well as removing the ‘close’ column." }, { "code": null, "e": 4999, "s": 4841, "text": "Because we used Pandas’ shift() function, we lose about 15 rows from the end of the dataset (which is why I captured the week of July 27th before this step)." }, { "code": null, "e": 5367, "s": 4999, "text": "Right before we train our model we must split up the data into a train set and test set. However, due to the nature of time-series’, we need to handle this part carefully. If we randomize our train-test set, we could encounter a look-ahead bias which is not good for predicting the stock market. It’s caused when you train your model on data it would’ve already seen." }, { "code": null, "e": 5577, "s": 5367, "text": "To prevent this we are going to be training the model using a different technique called cross-validation. The image below illustrates how we are going to partition our data and test the accuracy of the model." }, { "code": null, "e": 5889, "s": 5577, "text": "First, we’re going to use multiple classifiers to create an ensemble model. The goal here is to combine the predictions of several models to try and improve on predictability. For each sub-model, we’re also going to use a feature from Sklearn, GridSearchCV, to optimize each model for the best possible results." }, { "code": null, "e": 5930, "s": 5889, "text": "First we create the random forest model." }, { "code": null, "e": 5950, "s": 5930, "text": "Then the KNN model." }, { "code": null, "e": 5998, "s": 5950, "text": "And now finally we create the voting classifier" }, { "code": null, "e": 6180, "s": 5998, "text": "Once we set up our models, we can put it together with the cross-validation. We start by writing some code that will allow us to iterate over our data with many evenly sized chunks." }, { "code": null, "e": 6299, "s": 6180, "text": "Printing out the indices of our dataframe, we have successfully partitioned our data like in the sliding window image." }, { "code": null, "e": 6352, "s": 6299, "text": "10 5020 6030 7040 8050 9060 100...6820 68606830 6870" }, { "code": null, "e": 6547, "s": 6352, "text": "Now we add in the code that will split the partitions into train and test sets. It’s very important to set shuffle=False in the train_test_split function —it’s how you avoid the look-ahead bias." }, { "code": null, "e": 6582, "s": 6547, "text": "Finally we incorporate our models." }, { "code": null, "e": 6646, "s": 6582, "text": "A sample run of this looks like... the results are exaggerated." }, { "code": null, "e": 6930, "s": 6646, "text": "rf prediction is [1. 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1.]knn prediction is [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]ensemble prediction is [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]truth values are [1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1.]0.9166666666666666 0.9166666666666666 0.9166666666666666" }, { "code": null, "e": 6966, "s": 6930, "text": "And then the final results gives us" }, { "code": null, "e": 7068, "s": 6966, "text": "RF Accuracy = 0.6732649071358748KNN Accuracy = 0.67460899315738Ensemble Accuracy = 0.6925708699902248" }, { "code": null, "e": 7330, "s": 7068, "text": "We can see that we gain slightly more accuracy by using ensemble modelling. Compared to not using cross-validation, the resulting accuracy is much less. However this is a more correct way of going about this problem... and about a 70% accuracy isn’t bad either!" }, { "code": null, "e": 7751, "s": 7330, "text": "For the next step we’re going to predict how the S&P500 will behave with our predictive model. I’m writing this article on the weekend of August 17th. So to see if this model can produce accurate results, I’m going to use the closing data from this week as the ‘truth’ values for the prediction. Since this model is tuned to have a 15 day window, we need to feed in the input data with the days in the week of July 27th." }, { "code": null, "e": 7776, "s": 7751, "text": "July 27th -> August 17th" }, { "code": null, "e": 7801, "s": 7776, "text": "July 28th -> August 18th" }, { "code": null, "e": 7826, "s": 7801, "text": "July 29th -> August 19th" }, { "code": null, "e": 7851, "s": 7826, "text": "July 30th -> August 20th" }, { "code": null, "e": 7876, "s": 7851, "text": "July 31st -> August 21st" }, { "code": null, "e": 7932, "s": 7876, "text": "We saved the week we’re going to use in live_pred_data." }, { "code": null, "e": 7954, "s": 7932, "text": "live_pred_data.head()" }, { "code": null, "e": 8099, "s": 7954, "text": "Here are the five main days we are going to generate a prediction for. Looks like the models predicts that the price will increase for each day." }, { "code": null, "e": 8153, "s": 8099, "text": "Lets validate our prediction with the actual results." }, { "code": null, "e": 8266, "s": 8153, "text": "del(live_pred_data['close'])prediction = ensemble_model.predict(live_pred_data)print(prediction)[1. 1. 1. 1. 1.]" }, { "code": null, "e": 8274, "s": 8266, "text": "Results" }, { "code": null, "e": 8320, "s": 8274, "text": "July 27th : $ 322.78 — August 17th : $ 337.91" }, { "code": null, "e": 8366, "s": 8320, "text": "July 28th : $ 321.74 — August 18th : $ 338.64" }, { "code": null, "e": 8412, "s": 8366, "text": "July 29th : $ 323.93 — August 19th : $ 337.23" }, { "code": null, "e": 8458, "s": 8412, "text": "July 30th : $ 323.95 — August 20th : $ 338.28" }, { "code": null, "e": 8504, "s": 8458, "text": "July 31st : $ 325.62 — August 21st : $ 339.48" }, { "code": null, "e": 8926, "s": 8504, "text": "As we can see from the actual results, we can confirm that the model was correct in all of its predictions. However there are many factors that go into determining the stock price, so to say that the model will produce similar results every time is naive. However, during relatively normal periods of time (without major panic that causes volatility in the stock market), the model should be able to produce good results." }, { "code": null, "e": 8972, "s": 8926, "text": "To summarize what we’ve done in this project," }, { "code": null, "e": 9428, "s": 8972, "text": "We’ve collected data to be used in analysis and feature creation.We’ve used pandas to compute many model features and produce clean data to help us in machine learning. Created predictions or truth values using pandas.Utilized cross-validation to avoid the look-ahead bias. Trained many machine learning models and then combined them using ensemble learning to produce higher prediction accuracy.Ensured our predictions were accurate with real world data." }, { "code": null, "e": 9494, "s": 9428, "text": "We’ve collected data to be used in analysis and feature creation." }, { "code": null, "e": 9648, "s": 9494, "text": "We’ve used pandas to compute many model features and produce clean data to help us in machine learning. Created predictions or truth values using pandas." }, { "code": null, "e": 9827, "s": 9648, "text": "Utilized cross-validation to avoid the look-ahead bias. Trained many machine learning models and then combined them using ensemble learning to produce higher prediction accuracy." }, { "code": null, "e": 9887, "s": 9827, "text": "Ensured our predictions were accurate with real world data." }, { "code": null, "e": 10108, "s": 9887, "text": "I’ve learned a lot about data science and machine learning through this project, and I hope you did too. Being my first article, I’d love any form of feedback to help improve my skills as a programmer and data scientist." } ]
Convert Unicode to ASCII in Python - GeeksforGeeks
05 Aug, 2021 Unicode is the universal character set and a standard to support all the world’s languages. It contains 140,000+ characters used by 150+ scripts along with various symbols. ASCII on the other hand is a subset of Unicode and the most compatible character set, consisting of 128 letters made of English letters, digits, and punctuation, with the remaining being control characters. This article deals with the conversion of a wide range of Unicode characters to a simpler ASCII representation using the Python library anyascii. The text is converted from character to character. The mappings for each script are based on conventional schemes. Symbolic characters are converted based on their meaning or appearance. If the input contains ASCII characters, they are untouched, the rest are all tried to be converted to ASCII. Unknown characters are removed. To install this module type the below command in the terminal. pip install anyascii Example 1: Working with Several languages In this, various different languages like Unicode are set as input, and output is given as converted ASCII characters. Python3 from anyascii import anyascii # checking for Hindi scripthindi_uni = anyascii('नमस्ते विद्यार्थी') print("The translation from hindi Script : " + str(hindi_uni)) # checking for Punjabi scriptpun_uni = anyascii('ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ') print("The translation from Punjabi Script : " + str(pun_uni)) Output : The translation from hindi Script : nmste vidyarthi The translation from Punjabi Script : sti sri akal Example 2: Working with Unicode Emojis and Symbols This library also handles working with emojis and symbols, which are generally Unicode representations. from anyascii import anyascii # working with emoji example emoji_uni = anyascii(' ') print("The ASCII from emojis : " + str(emoji_uni)) # checking for Symbols sym_uni = anyascii(' ☆ M') print("The ASCII from Symbols : " + str(sym_uni)) Output: The ASCII from emojis : :sunglasses: :crown: :apple: The ASCII from Symbols : :heavy_plus_sign: * M python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions 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 Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24818, "s": 24292, "text": "Unicode is the universal character set and a standard to support all the world’s languages. It contains 140,000+ characters used by 150+ scripts along with various symbols. ASCII on the other hand is a subset of Unicode and the most compatible character set, consisting of 128 letters made of English letters, digits, and punctuation, with the remaining being control characters. This article deals with the conversion of a wide range of Unicode characters to a simpler ASCII representation using the Python library anyascii." }, { "code": null, "e": 25146, "s": 24818, "text": "The text is converted from character to character. The mappings for each script are based on conventional schemes. Symbolic characters are converted based on their meaning or appearance. If the input contains ASCII characters, they are untouched, the rest are all tried to be converted to ASCII. Unknown characters are removed." }, { "code": null, "e": 25209, "s": 25146, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 25230, "s": 25209, "text": "pip install anyascii" }, { "code": null, "e": 25272, "s": 25230, "text": "Example 1: Working with Several languages" }, { "code": null, "e": 25392, "s": 25272, "text": "In this, various different languages like Unicode are set as input, and output is given as converted ASCII characters. " }, { "code": null, "e": 25400, "s": 25392, "text": "Python3" }, { "code": "from anyascii import anyascii # checking for Hindi scripthindi_uni = anyascii('नमस्ते विद्यार्थी') print(\"The translation from hindi Script : \" + str(hindi_uni)) # checking for Punjabi scriptpun_uni = anyascii('ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ') print(\"The translation from Punjabi Script : \" + str(pun_uni))", "e": 25704, "s": 25400, "text": null }, { "code": null, "e": 25714, "s": 25704, "text": "Output : " }, { "code": null, "e": 25817, "s": 25714, "text": "The translation from hindi Script : nmste vidyarthi\nThe translation from Punjabi Script : sti sri akal" }, { "code": null, "e": 25868, "s": 25817, "text": "Example 2: Working with Unicode Emojis and Symbols" }, { "code": null, "e": 25973, "s": 25868, "text": "This library also handles working with emojis and symbols, which are generally Unicode representations. " }, { "code": null, "e": 26226, "s": 25973, "text": "from anyascii import anyascii\n\n# working with emoji example\nemoji_uni = anyascii(' ')\n\nprint(\"The ASCII from emojis : \"\n + str(emoji_uni))\n\n# checking for Symbols\nsym_uni = anyascii(' ☆ M')\n\nprint(\"The ASCII from Symbols : \"\n + str(sym_uni))" }, { "code": null, "e": 26234, "s": 26226, "text": "Output:" }, { "code": null, "e": 26334, "s": 26234, "text": "The ASCII from emojis : :sunglasses: :crown: :apple:\nThe ASCII from Symbols : :heavy_plus_sign: * M" }, { "code": null, "e": 26349, "s": 26334, "text": "python-modules" }, { "code": null, "e": 26356, "s": 26349, "text": "Python" }, { "code": null, "e": 26454, "s": 26356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26463, "s": 26454, "text": "Comments" }, { "code": null, "e": 26476, "s": 26463, "text": "Old Comments" }, { "code": null, "e": 26508, "s": 26476, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26563, "s": 26508, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26619, "s": 26563, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26661, "s": 26619, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26703, "s": 26661, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26742, "s": 26703, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26764, "s": 26742, "text": "Defaultdict in Python" }, { "code": null, "e": 26785, "s": 26764, "text": "Python OOPs Concepts" }, { "code": null, "e": 26816, "s": 26785, "text": "Python | os.path.join() method" } ]
How to convert a JavaScript date to UTC? - GeeksforGeeks
22 Apr, 2019 The Javascript date can be converted to UTC by using functions present in Javascript Date object.The toUTCString() method is used to convert a Date object into a string, according to universal time.The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone. By default, JavaScript uses the browser’s time zone and display a date as a full-text string:Fri Apr 12 2019 10:32:15 GMT+0530 (India Standard Time).To create a new Date object we use javascript Date() constructor. Syntax: dateObj.toUTCString() Example-1: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Document </title></head> <body> <div id="date"> </div></body><script> var d = new Date(); var n = d.toUTCString(); var e = document.querySelector("#date"); e.innerHTML = n;</script> </html> Output: Fri, 12 Apr 2019 05:14:31 GMT Example-2: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Document </title></head> <body> <div id="date"> </div></body><script> var d = new Date(); var e = document.querySelector("#date"); e.innerHTML = d.toGMTString();</script> </html> Output: Fri, 12 Apr 2019 05:39:32 GMT ReferencesJavascript Date Object javascript-date Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26646, "s": 26618, "text": "\n22 Apr, 2019" }, { "code": null, "e": 26938, "s": 26646, "text": "The Javascript date can be converted to UTC by using functions present in Javascript Date object.The toUTCString() method is used to convert a Date object into a string, according to universal time.The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone." }, { "code": null, "e": 27153, "s": 26938, "text": "By default, JavaScript uses the browser’s time zone and display a date as a full-text string:Fri Apr 12 2019 10:32:15 GMT+0530 (India Standard Time).To create a new Date object we use javascript Date() constructor." }, { "code": null, "e": 27161, "s": 27153, "text": "Syntax:" }, { "code": null, "e": 27183, "s": 27161, "text": "dateObj.toUTCString()" }, { "code": null, "e": 27194, "s": 27183, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title> Document </title></head> <body> <div id=\"date\"> </div></body><script> var d = new Date(); var n = d.toUTCString(); var e = document.querySelector(\"#date\"); e.innerHTML = n;</script> </html>", "e": 27658, "s": 27194, "text": null }, { "code": null, "e": 27666, "s": 27658, "text": "Output:" }, { "code": null, "e": 27696, "s": 27666, "text": "Fri, 12 Apr 2019 05:14:31 GMT" }, { "code": null, "e": 27707, "s": 27696, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title> Document </title></head> <body> <div id=\"date\"> </div></body><script> var d = new Date(); var e = document.querySelector(\"#date\"); e.innerHTML = d.toGMTString();</script> </html>", "e": 28160, "s": 27707, "text": null }, { "code": null, "e": 28168, "s": 28160, "text": "Output:" }, { "code": null, "e": 28198, "s": 28168, "text": "Fri, 12 Apr 2019 05:39:32 GMT" }, { "code": null, "e": 28231, "s": 28198, "text": "ReferencesJavascript Date Object" }, { "code": null, "e": 28247, "s": 28231, "text": "javascript-date" }, { "code": null, "e": 28254, "s": 28247, "text": "Picked" }, { "code": null, "e": 28265, "s": 28254, "text": "JavaScript" }, { "code": null, "e": 28282, "s": 28265, "text": "Web Technologies" }, { "code": null, "e": 28380, "s": 28282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28420, "s": 28380, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28465, "s": 28420, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28526, "s": 28465, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28598, "s": 28526, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28650, "s": 28598, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28690, "s": 28650, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28723, "s": 28690, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28768, "s": 28723, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28811, "s": 28768, "text": "How to fetch data from an API in ReactJS ?" } ]
Percentage increase in volume of the cube if a side of cube is increased by a given percentage - GeeksforGeeks
27 Mar, 2022 Given here is a cube, whose one side is increased by a given percentage. The task is to find percentage increase in the volume of the cube.Examples: Input: x = 10 Output: 33.1% Input: x = 50 Output: 237.5% Approach In a cube, all sides are equal, so, length = breadth = height let side of the cube = a given percentage increase = x% so, volume before increase = a^3 after increase, new side = a + ax/100 so, new volume = (a + ax/100)^3 = a^3 + (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000 increase in volume = new volume – old volume = (a^3 + (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000) – a^3 = (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000 so, percentage increase in volume = (((ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000)/a^3) * 100 = ((x/100)^3 + 3x/100 + 3x^2/10000) * 100 = x^3/10000 + 3x + 3x^2/100 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentage #include <bits/stdc++.h>using namespace std; void newvol(double x){ cout << "percentage increase " << "in the volume of the cube is " << pow(x, 3) / 10000 + 3 * x + (3 * pow(x, 2)) / 100 << "%" << endl;} // Driver codeint main(){ double x = 10; newvol(x); return 0;} // Java program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentageimport java.io.*; class GFG{ static void newvol(double x){ System.out.print( "percentage increase " +"in the volume of the cube is " + (Math.pow(x, 3) / 10000 + 3 * x + (3 * Math.pow(x, 2)) / 100) ); System.out.print("%");} // Driver codepublic static void main (String[] args){ double x = 10; newvol(x);}} // This code is contributed by anuj_67.. # Python program to find percentage increase# in the volume of the cube# if a side of cube is increased# by a given percentage def newvol(x): print("percentage increase" "in the volume of the cube is ", ((x**(3)) / 10000 + 3 * x + (3 * (x**(2))) / 100),"%"); x = 10;newvol(x); # This code is contributed by PrinciRaj1992 // C# program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentageusing System; class GFG{ static void newvol(double x){ Console.Write( "percentage increase " +"in the volume of the cube is " + (Math.Pow(x, 3) / 10000 + 3 * x + (3 * Math.Pow(x, 2)) / 100) ); Console.Write("%");} // Driver codepublic static void Main (){ double x = 10; newvol(x);}} // This code is contributed by anuj_67.. <script>// javascript program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentagefunction newvol( x){ document.write("percentage increase " + "in the volume of the cube is " + (Math.pow(x, 3) / 10000 + 3 * x + (3 * Math.pow(x, 2)) / 100) + "%" );} // Driver code let x = 10; newvol(x); // This code is contributed by gauravrajput1</script> percentage increase in the volume of the cube is 33.1% Time Complexity: O(log(x)) Auxiliary Space: O(log(x)) vt_m princiraj1992 GauravRajput1 rohitkumarsinghcna Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Convex Hull using Divide and Conquer Algorithm Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26451, "s": 26423, "text": "\n27 Mar, 2022" }, { "code": null, "e": 26602, "s": 26451, "text": "Given here is a cube, whose one side is increased by a given percentage. The task is to find percentage increase in the volume of the cube.Examples: " }, { "code": null, "e": 26660, "s": 26602, "text": "Input: x = 10\nOutput: 33.1%\n\nInput: x = 50\nOutput: 237.5%" }, { "code": null, "e": 26671, "s": 26660, "text": "Approach " }, { "code": null, "e": 26733, "s": 26671, "text": "In a cube, all sides are equal, so, length = breadth = height" }, { "code": null, "e": 26758, "s": 26733, "text": "let side of the cube = a" }, { "code": null, "e": 26789, "s": 26758, "text": "given percentage increase = x%" }, { "code": null, "e": 26822, "s": 26789, "text": "so, volume before increase = a^3" }, { "code": null, "e": 26860, "s": 26822, "text": "after increase, new side = a + ax/100" }, { "code": null, "e": 26939, "s": 26860, "text": "so, new volume = (a + ax/100)^3 = a^3 + (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000" }, { "code": null, "e": 27080, "s": 26939, "text": "increase in volume = new volume – old volume = (a^3 + (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000) – a^3 = (ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000" }, { "code": null, "e": 27239, "s": 27080, "text": "so, percentage increase in volume = (((ax/100)^3 + 3a^3x/100 + 3a^3x^2/10000)/a^3) * 100 = ((x/100)^3 + 3x/100 + 3x^2/10000) * 100 = x^3/10000 + 3x + 3x^2/100" }, { "code": null, "e": 27292, "s": 27239, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27296, "s": 27292, "text": "C++" }, { "code": null, "e": 27301, "s": 27296, "text": "Java" }, { "code": null, "e": 27309, "s": 27301, "text": "Python3" }, { "code": null, "e": 27312, "s": 27309, "text": "C#" }, { "code": null, "e": 27323, "s": 27312, "text": "Javascript" }, { "code": "// C++ program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentage #include <bits/stdc++.h>using namespace std; void newvol(double x){ cout << \"percentage increase \" << \"in the volume of the cube is \" << pow(x, 3) / 10000 + 3 * x + (3 * pow(x, 2)) / 100 << \"%\" << endl;} // Driver codeint main(){ double x = 10; newvol(x); return 0;}", "e": 27769, "s": 27323, "text": null }, { "code": "// Java program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentageimport java.io.*; class GFG{ static void newvol(double x){ System.out.print( \"percentage increase \" +\"in the volume of the cube is \" + (Math.pow(x, 3) / 10000 + 3 * x + (3 * Math.pow(x, 2)) / 100) ); System.out.print(\"%\");} // Driver codepublic static void main (String[] args){ double x = 10; newvol(x);}} // This code is contributed by anuj_67..", "e": 28294, "s": 27769, "text": null }, { "code": "# Python program to find percentage increase# in the volume of the cube# if a side of cube is increased# by a given percentage def newvol(x): print(\"percentage increase\" \"in the volume of the cube is \", ((x**(3)) / 10000 + 3 * x + (3 * (x**(2))) / 100),\"%\"); x = 10;newvol(x); # This code is contributed by PrinciRaj1992", "e": 28656, "s": 28294, "text": null }, { "code": "// C# program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentageusing System; class GFG{ static void newvol(double x){ Console.Write( \"percentage increase \" +\"in the volume of the cube is \" + (Math.Pow(x, 3) / 10000 + 3 * x + (3 * Math.Pow(x, 2)) / 100) ); Console.Write(\"%\");} // Driver codepublic static void Main (){ double x = 10; newvol(x);}} // This code is contributed by anuj_67..", "e": 29156, "s": 28656, "text": null }, { "code": "<script>// javascript program to find percentage increase// in the volume of the cube// if a side of cube is increased// by a given percentagefunction newvol( x){ document.write(\"percentage increase \" + \"in the volume of the cube is \" + (Math.pow(x, 3) / 10000 + 3 * x + (3 * Math.pow(x, 2)) / 100) + \"%\" );} // Driver code let x = 10; newvol(x); // This code is contributed by gauravrajput1</script>", "e": 29609, "s": 29156, "text": null }, { "code": null, "e": 29664, "s": 29609, "text": "percentage increase in the volume of the cube is 33.1%" }, { "code": null, "e": 29693, "s": 29666, "text": "Time Complexity: O(log(x))" }, { "code": null, "e": 29720, "s": 29693, "text": "Auxiliary Space: O(log(x))" }, { "code": null, "e": 29725, "s": 29720, "text": "vt_m" }, { "code": null, "e": 29739, "s": 29725, "text": "princiraj1992" }, { "code": null, "e": 29753, "s": 29739, "text": "GauravRajput1" }, { "code": null, "e": 29772, "s": 29753, "text": "rohitkumarsinghcna" }, { "code": null, "e": 29782, "s": 29772, "text": "Geometric" }, { "code": null, "e": 29795, "s": 29782, "text": "Mathematical" }, { "code": null, "e": 29808, "s": 29795, "text": "Mathematical" }, { "code": null, "e": 29818, "s": 29808, "text": "Geometric" }, { "code": null, "e": 29916, "s": 29818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29969, "s": 29916, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 30020, "s": 29969, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 30054, "s": 30020, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 30112, "s": 30054, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 30159, "s": 30112, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 30189, "s": 30159, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30249, "s": 30189, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30264, "s": 30249, "text": "C++ Data Types" }, { "code": null, "e": 30307, "s": 30264, "text": "Set in C++ Standard Template Library (STL)" } ]
Sorting element of an array by frequency in decreasing order - GeeksforGeeks
21 Apr, 2022 Given an array arr[] of N integers. The task is to sort the array arr[] according to the frequency of elements in decreasing order. Note: If the frequencies of the two elements are the same, then the smaller element should come first. Examples: Input: arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 } Output: 4 4 4 2 2 5 5 6 8 Input: arr[] = { 9, 9, 5, 8, 5 } Output: 5 5 9 9 8 Approach: Store the frequency of all elements in array arr[]. For arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }The frequency array of the above array is:freq[] = { 0, 0, 2, 0, 3, 2, 0, 1, 0, 1} Traverse the frequency array and for all the element having frequency greater than 1, update the value in the array arr[] as: freq[2] = 2 arr[0] = 100000*freq[2] + (100000 – 2) = 299998 freq[4] = 3 arr[1] = 100000*freq[2] + (100000 – 4) = 399996 freq[5] = 2 arr[2] = 100000*freq[2] + (100000 – 5) = 299995 freq[6] = 2 arr[3] = 100000*freq[2] + (100000 – 6) = 199994 freq[8] = 2 arr[4] = 100000*freq[2] + (100000 – 2) = 199994 Now array becomes: arr[] = {299998, 399996, 299995, 199994, 199992, 2, 2, 8, 5} Sort the array arr[] in decreasing order. Traverse the array arr[] and to get the element and frequency of that element as per the updation of array element in step 2, do the following: To get the frequency of current element: frequency = arr[i]/100000; To get the value: value = 100000 – arr[i]%100000 For Example: if arr[i] = 399996 frequency = arr[i]/100000 = 399996/100000 = 3 value = 100000 – arr[i]%100000 = 100000 – 99996 = 4 The element 4 is having frequency 3. For each element in arr[] find the value and frequency(say f) at each index and print the value f number of times. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to sort an array in// decreasing order of their frequency#include "bits/stdc++.h"using namespace std; // Function that return the index// upto all the array elements are// updated.int sortByFreq(int* arr, int n){ // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = max(maxE, arr[i]); } // Create frequency array freq[] int freq[maxE + 1] = { 0 }; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt;} // Function that print array arr[]// elements in sorted ordervoid printSortedArray(int* arr, int cnt){ // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { cout << value << ' '; } }} // Driver codeint main(){ int arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = sizeof(arr) / sizeof(arr[0]); // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order sort(arr, arr + cnt, greater<int>()); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); return 0;} // Java program to sort an array in// decreasing order of their frequencyimport java.util.*; class GFG{ // Function that return the index// upto all the array elements are// updated.static int sortByFreq(Integer []arr, int n){ // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = Math.max(maxE, arr[i]); } // Create frequency array freq[] int freq[] = new int[maxE + 1]; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt;} // Function that print array arr[]// elements in sorted orderstatic void printSortedArray(Integer []arr, int cnt){ // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { System.out.print(value + " "); } }} // Driver codepublic static void main(String[] args){ Integer arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = arr.length; // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order Arrays.sort(arr, Collections.reverseOrder()); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); }} // This code is contributed by sapnasingh4991 # Python program to sort an array in# decreasing order of their frequency # Function that return the index# upto all the array elements are# updated.def sortByFreq(arr, n): # Initialise maxE = -1 maxE = -1; # Find the maximum element of # arr[] for i in range(n): maxE = max(maxE, arr[i]) # Create frequency array freq[] freq = [0]*(maxE + 1); # Update the frequency array as # per the occurrence of element in # arr[] for i in range(n): freq[arr[i]] += 1; # Initialise cnt to 0 cnt = 0; # Traversing freq[] for i in range(maxE+1): # If freq of an element is # greater than 0 update the # value of arr[] at index cnt # & increment cnt if (freq[i] > 0): value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt += 1; # Return cnt return cnt; # Function that print array arr[]# elements in sorted orderdef printSortedArray(arr, cnt): # Traversing arr[] till index cnt for i in range(cnt): # Find frequency of elements frequency = arr[i] / 100000; # Find value at index i value = 100000 - (arr[i] % 100000); # Traversing till frequency # to print value at index i for j in range(int(frequency)): print(value, end=" ") # Driver codeif __name__=='__main__': arr = [ 4, 4, 5, 6, 4, 2, 2, 8, 5 ] # Size of array arr[] n = len(arr) # Function call to get cnt cnt = sortByFreq(arr, n); # Sort the arr[] in decreasing order arr.sort(reverse = True) # Function that prints elements # in decreasing order printSortedArray(arr, cnt); # This code is contributed by Princi Singh // C# program to sort an array in// decreasing order of their frequencyusing System; class GFG { // Function that return the index // upto all the array elements are // updated. static int sortByFreq(int[] arr, int n) { // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = Math.Max(maxE, arr[i]); } // Create frequency array freq[] int[] freq = new int[maxE + 1]; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt; } // Function that print array arr[] // elements in sorted order static void printSortedArray(int[] arr, int cnt) { // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { Console.Write(value + " "); } } } // Driver code public static void Main() { int[] arr = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = arr.Length; // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order Array.Sort(arr); Array.Reverse(arr); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); }} // This code is contributed by subhamahato348 <script> // JavaScript program to sort an array in // decreasing order of their frequency // Function that return the index // upto all the array elements are // updated. function sortByFreq(arr, n) { // Initialise maxE = -1 var maxE = -1; // Find the maximum element of // arr[] for (var i = 0; i < n; i++) { maxE = Math.max(maxE, arr[i]); } // Create frequency array freq[] var freq = new Array(maxE + 1).fill(0); // Update the frequency array as // per the occurrence of element in // arr[] for (var i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 var cnt = 0; // Traversing freq[] for (var i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { var value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt; } // Function that print array arr[] // elements in sorted order function printSortedArray(arr, cnt) { // Traversing arr[] till index cnt for (var i = 0; i < cnt; i++) { // Find frequency of elements var frequency = parseInt(arr[i] / 100000); // Find value at index i var value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (var j = 0; j < frequency; j++) { document.write(value + " "); } } } // Driver code var arr = [4, 4, 5, 6, 4, 2, 2, 8, 5]; // Size of array arr[] var n = arr.length; // Function call to get cnt var cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order arr.sort((a, b) => b - a); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); </script> 4 4 4 2 2 5 5 6 8 Time Complexity: O(N*log N) Auxiliary Space: O(N) STL Pair and Comparator based approach : Approach: 1. Store the frequency of each element in a map. 2. Iterate the map and store the each element and it’s frequency in a vector of pairs. 3. Pass a comparator which sorts the elements in decreasing order of their frequency and by elements value if frequency is equal. 4.Push the elements their frequency number of times inside the final array. C++ Python3 Javascript #include<bits/stdc++.h>using namespace std;bool compare(pair<int,int>p1,pair<int,int>p2){ if(p1.second==p2.second) //if frequency is equal { return p1.first<p2.first; //return the smaller value } return p1.second>p2.second; //return the element with greater frequency}int main(){ vector<int>arr={4,4,5,6,4,2,2,8,5}; int n=arr.size(); map<int,int>m; for(int i=0;i<n;i++) { m[arr[i]]+=1; } vector<pair<int,int>>a; for(auto it=m.begin();it!=m.end();it++) { a.push_back(make_pair(it->first,it->second)); //making pair of element and it's frequency } sort(a.begin(),a.end(),compare); vector<int>ans; for(auto x:a) { while(x.second--) { ans.push_back(x.first); } } for(auto x:ans) { cout<<x<<" "; } return 0;} # Python code for the approachfrom functools import cmp_to_key def compare(p1, p2): if(p1[1] == p2[1]): #if frequency is equal return p1[0] - p2[0] #return the smaller value return p2[1] - p1[1] #return the element with greater frequency # driver codearr = [4, 4, 5, 6, 4, 2, 2, 8, 5]n = len(arr)m = {}for i in range(n): if(arr[i] in m): m[arr[i]] = m[arr[i]] + 1 else: m[arr[i]] = 1 a = []for x,y in m.items(): a.append([x,y]) #making pair of element and it's frequency a.sort(key = cmp_to_key(compare))ans = []for x in a: while(x[1]): ans.append(x[0]) x[1] -= 1 for x in ans: print(x, end = " ") # This code is contributed by shinjanpatra <script> // JavaScript code for the approachfunction compare(p1, p2){ if(p1[1] == p2[1]) //if frequency is equal { return p1[0] - p2[0]; //return the smaller value } return p2[1] - p1[1]; //return the element with greater frequency} // driver codelet arr = [4,4,5,6,4,2,2,8,5];let n = arr.length;let m = new Map();for(let i = 0; i < n; i++){ if(m.has(arr[i])){ m.set(arr[i], m.get(arr[i]) + 1); } else m.set(arr[i],1);}let a = [];for(let [x,y] of m){ a.push([x,y]); //making pair of element and it's frequency}a.sort(compare);let ans = [];for(let x of a){ while(x[1]--){ ans.push(x[0]); }}for(let x of ans){ document.write(x," ");} // This code is contributed by shinjanpatra </script> 4 4 4 2 2 5 5 6 8 princi singh sapnasingh4991 subhammahato348 rdtank arorakashish0911 akshaysingh98088 adityamutharia shinjanpatra frequency-counting Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26067, "s": 26039, "text": "\n21 Apr, 2022" }, { "code": null, "e": 26302, "s": 26067, "text": "Given an array arr[] of N integers. The task is to sort the array arr[] according to the frequency of elements in decreasing order. Note: If the frequencies of the two elements are the same, then the smaller element should come first." }, { "code": null, "e": 26314, "s": 26302, "text": "Examples: " }, { "code": null, "e": 26385, "s": 26314, "text": "Input: arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 } Output: 4 4 4 2 2 5 5 6 8" }, { "code": null, "e": 26439, "s": 26385, "text": "Input: arr[] = { 9, 9, 5, 8, 5 } Output: 5 5 9 9 8 " }, { "code": null, "e": 26450, "s": 26439, "text": "Approach: " }, { "code": null, "e": 26502, "s": 26450, "text": "Store the frequency of all elements in array arr[]." }, { "code": null, "e": 26626, "s": 26502, "text": "For arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }The frequency array of the above array is:freq[] = { 0, 0, 2, 0, 3, 2, 0, 1, 0, 1}" }, { "code": null, "e": 26752, "s": 26626, "text": "Traverse the frequency array and for all the element having frequency greater than 1, update the value in the array arr[] as:" }, { "code": null, "e": 27134, "s": 26752, "text": "freq[2] = 2 arr[0] = 100000*freq[2] + (100000 – 2) = 299998 freq[4] = 3 arr[1] = 100000*freq[2] + (100000 – 4) = 399996 freq[5] = 2 arr[2] = 100000*freq[2] + (100000 – 5) = 299995 freq[6] = 2 arr[3] = 100000*freq[2] + (100000 – 6) = 199994 freq[8] = 2 arr[4] = 100000*freq[2] + (100000 – 2) = 199994 Now array becomes: arr[] = {299998, 399996, 299995, 199994, 199992, 2, 2, 8, 5} " }, { "code": null, "e": 27176, "s": 27134, "text": "Sort the array arr[] in decreasing order." }, { "code": null, "e": 27320, "s": 27176, "text": "Traverse the array arr[] and to get the element and frequency of that element as per the updation of array element in step 2, do the following:" }, { "code": null, "e": 27439, "s": 27320, "text": "To get the frequency of current element: frequency = arr[i]/100000; To get the value: value = 100000 – arr[i]%100000 " }, { "code": null, "e": 27454, "s": 27439, "text": "For Example: " }, { "code": null, "e": 27610, "s": 27454, "text": "if arr[i] = 399996 frequency = arr[i]/100000 = 399996/100000 = 3 value = 100000 – arr[i]%100000 = 100000 – 99996 = 4 The element 4 is having frequency 3. " }, { "code": null, "e": 27725, "s": 27610, "text": "For each element in arr[] find the value and frequency(say f) at each index and print the value f number of times." }, { "code": null, "e": 27778, "s": 27725, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27782, "s": 27778, "text": "C++" }, { "code": null, "e": 27787, "s": 27782, "text": "Java" }, { "code": null, "e": 27795, "s": 27787, "text": "Python3" }, { "code": null, "e": 27798, "s": 27795, "text": "C#" }, { "code": null, "e": 27809, "s": 27798, "text": "Javascript" }, { "code": "// C++ program to sort an array in// decreasing order of their frequency#include \"bits/stdc++.h\"using namespace std; // Function that return the index// upto all the array elements are// updated.int sortByFreq(int* arr, int n){ // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = max(maxE, arr[i]); } // Create frequency array freq[] int freq[maxE + 1] = { 0 }; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt;} // Function that print array arr[]// elements in sorted ordervoid printSortedArray(int* arr, int cnt){ // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { cout << value << ' '; } }} // Driver codeint main(){ int arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = sizeof(arr) / sizeof(arr[0]); // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order sort(arr, arr + cnt, greater<int>()); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); return 0;}", "e": 29734, "s": 27809, "text": null }, { "code": "// Java program to sort an array in// decreasing order of their frequencyimport java.util.*; class GFG{ // Function that return the index// upto all the array elements are// updated.static int sortByFreq(Integer []arr, int n){ // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = Math.max(maxE, arr[i]); } // Create frequency array freq[] int freq[] = new int[maxE + 1]; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt;} // Function that print array arr[]// elements in sorted orderstatic void printSortedArray(Integer []arr, int cnt){ // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { System.out.print(value + \" \"); } }} // Driver codepublic static void main(String[] args){ Integer arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = arr.length; // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order Arrays.sort(arr, Collections.reverseOrder()); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); }} // This code is contributed by sapnasingh4991", "e": 31766, "s": 29734, "text": null }, { "code": "# Python program to sort an array in# decreasing order of their frequency # Function that return the index# upto all the array elements are# updated.def sortByFreq(arr, n): # Initialise maxE = -1 maxE = -1; # Find the maximum element of # arr[] for i in range(n): maxE = max(maxE, arr[i]) # Create frequency array freq[] freq = [0]*(maxE + 1); # Update the frequency array as # per the occurrence of element in # arr[] for i in range(n): freq[arr[i]] += 1; # Initialise cnt to 0 cnt = 0; # Traversing freq[] for i in range(maxE+1): # If freq of an element is # greater than 0 update the # value of arr[] at index cnt # & increment cnt if (freq[i] > 0): value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt += 1; # Return cnt return cnt; # Function that print array arr[]# elements in sorted orderdef printSortedArray(arr, cnt): # Traversing arr[] till index cnt for i in range(cnt): # Find frequency of elements frequency = arr[i] / 100000; # Find value at index i value = 100000 - (arr[i] % 100000); # Traversing till frequency # to print value at index i for j in range(int(frequency)): print(value, end=\" \") # Driver codeif __name__=='__main__': arr = [ 4, 4, 5, 6, 4, 2, 2, 8, 5 ] # Size of array arr[] n = len(arr) # Function call to get cnt cnt = sortByFreq(arr, n); # Sort the arr[] in decreasing order arr.sort(reverse = True) # Function that prints elements # in decreasing order printSortedArray(arr, cnt); # This code is contributed by Princi Singh", "e": 33505, "s": 31766, "text": null }, { "code": "// C# program to sort an array in// decreasing order of their frequencyusing System; class GFG { // Function that return the index // upto all the array elements are // updated. static int sortByFreq(int[] arr, int n) { // Initialise maxE = -1 int maxE = -1; // Find the maximum element of // arr[] for (int i = 0; i < n; i++) { maxE = Math.Max(maxE, arr[i]); } // Create frequency array freq[] int[] freq = new int[maxE + 1]; // Update the frequency array as // per the occurrence of element in // arr[] for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 int cnt = 0; // Traversing freq[] for (int i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { int value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt; } // Function that print array arr[] // elements in sorted order static void printSortedArray(int[] arr, int cnt) { // Traversing arr[] till index cnt for (int i = 0; i < cnt; i++) { // Find frequency of elements int frequency = arr[i] / 100000; // Find value at index i int value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (int j = 0; j < frequency; j++) { Console.Write(value + \" \"); } } } // Driver code public static void Main() { int[] arr = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }; // Size of array arr[] int n = arr.Length; // Function call to get cnt int cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order Array.Sort(arr); Array.Reverse(arr); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); }} // This code is contributed by subhamahato348", "e": 35475, "s": 33505, "text": null }, { "code": "<script> // JavaScript program to sort an array in // decreasing order of their frequency // Function that return the index // upto all the array elements are // updated. function sortByFreq(arr, n) { // Initialise maxE = -1 var maxE = -1; // Find the maximum element of // arr[] for (var i = 0; i < n; i++) { maxE = Math.max(maxE, arr[i]); } // Create frequency array freq[] var freq = new Array(maxE + 1).fill(0); // Update the frequency array as // per the occurrence of element in // arr[] for (var i = 0; i < n; i++) { freq[arr[i]]++; } // Initialise cnt to 0 var cnt = 0; // Traversing freq[] for (var i = 0; i <= maxE; i++) { // If freq of an element is // greater than 0 update the // value of arr[] at index cnt // & increment cnt if (freq[i] > 0) { var value = 100000 - i; arr[cnt] = 100000 * freq[i] + value; cnt++; } } // Return cnt return cnt; } // Function that print array arr[] // elements in sorted order function printSortedArray(arr, cnt) { // Traversing arr[] till index cnt for (var i = 0; i < cnt; i++) { // Find frequency of elements var frequency = parseInt(arr[i] / 100000); // Find value at index i var value = 100000 - (arr[i] % 100000); // Traversing till frequency // to print value at index i for (var j = 0; j < frequency; j++) { document.write(value + \" \"); } } } // Driver code var arr = [4, 4, 5, 6, 4, 2, 2, 8, 5]; // Size of array arr[] var n = arr.length; // Function call to get cnt var cnt = sortByFreq(arr, n); // Sort the arr[] in decreasing order arr.sort((a, b) => b - a); // Function that prints elements // in decreasing order printSortedArray(arr, cnt); </script>", "e": 37572, "s": 35475, "text": null }, { "code": null, "e": 37590, "s": 37572, "text": "4 4 4 2 2 5 5 6 8" }, { "code": null, "e": 37642, "s": 37592, "text": "Time Complexity: O(N*log N) Auxiliary Space: O(N)" }, { "code": null, "e": 37683, "s": 37642, "text": "STL Pair and Comparator based approach :" }, { "code": null, "e": 37693, "s": 37683, "text": "Approach:" }, { "code": null, "e": 37742, "s": 37693, "text": "1. Store the frequency of each element in a map." }, { "code": null, "e": 37829, "s": 37742, "text": "2. Iterate the map and store the each element and it’s frequency in a vector of pairs." }, { "code": null, "e": 37959, "s": 37829, "text": "3. Pass a comparator which sorts the elements in decreasing order of their frequency and by elements value if frequency is equal." }, { "code": null, "e": 38035, "s": 37959, "text": "4.Push the elements their frequency number of times inside the final array." }, { "code": null, "e": 38039, "s": 38035, "text": "C++" }, { "code": null, "e": 38047, "s": 38039, "text": "Python3" }, { "code": null, "e": 38058, "s": 38047, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std;bool compare(pair<int,int>p1,pair<int,int>p2){ if(p1.second==p2.second) //if frequency is equal { return p1.first<p2.first; //return the smaller value } return p1.second>p2.second; //return the element with greater frequency}int main(){ vector<int>arr={4,4,5,6,4,2,2,8,5}; int n=arr.size(); map<int,int>m; for(int i=0;i<n;i++) { m[arr[i]]+=1; } vector<pair<int,int>>a; for(auto it=m.begin();it!=m.end();it++) { a.push_back(make_pair(it->first,it->second)); //making pair of element and it's frequency } sort(a.begin(),a.end(),compare); vector<int>ans; for(auto x:a) { while(x.second--) { ans.push_back(x.first); } } for(auto x:ans) { cout<<x<<\" \"; } return 0;}", "e": 38887, "s": 38058, "text": null }, { "code": "# Python code for the approachfrom functools import cmp_to_key def compare(p1, p2): if(p1[1] == p2[1]): #if frequency is equal return p1[0] - p2[0] #return the smaller value return p2[1] - p1[1] #return the element with greater frequency # driver codearr = [4, 4, 5, 6, 4, 2, 2, 8, 5]n = len(arr)m = {}for i in range(n): if(arr[i] in m): m[arr[i]] = m[arr[i]] + 1 else: m[arr[i]] = 1 a = []for x,y in m.items(): a.append([x,y]) #making pair of element and it's frequency a.sort(key = cmp_to_key(compare))ans = []for x in a: while(x[1]): ans.append(x[0]) x[1] -= 1 for x in ans: print(x, end = \" \") # This code is contributed by shinjanpatra", "e": 39592, "s": 38887, "text": null }, { "code": "<script> // JavaScript code for the approachfunction compare(p1, p2){ if(p1[1] == p2[1]) //if frequency is equal { return p1[0] - p2[0]; //return the smaller value } return p2[1] - p1[1]; //return the element with greater frequency} // driver codelet arr = [4,4,5,6,4,2,2,8,5];let n = arr.length;let m = new Map();for(let i = 0; i < n; i++){ if(m.has(arr[i])){ m.set(arr[i], m.get(arr[i]) + 1); } else m.set(arr[i],1);}let a = [];for(let [x,y] of m){ a.push([x,y]); //making pair of element and it's frequency}a.sort(compare);let ans = [];for(let x of a){ while(x[1]--){ ans.push(x[0]); }}for(let x of ans){ document.write(x,\" \");} // This code is contributed by shinjanpatra </script>", "e": 40332, "s": 39592, "text": null }, { "code": null, "e": 40351, "s": 40332, "text": "4 4 4 2 2 5 5 6 8 " }, { "code": null, "e": 40366, "s": 40353, "text": "princi singh" }, { "code": null, "e": 40381, "s": 40366, "text": "sapnasingh4991" }, { "code": null, "e": 40397, "s": 40381, "text": "subhammahato348" }, { "code": null, "e": 40404, "s": 40397, "text": "rdtank" }, { "code": null, "e": 40421, "s": 40404, "text": "arorakashish0911" }, { "code": null, "e": 40438, "s": 40421, "text": "akshaysingh98088" }, { "code": null, "e": 40453, "s": 40438, "text": "adityamutharia" }, { "code": null, "e": 40466, "s": 40453, "text": "shinjanpatra" }, { "code": null, "e": 40485, "s": 40466, "text": "frequency-counting" }, { "code": null, "e": 40492, "s": 40485, "text": "Arrays" }, { "code": null, "e": 40500, "s": 40492, "text": "Sorting" }, { "code": null, "e": 40507, "s": 40500, "text": "Arrays" }, { "code": null, "e": 40515, "s": 40507, "text": "Sorting" }, { "code": null, "e": 40613, "s": 40515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40640, "s": 40613, "text": "Count pairs with given sum" }, { "code": null, "e": 40671, "s": 40640, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 40696, "s": 40671, "text": "Window Sliding Technique" }, { "code": null, "e": 40734, "s": 40696, "text": "Reversal algorithm for array rotation" } ]
lvalue and rvalue in C language - GeeksforGeeks
27 Sep, 2017 L-value: “l-value” refers to memory location which identifies an object. l-value may appear as either left hand or right hand side of an assignment operator(=). l-value often represents as identifier. Expressions referring to modifiable locations are called “modifiable l-values“. A modifiable l-value cannot have an array type, an incomplete type, or a type with the const attribute. For structures and unions to be modifiable lvalues, they must not have any members with the const attribute. The name of the identifier denotes a storage location, while the value of the variable is the value stored at that location. An identifier is a modifiable lvalue if it refers to a memory location and if its type is arithmetic, structure, union, or pointer. For example, if ptr is a pointer to a storage region, then *ptr is a modifiable l-value that designates the storage region to which ptr points. In C, the concept was renamed as “locator value”, and referred to expressions that locate (designate) objects. The l-value is one of the following: The name of the variable of any type i.e, an identifier of integral, floating, pointer, structure, or union type.A subscript ([ ]) expression that does not evaluate to an array.A unary-indirection (*) expression that does not refer to an arrayAn l-value expression in parentheses.A const object (a nonmodifiable l-value).The result of indirection through a pointer, provided that it isn’t a function pointer.The result of member access through pointer(-> or .) The name of the variable of any type i.e, an identifier of integral, floating, pointer, structure, or union type. A subscript ([ ]) expression that does not evaluate to an array. A unary-indirection (*) expression that does not refer to an array An l-value expression in parentheses. A const object (a nonmodifiable l-value). The result of indirection through a pointer, provided that it isn’t a function pointer. The result of member access through pointer(-> or .) // declare a an object of type 'int'int a; // a is an expression referring to an// 'int' object as l-valuea = 1; int b = a; // Ok, as l-value can appear on right // Switch the operand around '=' operator9 = a; // Compilation error:// as assignment is trying to change the// value of assignment operator R-value: r-value” refers to data value that is stored at some address in memory. A r-value is an expression that can’t have a value assigned to it which means r-value can appear on right but not on left hand side of an assignment operator(=). // declare a, b an object of type 'int'int a = 1, b; a + 1 = b; // Error, left expression is // is not variable(a + 1) // declare pointer variable 'p', and 'q'int *p, *q; // *p, *q are lvalue *p = 1; // valid l-value assignment // below is invalid - "p + 2" is not an l-value // p + 2 = 18; q = p + 5; // valid - "p + 5" is an r-value // Below is valid - dereferencing pointer// expression gives an l-value*(p + 2) = 18; p = &b; int arr[20]; // arr[12] is an lvalue; equivalent // to *(arr+12) // Note: arr itself is also an lvalue struct S { int m; }; struct S obj; // obj and obj.m are lvalues // ptr-> is an lvalue; equivalent to (*ptr).m// Note: ptr and *ptr are also lvaluesstruct S* ptr = &obj; Note: The unary & (address-of) operator requires an lvalue as its operand. That is, &n is a valid expression only if n is an lvalue. Thus, an expression such as &12 is an error. Again, 12 does not refer to an object, so it’s not addressable. For instance, // declare a as int variable and// 'p' as pointer variableint a, *p; p = &a; // ok, assignment of address // at l-value &a = p; // error: &a is an r-value int x, y; ( x < y ? y : x) = 0; // It's valid because the ternary // expression preserves the "lvalue-ness" // of both its possible return values Remembering the mnemonic, that lvalues can appear on the left of an assignment operator while rvalues can appear on the right Reference:https://msdn.microsoft.com/en-us/library/bkbs2cds.aspx This article is contributed by Shubham Bansal. 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. C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Substring in C++ rand() and srand() in C/C++ fork() in C std::string class in C++ Converting Strings to Numbers in C/C++ Enumeration (or enum) in C Command line arguments in C/C++
[ { "code": null, "e": 25795, "s": 25767, "text": "\n27 Sep, 2017" }, { "code": null, "e": 25996, "s": 25795, "text": "L-value: “l-value” refers to memory location which identifies an object. l-value may appear as either left hand or right hand side of an assignment operator(=). l-value often represents as identifier." }, { "code": null, "e": 26414, "s": 25996, "text": "Expressions referring to modifiable locations are called “modifiable l-values“. A modifiable l-value cannot have an array type, an incomplete type, or a type with the const attribute. For structures and unions to be modifiable lvalues, they must not have any members with the const attribute. The name of the identifier denotes a storage location, while the value of the variable is the value stored at that location." }, { "code": null, "e": 26690, "s": 26414, "text": "An identifier is a modifiable lvalue if it refers to a memory location and if its type is arithmetic, structure, union, or pointer. For example, if ptr is a pointer to a storage region, then *ptr is a modifiable l-value that designates the storage region to which ptr points." }, { "code": null, "e": 26838, "s": 26690, "text": "In C, the concept was renamed as “locator value”, and referred to expressions that locate (designate) objects. The l-value is one of the following:" }, { "code": null, "e": 27299, "s": 26838, "text": "The name of the variable of any type i.e, an identifier of integral, floating, pointer, structure, or union type.A subscript ([ ]) expression that does not evaluate to an array.A unary-indirection (*) expression that does not refer to an arrayAn l-value expression in parentheses.A const object (a nonmodifiable l-value).The result of indirection through a pointer, provided that it isn’t a function pointer.The result of member access through pointer(-> or .)" }, { "code": null, "e": 27413, "s": 27299, "text": "The name of the variable of any type i.e, an identifier of integral, floating, pointer, structure, or union type." }, { "code": null, "e": 27478, "s": 27413, "text": "A subscript ([ ]) expression that does not evaluate to an array." }, { "code": null, "e": 27545, "s": 27478, "text": "A unary-indirection (*) expression that does not refer to an array" }, { "code": null, "e": 27583, "s": 27545, "text": "An l-value expression in parentheses." }, { "code": null, "e": 27625, "s": 27583, "text": "A const object (a nonmodifiable l-value)." }, { "code": null, "e": 27713, "s": 27625, "text": "The result of indirection through a pointer, provided that it isn’t a function pointer." }, { "code": null, "e": 27766, "s": 27713, "text": "The result of member access through pointer(-> or .)" }, { "code": "// declare a an object of type 'int'int a; // a is an expression referring to an// 'int' object as l-valuea = 1; int b = a; // Ok, as l-value can appear on right // Switch the operand around '=' operator9 = a; // Compilation error:// as assignment is trying to change the// value of assignment operator", "e": 28070, "s": 27766, "text": null }, { "code": null, "e": 28313, "s": 28070, "text": "R-value: r-value” refers to data value that is stored at some address in memory. A r-value is an expression that can’t have a value assigned to it which means r-value can appear on right but not on left hand side of an assignment operator(=)." }, { "code": "// declare a, b an object of type 'int'int a = 1, b; a + 1 = b; // Error, left expression is // is not variable(a + 1) // declare pointer variable 'p', and 'q'int *p, *q; // *p, *q are lvalue *p = 1; // valid l-value assignment // below is invalid - \"p + 2\" is not an l-value // p + 2 = 18; q = p + 5; // valid - \"p + 5\" is an r-value // Below is valid - dereferencing pointer// expression gives an l-value*(p + 2) = 18; p = &b; int arr[20]; // arr[12] is an lvalue; equivalent // to *(arr+12) // Note: arr itself is also an lvalue struct S { int m; }; struct S obj; // obj and obj.m are lvalues // ptr-> is an lvalue; equivalent to (*ptr).m// Note: ptr and *ptr are also lvaluesstruct S* ptr = &obj;", "e": 29052, "s": 28313, "text": null }, { "code": null, "e": 29308, "s": 29052, "text": "Note: The unary & (address-of) operator requires an lvalue as its operand. That is, &n is a valid expression only if n is an lvalue. Thus, an expression such as &12 is an error. Again, 12 does not refer to an object, so it’s not addressable. For instance," }, { "code": "// declare a as int variable and// 'p' as pointer variableint a, *p; p = &a; // ok, assignment of address // at l-value &a = p; // error: &a is an r-value int x, y; ( x < y ? y : x) = 0; // It's valid because the ternary // expression preserves the \"lvalue-ness\" // of both its possible return values", "e": 29653, "s": 29308, "text": null }, { "code": null, "e": 29779, "s": 29653, "text": "Remembering the mnemonic, that lvalues can appear on the left of an assignment operator while rvalues can appear on the right" }, { "code": null, "e": 29844, "s": 29779, "text": "Reference:https://msdn.microsoft.com/en-us/library/bkbs2cds.aspx" }, { "code": null, "e": 30146, "s": 29844, "text": "This article is contributed by Shubham Bansal. 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": 30157, "s": 30146, "text": "C Language" }, { "code": null, "e": 30255, "s": 30157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30290, "s": 30255, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30336, "s": 30290, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30358, "s": 30336, "text": "Function Pointer in C" }, { "code": null, "e": 30375, "s": 30358, "text": "Substring in C++" }, { "code": null, "e": 30403, "s": 30375, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 30415, "s": 30403, "text": "fork() in C" }, { "code": null, "e": 30440, "s": 30415, "text": "std::string class in C++" }, { "code": null, "e": 30479, "s": 30440, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 30506, "s": 30479, "text": "Enumeration (or enum) in C" } ]
How to get the n-largest values of an array using NumPy? - GeeksforGeeks
29 Aug, 2020 Let’s see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing. Syntax: numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None) Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr. Let’s see an example: Example 1: Getting the 1st largest value from a NumPy array. Python3 # import libraryimport numpy as np # create numpy 1d-arrayarr = np.array([2, 0, 1, 5, 4, 1, 9]) print("Given array:", arr) # sort an array in# ascending order # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr) # sorted arraysorted_array = arr[sorted_index_array] print("Sorted array:", sorted_array) # we want 1 largest valuen = 1 # we are using negative# indexing concept # take n largest valuerslt = sorted_array[-n : ] # show the outputprint("{} largest value:".format(n), rslt[0]) Output: Given array: [2 0 1 5 4 1 9] Sorted array: [0 1 1 2 4 5 9] 1 largest value: 9 Example 2: Getting the 3-largest values from a NumPy array. Python3 # import libraryimport numpy as np # create numpy 1d-arrayarr = np.array([2, 0, 1, 5, 4, 1, 9]) print("Given array:", arr) # sort an array in# ascending order # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr) # sorted arraysorted_array = arr[sorted_index_array] print("Sorted array:", sorted_array) # we want 3 largest valuen = 3 # we are using negative# indexing concept # find n largest valuerslt = sorted_array[-n : ] # show the outputprint("{} largest value:".format(n), rslt) Output: Given array: [2 0 1 5 4 1 9] Sorted array: [0 1 1 2 4 5 9] 3 largest value: [4 5 9] Python numpy-Mathematical Function Python numpy-program Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25808, "s": 25537, "text": "Let’s see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing." }, { "code": null, "e": 25874, "s": 25808, "text": "Syntax: numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None)" }, { "code": null, "e": 26031, "s": 25874, "text": "Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr." }, { "code": null, "e": 26053, "s": 26031, "text": "Let’s see an example:" }, { "code": null, "e": 26114, "s": 26053, "text": "Example 1: Getting the 1st largest value from a NumPy array." }, { "code": null, "e": 26122, "s": 26114, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create numpy 1d-arrayarr = np.array([2, 0, 1, 5, 4, 1, 9]) print(\"Given array:\", arr) # sort an array in# ascending order # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr) # sorted arraysorted_array = arr[sorted_index_array] print(\"Sorted array:\", sorted_array) # we want 1 largest valuen = 1 # we are using negative# indexing concept # take n largest valuerslt = sorted_array[-n : ] # show the outputprint(\"{} largest value:\".format(n), rslt[0])", "e": 26681, "s": 26122, "text": null }, { "code": null, "e": 26689, "s": 26681, "text": "Output:" }, { "code": null, "e": 26768, "s": 26689, "text": "Given array: [2 0 1 5 4 1 9]\nSorted array: [0 1 1 2 4 5 9]\n1 largest value: 9\n" }, { "code": null, "e": 26828, "s": 26768, "text": "Example 2: Getting the 3-largest values from a NumPy array." }, { "code": null, "e": 26836, "s": 26828, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create numpy 1d-arrayarr = np.array([2, 0, 1, 5, 4, 1, 9]) print(\"Given array:\", arr) # sort an array in# ascending order # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr) # sorted arraysorted_array = arr[sorted_index_array] print(\"Sorted array:\", sorted_array) # we want 3 largest valuen = 3 # we are using negative# indexing concept # find n largest valuerslt = sorted_array[-n : ] # show the outputprint(\"{} largest value:\".format(n), rslt)", "e": 27392, "s": 26836, "text": null }, { "code": null, "e": 27400, "s": 27392, "text": "Output:" }, { "code": null, "e": 27485, "s": 27400, "text": "Given array: [2 0 1 5 4 1 9]\nSorted array: [0 1 1 2 4 5 9]\n3 largest value: [4 5 9]\n" }, { "code": null, "e": 27520, "s": 27485, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27541, "s": 27520, "text": "Python numpy-program" }, { "code": null, "e": 27554, "s": 27541, "text": "Python-numpy" }, { "code": null, "e": 27561, "s": 27554, "text": "Python" }, { "code": null, "e": 27659, "s": 27561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27691, "s": 27659, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27733, "s": 27691, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27775, "s": 27733, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27831, "s": 27775, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27858, "s": 27831, "text": "Python Classes and Objects" }, { "code": null, "e": 27897, "s": 27858, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27928, "s": 27897, "text": "Python | os.path.join() method" }, { "code": null, "e": 27950, "s": 27928, "text": "Defaultdict in Python" }, { "code": null, "e": 27979, "s": 27950, "text": "Create a directory in Python" } ]
CSS - Responsive
Responsive web design provides an optimal experience, easy reading and easy navigation with a minimum of resizing on different devices such as desktops, mobiles and tabs). Below image shows the responsive structure of web pages. <html> <head> <style> body { font: 600 14px/24px "Open Sans", "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", Sans-Serif; } h1 { color: #9799a7; font-size: 14px; font-weight: bold; margin-bottom: 6px; } .container:before, .container:after { content: ""; display: table; } .container:after { clear: both; } .container { background: #eaeaed; margin-bottom: 24px; *zoom: 1; } .container-75 { width: 75%; } .container-50 { margin-bottom: 0; width: 50%; } .container, section, aside { border-radius: 6px; } section, aside { background: #2db34a; color: #fff; margin: 1.858736059%; padding: 20px 0; text-align: center; } section { float: left; width: 63.197026%; } aside { float: right; width: 29.3680297%; } </style> </head> <body> <h1>100% Wide Container</h1> <div class = "container"> <section>Section</section> <aside>Aside</aside> </div> <h1>75% Wide Container</h1> <div class = "container container-75"> <section>Section</section> <aside>Aside</aside> </div> <h1>50% Wide Container</h1> <div class = "container container-50"> <section>Section</section> <aside>Aside</aside> </div> </body> </html> It will produce the following result − Media queries is for different style rules for different size devices such as mobiles, desktops, etc., <html> <head> <style> body { background-color: lightpink; } @media screen and (max-width: 420px) { body { background-color: lightblue; } } </style> </head> <body> <p> If screen size is less than 420px, then it will show lightblue color, or else it will show light pink color </p> </body> </html> It will produce the following result − If screen size is less than 420px,then it will show lightblue color, or else it will show light pink color Bootstrap is most popular web design framework based on HTML,CSS and Java script and it helps you to design web pages in responsive way for all devices. <html> <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <style> body { color:green; } </style> </head> <body> <div class = "container"> <div class = "jumbotron"> <h1>Tutorials point</h1> <p> Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. </p> </div> <div class = "row"> <div class = "col-md-4"> <h2>Android</h2> <p> Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. </p> </div> <div class = "col-md-4"> <h2>CSS</h2> <p> Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable. </p> </div> <div class = "col-md-4"> <h2>Java</h2> <p> Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java. </p> </div> </div> </body> </html> It will produce the following result − Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable. Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2798, "s": 2626, "text": "Responsive web design provides an optimal experience, easy reading and easy navigation with a minimum of resizing on different devices such as desktops, mobiles and tabs)." }, { "code": null, "e": 2855, "s": 2798, "text": "Below image shows the responsive structure of web pages." }, { "code": null, "e": 4767, "s": 2855, "text": "<html>\n <head>\n <style>\n body {\n font: 600 14px/24px \"Open Sans\", \n \"HelveticaNeue-Light\", \n \"Helvetica Neue Light\", \n \"Helvetica Neue\", \n Helvetica, Arial, \n \"Lucida Grande\", \n Sans-Serif;\n }\n h1 {\n color: #9799a7;\n font-size: 14px;\n font-weight: bold;\n margin-bottom: 6px;\n }\n .container:before, .container:after {\n content: \"\";\n display: table;\n }\n .container:after {\n clear: both;\n }\n .container {\n background: #eaeaed;\n margin-bottom: 24px;\n *zoom: 1;\n }\n .container-75 {\n width: 75%;\n }\n .container-50 {\n margin-bottom: 0;\n width: 50%;\n }\n .container, section, aside {\n border-radius: 6px;\n }\n section, aside {\n background: #2db34a;\n color: #fff;\n margin: 1.858736059%;\n padding: 20px 0;\n text-align: center;\n }\n section {\n float: left;\n width: 63.197026%;\n }\n aside {\n float: right;\n width: 29.3680297%;\n }\n </style>\n </head>\n \n <body>\n \n <h1>100% Wide Container</h1>\n \n <div class = \"container\">\n <section>Section</section>\n <aside>Aside</aside>\n </div>\n \n <h1>75% Wide Container</h1>\n \n <div class = \"container container-75\">\n <section>Section</section>\n <aside>Aside</aside>\n </div>\n \n <h1>50% Wide Container</h1>\n \n <div class = \"container container-50\">\n <section>Section</section>\n <aside>Aside</aside>\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 4806, "s": 4767, "text": "It will produce the following result −" }, { "code": null, "e": 4909, "s": 4806, "text": "Media queries is for different style rules for different size devices such as mobiles, desktops, etc.," }, { "code": null, "e": 5348, "s": 4909, "text": "<html>\n <head>\n <style>\n body {\n background-color: lightpink;\n }\n @media screen and (max-width: 420px) {\n body {\n background-color: lightblue;\n }\n }\n </style>\n </head>\n\n <body>\n <p>\n If screen size is less than 420px, then it will show lightblue \n color, or else it will show light pink color\n </p>\n </body>\n</html>" }, { "code": null, "e": 5387, "s": 5348, "text": "It will produce the following result −" }, { "code": null, "e": 5494, "s": 5387, "text": "If screen size is less than 420px,then it will show lightblue color, or else it will show light pink color" }, { "code": null, "e": 5647, "s": 5494, "text": "Bootstrap is most popular web design framework based on HTML,CSS and Java script and it helps you to design web pages in responsive way for all devices." }, { "code": null, "e": 7607, "s": 5647, "text": "<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\">\n <style>\n body {\n color:green;\n }\n </style>\n </head>\n\n <body>\n \n <div class = \"container\">\n \n <div class = \"jumbotron\">\n <h1>Tutorials point</h1> \n <p>\n Tutorials Point originated from the idea that there exists a class \n of readers who respond better to online content and prefer to learn \n new skills at their own pace from the comforts of their drawing rooms.\n </p> \n </div>\n \n <div class = \"row\">\n <div class = \"col-md-4\">\n <h2>Android</h2>\n <p>\n Android is an open source and Linux-based operating system for mobile \n devices such as smartphones and tablet computers. Android was developed \n by the Open Handset Alliance, led by Google, and other companies.\n </p>\n </div>\n \n <div class = \"col-md-4\">\n <h2>CSS</h2>\n <p>\n Cascading Style Sheets, fondly referred to as CSS, is a simple design \n language intended to simplify the process of making web pages presentable.\n </p>\n </div>\n \n <div class = \"col-md-4\">\n <h2>Java</h2>\n <p>\n Java is a high-level programming language originally developed by Sun \n Microsystems and released in 1995. Java runs on a variety of platforms,\n such as Windows, Mac OS, and the various versions of UNIX. This tutorial\n gives a complete understanding of Java.\n </p>\n </div>\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 7646, "s": 7607, "text": "It will produce the following result −" }, { "code": null, "e": 7852, "s": 7646, "text": "Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms." }, { "code": null, "e": 8060, "s": 7852, "text": "Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies." }, { "code": null, "e": 8205, "s": 8060, "text": "Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable." }, { "code": null, "e": 8460, "s": 8205, "text": "Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java." }, { "code": null, "e": 8495, "s": 8460, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8509, "s": 8495, "text": " Anadi Sharma" }, { "code": null, "e": 8544, "s": 8509, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8561, "s": 8544, "text": " Frahaan Hussain" }, { "code": null, "e": 8596, "s": 8561, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8627, "s": 8596, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8662, "s": 8627, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8693, "s": 8662, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8728, "s": 8693, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8759, "s": 8728, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8792, "s": 8759, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8823, "s": 8792, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8830, "s": 8823, "text": " Print" }, { "code": null, "e": 8841, "s": 8830, "text": " Add Notes" } ]
C++ Library - <basic_istream>
It is used for Input stream objects can read and interpret input from sequences of characters. Specific members are provided to perform these input operations. The standard objects cin and wcin use particular instantiations of this class template. Below is definition of std::basic_istream. template <class charT, class traits = char_traits<charT>> class basic_istream; charT − Character type. charT − Character type. traits − Character traits class that defines essential properties of the characters used by stream objects. traits − Character traits class that defines essential properties of the characters used by stream objects. Print Add Notes Bookmark this page
[ { "code": null, "e": 2763, "s": 2603, "text": "It is used for Input stream objects can read and interpret input from sequences of characters. Specific members are provided to perform these input operations." }, { "code": null, "e": 2851, "s": 2763, "text": "The standard objects cin and wcin use particular instantiations of this class template." }, { "code": null, "e": 2894, "s": 2851, "text": "Below is definition of std::basic_istream." }, { "code": null, "e": 2976, "s": 2894, "text": "template <class charT, class traits = char_traits<charT>>\n class basic_istream;" }, { "code": null, "e": 3000, "s": 2976, "text": "charT − Character type." }, { "code": null, "e": 3024, "s": 3000, "text": "charT − Character type." }, { "code": null, "e": 3132, "s": 3024, "text": "traits − Character traits class that defines essential properties of the characters used by stream objects." }, { "code": null, "e": 3240, "s": 3132, "text": "traits − Character traits class that defines essential properties of the characters used by stream objects." }, { "code": null, "e": 3247, "s": 3240, "text": " Print" }, { "code": null, "e": 3258, "s": 3247, "text": " Add Notes" } ]
K-Primes (Numbers with k prime factors) in a range - GeeksforGeeks
21 Apr, 2021 Given three integers A, B and K. We need to find no. of K-prime numbers in the range [A, B]. A number is called K-prime if it has exactly K distinct prime factors. Examples: Input : A = 4, B = 10, K = 2. Output : 6 10 Given range is [4, 5, 6, 7, 8, 9, 10]. From the above range 6 and 10 have 2 distinct prime factors, 6 = 3*2; 10 = 5*2. Input : A = 14, B = 18, K = 2. Output : 14 15 18 Range = [14, 15]. Both 14, 15 and 18 have 2 distinct prime factors, 14 = 7*2, 15 = 3*5 and 18 = 2*3*3 A simple solution is to traverse through given range. For every element of the range, find its prime factors. Finally print all those numbers whose prime factors are k. An efficient solution is to use Sieve Of Eratosthenes Algorithm prime[n] = {true}; for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } If we observe the above algorithm clearly it has a property of iterating through all the multiples of prime numbers less than N. So the number of times the algorithm marks a number not prime is equal to the number of prime factors of that number. To achieve this, maintain an array called marked and increase the count of a number every time when it is marked as not prime by the algorithm. And in the next step, we iterate through all the numbers in the range [A, B] and increase our count of k-prime numbers if marked[number] == K. C++ Java Python3 C# PHP Javascript // CPP program to count all those numbers in// given range whose count of prime factors// is k#include <bits/stdc++.h>using namespace std; void printKPFNums(int A, int B, int K){ // Count prime factors of all numbers // till B. bool prime[B+1] = { true }; int p_factors[B+1] = { 0 }; for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) cout << i << " ";} // Driver codeint main(){ int A = 14, B = 18, K = 2; printKPFNums(A, B, K); return 0;} // Java program to count// all those numbers in// given range whose count// of prime factors// is k import java.io.*;import java.util.*; class GFG { static void printKPFNums(int A, int B, int K) { // Count prime factors of all numbers // till B. int p_factors[] = new int[B+1]; Arrays.fill(p_factors,0); for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) System.out.print( i + " "); } // Driver code public static void main(String args[]) { int A = 14, B = 18, K = 2; printKPFNums(A, B, K); }} // This code is contributed// by Nikita Tiwari. # Python 3 program to count# all those numbers in# given range whose count# of prime factors# is k def printKPFNums(A, B, K) : # Count prime factors # of all numbers # till B. prime = [ True]*(B+1) p_factors= [ 0 ]*(B+1) for p in range(2,B+1) : if (p_factors[p] == 0) : for i in range(p,B+1,p) : p_factors[i] = p_factors[i] + 1 # Print all numbers with # k prime factors for i in range(A,B+1) : if (p_factors[i] == K) : print( i ,end=" ") # Driver codeA = 14B = 18K = 2printKPFNums(A, B, K) # This code is contributed# by Nikita Tiwari. // C# program to count all// those numbers in given// range whose count of// prime factors is kusing System; class GFG { static void printKPFNums(int A, int B, int K) { // Count prime factors of // all numbers till B. bool []prime = new bool[B + 1]; for(int i = 0; i < B + 1; i++) prime[i] = true; int []p_factors = new int[B + 1]; for(int i = 0; i < B + 1; i++) p_factors[i] = 0; for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with // k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) Console.Write( i + " "); } // Driver code public static void Main() { int A = 14, B = 18, K = 2; printKPFNums(A, B, K); }} // This code is contributed by nitin mittal. <?php// PHP program to count all those numbers// in given range whose count of prime// factors is k function printKPFNums($A, $B, $K){ // Count prime factors of all // numbers till B. $prime = array_fill(true, $B + 1, NULL); $p_factors = array_fill(0, $B + 1, NULL); for ($p = 2; $p <= $B; $p++) if ($p_factors[$p] == 0) for ($i = $p; $i <= $B; $i += $p) $p_factors[$i]++; // Print all numbers with // k prime factors for ($i = $A; $i <= $B; $i++) if ($p_factors[$i] == $K) echo $i . " ";} // Driver code$A = 14;$B = 18;$K = 2;printKPFNums($A, $B, $K); // This code is contributed// by ChitraNayal?> <script> // Javascript program to count all those// numbers in given range whose count// of prime factors is k // Returns the sum of first// n odd numbersfunction prletKPFNums(A, B, K){ // Count prime factors of // all numbers till B. let prime = []; for(let i = 0; i < B + 1; i++) prime[i] = true; let p_factors = []; for(let i = 0; i < B + 1; i++) p_factors[i] = 0; for (let p = 2; p <= B; p++) if (p_factors[p] == 0) for(let i = p; i <= B; i += p) p_factors[i]++; // Print let all numbers with // k prime factors for(let i = A; i <= B; i++) if (p_factors[i] == K) document.write( i + " ");} // Driver codelet A = 14, B = 18, K = 2; prletKPFNums(A, B, K); // This code is contributed by sanjoy_62 </script> Output: 14 15 18 nitin mittal ukasp divesh1 sanjoy_62 number-theory prime-factor sieve Mathematical number-theory Mathematical sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end Find minimum number of coins that make a given value
[ { "code": null, "e": 24524, "s": 24496, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24689, "s": 24524, "text": "Given three integers A, B and K. We need to find no. of K-prime numbers in the range [A, B]. A number is called K-prime if it has exactly K distinct prime factors. " }, { "code": null, "e": 24700, "s": 24689, "text": "Examples: " }, { "code": null, "e": 25016, "s": 24700, "text": "Input : A = 4, B = 10, K = 2.\nOutput : 6 10\nGiven range is [4, 5, 6, 7, 8, 9, 10].\nFrom the above range 6 and 10 have 2 distinct \nprime factors, 6 = 3*2; 10 = 5*2.\n\nInput : A = 14, B = 18, K = 2.\nOutput : 14 15 18\nRange = [14, 15].\nBoth 14, 15 and 18 have 2 distinct prime factors,\n14 = 7*2, 15 = 3*5 and 18 = 2*3*3" }, { "code": null, "e": 25185, "s": 25016, "text": "A simple solution is to traverse through given range. For every element of the range, find its prime factors. Finally print all those numbers whose prime factors are k." }, { "code": null, "e": 25251, "s": 25185, "text": "An efficient solution is to use Sieve Of Eratosthenes Algorithm " }, { "code": null, "e": 25497, "s": 25251, "text": "prime[n] = {true};\nfor (int p=2; p*p<=n; p++)\n{\n // If prime[p] is not changed, then \n // it is a prime\n if (prime[p] == true)\n {\n // Update all multiples of p\n for (int i=p*2; i<=n; i += p)\n prime[i] = false;\n }\n}\n " }, { "code": null, "e": 26033, "s": 25497, "text": "If we observe the above algorithm clearly it has a property of iterating through all the multiples of prime numbers less than N. So the number of times the algorithm marks a number not prime is equal to the number of prime factors of that number. To achieve this, maintain an array called marked and increase the count of a number every time when it is marked as not prime by the algorithm. And in the next step, we iterate through all the numbers in the range [A, B] and increase our count of k-prime numbers if marked[number] == K. " }, { "code": null, "e": 26037, "s": 26033, "text": "C++" }, { "code": null, "e": 26042, "s": 26037, "text": "Java" }, { "code": null, "e": 26050, "s": 26042, "text": "Python3" }, { "code": null, "e": 26053, "s": 26050, "text": "C#" }, { "code": null, "e": 26057, "s": 26053, "text": "PHP" }, { "code": null, "e": 26068, "s": 26057, "text": "Javascript" }, { "code": "// CPP program to count all those numbers in// given range whose count of prime factors// is k#include <bits/stdc++.h>using namespace std; void printKPFNums(int A, int B, int K){ // Count prime factors of all numbers // till B. bool prime[B+1] = { true }; int p_factors[B+1] = { 0 }; for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) cout << i << \" \";} // Driver codeint main(){ int A = 14, B = 18, K = 2; printKPFNums(A, B, K); return 0;}", "e": 26734, "s": 26068, "text": null }, { "code": "// Java program to count// all those numbers in// given range whose count// of prime factors// is k import java.io.*;import java.util.*; class GFG { static void printKPFNums(int A, int B, int K) { // Count prime factors of all numbers // till B. int p_factors[] = new int[B+1]; Arrays.fill(p_factors,0); for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) System.out.print( i + \" \"); } // Driver code public static void main(String args[]) { int A = 14, B = 18, K = 2; printKPFNums(A, B, K); }} // This code is contributed// by Nikita Tiwari.", "e": 27593, "s": 26734, "text": null }, { "code": "# Python 3 program to count# all those numbers in# given range whose count# of prime factors# is k def printKPFNums(A, B, K) : # Count prime factors # of all numbers # till B. prime = [ True]*(B+1) p_factors= [ 0 ]*(B+1) for p in range(2,B+1) : if (p_factors[p] == 0) : for i in range(p,B+1,p) : p_factors[i] = p_factors[i] + 1 # Print all numbers with # k prime factors for i in range(A,B+1) : if (p_factors[i] == K) : print( i ,end=\" \") # Driver codeA = 14B = 18K = 2printKPFNums(A, B, K) # This code is contributed# by Nikita Tiwari.", "e": 28214, "s": 27593, "text": null }, { "code": "// C# program to count all// those numbers in given// range whose count of// prime factors is kusing System; class GFG { static void printKPFNums(int A, int B, int K) { // Count prime factors of // all numbers till B. bool []prime = new bool[B + 1]; for(int i = 0; i < B + 1; i++) prime[i] = true; int []p_factors = new int[B + 1]; for(int i = 0; i < B + 1; i++) p_factors[i] = 0; for (int p = 2; p <= B; p++) if (p_factors[p] == 0) for (int i = p; i <= B; i += p) p_factors[i]++; // Print all numbers with // k prime factors for (int i = A; i <= B; i++) if (p_factors[i] == K) Console.Write( i + \" \"); } // Driver code public static void Main() { int A = 14, B = 18, K = 2; printKPFNums(A, B, K); }} // This code is contributed by nitin mittal.", "e": 29240, "s": 28214, "text": null }, { "code": "<?php// PHP program to count all those numbers// in given range whose count of prime// factors is k function printKPFNums($A, $B, $K){ // Count prime factors of all // numbers till B. $prime = array_fill(true, $B + 1, NULL); $p_factors = array_fill(0, $B + 1, NULL); for ($p = 2; $p <= $B; $p++) if ($p_factors[$p] == 0) for ($i = $p; $i <= $B; $i += $p) $p_factors[$i]++; // Print all numbers with // k prime factors for ($i = $A; $i <= $B; $i++) if ($p_factors[$i] == $K) echo $i . \" \";} // Driver code$A = 14;$B = 18;$K = 2;printKPFNums($A, $B, $K); // This code is contributed// by ChitraNayal?>", "e": 29916, "s": 29240, "text": null }, { "code": "<script> // Javascript program to count all those// numbers in given range whose count// of prime factors is k // Returns the sum of first// n odd numbersfunction prletKPFNums(A, B, K){ // Count prime factors of // all numbers till B. let prime = []; for(let i = 0; i < B + 1; i++) prime[i] = true; let p_factors = []; for(let i = 0; i < B + 1; i++) p_factors[i] = 0; for (let p = 2; p <= B; p++) if (p_factors[p] == 0) for(let i = p; i <= B; i += p) p_factors[i]++; // Print let all numbers with // k prime factors for(let i = A; i <= B; i++) if (p_factors[i] == K) document.write( i + \" \");} // Driver codelet A = 14, B = 18, K = 2; prletKPFNums(A, B, K); // This code is contributed by sanjoy_62 </script>", "e": 30754, "s": 29916, "text": null }, { "code": null, "e": 30763, "s": 30754, "text": "Output: " }, { "code": null, "e": 30772, "s": 30763, "text": "14 15 18" }, { "code": null, "e": 30787, "s": 30774, "text": "nitin mittal" }, { "code": null, "e": 30793, "s": 30787, "text": "ukasp" }, { "code": null, "e": 30801, "s": 30793, "text": "divesh1" }, { "code": null, "e": 30811, "s": 30801, "text": "sanjoy_62" }, { "code": null, "e": 30825, "s": 30811, "text": "number-theory" }, { "code": null, "e": 30838, "s": 30825, "text": "prime-factor" }, { "code": null, "e": 30844, "s": 30838, "text": "sieve" }, { "code": null, "e": 30857, "s": 30844, "text": "Mathematical" }, { "code": null, "e": 30871, "s": 30857, "text": "number-theory" }, { "code": null, "e": 30884, "s": 30871, "text": "Mathematical" }, { "code": null, "e": 30890, "s": 30884, "text": "sieve" }, { "code": null, "e": 30988, "s": 30890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30997, "s": 30988, "text": "Comments" }, { "code": null, "e": 31010, "s": 30997, "text": "Old Comments" }, { "code": null, "e": 31053, "s": 31010, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31077, "s": 31053, "text": "Merge two sorted arrays" }, { "code": null, "e": 31126, "s": 31077, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31147, "s": 31126, "text": "Operators in C / C++" }, { "code": null, "e": 31181, "s": 31147, "text": "Program for factorial of a number" }, { "code": null, "e": 31213, "s": 31181, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 31286, "s": 31213, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31329, "s": 31286, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31366, "s": 31329, "text": "Minimum number of jumps to reach end" } ]
How to get current day, month and year in Java 8?
The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives. Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock. This class also provides various other useful methods among them − The getYear() method returns an integer representing the year filed in the current LocalDate object. The getMonth() method returns an object of the java.timeMonth class representing the month in the LocalDate object. The getDaYofMonth() method returns an integer representing the day in the LocalDate object. Following Java example retrieves the current date and prints the day, year and, month separately using the above specified methods. import java.time.LocalDate; import java.time.Month; public class LocalDateJava8 { public static void main(String args[]) { //Getting the current date value LocalDate currentdate = LocalDate.now(); System.out.println("Current date: "+currentdate); //Getting the current day int currentDay = currentdate.getDayOfMonth(); System.out.println("Current day: "+currentDay); //Getting the current month Month currentMonth = currentdate.getMonth(); System.out.println("Current month: "+currentMonth); //getting the current year int currentYear = currentdate.getYear(); System.out.println("Current month: "+currentYear); } } Current date: 2019-07-24 Current day: 24 Current month: JULY Current month: 2019
[ { "code": null, "e": 1387, "s": 1062, "text": "The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives." }, { "code": null, "e": 1571, "s": 1387, "text": "Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock." }, { "code": null, "e": 1638, "s": 1571, "text": "This class also provides various other useful methods among them −" }, { "code": null, "e": 1739, "s": 1638, "text": "The getYear() method returns an integer representing the year filed in the current LocalDate object." }, { "code": null, "e": 1855, "s": 1739, "text": "The getMonth() method returns an object of the java.timeMonth class representing the month in the LocalDate object." }, { "code": null, "e": 1947, "s": 1855, "text": "The getDaYofMonth() method returns an integer representing the day in the LocalDate object." }, { "code": null, "e": 2079, "s": 1947, "text": "Following Java example retrieves the current date and prints the day, year and, month separately using the above specified methods." }, { "code": null, "e": 2772, "s": 2079, "text": "import java.time.LocalDate;\nimport java.time.Month;\npublic class LocalDateJava8 {\n public static void main(String args[]) {\n //Getting the current date value\n LocalDate currentdate = LocalDate.now();\n System.out.println(\"Current date: \"+currentdate);\n //Getting the current day\n int currentDay = currentdate.getDayOfMonth();\n System.out.println(\"Current day: \"+currentDay);\n //Getting the current month\n Month currentMonth = currentdate.getMonth();\n System.out.println(\"Current month: \"+currentMonth);\n //getting the current year\n int currentYear = currentdate.getYear();\n System.out.println(\"Current month: \"+currentYear);\n }\n}" }, { "code": null, "e": 2853, "s": 2772, "text": "Current date: 2019-07-24\nCurrent day: 24\nCurrent month: JULY\nCurrent month: 2019" } ]
Joining DataFrames matching by substring with Python Pandas | by Cristian Saavedra Desmoineaux | Towards Data Science
The next Python Pandas code made it for Jupyter Notebook is available in GitHub, and It answers the question: “Which tasks don’t match?” The first part of the code creates two DataFrames: df1 and df2. The df1 DataFrame has the complete name of the tasks in the task_name column. And the df2 DataFrame has a substring in the partial_task_name column. Look that the value BC in partial_task_name is a substring of ABC and BCD, the expected result must produce many rows for this case, but how can we get many rows? The answer is using a Cartesian Product or Cross Join. To do a Cartesian Product in Pandas, do the following steps: Add a dummy column with the same value en each of the DataFramesDo a join by the new columnRemove the new column in each DataFrame Add a dummy column with the same value en each of the DataFrames Do a join by the new column Remove the new column in each DataFrame df1['join'] = 1df2['join'] = 1dfFull = df1.merge(df2, on='join').drop('join', axis=1)df2.drop('join', axis=1, inplace=True) The next step is to add a new column in the result DataFrame returning if the partial_task_name column is in the task_name column. We are going to use a lambda and “find” function where the result is ≥ 0 dfFull['match'] = dfFull.apply(lambda x: x.task_name.find(x.partial_task_name), axis=1).ge(0) The product is the dfFull DataFrame We do a group by task_name, pipeline_name, and get the match's maximum to filter. To know which tasks don’t exist in the df2 DataFrame we do a negative filter by the match column: If we don't use the Cartesian Product and instead we try adding the first match in df2 DataFrame and then do a left join with df1 DataFrame We are making a common mistake that it gives us the wrong answer BCD. Because when we used the first match, ABC matched with BC instead of BCD. There is a more generic technique called Approximate string matching or colloquially know it as Fuzzy Lookup that tries to solve similar or partial non-consecutive substrings too. If It is your case, you can try with fuzzywuzzy. Thank you to Charles Romestant to giving me the inspiration for this post
[ { "code": null, "e": 184, "s": 47, "text": "The next Python Pandas code made it for Jupyter Notebook is available in GitHub, and It answers the question: “Which tasks don’t match?”" }, { "code": null, "e": 248, "s": 184, "text": "The first part of the code creates two DataFrames: df1 and df2." }, { "code": null, "e": 326, "s": 248, "text": "The df1 DataFrame has the complete name of the tasks in the task_name column." }, { "code": null, "e": 397, "s": 326, "text": "And the df2 DataFrame has a substring in the partial_task_name column." }, { "code": null, "e": 615, "s": 397, "text": "Look that the value BC in partial_task_name is a substring of ABC and BCD, the expected result must produce many rows for this case, but how can we get many rows? The answer is using a Cartesian Product or Cross Join." }, { "code": null, "e": 676, "s": 615, "text": "To do a Cartesian Product in Pandas, do the following steps:" }, { "code": null, "e": 807, "s": 676, "text": "Add a dummy column with the same value en each of the DataFramesDo a join by the new columnRemove the new column in each DataFrame" }, { "code": null, "e": 872, "s": 807, "text": "Add a dummy column with the same value en each of the DataFrames" }, { "code": null, "e": 900, "s": 872, "text": "Do a join by the new column" }, { "code": null, "e": 940, "s": 900, "text": "Remove the new column in each DataFrame" }, { "code": null, "e": 1064, "s": 940, "text": "df1['join'] = 1df2['join'] = 1dfFull = df1.merge(df2, on='join').drop('join', axis=1)df2.drop('join', axis=1, inplace=True)" }, { "code": null, "e": 1268, "s": 1064, "text": "The next step is to add a new column in the result DataFrame returning if the partial_task_name column is in the task_name column. We are going to use a lambda and “find” function where the result is ≥ 0" }, { "code": null, "e": 1362, "s": 1268, "text": "dfFull['match'] = dfFull.apply(lambda x: x.task_name.find(x.partial_task_name), axis=1).ge(0)" }, { "code": null, "e": 1398, "s": 1362, "text": "The product is the dfFull DataFrame" }, { "code": null, "e": 1480, "s": 1398, "text": "We do a group by task_name, pipeline_name, and get the match's maximum to filter." }, { "code": null, "e": 1578, "s": 1480, "text": "To know which tasks don’t exist in the df2 DataFrame we do a negative filter by the match column:" }, { "code": null, "e": 1718, "s": 1578, "text": "If we don't use the Cartesian Product and instead we try adding the first match in df2 DataFrame and then do a left join with df1 DataFrame" }, { "code": null, "e": 1788, "s": 1718, "text": "We are making a common mistake that it gives us the wrong answer BCD." }, { "code": null, "e": 1862, "s": 1788, "text": "Because when we used the first match, ABC matched with BC instead of BCD." }, { "code": null, "e": 2091, "s": 1862, "text": "There is a more generic technique called Approximate string matching or colloquially know it as Fuzzy Lookup that tries to solve similar or partial non-consecutive substrings too. If It is your case, you can try with fuzzywuzzy." } ]
Find a pair of overlapping intervals from a given Set - GeeksforGeeks
15 Jun, 2021 Given a 2D array arr[][] with each row of the form {l, r}, the task is to find a pair (i, j) such that the ith interval lies within the jth interval. If multiple solutions exist, then print anyone of them. Otherwise, print -1. Examples: Input: N = 5, arr[][] = { { 1, 5 }, { 2, 10 }, { 3, 10}, {2, 2}, {2, 15}}Output: 3 0Explanation: [2, 2] lies inside [1, 5]. Input: N = 4, arr[][] = { { 2, 10 }, { 1, 9 }, { 1, 8 }, { 1, 7 } }Output: -1Explanation: No such pair of intervals exist. Native Approach: The simplest approach to solve this problem is to generate all possible pairs of the array. For every pair (i, j), check if the ith interval lies within the jth interval or not. If found to be true, then print the pairs. Otherwise, print -1. Time Complexity: O(N2)Auxiliary Space:O(1) Efficient Approach: The idea is to sort the segments firstly by their left border in increasing order and in case of equal left borders, sort them by their right borders in decreasing order. Then, just find the intersecting intervals by keeping track of the maximum right border. Follow the steps below to solve the problem: Sort the given array of intervals according to their left border and if any two left borders are equal, sort them with their right border in decreasing order.Now, traverse from left to right, keep the maximum right border of processed segments and compare it to the current segment.If the segments are overlapping, print their indices.Otherwise, after traversing, if no overlapping segments are found, print -1. Sort the given array of intervals according to their left border and if any two left borders are equal, sort them with their right border in decreasing order. Now, traverse from left to right, keep the maximum right border of processed segments and compare it to the current segment. If the segments are overlapping, print their indices. Otherwise, after traversing, if no overlapping segments are found, print -1. 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 a pair(i, j) such that// i-th interval lies within the j-th intervalvoid findOverlapSegement(int N, int a[], int b[]){ // Store interval and index of the interval // in the form of { {l, r}, index } vector<pair<pair<int, int>, int> > tup; // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.push_back(pair<pair<int, int>, int>( pair<int, int>(x, y), i)); } // Sort the vector based on l-value // of the intervals sort(tup.begin(), tup.end()); // Stores r-value of current interval int curr = tup[0].first.second; // Stores index of current interval int currPos = tup[0].second; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup[i - 1].first.first; // Stores l-value of current interval int R = tup[i].first.first; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup[i - 1].first.second < tup[i].first.second) cout << tup[i - 1].second << ' ' << tup[i].second; else cout << tup[i].second << ' ' << tup[i - 1].second; return; } // Stores r-value of current interval int T = tup[i].first.second; // If T is less than or equal to curr if (T <= curr) { cout << tup[i].second << ' ' << currPos; return; } else { // Update curr curr = T; // Update currPos currPos = tup[i].second; } } // If such intervals found cout << "-1 -1";} // Driver Codeint main(){ // Given l-value of segments int a[] = { 1, 2, 3, 2, 2 }; // Given r-value of segments int b[] = { 5, 10, 10, 2, 15 }; // Given size int N = sizeof(a) / sizeof(int); // Function Call findOverlapSegement(N, a, b);} // Java program to implement// the above approachimport java.util.*;import java.lang.*; class pair{ int l,r,index; pair(int l, int r, int index){ this.l = l; this.r = r; this.index=index; }}class GFG { // Function to find a pair(i, j) such that // i-th interval lies within the j-th interval static void findOverlapSegement(int N, int[] a, int[] b) { // Store interval and index of the interval // in the form of { {l, r}, index } ArrayList<pair> tup = new ArrayList<>(); // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.add(new pair(x, y, i)); } // Sort the vector based on l-value // of the intervals Collections.sort(tup,(aa,bb)->(aa.l!=bb.l)?aa.l-bb.l:aa.r-bb.r); // Stores r-value of current interval int curr = tup.get(0).r; // Stores index of current interval int currPos = tup.get(0).index; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup.get(i - 1).l; // Stores l-value of current interval int R = tup.get(i).l; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup.get(i - 1).r < tup.get(i).r) System.out.print(tup.get(i - 1).index + " " + tup.get(i).index); else System.out.print(tup.get(i).index + " " + tup.get(i - 1).index); return; } // Stores r-value of current interval int T = tup.get(i).r; // If T is less than or equal to curr if (T <= curr) { System.out.print(tup.get(i).index + " " + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup.get(i).index; } } // If such intervals found System.out.print("-1 -1"); } // Driver code public static void main (String[] args) { // Given l-value of segments int[] a = { 1, 2, 3, 2, 2 }; // Given r-value of segments int[] b = { 5, 10, 10, 2, 15 }; // Given size int N = a.length; // Function Call findOverlapSegement(N, a, b); }} // This code is contributed by offbeat. # Python3 program to implement# the above approach # Function to find a pair(i, j) such that# i-th interval lies within the j-th intervaldef findOverlapSegement(N, a, b) : # Store interval and index of the interval # in the form of { {l, r}, index } tup = [] # Traverse the array, arr[][] for i in range(N) : # Stores l-value of # the interval x = a[i] # Stores r-value of # the interval y = b[i] # Push current interval and index into tup tup.append(((x,y),i)) # Sort the vector based on l-value # of the intervals tup.sort() # Stores r-value of current interval curr = tup[0][0][1] # Stores index of current interval currPos = tup[0][1] # Traverse the vector, tup[] for i in range(1,N) : # Stores l-value of previous interval Q = tup[i - 1][0][0] # Stores l-value of current interval R = tup[i][0][0] # If Q and R are equal if Q == R : # Print the index of interval if tup[i - 1][0][1] < tup[i][0][1] : print(tup[i - 1][1], tup[i][1]) else : print(tup[i][1], tup[i - 1][1]) return # Stores r-value of current interval T = tup[i][0][1] # If T is less than or equal to curr if (T <= curr) : print(tup[i][1], currPos) return else : # Update curr curr = T # Update currPos currPos = tup[i][1] # If such intervals found print("-1", "-1", end = "") # Given l-value of segmentsa = [ 1, 2, 3, 2, 2 ] # Given r-value of segmentsb = [ 5, 10, 10, 2, 15 ] # Given sizeN = len(a) # Function CallfindOverlapSegement(N, a, b) # This code is contributed by divyesh072019 // C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to find a pair(i, j) such that // i-th interval lies within the j-th interval static void findOverlapSegement(int N, int[] a, int[] b) { // Store interval and index of the interval // in the form of { {l, r}, index } List<Tuple<Tuple<int,int>, int>> tup = new List<Tuple<Tuple<int,int>, int>>(); // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.Add(new Tuple<Tuple<int,int>, int>(new Tuple<int, int>(x, y), i)); } // Sort the vector based on l-value // of the intervals tup.Sort(); // Stores r-value of current interval int curr = tup[0].Item1.Item2; // Stores index of current interval int currPos = tup[0].Item2; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup[i - 1].Item1.Item1; // Stores l-value of current interval int R = tup[i].Item1.Item1; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup[i - 1].Item1.Item2 < tup[i].Item1.Item2) Console.Write(tup[i - 1].Item2 + " " + tup[i].Item2); else Console.Write(tup[i].Item2 + " " + tup[i - 1].Item2); return; } // Stores r-value of current interval int T = tup[i].Item1.Item2; // If T is less than or equal to curr if (T <= curr) { Console.Write(tup[i].Item2 + " " + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup[i].Item2; } } // If such intervals found Console.Write("-1 -1"); } // Driver code static void Main() { // Given l-value of segments int[] a = { 1, 2, 3, 2, 2 }; // Given r-value of segments int[] b = { 5, 10, 10, 2, 15 }; // Given size int N = a.Length; // Function Call findOverlapSegement(N, a, b); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function to find a pair(i, j) such that// i-th interval lies within the j-th intervalfunction findOverlapSegement(N, a, b){ // Store interval and index of the interval // in the form of { {l, r}, index } var tup = []; // Traverse the array, arr[][] for (var i = 0; i < N; i++) { var x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.push([[x, y], i]); } // Sort the vector based on l-value // of the intervals tup.sort((a,b) => { if(a[0][0] == b[0][0]) { return a[0][1] - b[0][1]; } var tmp = (a[0][0] - b[0][0]); console.log(tmp); return (a[0][0] - b[0][0]) }); // Stores r-value of current interval var curr = tup[0][0][1]; // Stores index of current interval var currPos = tup[0][1]; // Traverse the vector, tup[] for (var i = 1; i < N; i++) { // Stores l-value of previous interval var Q = tup[i - 1][0][0]; // Stores l-value of current interval var R = tup[i][0][0]; // If Q and R equal if (Q == R) { // If Y value of immediate previous // interval is less than Y value of // current interval if (tup[i - 1][0][1] < tup[i][0][1]) { // Print the index of interval document.write(tup[i - 1][1] + " " + tup[i][1]); return; } else { document.write(tup[i][1] + " " + tup[i - 1][1]); return; } } // Stores r-value of current interval var T = tup[i][0][1]; // T is less than or equal to curr if (T <= curr) { document.write(tup[i][1] + " " + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup[i][1]; } } // If such intervals found document.write("-1 -1");} // Driver Code// Given l-value of segments let a = [ 1, 2, 3, 2, 2 ]; // Given r-value of segments let b = [ 5, 10, 10, 2, 15 ]; // Given size let N = a.length; // Function Call findOverlapSegement(N, a, b); // This code is contributed by Dharanendra L V.</script> 3 0 Time Complexity: O(N * log(N))Auxiliary Space: O(N) divyeshrabadiya07 divyesh072019 offbeat dharanendralv23 Technical Scripter 2020 Arrays Competitive Programming Mathematical Searching Technical Scripter Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26297, "s": 26269, "text": "\n15 Jun, 2021" }, { "code": null, "e": 26524, "s": 26297, "text": "Given a 2D array arr[][] with each row of the form {l, r}, the task is to find a pair (i, j) such that the ith interval lies within the jth interval. If multiple solutions exist, then print anyone of them. Otherwise, print -1." }, { "code": null, "e": 26534, "s": 26524, "text": "Examples:" }, { "code": null, "e": 26658, "s": 26534, "text": "Input: N = 5, arr[][] = { { 1, 5 }, { 2, 10 }, { 3, 10}, {2, 2}, {2, 15}}Output: 3 0Explanation: [2, 2] lies inside [1, 5]." }, { "code": null, "e": 26781, "s": 26658, "text": "Input: N = 4, arr[][] = { { 2, 10 }, { 1, 9 }, { 1, 8 }, { 1, 7 } }Output: -1Explanation: No such pair of intervals exist." }, { "code": null, "e": 27083, "s": 26781, "text": "Native Approach: The simplest approach to solve this problem is to generate all possible pairs of the array. For every pair (i, j), check if the ith interval lies within the jth interval or not. If found to be true, then print the pairs. Otherwise, print -1. Time Complexity: O(N2)Auxiliary Space:O(1)" }, { "code": null, "e": 27363, "s": 27083, "text": "Efficient Approach: The idea is to sort the segments firstly by their left border in increasing order and in case of equal left borders, sort them by their right borders in decreasing order. Then, just find the intersecting intervals by keeping track of the maximum right border." }, { "code": null, "e": 27408, "s": 27363, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27820, "s": 27408, "text": "Sort the given array of intervals according to their left border and if any two left borders are equal, sort them with their right border in decreasing order.Now, traverse from left to right, keep the maximum right border of processed segments and compare it to the current segment.If the segments are overlapping, print their indices.Otherwise, after traversing, if no overlapping segments are found, print -1." }, { "code": null, "e": 27979, "s": 27820, "text": "Sort the given array of intervals according to their left border and if any two left borders are equal, sort them with their right border in decreasing order." }, { "code": null, "e": 28104, "s": 27979, "text": "Now, traverse from left to right, keep the maximum right border of processed segments and compare it to the current segment." }, { "code": null, "e": 28158, "s": 28104, "text": "If the segments are overlapping, print their indices." }, { "code": null, "e": 28235, "s": 28158, "text": "Otherwise, after traversing, if no overlapping segments are found, print -1." }, { "code": null, "e": 28286, "s": 28235, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28290, "s": 28286, "text": "C++" }, { "code": null, "e": 28295, "s": 28290, "text": "Java" }, { "code": null, "e": 28303, "s": 28295, "text": "Python3" }, { "code": null, "e": 28306, "s": 28303, "text": "C#" }, { "code": null, "e": 28317, "s": 28306, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find a pair(i, j) such that// i-th interval lies within the j-th intervalvoid findOverlapSegement(int N, int a[], int b[]){ // Store interval and index of the interval // in the form of { {l, r}, index } vector<pair<pair<int, int>, int> > tup; // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.push_back(pair<pair<int, int>, int>( pair<int, int>(x, y), i)); } // Sort the vector based on l-value // of the intervals sort(tup.begin(), tup.end()); // Stores r-value of current interval int curr = tup[0].first.second; // Stores index of current interval int currPos = tup[0].second; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup[i - 1].first.first; // Stores l-value of current interval int R = tup[i].first.first; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup[i - 1].first.second < tup[i].first.second) cout << tup[i - 1].second << ' ' << tup[i].second; else cout << tup[i].second << ' ' << tup[i - 1].second; return; } // Stores r-value of current interval int T = tup[i].first.second; // If T is less than or equal to curr if (T <= curr) { cout << tup[i].second << ' ' << currPos; return; } else { // Update curr curr = T; // Update currPos currPos = tup[i].second; } } // If such intervals found cout << \"-1 -1\";} // Driver Codeint main(){ // Given l-value of segments int a[] = { 1, 2, 3, 2, 2 }; // Given r-value of segments int b[] = { 5, 10, 10, 2, 15 }; // Given size int N = sizeof(a) / sizeof(int); // Function Call findOverlapSegement(N, a, b);}", "e": 30610, "s": 28317, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;import java.lang.*; class pair{ int l,r,index; pair(int l, int r, int index){ this.l = l; this.r = r; this.index=index; }}class GFG { // Function to find a pair(i, j) such that // i-th interval lies within the j-th interval static void findOverlapSegement(int N, int[] a, int[] b) { // Store interval and index of the interval // in the form of { {l, r}, index } ArrayList<pair> tup = new ArrayList<>(); // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.add(new pair(x, y, i)); } // Sort the vector based on l-value // of the intervals Collections.sort(tup,(aa,bb)->(aa.l!=bb.l)?aa.l-bb.l:aa.r-bb.r); // Stores r-value of current interval int curr = tup.get(0).r; // Stores index of current interval int currPos = tup.get(0).index; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup.get(i - 1).l; // Stores l-value of current interval int R = tup.get(i).l; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup.get(i - 1).r < tup.get(i).r) System.out.print(tup.get(i - 1).index + \" \" + tup.get(i).index); else System.out.print(tup.get(i).index + \" \" + tup.get(i - 1).index); return; } // Stores r-value of current interval int T = tup.get(i).r; // If T is less than or equal to curr if (T <= curr) { System.out.print(tup.get(i).index + \" \" + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup.get(i).index; } } // If such intervals found System.out.print(\"-1 -1\"); } // Driver code public static void main (String[] args) { // Given l-value of segments int[] a = { 1, 2, 3, 2, 2 }; // Given r-value of segments int[] b = { 5, 10, 10, 2, 15 }; // Given size int N = a.length; // Function Call findOverlapSegement(N, a, b); }} // This code is contributed by offbeat.", "e": 32956, "s": 30610, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find a pair(i, j) such that# i-th interval lies within the j-th intervaldef findOverlapSegement(N, a, b) : # Store interval and index of the interval # in the form of { {l, r}, index } tup = [] # Traverse the array, arr[][] for i in range(N) : # Stores l-value of # the interval x = a[i] # Stores r-value of # the interval y = b[i] # Push current interval and index into tup tup.append(((x,y),i)) # Sort the vector based on l-value # of the intervals tup.sort() # Stores r-value of current interval curr = tup[0][0][1] # Stores index of current interval currPos = tup[0][1] # Traverse the vector, tup[] for i in range(1,N) : # Stores l-value of previous interval Q = tup[i - 1][0][0] # Stores l-value of current interval R = tup[i][0][0] # If Q and R are equal if Q == R : # Print the index of interval if tup[i - 1][0][1] < tup[i][0][1] : print(tup[i - 1][1], tup[i][1]) else : print(tup[i][1], tup[i - 1][1]) return # Stores r-value of current interval T = tup[i][0][1] # If T is less than or equal to curr if (T <= curr) : print(tup[i][1], currPos) return else : # Update curr curr = T # Update currPos currPos = tup[i][1] # If such intervals found print(\"-1\", \"-1\", end = \"\") # Given l-value of segmentsa = [ 1, 2, 3, 2, 2 ] # Given r-value of segmentsb = [ 5, 10, 10, 2, 15 ] # Given sizeN = len(a) # Function CallfindOverlapSegement(N, a, b) # This code is contributed by divyesh072019", "e": 34990, "s": 32956, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to find a pair(i, j) such that // i-th interval lies within the j-th interval static void findOverlapSegement(int N, int[] a, int[] b) { // Store interval and index of the interval // in the form of { {l, r}, index } List<Tuple<Tuple<int,int>, int>> tup = new List<Tuple<Tuple<int,int>, int>>(); // Traverse the array, arr[][] for (int i = 0; i < N; i++) { int x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.Add(new Tuple<Tuple<int,int>, int>(new Tuple<int, int>(x, y), i)); } // Sort the vector based on l-value // of the intervals tup.Sort(); // Stores r-value of current interval int curr = tup[0].Item1.Item2; // Stores index of current interval int currPos = tup[0].Item2; // Traverse the vector, tup[] for (int i = 1; i < N; i++) { // Stores l-value of previous interval int Q = tup[i - 1].Item1.Item1; // Stores l-value of current interval int R = tup[i].Item1.Item1; // If Q and R are equal if (Q == R) { // Print the index of interval if (tup[i - 1].Item1.Item2 < tup[i].Item1.Item2) Console.Write(tup[i - 1].Item2 + \" \" + tup[i].Item2); else Console.Write(tup[i].Item2 + \" \" + tup[i - 1].Item2); return; } // Stores r-value of current interval int T = tup[i].Item1.Item2; // If T is less than or equal to curr if (T <= curr) { Console.Write(tup[i].Item2 + \" \" + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup[i].Item2; } } // If such intervals found Console.Write(\"-1 -1\"); } // Driver code static void Main() { // Given l-value of segments int[] a = { 1, 2, 3, 2, 2 }; // Given r-value of segments int[] b = { 5, 10, 10, 2, 15 }; // Given size int N = a.Length; // Function Call findOverlapSegement(N, a, b); }} // This code is contributed by divyeshrabadiya07", "e": 37238, "s": 34990, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find a pair(i, j) such that// i-th interval lies within the j-th intervalfunction findOverlapSegement(N, a, b){ // Store interval and index of the interval // in the form of { {l, r}, index } var tup = []; // Traverse the array, arr[][] for (var i = 0; i < N; i++) { var x, y; // Stores l-value of // the interval x = a[i]; // Stores r-value of // the interval y = b[i]; // Push current interval and index into tup tup.push([[x, y], i]); } // Sort the vector based on l-value // of the intervals tup.sort((a,b) => { if(a[0][0] == b[0][0]) { return a[0][1] - b[0][1]; } var tmp = (a[0][0] - b[0][0]); console.log(tmp); return (a[0][0] - b[0][0]) }); // Stores r-value of current interval var curr = tup[0][0][1]; // Stores index of current interval var currPos = tup[0][1]; // Traverse the vector, tup[] for (var i = 1; i < N; i++) { // Stores l-value of previous interval var Q = tup[i - 1][0][0]; // Stores l-value of current interval var R = tup[i][0][0]; // If Q and R equal if (Q == R) { // If Y value of immediate previous // interval is less than Y value of // current interval if (tup[i - 1][0][1] < tup[i][0][1]) { // Print the index of interval document.write(tup[i - 1][1] + \" \" + tup[i][1]); return; } else { document.write(tup[i][1] + \" \" + tup[i - 1][1]); return; } } // Stores r-value of current interval var T = tup[i][0][1]; // T is less than or equal to curr if (T <= curr) { document.write(tup[i][1] + \" \" + currPos); return; } else { // Update curr curr = T; // Update currPos currPos = tup[i][1]; } } // If such intervals found document.write(\"-1 -1\");} // Driver Code// Given l-value of segments let a = [ 1, 2, 3, 2, 2 ]; // Given r-value of segments let b = [ 5, 10, 10, 2, 15 ]; // Given size let N = a.length; // Function Call findOverlapSegement(N, a, b); // This code is contributed by Dharanendra L V.</script>", "e": 39718, "s": 37238, "text": null }, { "code": null, "e": 39722, "s": 39718, "text": "3 0" }, { "code": null, "e": 39776, "s": 39724, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(N)" }, { "code": null, "e": 39794, "s": 39776, "text": "divyeshrabadiya07" }, { "code": null, "e": 39808, "s": 39794, "text": "divyesh072019" }, { "code": null, "e": 39816, "s": 39808, "text": "offbeat" }, { "code": null, "e": 39832, "s": 39816, "text": "dharanendralv23" }, { "code": null, "e": 39856, "s": 39832, "text": "Technical Scripter 2020" }, { "code": null, "e": 39863, "s": 39856, "text": "Arrays" }, { "code": null, "e": 39887, "s": 39863, "text": "Competitive Programming" }, { "code": null, "e": 39900, "s": 39887, "text": "Mathematical" }, { "code": null, "e": 39910, "s": 39900, "text": "Searching" }, { "code": null, "e": 39929, "s": 39910, "text": "Technical Scripter" }, { "code": null, "e": 39936, "s": 39929, "text": "Arrays" }, { "code": null, "e": 39946, "s": 39936, "text": "Searching" }, { "code": null, "e": 39959, "s": 39946, "text": "Mathematical" }, { "code": null, "e": 40057, "s": 39959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40125, "s": 40057, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40169, "s": 40125, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40192, "s": 40169, "text": "Introduction to Arrays" }, { "code": null, "e": 40224, "s": 40192, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40238, "s": 40224, "text": "Linear Search" }, { "code": null, "e": 40281, "s": 40238, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 40324, "s": 40281, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 40365, "s": 40324, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 40443, "s": 40365, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Python | os.access() Method - GeeksforGeeks
12 Sep, 2018 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.access() method uses the real uid/gid to test for access to path. Most operations uses the effective uid/gid, therefore, this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path. Syntax: os.access(path, mode) Parameters: path: path to be tested for access or existencemode: Should be F_OK to test the existence of path, or can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions. Following values can be passed as the mode parameter of access() to test the following: os.F_OK: Tests existence of the path. os.R_OK: Tests readability of the path. os.W_OK: Tests writability of the path. os.X_OK: Checks if path can be executed. Returns: True if access is allowed, else returns False.Code #1: Understand access() method# Python program tyring to access# file with different mode parameter # importing all necessary librariesimport osimport sys # Different mode parameters will # return True if access is allowed,# else returns False. # Assuming only read operation is allowed on file# Checking access with os.F_OKpath1 = os.access("gfg.txt", os.F_OK)print("Exists the path:", path1) # Checking access with os.R_OKpath2 = os.access("gfg.txt", os.R_OK)print("Access to read the file:", path2) # Checking access with os.W_OKpath3 = os.access("gfg.txt", os.W_OK)print("Access to write the file:", path3) # Checking access with os.X_OKpath4 = os.access("gfg.txt", os.X_OK)print("Check if path can be executed:", path4)Output:Exists the path: True Access to read the file: True Access to write the file: False Check if path can be executed: False Code #2: Code to open a file after validating access is allowed# Python program to open a file# after validating the access # checking readability of the pathif os.access("gfg.txt", os.R_OK): # open txt file as file with open("gfg.txt") as file: return file.read() # in case can't access the file return "Facing some issue"Output:Facing some issueMy Personal Notes arrow_drop_upSave Returns: True if access is allowed, else returns False. Code #1: Understand access() method # Python program tyring to access# file with different mode parameter # importing all necessary librariesimport osimport sys # Different mode parameters will # return True if access is allowed,# else returns False. # Assuming only read operation is allowed on file# Checking access with os.F_OKpath1 = os.access("gfg.txt", os.F_OK)print("Exists the path:", path1) # Checking access with os.R_OKpath2 = os.access("gfg.txt", os.R_OK)print("Access to read the file:", path2) # Checking access with os.W_OKpath3 = os.access("gfg.txt", os.W_OK)print("Access to write the file:", path3) # Checking access with os.X_OKpath4 = os.access("gfg.txt", os.X_OK)print("Check if path can be executed:", path4) Output: Exists the path: True Access to read the file: True Access to write the file: False Check if path can be executed: False Code #2: Code to open a file after validating access is allowed # Python program to open a file# after validating the access # checking readability of the pathif os.access("gfg.txt", os.R_OK): # open txt file as file with open("gfg.txt") as file: return file.read() # in case can't access the file return "Facing some issue" Output: Facing some issue python-modules python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Selecting rows in pandas DataFrame based on conditions sum() function in Python
[ { "code": null, "e": 24290, "s": 24262, "text": "\n12 Sep, 2018" }, { "code": null, "e": 24510, "s": 24290, "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." }, { "code": null, "e": 24749, "s": 24510, "text": "os.access() method uses the real uid/gid to test for access to path. Most operations uses the effective uid/gid, therefore, this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path." }, { "code": null, "e": 24757, "s": 24749, "text": "Syntax:" }, { "code": null, "e": 24779, "s": 24757, "text": "os.access(path, mode)" }, { "code": null, "e": 24791, "s": 24779, "text": "Parameters:" }, { "code": null, "e": 24977, "s": 24791, "text": "path: path to be tested for access or existencemode: Should be F_OK to test the existence of path, or can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions." }, { "code": null, "e": 25065, "s": 24977, "text": "Following values can be passed as the mode parameter of access() to test the following:" }, { "code": null, "e": 25103, "s": 25065, "text": "os.F_OK: Tests existence of the path." }, { "code": null, "e": 25143, "s": 25103, "text": "os.R_OK: Tests readability of the path." }, { "code": null, "e": 25183, "s": 25143, "text": "os.W_OK: Tests writability of the path." }, { "code": null, "e": 26561, "s": 25183, "text": "os.X_OK: Checks if path can be executed. Returns: True if access is allowed, else returns False.Code #1: Understand access() method# Python program tyring to access# file with different mode parameter # importing all necessary librariesimport osimport sys # Different mode parameters will # return True if access is allowed,# else returns False. # Assuming only read operation is allowed on file# Checking access with os.F_OKpath1 = os.access(\"gfg.txt\", os.F_OK)print(\"Exists the path:\", path1) # Checking access with os.R_OKpath2 = os.access(\"gfg.txt\", os.R_OK)print(\"Access to read the file:\", path2) # Checking access with os.W_OKpath3 = os.access(\"gfg.txt\", os.W_OK)print(\"Access to write the file:\", path3) # Checking access with os.X_OKpath4 = os.access(\"gfg.txt\", os.X_OK)print(\"Check if path can be executed:\", path4)Output:Exists the path: True\nAccess to read the file: True\nAccess to write the file: False\nCheck if path can be executed: False Code #2: Code to open a file after validating access is allowed# Python program to open a file# after validating the access # checking readability of the pathif os.access(\"gfg.txt\", os.R_OK): # open txt file as file with open(\"gfg.txt\") as file: return file.read() # in case can't access the file return \"Facing some issue\"Output:Facing some issueMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26619, "s": 26563, "text": "Returns: True if access is allowed, else returns False." }, { "code": null, "e": 26655, "s": 26619, "text": "Code #1: Understand access() method" }, { "code": "# Python program tyring to access# file with different mode parameter # importing all necessary librariesimport osimport sys # Different mode parameters will # return True if access is allowed,# else returns False. # Assuming only read operation is allowed on file# Checking access with os.F_OKpath1 = os.access(\"gfg.txt\", os.F_OK)print(\"Exists the path:\", path1) # Checking access with os.R_OKpath2 = os.access(\"gfg.txt\", os.R_OK)print(\"Access to read the file:\", path2) # Checking access with os.W_OKpath3 = os.access(\"gfg.txt\", os.W_OK)print(\"Access to write the file:\", path3) # Checking access with os.X_OKpath4 = os.access(\"gfg.txt\", os.X_OK)print(\"Check if path can be executed:\", path4)", "e": 27356, "s": 26655, "text": null }, { "code": null, "e": 27364, "s": 27356, "text": "Output:" }, { "code": null, "e": 27485, "s": 27364, "text": "Exists the path: True\nAccess to read the file: True\nAccess to write the file: False\nCheck if path can be executed: False" }, { "code": null, "e": 27550, "s": 27485, "text": " Code #2: Code to open a file after validating access is allowed" }, { "code": "# Python program to open a file# after validating the access # checking readability of the pathif os.access(\"gfg.txt\", os.R_OK): # open txt file as file with open(\"gfg.txt\") as file: return file.read() # in case can't access the file return \"Facing some issue\"", "e": 27847, "s": 27550, "text": null }, { "code": null, "e": 27855, "s": 27847, "text": "Output:" }, { "code": null, "e": 27873, "s": 27855, "text": "Facing some issue" }, { "code": null, "e": 27888, "s": 27873, "text": "python-modules" }, { "code": null, "e": 27905, "s": 27888, "text": "python-os-module" }, { "code": null, "e": 27912, "s": 27905, "text": "Python" }, { "code": null, "e": 28010, "s": 27912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28019, "s": 28010, "text": "Comments" }, { "code": null, "e": 28032, "s": 28019, "text": "Old Comments" }, { "code": null, "e": 28050, "s": 28032, "text": "Python Dictionary" }, { "code": null, "e": 28072, "s": 28050, "text": "Enumerate() in Python" }, { "code": null, "e": 28102, "s": 28072, "text": "Iterate over a list in Python" }, { "code": null, "e": 28134, "s": 28102, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28176, "s": 28134, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28202, "s": 28176, "text": "Python String | replace()" }, { "code": null, "e": 28239, "s": 28202, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28282, "s": 28239, "text": "Python program to convert a list to string" }, { "code": null, "e": 28337, "s": 28282, "text": "Selecting rows in pandas DataFrame based on conditions" } ]
Get Started With Examples of Reactivity in Shiny apps. | by Lorna Maria A | Towards Data Science
One of the things that makes shiny apps interactive is reactivity. In the simplest of terms reactivity/reactive programming is the ability of a program to compute outputs from a given set of user inputs. The ability of a shiny app to handle reactivity makes a two-way communication between the user and the existing information. Reactivity is applied in cases such as performing calculations, data manipulation, the collection of user information among other scenarios. As a beginner setting out to build shiny apps, having the basic knowledge to handle reactivity will help you go a long way to exploring different use cases of shiny apps. The idea of reactivity will not occur to one until the error message below. This error occurs when a reactive component is placed inside a non reactive function. The app will not load and will parse this error. Let’s us look at what a reactive function is and what it does. There are three major reactive components of a shiny app: A reactive input is defined as an input that a user provides through the browser interface. For example when a user fills a form,selects an item or clicks a button. These actions will trigger values to be set form the reactive inputs. A reactive output is defined as program provided output in the browser interface. For example a graph, a map, a plot or a table of values. A reactive expression is defined as one that transforms the reactive inputs to reactive outputs.These perform computations before sending reactive outputs.These will also mask slow operations like reading data from a server, making network calls among other scenarios.We shall see one in our example. Let’s start with a simple example of adding up two integers and returning their sum in a shiny app. titlePanel("Sum of two integers"), #number input form sidebarLayout( sidebarPanel( textInput("one", "First Integer"), textInput("two", "Second Integer"), actionButton("add", "Add") ), # Show result mainPanel( textOutput("sum") ) server <- function(input,output,session) {#observe the add click and perform a reactive expression observeEvent( input$add,{ x <- as.numeric(input$one) y <- as.numeric(input$two) #reactive expression n <- x+y output$sum <- renderPrint(n) } ) Now let’s build something a bit complex while handling reactivity. fields <- c("name","age","height","weight")ui <- fluidPage( # Application title titlePanel("Health card"), # Sidebar with reactive inputs sidebarLayout( sidebarPanel( textInput("name","Your Name"), selectInput("age","Age bracket",c("18-25","25-45","above 45")), textInput("weight","Please enter your weight in kg"), textInput("height","Please enter your height in cm"), actionButton("save","Add") ), # a table of reactive outputs mainPanel( mainPanel( DT::dataTableOutput("responses", width = 500), tags$hr() ) ) )) # Define server logic server <- function(input, output,session) { #create a data frame called responses saveData <- function(data) { data <- as.data.frame(t(data)) if (exists("responses")) { responses <<- rbind(responses, data) } else { responses <<- data } } loadData <- function() { if (exists("responses")) { responses } } # Whenever a field is filled, aggregate all form data #formData is a reactive function formData <- reactive({ data <- sapply(fields, function(x) input[[x]]) data }) # When the Save button is clicked, save the form data observeEvent(input$save, { saveData(formData()) }) # Show the previous responses # (update with current response when save is clicked) output$responses <- DT::renderDataTable({ input$save loadData() }) } Project Demo: https://rstudio.cloud/project/22236 There you go! Now that you can handle the basics, please go ahead and try it out.Feel free to share and ask me questions or give feedback on twitter @lornamariak
[ { "code": null, "e": 500, "s": 171, "text": "One of the things that makes shiny apps interactive is reactivity. In the simplest of terms reactivity/reactive programming is the ability of a program to compute outputs from a given set of user inputs. The ability of a shiny app to handle reactivity makes a two-way communication between the user and the existing information." }, { "code": null, "e": 641, "s": 500, "text": "Reactivity is applied in cases such as performing calculations, data manipulation, the collection of user information among other scenarios." }, { "code": null, "e": 812, "s": 641, "text": "As a beginner setting out to build shiny apps, having the basic knowledge to handle reactivity will help you go a long way to exploring different use cases of shiny apps." }, { "code": null, "e": 888, "s": 812, "text": "The idea of reactivity will not occur to one until the error message below." }, { "code": null, "e": 1086, "s": 888, "text": "This error occurs when a reactive component is placed inside a non reactive function. The app will not load and will parse this error. Let’s us look at what a reactive function is and what it does." }, { "code": null, "e": 1144, "s": 1086, "text": "There are three major reactive components of a shiny app:" }, { "code": null, "e": 1379, "s": 1144, "text": "A reactive input is defined as an input that a user provides through the browser interface. For example when a user fills a form,selects an item or clicks a button. These actions will trigger values to be set form the reactive inputs." }, { "code": null, "e": 1518, "s": 1379, "text": "A reactive output is defined as program provided output in the browser interface. For example a graph, a map, a plot or a table of values." }, { "code": null, "e": 1819, "s": 1518, "text": "A reactive expression is defined as one that transforms the reactive inputs to reactive outputs.These perform computations before sending reactive outputs.These will also mask slow operations like reading data from a server, making network calls among other scenarios.We shall see one in our example." }, { "code": null, "e": 1919, "s": 1819, "text": "Let’s start with a simple example of adding up two integers and returning their sum in a shiny app." }, { "code": null, "e": 2200, "s": 1919, "text": "titlePanel(\"Sum of two integers\"), #number input form sidebarLayout( sidebarPanel( textInput(\"one\", \"First Integer\"), textInput(\"two\", \"Second Integer\"), actionButton(\"add\", \"Add\") ), # Show result mainPanel( textOutput(\"sum\") )" }, { "code": null, "e": 2464, "s": 2200, "text": "server <- function(input,output,session) {#observe the add click and perform a reactive expression observeEvent( input$add,{ x <- as.numeric(input$one) y <- as.numeric(input$two) #reactive expression n <- x+y output$sum <- renderPrint(n) } )" }, { "code": null, "e": 2531, "s": 2464, "text": "Now let’s build something a bit complex while handling reactivity." }, { "code": null, "e": 3192, "s": 2531, "text": "fields <- c(\"name\",\"age\",\"height\",\"weight\")ui <- fluidPage( # Application title titlePanel(\"Health card\"), # Sidebar with reactive inputs sidebarLayout( sidebarPanel( textInput(\"name\",\"Your Name\"), selectInput(\"age\",\"Age bracket\",c(\"18-25\",\"25-45\",\"above 45\")), textInput(\"weight\",\"Please enter your weight in kg\"), textInput(\"height\",\"Please enter your height in cm\"), actionButton(\"save\",\"Add\") ), # a table of reactive outputs mainPanel( mainPanel( DT::dataTableOutput(\"responses\", width = 500), tags$hr() ) ) ))" }, { "code": null, "e": 4182, "s": 3192, "text": "# Define server logic server <- function(input, output,session) { #create a data frame called responses saveData <- function(data) { data <- as.data.frame(t(data)) if (exists(\"responses\")) { responses <<- rbind(responses, data) } else { responses <<- data } } loadData <- function() { if (exists(\"responses\")) { responses } } # Whenever a field is filled, aggregate all form data #formData is a reactive function formData <- reactive({ data <- sapply(fields, function(x) input[[x]]) data }) # When the Save button is clicked, save the form data observeEvent(input$save, { saveData(formData()) }) # Show the previous responses # (update with current response when save is clicked) output$responses <- DT::renderDataTable({ input$save loadData() }) }" }, { "code": null, "e": 4232, "s": 4182, "text": "Project Demo: https://rstudio.cloud/project/22236" } ]
C# String.PadLeft Method
Pad the beginning of the string with spaces using the PadLeft() method. You can also pad it with a Unicode character. Let’s say the following is our string. string myStr = "DemoOne"; To set a padding at the beginning of the above string, use the PadLeft method. myStr.PadLeft(10); Here is the complete example. Live Demo using System; class Demo { static void Main() { string myStr = "DemoOne"; // set padding at the beginning Console.WriteLine(myStr.PadLeft(10)); myStr = "DemoTWO"; // set padding at the beginning Console.Write(myStr.PadLeft(15)); } } DemoOne DemoTWO
[ { "code": null, "e": 1180, "s": 1062, "text": "Pad the beginning of the string with spaces using the PadLeft() method. You can also pad it with a Unicode character." }, { "code": null, "e": 1219, "s": 1180, "text": "Let’s say the following is our string." }, { "code": null, "e": 1245, "s": 1219, "text": "string myStr = \"DemoOne\";" }, { "code": null, "e": 1324, "s": 1245, "text": "To set a padding at the beginning of the above string, use the PadLeft method." }, { "code": null, "e": 1343, "s": 1324, "text": "myStr.PadLeft(10);" }, { "code": null, "e": 1373, "s": 1343, "text": "Here is the complete example." }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1659, "s": 1384, "text": "using System;\nclass Demo {\n static void Main() {\n string myStr = \"DemoOne\";\n // set padding at the beginning\n Console.WriteLine(myStr.PadLeft(10));\n myStr = \"DemoTWO\";\n // set padding at the beginning\n Console.Write(myStr.PadLeft(15));\n }\n}" }, { "code": null, "e": 1675, "s": 1659, "text": "DemoOne\nDemoTWO" } ]
How to get all options in a drop-down list by Selenium WebDriver using C#?
We can get all options in a drop−down list by Selenium Webdriver in C#. The static drop−down in an html code is identified with a select tag. All the options for a drop−down have the option tag. To obtain all the options in the form of a list, we shall first identify that element with the help of any of the locators like id, xpath, name, and so on. Then we must create an object of the SelectElement class and apply Options method on it. Let us investigate the html code of drop−down. For implementation we shall be using the NUnit framework. using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; namespace NUnitTestProject1{ public class Tests{ String u = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"; IWebDriver d; [SetUp] public void Setup(){ //creating object of FirefoxDriver d = new FirefoxDriver(); } [Test] public void Test1(){ //launching URL d.Navigate() .GoToUrl(u); //identify dropdown IWebElement l = d.FindElement(By.Name("continents")); //object of SelectElement SelectElement s = new SelectElement(l); //Options method to get all options IList<IWebElement> els = s.Options; //count options int e = els.Count; for (int j = 0; j < e; j++){ Console.WriteLine("Option at " + j + " is: " + els.ElementAt(j).Text); } } [TearDown] public void close_Browser(){ d.Quit(); } } } Click on Run All Tests − Click on Open additional output for this result link − We should get the Test Outcome and Standard Output.
[ { "code": null, "e": 1257, "s": 1062, "text": "We can get all options in a drop−down list by Selenium Webdriver in C#. The static drop−down in an html code is identified with a select tag. All the options for a drop−down have the option tag." }, { "code": null, "e": 1502, "s": 1257, "text": "To obtain all the options in the form of a list, we shall first identify that element with the help of any of the locators like id, xpath, name, and so on. Then we must create an object of the SelectElement class and apply Options method on it." }, { "code": null, "e": 1549, "s": 1502, "text": "Let us investigate the html code of drop−down." }, { "code": null, "e": 1607, "s": 1549, "text": "For implementation we shall be using the NUnit framework." }, { "code": null, "e": 2731, "s": 1607, "text": "using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium.Support.UI;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace NUnitTestProject1{\n public class Tests{\n String u = \"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\";\n IWebDriver d;\n [SetUp]\n public void Setup(){\n //creating object of FirefoxDriver\n d = new FirefoxDriver();\n }\n [Test]\n public void Test1(){\n //launching URL\n d.Navigate()\n .GoToUrl(u);\n //identify dropdown\n IWebElement l = d.FindElement(By.Name(\"continents\"));\n //object of SelectElement\n SelectElement s = new SelectElement(l);\n //Options method to get all options\n IList<IWebElement> els = s.Options;\n //count options\n int e = els.Count;\n for (int j = 0; j < e; j++){\n Console.WriteLine(\"Option at \" + j + \" is: \" + els.ElementAt(j).Text);\n }\n }\n [TearDown]\n public void close_Browser(){\n d.Quit();\n }\n }\n}" }, { "code": null, "e": 2756, "s": 2731, "text": "Click on Run All Tests −" }, { "code": null, "e": 2811, "s": 2756, "text": "Click on Open additional output for this result link −" }, { "code": null, "e": 2863, "s": 2811, "text": "We should get the Test Outcome and Standard Output." } ]
An overview of time series forecasting models | by Davide Burba | Towards Data Science
What is this article about? This article provides an overview of the main models available for modelling univariate time series and forecasting their evolution. The models were developed in R and Python. The related code is available here. Time series forecasting is a hot topic which has many possible applications, such as stock prices forecasting, weather forecasting, business planning, resources allocation and many others. Even though forecasting can be considered as a subset of supervised regression problems, some specific tools are necessary due to the temporal nature of observations. What is a time series? A time series is usually modelled through a stochastic process Y(t), i.e. a sequence of random variables. In a forecasting setting we find ourselves at time t and we are interested in estimating Y(t+h), using only information available at time t. How to validate and test a time series model? Due to the temporal dependencies in time series data, we cannot rely on usual validation techniques. To avoid biased evaluations we must ensure that training sets contains observations that occurred prior to the ones in validation sets. A possible way to overcome this problem is to use a sliding window, as described here. This procedure is called time series cross validation and it is summarised in the following picture, in which the blue points represents the training sets in each “fold” and the red points represent the corresponding validation sets. If we are interested in forecasting the next n time steps, we can apply the cross validation procedure for 1,2,...,n steps ahead. In this way we can also compare the goodness of the forecasts for different time horizons. Once we have chosen the best model, we can fit it on the entire training set and evaluate its performance on a separate test set subsequent in time. The performance estimate can be done by using the same sliding window technique used for cross validation, but without re-estimating the model parameters. In the next section we will apply different forecasting models to predict the evolution of the industrial production index which quantifies the electrical equipment manufactured in the Euro area. The data can be easily downloaded through the fpp2 package in R. To make the data available outside R you can simply run the following code in a R environment. library(fpp2)write.csv(elecequip,file = “elecequip.csv”,row.names = FALSE) The dataset corresponds to monthly manufacture of electrical equipment (computer, electronic and optical products) in the Euro area (17 countries) in the period January 1996-March 2012. We keep the last 2 years for testing purposes. The time series has a peak at the end of 2000 and another one during 2007. The huge decrease that we observe at the end of 2008 is probably due to the global financial crisis which occurred during that year. There seems to be a yearly seasonal pattern. To better visualise this, we show data for each year separately in both original and polar coordinates. We observe a strong seasonal pattern. In particular there is a huge decline in production in August due to the summer holidays. We will consider the following models: Naïve, SNaïveSeasonal decomposition (+ any model)Exponential smoothingARIMA, SARIMAGARCHDynamic linear modelsTBATSProphetNNETARLSTM Naïve, SNaïve Seasonal decomposition (+ any model) Exponential smoothing ARIMA, SARIMA GARCH Dynamic linear models TBATS Prophet NNETAR LSTM We are interested in forecasting 12 months of the industrial production index. Therefore, given data up to time t, we would like to predict the values taken by the index at times t+1,...,t+12. We will use the Mean Absolute Error (MAE) to assess the performance of the models. In the Naïve model, the forecasts for every horizon correspond to the last observed value. Ŷ(t+h|t) = Y(t) This kind of forecast assumes that the stochastic model generating the time series is a random walk. An extension of the Naïve model is given by the SNaïve (Seasonal Naïve) model. Assuming that the time series has a seasonal component and that the period of the seasonality is T, the forecasts given by the SNaïve model are given by: Ŷ(t+h|t) = Y(t+h-T) Therefore the forecasts for the following T time steps are equal to the previous T time steps. In our application, the SNaïve forecast for the next year is equal to the last year’s observations. These models are often used as benchmark models. The following plots show the predictions obtained with the two models for the year 2007. The models were fitted by using the naive and snaive functions of the forecast R package. If data shows some seasonality (e.g. daily, weekly, quarterly, yearly) it may be useful to decompose the original time series into the sum of three components: Y(t) = S(t) + T(t) + R(t) where S(t) is the seasonal component, T(t) is the trend-cycle component, and R(t) is the remainder component. There exists several techniques to estimate such a decomposition. The most basic one is called classical decomposition and it consists in: Estimating trend T(t) through a rolling meanComputing S(t) as the average detrended series Y(t)-T(t) for each season (e.g. for each month)Computing the remainder series as R(t)=Y(t)-T(t)-S(t) Estimating trend T(t) through a rolling mean Computing S(t) as the average detrended series Y(t)-T(t) for each season (e.g. for each month) Computing the remainder series as R(t)=Y(t)-T(t)-S(t) The classical decomposition has been extended in several ways. Its extensions allow to: have a non-constant seasonality compute initial and last values of the decomposition avoid over-smoothing To get an overview of time series decomposition methods you can click here. We will take advantage of the STL decomposition, which is known to be versatile and robust. One way to use the decomposition for forecasting purposes is the following: Decompose the training time series with some decomposition algorithm (e.g. STL): Y(t)= S(t)+T(t)+R(t).Compute the seasonally adjusted time series Y(t)-S(t). Use any model you like to forecast the evolution of the seasonally adjusted time series.Add to the forecasts the seasonality of the last time period in the time series (in our case, the fitted S(t) for last year). Decompose the training time series with some decomposition algorithm (e.g. STL): Y(t)= S(t)+T(t)+R(t). Compute the seasonally adjusted time series Y(t)-S(t). Use any model you like to forecast the evolution of the seasonally adjusted time series. Add to the forecasts the seasonality of the last time period in the time series (in our case, the fitted S(t) for last year). In the following picture we show the seasonally adjusted industrial production index time series. The following plot shows the predictions obtained for the year 2007 by using the STL decomposition and the naïve model to fit the seasonally adjusted time series. The decomposition was fitted by using the stl function of the stats R package. Exponential smoothing is one of the most successful classical forecasting methods. In its basic form it is called simple exponential smoothing and its forecasts are given by: Ŷ(t+h|t) = ⍺y(t) + ⍺(1-⍺)y(t-1) + ⍺(1-⍺)2y(t-2) + ... with 0<⍺<1. We can see that forecasts are equal to a weighted average of past observations and the corresponding weights decrease exponentially as we go back in time. Several extensions of the simple exponential smoothing have been proposed in order to include trend or damped trend and seasonality. The exponential smoothing family is composed of 9 models which are fully described here. The following plots show the predictions obtained for the year 2007 by using exponential smoothing models (automatically selected) to fit both the original and the seasonally adjusted time series. The models were fitted by using the ets function of the forecast R package. As for exponential smoothing, also ARIMA models are among the most widely used approaches for time series forecasting. The name is an acronym for AutoRegressive Integrated Moving Average. In an AutoRegressive model the forecasts correspond to a linear combination of past values of the variable. In a Moving Average model the forecasts correspond to a linear combination of past forecast errors. Basically, the ARIMA models combine these two approaches. Since they require the time series to be stationary, differencing (Integrating) the time series may be a necessary step, i.e. considering the time series of the differences instead of the original one. The SARIMA model (Seasonal ARIMA) extends the ARIMA by adding a linear combination of seasonal past values and/or forecast errors. For a complete introduction to ARIMA and SARIMA models, click here. The following plots show the predictions obtained for the year 2007 by using a SARIMA model and an ARIMA model on the seasonally adjusted time series. The models were fitted by using the auto.arima and Arima functions of the forecast R package. The previous models assumed that the error terms in the stochastic processes generating the time series were homoskedastic, i.e. with constant variance. Instead, the GARCH model assumes that the variance of the error terms follows an AutoRegressive Moving Average (ARMA) process, therefore allowing it to change in time. It is particularly useful for modelling financial time series whose volatility changes across time. The name is an acronym for Generalised Autoregressive Conditional Heteroskedasticity. Usually an ARMA process is assumed for the mean as well. For a complete introduction to GARCH models you can click here and here. The following plots show the predictions obtained for the year 2007 by using a GARCH model to fit the seasonally adjusted time series. The model was fitted by using the ugarchfitfunction of the rugarch R package. Dynamic linear models represent another class of models for time series forecasting. The idea is that at each time t these models correspond to a linear model, but the regression coefficients change in time. An example of dynamic linear model is given below. y(t) = ⍺(t) + tβ(t) + w(t) ⍺(t) = ⍺(t-1) + m(t) β(t) = β(t-1) + r(t) w(t)~N(0,W) , m(t)~N(0,M) , r(t)~N(0,R) In the previous model the coefficients ⍺(t) and β(t) follow a random walk process. Dynamic linear models can be naturally modelled in a Bayesian framework; however maximum likelihood estimation techniques are still available. For a complete overview of dynamic linear models, click here. The following plot shows the predictions obtained for the year 2007 by using a dynamic linear model to fit the seasonally adjusted time series. Due to heavy computational costs I had to keep the model extremely simple which resulted in poor forecasts. The model was fitted by using the dlmMLEfunction of the dlm R package. The TBATS model is a forecasting model based on exponential smoothing. The name is an acronym for Trigonometric, Box-Cox transform, ARMA errors, Trend and Seasonal components. The main feature of TBATS model is its capability to deal with multiple seasonalities by modelling each seasonality with a trigonometric representation based on Fourier series. A classic example of complex seasonality is given by daily observations of sales volumes which often have both weekly and yearly seasonality. For a complete introduction of TBATS model, click here. The following plot shows the predictions obtained for the year 2007 by using a TBATS model to fit the time series. The model was fitted by using the tbats function of the forecast R package. Prophet is another forecasting model which allows to deal with multiple seasonalities. It is an open source software released by Facebook’s Core Data Science team. The prophet model assumes that the the time series can be decomposed as follows: y(t) = g(t) + s(t) + h(t) + ε(t) The three terms g(t), s(t) and h(t) correspond respectively to trend, seasonality and holiday. The last term is the error term. The model fitting is framed as a curve-fitting exercise, therefore it does not explicitly take into account the temporal dependence structure in the data. This also allows to have irregularly spaced observations. There are two options for trend time series: a saturating growth model, and a piecewise linear model. The multi-period seasonality model relies on Fourier series. The effect of known and custom holydays can be easily incorporated into the model. The prophet model is inserted in a Bayesian framework and it allows to make full posterior inference to include model parameter uncertainty in the forecast uncertainty. For a complete introduction to Prophet model, click here. The following plot shows the predictions obtained for the year 2007 by using a Prophet model to fit the time series. The model was fitted by using the prophet function of the prophet R package. The NNETAR model is a fully connected neural network. The acronym stands for Neural NETwork AutoRegression. The NNETAR model takes in input the last elements of the sequence up to time t and outputs the forecasted value at time t+1. To perform multi-steps forecasts the network is applied iteratively. In presence of seasonality, the input may include also the seasonally lagged time series. For a complete introduction to NNETAR models, click here. The following plots show the predictions obtained for the year 2007 obtained by using a NNETAR model with seasonally lagged input and a NNETAR model on the seasonally adjusted time series. The models were fitted by using the nnetar function of the forecast R package. LSTM models can be used to forecast time series (as well as other Recurrent Neural Networks). LSTM is an acronym that stands for Long-Short Term Memories. The state of a LSTM network is represented through a state space vector. This technique allows to keep tracks of dependencies of new observations with past ones (even very far ones). Generally speaking, LSTMs are complex models and they are rarely used for predicting a single time-series, because they require a large amount of data to be estimated. However, they are commonly used when predictions are needed for a large number of time-series (check here). For a complete introduction on using LSTM to forecast time series, click here. The following plot shows the predictions for the first year in the test set obtained by fitting a LSTM model on the seasonally adjusted time series. The model was fitted by using the Keras framework in Python. We performed model selection through the cross-validation procedure described previously. We didn’t compute it for dynamic linear models and LSTM models due to their high computational cost and poor performance. In the following picture we show the cross-validated MAE for each model and for each time horizon. We can see that, for time horizons greater than 4, the NNETAR model on the seasonally adjusted data performed better than the others. Let’s check the overall MAE computed by averaging over different time horizons. The NNETAR model on the seasonally adjusted data was the best model for this application since it corresponded to the lowest cross-validated MAE. To get an unbiased estimation of the best model performance, we computed the MAE on the test set, obtaining an estimate equal to 5,24. In the following picture we can see the MAE estimated on the test set for each time horizon. Other techniques to increase models performance could be: Using different models for different time horizons Combining multiple forecasts (e.g. considering the average prediction) Bootstrap Aggregating The last technique can be summarised as follows: Decompose the original time series (e.g. by using STL)Generate a set of similar time series by randomly shuffling chunks of the Remainder componentFit a model on each time seriesAverage forecasts of every model Decompose the original time series (e.g. by using STL) Generate a set of similar time series by randomly shuffling chunks of the Remainder component Fit a model on each time series Average forecasts of every model For a complete introduction to Bootstrap Aggregating, click here. The goal of this project wasn’t to fit the best possible forecasting model for industrial production index, but to give an overview of forecasting models. In a real world application a lot of time should be spent on preprocessing, feature engineering and feature selection. Most of the previously described models allow to easily incorporate time varying predictors. These could be extracted from the same time series or could correspond to external predictors (e.g. the time series of another index). In the latter case we should pay attention to not use information from the future, which could be satisfied by forecasting the predictors or by using their lagged versions. Finally, notice that in this article we only considered the case in which we have a single time-series to predict. When we have many time-series, a global approach may be preferred, since it allows us to estimate a more complex and potentially more accurate model. For an introduction to the global approach, click here.
[ { "code": null, "e": 199, "s": 171, "text": "What is this article about?" }, { "code": null, "e": 411, "s": 199, "text": "This article provides an overview of the main models available for modelling univariate time series and forecasting their evolution. The models were developed in R and Python. The related code is available here." }, { "code": null, "e": 767, "s": 411, "text": "Time series forecasting is a hot topic which has many possible applications, such as stock prices forecasting, weather forecasting, business planning, resources allocation and many others. Even though forecasting can be considered as a subset of supervised regression problems, some specific tools are necessary due to the temporal nature of observations." }, { "code": null, "e": 790, "s": 767, "text": "What is a time series?" }, { "code": null, "e": 1037, "s": 790, "text": "A time series is usually modelled through a stochastic process Y(t), i.e. a sequence of random variables. In a forecasting setting we find ourselves at time t and we are interested in estimating Y(t+h), using only information available at time t." }, { "code": null, "e": 1083, "s": 1037, "text": "How to validate and test a time series model?" }, { "code": null, "e": 1320, "s": 1083, "text": "Due to the temporal dependencies in time series data, we cannot rely on usual validation techniques. To avoid biased evaluations we must ensure that training sets contains observations that occurred prior to the ones in validation sets." }, { "code": null, "e": 1641, "s": 1320, "text": "A possible way to overcome this problem is to use a sliding window, as described here. This procedure is called time series cross validation and it is summarised in the following picture, in which the blue points represents the training sets in each “fold” and the red points represent the corresponding validation sets." }, { "code": null, "e": 1862, "s": 1641, "text": "If we are interested in forecasting the next n time steps, we can apply the cross validation procedure for 1,2,...,n steps ahead. In this way we can also compare the goodness of the forecasts for different time horizons." }, { "code": null, "e": 2166, "s": 1862, "text": "Once we have chosen the best model, we can fit it on the entire training set and evaluate its performance on a separate test set subsequent in time. The performance estimate can be done by using the same sliding window technique used for cross validation, but without re-estimating the model parameters." }, { "code": null, "e": 2362, "s": 2166, "text": "In the next section we will apply different forecasting models to predict the evolution of the industrial production index which quantifies the electrical equipment manufactured in the Euro area." }, { "code": null, "e": 2522, "s": 2362, "text": "The data can be easily downloaded through the fpp2 package in R. To make the data available outside R you can simply run the following code in a R environment." }, { "code": null, "e": 2597, "s": 2522, "text": "library(fpp2)write.csv(elecequip,file = “elecequip.csv”,row.names = FALSE)" }, { "code": null, "e": 2830, "s": 2597, "text": "The dataset corresponds to monthly manufacture of electrical equipment (computer, electronic and optical products) in the Euro area (17 countries) in the period January 1996-March 2012. We keep the last 2 years for testing purposes." }, { "code": null, "e": 3038, "s": 2830, "text": "The time series has a peak at the end of 2000 and another one during 2007. The huge decrease that we observe at the end of 2008 is probably due to the global financial crisis which occurred during that year." }, { "code": null, "e": 3187, "s": 3038, "text": "There seems to be a yearly seasonal pattern. To better visualise this, we show data for each year separately in both original and polar coordinates." }, { "code": null, "e": 3315, "s": 3187, "text": "We observe a strong seasonal pattern. In particular there is a huge decline in production in August due to the summer holidays." }, { "code": null, "e": 3354, "s": 3315, "text": "We will consider the following models:" }, { "code": null, "e": 3488, "s": 3354, "text": "Naïve, SNaïveSeasonal decomposition (+ any model)Exponential smoothingARIMA, SARIMAGARCHDynamic linear modelsTBATSProphetNNETARLSTM" }, { "code": null, "e": 3504, "s": 3488, "text": "Naïve, SNaïve" }, { "code": null, "e": 3541, "s": 3504, "text": "Seasonal decomposition (+ any model)" }, { "code": null, "e": 3563, "s": 3541, "text": "Exponential smoothing" }, { "code": null, "e": 3577, "s": 3563, "text": "ARIMA, SARIMA" }, { "code": null, "e": 3583, "s": 3577, "text": "GARCH" }, { "code": null, "e": 3605, "s": 3583, "text": "Dynamic linear models" }, { "code": null, "e": 3611, "s": 3605, "text": "TBATS" }, { "code": null, "e": 3619, "s": 3611, "text": "Prophet" }, { "code": null, "e": 3626, "s": 3619, "text": "NNETAR" }, { "code": null, "e": 3631, "s": 3626, "text": "LSTM" }, { "code": null, "e": 3824, "s": 3631, "text": "We are interested in forecasting 12 months of the industrial production index. Therefore, given data up to time t, we would like to predict the values taken by the index at times t+1,...,t+12." }, { "code": null, "e": 3907, "s": 3824, "text": "We will use the Mean Absolute Error (MAE) to assess the performance of the models." }, { "code": null, "e": 3999, "s": 3907, "text": "In the Naïve model, the forecasts for every horizon correspond to the last observed value." }, { "code": null, "e": 4016, "s": 3999, "text": "Ŷ(t+h|t) = Y(t)" }, { "code": null, "e": 4117, "s": 4016, "text": "This kind of forecast assumes that the stochastic model generating the time series is a random walk." }, { "code": null, "e": 4354, "s": 4117, "text": "An extension of the Naïve model is given by the SNaïve (Seasonal Naïve) model. Assuming that the time series has a seasonal component and that the period of the seasonality is T, the forecasts given by the SNaïve model are given by:" }, { "code": null, "e": 4375, "s": 4354, "text": "Ŷ(t+h|t) = Y(t+h-T)" }, { "code": null, "e": 4571, "s": 4375, "text": "Therefore the forecasts for the following T time steps are equal to the previous T time steps. In our application, the SNaïve forecast for the next year is equal to the last year’s observations." }, { "code": null, "e": 4709, "s": 4571, "text": "These models are often used as benchmark models. The following plots show the predictions obtained with the two models for the year 2007." }, { "code": null, "e": 4799, "s": 4709, "text": "The models were fitted by using the naive and snaive functions of the forecast R package." }, { "code": null, "e": 4959, "s": 4799, "text": "If data shows some seasonality (e.g. daily, weekly, quarterly, yearly) it may be useful to decompose the original time series into the sum of three components:" }, { "code": null, "e": 4985, "s": 4959, "text": "Y(t) = S(t) + T(t) + R(t)" }, { "code": null, "e": 5095, "s": 4985, "text": "where S(t) is the seasonal component, T(t) is the trend-cycle component, and R(t) is the remainder component." }, { "code": null, "e": 5234, "s": 5095, "text": "There exists several techniques to estimate such a decomposition. The most basic one is called classical decomposition and it consists in:" }, { "code": null, "e": 5426, "s": 5234, "text": "Estimating trend T(t) through a rolling meanComputing S(t) as the average detrended series Y(t)-T(t) for each season (e.g. for each month)Computing the remainder series as R(t)=Y(t)-T(t)-S(t)" }, { "code": null, "e": 5471, "s": 5426, "text": "Estimating trend T(t) through a rolling mean" }, { "code": null, "e": 5566, "s": 5471, "text": "Computing S(t) as the average detrended series Y(t)-T(t) for each season (e.g. for each month)" }, { "code": null, "e": 5620, "s": 5566, "text": "Computing the remainder series as R(t)=Y(t)-T(t)-S(t)" }, { "code": null, "e": 5708, "s": 5620, "text": "The classical decomposition has been extended in several ways. Its extensions allow to:" }, { "code": null, "e": 5740, "s": 5708, "text": "have a non-constant seasonality" }, { "code": null, "e": 5793, "s": 5740, "text": "compute initial and last values of the decomposition" }, { "code": null, "e": 5814, "s": 5793, "text": "avoid over-smoothing" }, { "code": null, "e": 5982, "s": 5814, "text": "To get an overview of time series decomposition methods you can click here. We will take advantage of the STL decomposition, which is known to be versatile and robust." }, { "code": null, "e": 6058, "s": 5982, "text": "One way to use the decomposition for forecasting purposes is the following:" }, { "code": null, "e": 6429, "s": 6058, "text": "Decompose the training time series with some decomposition algorithm (e.g. STL): Y(t)= S(t)+T(t)+R(t).Compute the seasonally adjusted time series Y(t)-S(t). Use any model you like to forecast the evolution of the seasonally adjusted time series.Add to the forecasts the seasonality of the last time period in the time series (in our case, the fitted S(t) for last year)." }, { "code": null, "e": 6532, "s": 6429, "text": "Decompose the training time series with some decomposition algorithm (e.g. STL): Y(t)= S(t)+T(t)+R(t)." }, { "code": null, "e": 6676, "s": 6532, "text": "Compute the seasonally adjusted time series Y(t)-S(t). Use any model you like to forecast the evolution of the seasonally adjusted time series." }, { "code": null, "e": 6802, "s": 6676, "text": "Add to the forecasts the seasonality of the last time period in the time series (in our case, the fitted S(t) for last year)." }, { "code": null, "e": 6900, "s": 6802, "text": "In the following picture we show the seasonally adjusted industrial production index time series." }, { "code": null, "e": 7064, "s": 6900, "text": "The following plot shows the predictions obtained for the year 2007 by using the STL decomposition and the naïve model to fit the seasonally adjusted time series." }, { "code": null, "e": 7143, "s": 7064, "text": "The decomposition was fitted by using the stl function of the stats R package." }, { "code": null, "e": 7318, "s": 7143, "text": "Exponential smoothing is one of the most successful classical forecasting methods. In its basic form it is called simple exponential smoothing and its forecasts are given by:" }, { "code": null, "e": 7373, "s": 7318, "text": "Ŷ(t+h|t) = ⍺y(t) + ⍺(1-⍺)y(t-1) + ⍺(1-⍺)2y(t-2) + ..." }, { "code": null, "e": 7385, "s": 7373, "text": "with 0<⍺<1." }, { "code": null, "e": 7540, "s": 7385, "text": "We can see that forecasts are equal to a weighted average of past observations and the corresponding weights decrease exponentially as we go back in time." }, { "code": null, "e": 7762, "s": 7540, "text": "Several extensions of the simple exponential smoothing have been proposed in order to include trend or damped trend and seasonality. The exponential smoothing family is composed of 9 models which are fully described here." }, { "code": null, "e": 7959, "s": 7762, "text": "The following plots show the predictions obtained for the year 2007 by using exponential smoothing models (automatically selected) to fit both the original and the seasonally adjusted time series." }, { "code": null, "e": 8035, "s": 7959, "text": "The models were fitted by using the ets function of the forecast R package." }, { "code": null, "e": 8223, "s": 8035, "text": "As for exponential smoothing, also ARIMA models are among the most widely used approaches for time series forecasting. The name is an acronym for AutoRegressive Integrated Moving Average." }, { "code": null, "e": 8431, "s": 8223, "text": "In an AutoRegressive model the forecasts correspond to a linear combination of past values of the variable. In a Moving Average model the forecasts correspond to a linear combination of past forecast errors." }, { "code": null, "e": 8691, "s": 8431, "text": "Basically, the ARIMA models combine these two approaches. Since they require the time series to be stationary, differencing (Integrating) the time series may be a necessary step, i.e. considering the time series of the differences instead of the original one." }, { "code": null, "e": 8822, "s": 8691, "text": "The SARIMA model (Seasonal ARIMA) extends the ARIMA by adding a linear combination of seasonal past values and/or forecast errors." }, { "code": null, "e": 8890, "s": 8822, "text": "For a complete introduction to ARIMA and SARIMA models, click here." }, { "code": null, "e": 9041, "s": 8890, "text": "The following plots show the predictions obtained for the year 2007 by using a SARIMA model and an ARIMA model on the seasonally adjusted time series." }, { "code": null, "e": 9135, "s": 9041, "text": "The models were fitted by using the auto.arima and Arima functions of the forecast R package." }, { "code": null, "e": 9288, "s": 9135, "text": "The previous models assumed that the error terms in the stochastic processes generating the time series were homoskedastic, i.e. with constant variance." }, { "code": null, "e": 9642, "s": 9288, "text": "Instead, the GARCH model assumes that the variance of the error terms follows an AutoRegressive Moving Average (ARMA) process, therefore allowing it to change in time. It is particularly useful for modelling financial time series whose volatility changes across time. The name is an acronym for Generalised Autoregressive Conditional Heteroskedasticity." }, { "code": null, "e": 9772, "s": 9642, "text": "Usually an ARMA process is assumed for the mean as well. For a complete introduction to GARCH models you can click here and here." }, { "code": null, "e": 9907, "s": 9772, "text": "The following plots show the predictions obtained for the year 2007 by using a GARCH model to fit the seasonally adjusted time series." }, { "code": null, "e": 9985, "s": 9907, "text": "The model was fitted by using the ugarchfitfunction of the rugarch R package." }, { "code": null, "e": 10244, "s": 9985, "text": "Dynamic linear models represent another class of models for time series forecasting. The idea is that at each time t these models correspond to a linear model, but the regression coefficients change in time. An example of dynamic linear model is given below." }, { "code": null, "e": 10271, "s": 10244, "text": "y(t) = ⍺(t) + tβ(t) + w(t)" }, { "code": null, "e": 10292, "s": 10271, "text": "⍺(t) = ⍺(t-1) + m(t)" }, { "code": null, "e": 10313, "s": 10292, "text": "β(t) = β(t-1) + r(t)" }, { "code": null, "e": 10353, "s": 10313, "text": "w(t)~N(0,W) , m(t)~N(0,M) , r(t)~N(0,R)" }, { "code": null, "e": 10436, "s": 10353, "text": "In the previous model the coefficients ⍺(t) and β(t) follow a random walk process." }, { "code": null, "e": 10641, "s": 10436, "text": "Dynamic linear models can be naturally modelled in a Bayesian framework; however maximum likelihood estimation techniques are still available. For a complete overview of dynamic linear models, click here." }, { "code": null, "e": 10893, "s": 10641, "text": "The following plot shows the predictions obtained for the year 2007 by using a dynamic linear model to fit the seasonally adjusted time series. Due to heavy computational costs I had to keep the model extremely simple which resulted in poor forecasts." }, { "code": null, "e": 10964, "s": 10893, "text": "The model was fitted by using the dlmMLEfunction of the dlm R package." }, { "code": null, "e": 11140, "s": 10964, "text": "The TBATS model is a forecasting model based on exponential smoothing. The name is an acronym for Trigonometric, Box-Cox transform, ARMA errors, Trend and Seasonal components." }, { "code": null, "e": 11459, "s": 11140, "text": "The main feature of TBATS model is its capability to deal with multiple seasonalities by modelling each seasonality with a trigonometric representation based on Fourier series. A classic example of complex seasonality is given by daily observations of sales volumes which often have both weekly and yearly seasonality." }, { "code": null, "e": 11515, "s": 11459, "text": "For a complete introduction of TBATS model, click here." }, { "code": null, "e": 11630, "s": 11515, "text": "The following plot shows the predictions obtained for the year 2007 by using a TBATS model to fit the time series." }, { "code": null, "e": 11706, "s": 11630, "text": "The model was fitted by using the tbats function of the forecast R package." }, { "code": null, "e": 11870, "s": 11706, "text": "Prophet is another forecasting model which allows to deal with multiple seasonalities. It is an open source software released by Facebook’s Core Data Science team." }, { "code": null, "e": 11951, "s": 11870, "text": "The prophet model assumes that the the time series can be decomposed as follows:" }, { "code": null, "e": 11984, "s": 11951, "text": "y(t) = g(t) + s(t) + h(t) + ε(t)" }, { "code": null, "e": 12112, "s": 11984, "text": "The three terms g(t), s(t) and h(t) correspond respectively to trend, seasonality and holiday. The last term is the error term." }, { "code": null, "e": 12325, "s": 12112, "text": "The model fitting is framed as a curve-fitting exercise, therefore it does not explicitly take into account the temporal dependence structure in the data. This also allows to have irregularly spaced observations." }, { "code": null, "e": 12571, "s": 12325, "text": "There are two options for trend time series: a saturating growth model, and a piecewise linear model. The multi-period seasonality model relies on Fourier series. The effect of known and custom holydays can be easily incorporated into the model." }, { "code": null, "e": 12740, "s": 12571, "text": "The prophet model is inserted in a Bayesian framework and it allows to make full posterior inference to include model parameter uncertainty in the forecast uncertainty." }, { "code": null, "e": 12798, "s": 12740, "text": "For a complete introduction to Prophet model, click here." }, { "code": null, "e": 12915, "s": 12798, "text": "The following plot shows the predictions obtained for the year 2007 by using a Prophet model to fit the time series." }, { "code": null, "e": 12992, "s": 12915, "text": "The model was fitted by using the prophet function of the prophet R package." }, { "code": null, "e": 13100, "s": 12992, "text": "The NNETAR model is a fully connected neural network. The acronym stands for Neural NETwork AutoRegression." }, { "code": null, "e": 13294, "s": 13100, "text": "The NNETAR model takes in input the last elements of the sequence up to time t and outputs the forecasted value at time t+1. To perform multi-steps forecasts the network is applied iteratively." }, { "code": null, "e": 13442, "s": 13294, "text": "In presence of seasonality, the input may include also the seasonally lagged time series. For a complete introduction to NNETAR models, click here." }, { "code": null, "e": 13631, "s": 13442, "text": "The following plots show the predictions obtained for the year 2007 obtained by using a NNETAR model with seasonally lagged input and a NNETAR model on the seasonally adjusted time series." }, { "code": null, "e": 13710, "s": 13631, "text": "The models were fitted by using the nnetar function of the forecast R package." }, { "code": null, "e": 13865, "s": 13710, "text": "LSTM models can be used to forecast time series (as well as other Recurrent Neural Networks). LSTM is an acronym that stands for Long-Short Term Memories." }, { "code": null, "e": 14048, "s": 13865, "text": "The state of a LSTM network is represented through a state space vector. This technique allows to keep tracks of dependencies of new observations with past ones (even very far ones)." }, { "code": null, "e": 14324, "s": 14048, "text": "Generally speaking, LSTMs are complex models and they are rarely used for predicting a single time-series, because they require a large amount of data to be estimated. However, they are commonly used when predictions are needed for a large number of time-series (check here)." }, { "code": null, "e": 14403, "s": 14324, "text": "For a complete introduction on using LSTM to forecast time series, click here." }, { "code": null, "e": 14552, "s": 14403, "text": "The following plot shows the predictions for the first year in the test set obtained by fitting a LSTM model on the seasonally adjusted time series." }, { "code": null, "e": 14613, "s": 14552, "text": "The model was fitted by using the Keras framework in Python." }, { "code": null, "e": 14825, "s": 14613, "text": "We performed model selection through the cross-validation procedure described previously. We didn’t compute it for dynamic linear models and LSTM models due to their high computational cost and poor performance." }, { "code": null, "e": 14924, "s": 14825, "text": "In the following picture we show the cross-validated MAE for each model and for each time horizon." }, { "code": null, "e": 15138, "s": 14924, "text": "We can see that, for time horizons greater than 4, the NNETAR model on the seasonally adjusted data performed better than the others. Let’s check the overall MAE computed by averaging over different time horizons." }, { "code": null, "e": 15284, "s": 15138, "text": "The NNETAR model on the seasonally adjusted data was the best model for this application since it corresponded to the lowest cross-validated MAE." }, { "code": null, "e": 15512, "s": 15284, "text": "To get an unbiased estimation of the best model performance, we computed the MAE on the test set, obtaining an estimate equal to 5,24. In the following picture we can see the MAE estimated on the test set for each time horizon." }, { "code": null, "e": 15570, "s": 15512, "text": "Other techniques to increase models performance could be:" }, { "code": null, "e": 15621, "s": 15570, "text": "Using different models for different time horizons" }, { "code": null, "e": 15692, "s": 15621, "text": "Combining multiple forecasts (e.g. considering the average prediction)" }, { "code": null, "e": 15714, "s": 15692, "text": "Bootstrap Aggregating" }, { "code": null, "e": 15763, "s": 15714, "text": "The last technique can be summarised as follows:" }, { "code": null, "e": 15974, "s": 15763, "text": "Decompose the original time series (e.g. by using STL)Generate a set of similar time series by randomly shuffling chunks of the Remainder componentFit a model on each time seriesAverage forecasts of every model" }, { "code": null, "e": 16029, "s": 15974, "text": "Decompose the original time series (e.g. by using STL)" }, { "code": null, "e": 16123, "s": 16029, "text": "Generate a set of similar time series by randomly shuffling chunks of the Remainder component" }, { "code": null, "e": 16155, "s": 16123, "text": "Fit a model on each time series" }, { "code": null, "e": 16188, "s": 16155, "text": "Average forecasts of every model" }, { "code": null, "e": 16254, "s": 16188, "text": "For a complete introduction to Bootstrap Aggregating, click here." }, { "code": null, "e": 16528, "s": 16254, "text": "The goal of this project wasn’t to fit the best possible forecasting model for industrial production index, but to give an overview of forecasting models. In a real world application a lot of time should be spent on preprocessing, feature engineering and feature selection." }, { "code": null, "e": 16929, "s": 16528, "text": "Most of the previously described models allow to easily incorporate time varying predictors. These could be extracted from the same time series or could correspond to external predictors (e.g. the time series of another index). In the latter case we should pay attention to not use information from the future, which could be satisfied by forecasting the predictors or by using their lagged versions." } ]
Possibility of moving out of maze in C++
In this problem, we are given a maze of n integers, each integer indicates the number of moves to be done. Along with the direction indicated using ‘>’ and ‘<’. Our task is to find whether it is possible to move out of the maze or not if the starting point is the position at 0 indexes. Let’s take an example to understand the problem Input − 3 2 1 1 4 > < > > Output − YES Explanation − moving from start, we will move 2 positions ahead, then 1 position ahead, then 4 positions ahead. This will move our of the maze. To solve this problem, we will check whether moving out of the maze is possible or not. For this either we need to go below 0 or above n. Starting from 0, we will process the direction based on the sign by given integer places. And check if the end is reached. One more condition that can arise is an infinite loop, i.e. the condition when the user never breaks out of the maze, this is when we come back to a visiting position. So, to check this condition we will mark all visited places. Program to show the implementation of our solution Live Demo #include <iostream> using namespace std; void isMazeSolvable (int a[], int n, string s){ int mark[n] = {0}; int start = 0; int possible = 1; while (start >= 0 && start < n){ if (s == "<"){ if (mark[start] == 0){ mark[start] = 1; start -= a[start]; } else { possible = 0; break; } } else { if (mark[start] == 0){ mark[start] = 1; start += a[start]; } else { possible = 0; break; } } } if (possible == 0) cout << "It stays inside the maze forever"; else cout << "It will come out of the maze"; } int main (){ int n = 3; string s = ">><"; int a[] = { 1, 2, 4 }; isMazeSolvable (a, n, s); } It will come out of the maze
[ { "code": null, "e": 1349, "s": 1062, "text": "In this problem, we are given a maze of n integers, each integer indicates the number of moves to be done. Along with the direction indicated using ‘>’ and ‘<’. Our task is to find whether it is possible to move out of the maze or not if the starting point is the position at 0 indexes." }, { "code": null, "e": 1397, "s": 1349, "text": "Let’s take an example to understand the problem" }, { "code": null, "e": 1405, "s": 1397, "text": "Input −" }, { "code": null, "e": 1423, "s": 1405, "text": "3\n2 1 1 4\n> < > >" }, { "code": null, "e": 1436, "s": 1423, "text": "Output − YES" }, { "code": null, "e": 1580, "s": 1436, "text": "Explanation − moving from start, we will move 2 positions ahead, then 1 position ahead, then 4 positions ahead. This will move our of the maze." }, { "code": null, "e": 1841, "s": 1580, "text": "To solve this problem, we will check whether moving out of the maze is possible or not. For this either we need to go below 0 or above n. Starting from 0, we will process the direction based on the sign by given integer places. And check if the end is reached." }, { "code": null, "e": 2070, "s": 1841, "text": "One more condition that can arise is an infinite loop, i.e. the condition when the user never breaks out of the maze, this is when we come back to a visiting position. So, to check this condition we will mark all visited places." }, { "code": null, "e": 2121, "s": 2070, "text": "Program to show the implementation of our solution" }, { "code": null, "e": 2132, "s": 2121, "text": " Live Demo" }, { "code": null, "e": 2932, "s": 2132, "text": "#include <iostream>\nusing namespace std;\nvoid isMazeSolvable (int a[], int n, string s){\n int mark[n] = {0};\n int start = 0;\n int possible = 1;\n while (start >= 0 && start < n){\n if (s == \"<\"){\n if (mark[start] == 0){\n mark[start] = 1;\n start -= a[start];\n } else {\n possible = 0;\n break;\n }\n } else {\n if (mark[start] == 0){\n mark[start] = 1;\n start += a[start];\n } else {\n possible = 0;\n break;\n }\n }\n }\n if (possible == 0)\n cout << \"It stays inside the maze forever\";\n else\n cout << \"It will come out of the maze\";\n}\nint main (){\n int n = 3;\n string s = \">><\";\n int a[] = { 1, 2, 4 };\n isMazeSolvable (a, n, s);\n}" }, { "code": null, "e": 2961, "s": 2932, "text": "It will come out of the maze" } ]
Largest Values From Labels in Python
Suppose we have a set of items: the i-th item has value values[i] and label labels[i]. Then, we will take a subset S of these items, such that − |S| <= num_wanted For every label L, the number of items present in S with label L is <= use_limit. We have to find the largest possible sum of the subset S. For example, if the input is like values = [5,4,3,2,1] and labels are [1,1,2,2,3], num_wanted = 3, use_limit = 1, then the output will be 9. This is because the subset chosen in the first, third and fifth item. To solve this, we will follow these steps − make one array v for i in range 0 to length of valuesinsert [values[i], labels[i]] into v insert [values[i], labels[i]] into v sort the v array ans := 0, use := empty map, and i := 0 while num_wanted and i < length of vif v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1increase i by 1 if v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1 decrease num_wanted by 1 ans := ans + v[i, 0] use[v[i, 1]] := 1 else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1 decrease num_wanted by 1 ans := ans + v[i, 0] increase use[v[i, 1]] by 1 increase i by 1 return ans Let us see the following implementation to get better understanding − Live Demo class Solution(object): def largestValsFromLabels(self, values, labels, num_wanted, use_limit): v = [] for i in range(len(values)): v.append([values[i],labels[i]]) v = sorted(v,key = lambda v:v[0],reverse=True) ans = 0 use = {} i = 0 while num_wanted and i < len(v): if v[i][1] not in use: num_wanted -=1 ans+=v[i][0] use[v[i][1]] = 1 elif use[v[i][1]]<use_limit: num_wanted -=1 ans+=v[i][0] use[v[i][1]]+=1 i+=1 return ans ob = Solution() print(ob.largestValsFromLabels([5,4,3,2,1],[1,1,2,2,3],3,1)) [5,4,3,2,1] [1,1,2,2,3] 3 1 9
[ { "code": null, "e": 1207, "s": 1062, "text": "Suppose we have a set of items: the i-th item has value values[i] and label labels[i]. Then, we will take a subset S of these items, such that −" }, { "code": null, "e": 1225, "s": 1207, "text": "|S| <= num_wanted" }, { "code": null, "e": 1307, "s": 1225, "text": "For every label L, the number of items present in S with label L is <= use_limit." }, { "code": null, "e": 1365, "s": 1307, "text": "We have to find the largest possible sum of the subset S." }, { "code": null, "e": 1576, "s": 1365, "text": "For example, if the input is like values = [5,4,3,2,1] and labels are [1,1,2,2,3], num_wanted = 3, use_limit = 1, then the output will be 9. This is because the subset chosen in the first, third and fifth item." }, { "code": null, "e": 1620, "s": 1576, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1637, "s": 1620, "text": "make one array v" }, { "code": null, "e": 1710, "s": 1637, "text": "for i in range 0 to length of valuesinsert [values[i], labels[i]] into v" }, { "code": null, "e": 1747, "s": 1710, "text": "insert [values[i], labels[i]] into v" }, { "code": null, "e": 1764, "s": 1747, "text": "sort the v array" }, { "code": null, "e": 1803, "s": 1764, "text": "ans := 0, use := empty map, and i := 0" }, { "code": null, "e": 2051, "s": 1803, "text": "while num_wanted and i < length of vif v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1increase i by 1" }, { "code": null, "e": 2149, "s": 2051, "text": "if v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1" }, { "code": null, "e": 2174, "s": 2149, "text": "decrease num_wanted by 1" }, { "code": null, "e": 2195, "s": 2174, "text": "ans := ans + v[i, 0]" }, { "code": null, "e": 2213, "s": 2195, "text": "use[v[i, 1]] := 1" }, { "code": null, "e": 2313, "s": 2213, "text": "else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1" }, { "code": null, "e": 2338, "s": 2313, "text": "decrease num_wanted by 1" }, { "code": null, "e": 2359, "s": 2338, "text": "ans := ans + v[i, 0]" }, { "code": null, "e": 2386, "s": 2359, "text": "increase use[v[i, 1]] by 1" }, { "code": null, "e": 2402, "s": 2386, "text": "increase i by 1" }, { "code": null, "e": 2413, "s": 2402, "text": "return ans" }, { "code": null, "e": 2483, "s": 2413, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2494, "s": 2483, "text": " Live Demo" }, { "code": null, "e": 3154, "s": 2494, "text": "class Solution(object):\n def largestValsFromLabels(self, values, labels, num_wanted, use_limit):\n v = []\n for i in range(len(values)):\n v.append([values[i],labels[i]])\n v = sorted(v,key = lambda v:v[0],reverse=True)\n ans = 0\n use = {}\n i = 0\n while num_wanted and i < len(v):\n if v[i][1] not in use:\n num_wanted -=1\n ans+=v[i][0]\n use[v[i][1]] = 1\n elif use[v[i][1]]<use_limit:\n num_wanted -=1\n ans+=v[i][0]\n use[v[i][1]]+=1\n i+=1\n return ans\nob = Solution()\nprint(ob.largestValsFromLabels([5,4,3,2,1],[1,1,2,2,3],3,1))" }, { "code": null, "e": 3182, "s": 3154, "text": "[5,4,3,2,1]\n[1,1,2,2,3]\n3\n1" }, { "code": null, "e": 3184, "s": 3182, "text": "9" } ]
Count Odd Even | Practice | GeeksforGeeks
Given an array A[] of N elements. The task is to count number of even and odd elements in the array. Example: Input: N = 5 A[] = 1 2 3 4 5 Output: 3 2 Explanation: There are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4). Your Task: Your task is to complete the function countOddEven() which should print number of odd and number of even elements in a single line seperated by space. Print a newline at the end of output. Constraints: 1 <= N <= 106 1 <= Ai <= 106 0 chitranshugupta20032 days ago void countOddEven(int arr[], int sizeof_array) { // your code here int i,counti=0,counto=0; for(i=0;i<sizeof_array;i++) { if(arr[i]%2!=0) { counti++; } else { counto++; } } cout<<counti<<" "<<counto<<endl; } 0 atif836146 days ago JAVA SOLUTION if(n==0){ return; } int even=0; int odd=0; for(int i=0;i<n;i++){ if(arr[i]%2==0){ even++; } else{ odd++; } } System.out.print(odd+" "+even); System.out.println(); 0 mehtay0376 days ago Python Solution: class Solution:def countOddEven(self, arr, n): #Code here count_e,count_o=0,0 for i in arr: if(i%2==0): count_e+=1 else: count_o+=1 print(count_o,count_e) 0 harshscode1 week ago long long int even=0,odd=0; for(int i=0;i<n;i++) { if(a[i]%2==0) even=even+1; else odd=odd+1; } cout<<odd<<" "<<even<<endl; 0 diagovenk1 week ago Hello guys. Easy java solution using bitwise operator. public void countOddEven(int[] arr, int n) { // Code here int odd = 0; int even = 0; for(int i=0; i<n; i++){ if((arr[i]&1)>0){ odd++; } else{ even++; } } System.out.print(odd+" "); System.out.print(even); System.out.println(); } 0 rajsinghrathour03 weeks ago simple and easy solution in c++ int odd=0; int even=0; for(int i=0;i<sizeof_array;i++){ if(arr[i]%2==1) odd=odd+1; else even=even+1; } cout<<odd<<" "<<even<<endl; 0 rafysiddiky3 weeks ago void countOddEven(int arr[], int sizeof_array) { int odd_count = 0 , even_count = 0; for(int i = 0; i < sizeof_array; i++){ if(arr[i] & 1){ odd_count++; }else{ even_count++; } } cout << odd_count << " " << even_count << "\n"; } 0 ashutosh0366tripathi3 weeks ago def countOddEven(self, arr, n): even=0 odd=0 for i in arr: if i%2==0: even+=1 else: odd+=1 print(odd,even) 0 hs00000ynr4 weeks ago int even=0, odd=0; for(int i=0; i<sizeof_array; i++) { if(arr[i]%2==0){ even++; } else{ odd++; } } cout<<odd<<" "<<even; } why my code is not pass the test cases 0 musheerjamadar10241 month ago int even =0; int odd =0; for(int a:arr){ if(a%2 == 0) even++; else odd++; } System.out.println(odd+ " "+even); We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 379, "s": 278, "text": "Given an array A[] of N elements. The task is to count number of even and odd elements in the array." }, { "code": null, "e": 388, "s": 379, "text": "Example:" }, { "code": null, "e": 508, "s": 388, "text": "Input:\nN = 5\nA[] = 1 2 3 4 5\nOutput:\n3 2\nExplanation:\nThere are 3 odd elements (1, 3, 5)\nand 2 even elements (2 and 4)." }, { "code": null, "e": 708, "s": 508, "text": "Your Task:\nYour task is to complete the function countOddEven() which should print number of odd and number of even elements in a single line seperated by space.\nPrint a newline at the end of output." }, { "code": null, "e": 750, "s": 708, "text": "Constraints:\n1 <= N <= 106\n1 <= Ai <= 106" }, { "code": null, "e": 752, "s": 750, "text": "0" }, { "code": null, "e": 782, "s": 752, "text": "chitranshugupta20032 days ago" }, { "code": null, "e": 1128, "s": 782, "text": "void countOddEven(int arr[], int sizeof_array) { // your code here int i,counti=0,counto=0; for(i=0;i<sizeof_array;i++) { if(arr[i]%2!=0) { counti++; } else { counto++; } } cout<<counti<<\" \"<<counto<<endl; } " }, { "code": null, "e": 1130, "s": 1128, "text": "0" }, { "code": null, "e": 1150, "s": 1130, "text": "atif836146 days ago" }, { "code": null, "e": 1164, "s": 1150, "text": "JAVA SOLUTION" }, { "code": null, "e": 1443, "s": 1164, "text": " if(n==0){ return; } int even=0; int odd=0; for(int i=0;i<n;i++){ if(arr[i]%2==0){ even++; } else{ odd++; } } System.out.print(odd+\" \"+even); System.out.println();" }, { "code": null, "e": 1445, "s": 1443, "text": "0" }, { "code": null, "e": 1465, "s": 1445, "text": "mehtay0376 days ago" }, { "code": null, "e": 1482, "s": 1465, "text": "Python Solution:" }, { "code": null, "e": 1670, "s": 1482, "text": "class Solution:def countOddEven(self, arr, n): #Code here count_e,count_o=0,0 for i in arr: if(i%2==0): count_e+=1 else: count_o+=1 print(count_o,count_e) " }, { "code": null, "e": 1674, "s": 1672, "text": "0" }, { "code": null, "e": 1695, "s": 1674, "text": "harshscode1 week ago" }, { "code": null, "e": 1895, "s": 1695, "text": " long long int even=0,odd=0; for(int i=0;i<n;i++) { if(a[i]%2==0) even=even+1; else odd=odd+1; } cout<<odd<<\" \"<<even<<endl; " }, { "code": null, "e": 1897, "s": 1895, "text": "0" }, { "code": null, "e": 1917, "s": 1897, "text": "diagovenk1 week ago" }, { "code": null, "e": 1972, "s": 1917, "text": "Hello guys. Easy java solution using bitwise operator." }, { "code": null, "e": 2321, "s": 1972, "text": "public void countOddEven(int[] arr, int n) { // Code here int odd = 0; int even = 0; for(int i=0; i<n; i++){ if((arr[i]&1)>0){ odd++; } else{ even++; } } System.out.print(odd+\" \"); System.out.print(even); System.out.println(); }" }, { "code": null, "e": 2323, "s": 2321, "text": "0" }, { "code": null, "e": 2351, "s": 2323, "text": "rajsinghrathour03 weeks ago" }, { "code": null, "e": 2383, "s": 2351, "text": "simple and easy solution in c++" }, { "code": null, "e": 2604, "s": 2387, "text": " int odd=0; int even=0; for(int i=0;i<sizeof_array;i++){ if(arr[i]%2==1) odd=odd+1; else even=even+1; } cout<<odd<<\" \"<<even<<endl; " }, { "code": null, "e": 2606, "s": 2604, "text": "0" }, { "code": null, "e": 2629, "s": 2606, "text": "rafysiddiky3 weeks ago" }, { "code": null, "e": 2970, "s": 2629, "text": "void countOddEven(int arr[], int sizeof_array) { int odd_count = 0 , even_count = 0; for(int i = 0; i < sizeof_array; i++){ if(arr[i] & 1){ odd_count++; }else{ even_count++; } } cout << odd_count << \" \" << even_count << \"\\n\"; }" }, { "code": null, "e": 2972, "s": 2970, "text": "0" }, { "code": null, "e": 3004, "s": 2972, "text": "ashutosh0366tripathi3 weeks ago" }, { "code": null, "e": 3162, "s": 3004, "text": "def countOddEven(self, arr, n): even=0 odd=0 for i in arr: if i%2==0: even+=1 else: odd+=1 print(odd,even)" }, { "code": null, "e": 3164, "s": 3162, "text": "0" }, { "code": null, "e": 3186, "s": 3164, "text": "hs00000ynr4 weeks ago" }, { "code": null, "e": 3402, "s": 3186, "text": "int even=0, odd=0; for(int i=0; i<sizeof_array; i++) { if(arr[i]%2==0){ even++; } else{ odd++; } } cout<<odd<<\" \"<<even; }" }, { "code": null, "e": 3447, "s": 3408, "text": "why my code is not pass the test cases" }, { "code": null, "e": 3451, "s": 3449, "text": "0" }, { "code": null, "e": 3481, "s": 3451, "text": "musheerjamadar10241 month ago" }, { "code": null, "e": 3661, "s": 3481, "text": " int even =0; int odd =0; for(int a:arr){ if(a%2 == 0) even++; else odd++; } System.out.println(odd+ \" \"+even);" }, { "code": null, "e": 3809, "s": 3663, "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": 3845, "s": 3809, "text": " Login to access your submissions. " }, { "code": null, "e": 3855, "s": 3845, "text": "\nProblem\n" }, { "code": null, "e": 3865, "s": 3855, "text": "\nContest\n" }, { "code": null, "e": 3928, "s": 3865, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4076, "s": 3928, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4284, "s": 4076, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4390, "s": 4284, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
AngularJS | angular.isDefined() Function - GeeksforGeeks
12 Apr, 2019 The angular.isDefined() function in AngularJS is used to determine the value inside isDefined function is defined or not. It returns true if the reference is a defined otherwise returns false. Syntax: angular.isDefined( value ) Return Value: It returns true if the passed value is defined otherwise returns false. Example: This example uses angular.isDefined() function to determine the value inside isDefined function is defined or not. <!DOCTYPE html><html> <head> <title>angular.isDefined()</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.isDefined()</h2> <div ng-controller="geek"> <b>Date:</b> {{date}}<br><br> {{isDefined}} </div> <!-- Script to uses angular.isDefined() function --> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.date; $scope.isDefined = angular.isDefined($scope.date) == true ? "$scope.date is defined." : "$scope.date is undefined."; }]); </script> </body></html> Output: Date not Defined: If Date is defined and its value is “2019-04-07T23:46:20.586”: AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular | keyup event Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Auth Guards in Angular 9/10/11 Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 30067, "s": 30039, "text": "\n12 Apr, 2019" }, { "code": null, "e": 30260, "s": 30067, "text": "The angular.isDefined() function in AngularJS is used to determine the value inside isDefined function is defined or not. It returns true if the reference is a defined otherwise returns false." }, { "code": null, "e": 30268, "s": 30260, "text": "Syntax:" }, { "code": null, "e": 30295, "s": 30268, "text": "angular.isDefined( value )" }, { "code": null, "e": 30381, "s": 30295, "text": "Return Value: It returns true if the passed value is defined otherwise returns false." }, { "code": null, "e": 30505, "s": 30381, "text": "Example: This example uses angular.isDefined() function to determine the value inside isDefined function is defined or not." }, { "code": "<!DOCTYPE html><html> <head> <title>angular.isDefined()</title> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.isDefined()</h2> <div ng-controller=\"geek\"> <b>Date:</b> {{date}}<br><br> {{isDefined}} </div> <!-- Script to uses angular.isDefined() function --> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.date; $scope.isDefined = angular.isDefined($scope.date) == true ? \"$scope.date is defined.\" : \"$scope.date is undefined.\"; }]); </script> </body></html> ", "e": 31437, "s": 30505, "text": null }, { "code": null, "e": 31445, "s": 31437, "text": "Output:" }, { "code": null, "e": 31463, "s": 31445, "text": "Date not Defined:" }, { "code": null, "e": 31526, "s": 31463, "text": "If Date is defined and its value is “2019-04-07T23:46:20.586”:" }, { "code": null, "e": 31536, "s": 31526, "text": "AngularJS" }, { "code": null, "e": 31553, "s": 31536, "text": "Web Technologies" }, { "code": null, "e": 31651, "s": 31553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31671, "s": 31651, "text": "Angular File Upload" }, { "code": null, "e": 31693, "s": 31671, "text": "Angular | keyup event" }, { "code": null, "e": 31728, "s": 31693, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31763, "s": 31728, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31794, "s": 31763, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31834, "s": 31794, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31867, "s": 31834, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31912, "s": 31867, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31955, "s": 31912, "text": "How to fetch data from an API in ReactJS ?" } ]
MySQL - CREATE EVENT Statement
A MySQL Event is nothing but a task that execute at a particular schedule. An event can contain one or more MySQL statements these statements are stored in the databases and gets executed at the specified schedule. The CREATE EVENT statement is used to create and schedule an MYSQL event. Following is the syntax of the MySQL CREATE EVENT statement − CREATE EVENT [IF NOT EXISTS] event_name ON SCHEDULE time_stamp DO event_body; Where, event_name is the name of the event you need to create, time_stamp is the time at which the statements should be executed and event_body is the set of statement to be executed. Assume we have created a table with name data using the CREATE TABLE statement as shown below − mysql> CREATE TABLE Data (Name VARCHAR(255), age INT); Query OK, 0 rows affected (2.70 sec) Following query creates an event with name test_event, it inserts a record in the above created table one minute after the execution − mysql> CREATE EVENT example_event1 ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 Minute DO INSERT INTO new.Data VALUES('Rahman', 25); Query OK, 0 rows affected (0.20 sec) You can also pass the exact time to execute the event. First of all let us retrieve the current time using the Now() function as shown below − mysql> Select Now(); +---------------------+ | Now() | +---------------------+ | 2021-02-10 12:09:30 | +---------------------+ MySQL CREATE EVENT Statement 1 row in set (0.09 sec) Following query creates another event to which we pass the current time stamp as schedule − mysql> CREATE EVENT example_event2 ON SCHEDULE AT '2021-02-10 12:09:30' DO INSERT INTO new.Data VALUES('Raju', 30); Query OK, 0 rows affected (0.17 sec) After one minute if you verify the contents of the table data using the SELECT statement you can observe the inserted records as shown below − mysql> SELECT * from data; +--------+------+ | Name | age | +--------+------+ | Rahman | 25 | | Raju | 30 | +--------+------+ 2 rows in set (0.00 sec) If you use the IF NOT EXISTS clause along with the CREATE EVENT statement as shown below a new event will be created and if an event with the given name, already exists the query will be ignored. mysql> CREATE EVENT IF NOT EXISTS example_event2 ON SCHEDULE AT CURRENT_TIMESTAMP DO DROP TABLE Data; Query OK, 0 rows affected (0.36 sec) Using EVERY clause, you can create an event with an interval as a schedule following is the syntax to do so − CREATE EVENT event_name ON SCHEDULE EVERY interval quantity DO event_body; Following query creates an event which truncates the table data every month − mysql> CREATE EVENT event_hourly ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data; Query OK, 0 rows affected (0.27 sec) You can add a comment while creating an event using this clause Following is the syntax to do so − CREATE EVENT event_name ON SCHEDULE schedule COMMENT 'comment_string' DO event_body; Where comment_string is the comment you need to add. Following query adds a comment while creating an event − mysql> CREATE EVENT event_hourly1 ON SCHEDULE EVERY 1 MONTH COMMENT 'This truncates the data table each month' DO TRUNCATE TABLE data; Query OK, 0 rows affected (0.25 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2548, "s": 2333, "text": "A MySQL Event is nothing but a task that execute at a particular schedule. An event can contain one or more MySQL statements these statements are stored in the databases and gets executed at the specified schedule." }, { "code": null, "e": 2622, "s": 2548, "text": "The CREATE EVENT statement is used to create and schedule an MYSQL event." }, { "code": null, "e": 2684, "s": 2622, "text": "Following is the syntax of the MySQL CREATE EVENT statement −" }, { "code": null, "e": 2769, "s": 2684, "text": "CREATE EVENT [IF NOT EXISTS] event_name\n ON SCHEDULE time_stamp\n DO event_body;\n" }, { "code": null, "e": 2953, "s": 2769, "text": "Where, event_name is the name of the event you need to create, time_stamp is the time at which the statements should be executed and event_body is the set of statement to be executed." }, { "code": null, "e": 3049, "s": 2953, "text": "Assume we have created a table with name data using the CREATE TABLE statement as shown below −" }, { "code": null, "e": 3142, "s": 3049, "text": "mysql> CREATE TABLE Data (Name VARCHAR(255), age INT);\nQuery OK, 0 rows affected (2.70 sec)\n" }, { "code": null, "e": 3277, "s": 3142, "text": "Following query creates an event with name test_event, it inserts a record in the above created table one minute after the execution −" }, { "code": null, "e": 3449, "s": 3277, "text": "mysql> CREATE EVENT example_event1 ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 Minute DO INSERT INTO new.Data VALUES('Rahman', 25);\nQuery OK, 0 rows affected (0.20 sec)\n" }, { "code": null, "e": 3592, "s": 3449, "text": "You can also pass the exact time to execute the event. First of all let us retrieve the current time using the Now() function as shown below −" }, { "code": null, "e": 3786, "s": 3592, "text": "mysql> Select Now();\n+---------------------+\n| Now() |\n+---------------------+\n| 2021-02-10 12:09:30 |\n+---------------------+ MySQL CREATE EVENT Statement\n1 row in set (0.09 sec)" }, { "code": null, "e": 3878, "s": 3786, "text": "Following query creates another event to which we pass the current time stamp as schedule −" }, { "code": null, "e": 4032, "s": 3878, "text": "mysql> CREATE EVENT example_event2 ON SCHEDULE AT '2021-02-10 12:09:30' DO INSERT INTO new.Data VALUES('Raju', 30);\nQuery OK, 0 rows affected (0.17 sec)\n" }, { "code": null, "e": 4175, "s": 4032, "text": "After one minute if you verify the contents of the table data using the SELECT statement you can observe the inserted records as shown below −" }, { "code": null, "e": 4336, "s": 4175, "text": "mysql> SELECT * from data;\n+--------+------+\n| Name | age |\n+--------+------+\n| Rahman | 25 |\n| Raju | 30 |\n+--------+------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 4532, "s": 4336, "text": "If you use the IF NOT EXISTS clause along with the CREATE EVENT statement as shown below a new event will be created and if an event with the given name, already exists the query will be ignored." }, { "code": null, "e": 4672, "s": 4532, "text": "mysql> CREATE EVENT IF NOT EXISTS example_event2 ON SCHEDULE AT CURRENT_TIMESTAMP DO DROP TABLE Data;\nQuery OK, 0 rows affected (0.36 sec)\n" }, { "code": null, "e": 4782, "s": 4672, "text": "Using EVERY clause, you can create an event with an interval as a schedule following is the syntax to do so −" }, { "code": null, "e": 4858, "s": 4782, "text": "CREATE EVENT event_name ON SCHEDULE EVERY interval quantity DO event_body;\n" }, { "code": null, "e": 4936, "s": 4858, "text": "Following query creates an event which truncates the table data every month −" }, { "code": null, "e": 5057, "s": 4936, "text": "mysql> CREATE EVENT event_hourly ON SCHEDULE EVERY 1 MONTH DO TRUNCATE TABLE data;\nQuery OK, 0 rows affected (0.27 sec)\n" }, { "code": null, "e": 5156, "s": 5057, "text": "You can add a comment while creating an event using this clause Following is the syntax to do so −" }, { "code": null, "e": 5242, "s": 5156, "text": "CREATE EVENT event_name ON SCHEDULE schedule COMMENT 'comment_string' DO event_body;\n" }, { "code": null, "e": 5352, "s": 5242, "text": "Where comment_string is the comment you need to add. Following query adds a comment while creating an event −" }, { "code": null, "e": 5524, "s": 5352, "text": "mysql> CREATE EVENT\nevent_hourly1\nON SCHEDULE\nEVERY 1 MONTH\nCOMMENT 'This truncates the data table each month'\nDO\nTRUNCATE TABLE data;\nQuery OK, 0 rows affected (0.25 sec)" }, { "code": null, "e": 5557, "s": 5524, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5585, "s": 5557, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5620, "s": 5585, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5637, "s": 5620, "text": " Frahaan Hussain" }, { "code": null, "e": 5671, "s": 5637, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5706, "s": 5671, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5740, "s": 5706, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5768, "s": 5740, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5801, "s": 5768, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5821, "s": 5801, "text": " Harshit Srivastava" }, { "code": null, "e": 5854, "s": 5821, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 5872, "s": 5854, "text": " Trevoir Williams" }, { "code": null, "e": 5879, "s": 5872, "text": " Print" }, { "code": null, "e": 5890, "s": 5879, "text": " Add Notes" } ]
Tryit Editor v3.7
CSS Style Images Tryit: Different filters on image
[ { "code": null, "e": 26, "s": 9, "text": "CSS Style Images" } ]
Tryit Editor v3.7
Tryit: HTML link to same folder
[]
How to remove a particular value from a vector in R?
To remove a particular value from a vector, we can use negation of value. For example, if we have a vector called V that contains repetitive values starting from 1 to 10 and if we want to remove all 10s from V then we can use the command given below − V<-V[V!=10] In order to remove 0 from vector x1, use the code given below − x1<-rpois(100,2) x1 If you execute the above given code, it generates the following output − [1] 1 1 1 1 3 1 1 2 3 4 2 2 1 2 2 5 2 1 4 1 2 1 2 3 1 3 1 1 4 4 3 3 4 2 0 1 1 [38] 2 1 0 0 2 5 1 1 3 1 1 2 1 1 4 1 4 0 1 0 2 2 1 2 2 1 4 2 2 2 5 4 2 0 0 1 8 [75] 1 2 4 1 2 0 0 1 0 0 2 4 1 3 1 1 3 1 3 0 2 3 1 2 8 4 Now, to remove 0 from vector x1, add the following code to the above code − x1<-rpois(100,2) x1<-x1[x1!=0] x1 If you execute all the above given codes as a single program, it generates the following output − [1] 1 1 1 1 3 1 1 2 3 4 2 2 1 2 2 5 2 1 4 1 2 1 2 3 1 3 1 1 4 4 3 3 4 2 1 1 2 1 [39] 2 5 1 1 3 1 1 2 1 1 4 1 4 1 2 2 1 2 2 1 4 2 2 2 5 4 2 1 8 1 2 4 1 2 1 2 4 1 [77] 3 1 1 3 1 3 2 3 1 2 8 4 Consider the code given below for vector x2 − x2<-rpois(200,5) x2 If you execute the above given code, it generates the following output − [1] 7 5 3 8 1 6 4 5 7 4 3 5 7 5 7 8 9 7 7 10 7 5 8 4 3 [26] 3 7 9 2 4 3 4 5 5 4 8 6 6 6 2 3 5 2 3 10 2 8 11 8 7 [51] 6 2 5 7 3 5 4 3 4 10 4 6 7 4 1 6 8 6 4 4 5 4 2 3 3 [76] 6 6 5 6 8 4 15 3 4 4 5 6 6 4 2 7 3 1 8 1 10 5 8 4 6 [101] 2 3 7 3 6 5 6 4 7 2 3 4 2 7 3 5 7 2 4 5 7 6 6 3 1 [126] 9 5 5 2 8 4 6 5 5 6 5 8 7 6 2 3 7 2 1 8 5 6 10 6 4 [151] 5 6 7 6 8 0 4 9 6 11 2 6 7 4 2 7 6 6 8 6 6 5 4 6 2 [176] 9 7 5 6 9 2 6 7 10 4 3 5 3 3 8 3 2 5 6 9 6 3 4 4 8 Now, to remove 5 from vector x2, add the following code to the above code − x2<-x2[x2!=5] x2 If you execute all the above given codes as a single program, it generates the following output − [1] 7 3 8 1 6 4 7 4 3 7 7 8 9 7 7 10 7 8 4 3 3 7 9 2 4 [26] 3 4 4 8 6 6 6 2 3 2 3 10 2 8 11 8 7 6 2 7 3 4 3 4 10 [51] 4 6 7 4 1 6 8 6 4 4 4 2 3 3 6 6 6 8 4 15 3 4 4 6 6 [76] 4 2 7 3 1 8 1 10 8 4 6 2 3 7 3 6 6 4 7 2 3 4 2 7 3 [101] 7 2 4 7 6 6 3 1 9 2 8 4 6 6 8 7 6 2 3 7 2 1 8 6 10 [126] 6 4 6 7 6 8 0 4 9 6 11 2 6 7 4 2 7 6 6 8 6 6 4 6 2 [151] 9 7 6 9 2 6 7 10 4 3 3 3 8 3 2 6 9 6 3 4 4 8 Consider the code given below for vector x3 − x3<-sample(0:9,200,replace=TRUE) x3 If you execute the above given code, it generates the following output − [1] 4 9 7 6 3 9 8 6 2 8 0 2 7 1 3 0 8 6 2 3 4 9 9 0 5 2 4 6 3 0 3 4 3 1 3 0 3 [38] 5 9 5 8 8 3 9 8 4 5 3 5 2 3 1 4 0 8 7 3 1 8 9 5 6 4 2 5 3 1 3 1 0 9 8 5 1 [75] 8 4 4 1 5 6 8 1 5 7 0 4 3 7 0 1 4 5 4 5 2 0 5 8 8 3 0 4 0 2 0 5 6 9 8 8 6 [112] 0 2 6 4 7 7 6 1 9 7 7 2 6 3 0 5 3 5 6 0 1 6 9 2 9 5 2 9 4 5 3 5 5 6 5 1 7 [149] 6 3 4 8 2 0 0 2 7 0 1 4 1 1 6 6 2 7 2 3 7 7 9 7 6 7 3 8 1 2 2 9 8 7 8 9 2 [186] 1 8 7 6 4 0 5 2 9 3 4 2 3 7 9 Now, to remove 4 from vector x3, add the following code to the above code − x3<-sample(0:9,200,replace=TRUE) x3<-x3[x3!=4] x3 If you execute all the above given codes as a single program, it generates the following output − [1] 9 7 6 3 9 8 6 2 8 0 2 7 1 3 0 8 6 2 3 9 9 0 5 2 6 3 0 3 3 1 3 0 3 5 9 5 8 [38] 8 3 9 8 5 3 5 2 3 1 0 8 7 3 1 8 9 5 6 2 5 3 1 3 1 0 9 8 5 1 8 1 5 6 8 1 5 [75] 7 0 3 7 0 1 5 5 2 0 5 8 8 3 0 0 2 0 5 6 9 8 8 6 0 2 6 7 7 6 1 9 7 7 2 6 3 [112] 0 5 3 5 6 0 1 6 9 2 9 5 2 9 5 3 5 5 6 5 1 7 6 3 8 2 0 0 2 7 0 1 1 1 6 6 2 [149] 7 2 3 7 7 9 7 6 7 3 8 1 2 2 9 8 7 8 9 2 1 8 7 6 0 5 2 9 3 2 3 7 9 Consider the code given below for vector x4 − x4<-sample(1:10,200,replace=TRUE) x4 If you execute the above given code, it generates the following output − [1] 10 2 5 6 8 10 1 5 8 4 5 6 5 8 5 10 1 1 3 6 7 9 8 7 9 [26] 1 9 4 6 10 3 1 6 6 9 8 5 1 2 8 2 8 3 5 1 9 7 2 2 10 [51] 3 10 2 6 9 4 10 2 4 4 10 8 3 3 4 10 3 4 7 1 10 10 10 10 7 [76] 6 1 3 4 4 9 9 7 7 2 9 7 2 6 2 9 4 10 5 5 2 3 10 4 5 [101] 6 3 7 4 5 9 3 10 6 2 2 2 9 3 3 9 5 8 9 10 1 2 7 6 8 [126] 10 4 10 4 2 9 2 10 8 9 6 4 7 8 2 9 7 3 3 7 5 10 10 2 1 [151] 7 2 10 6 6 9 7 10 6 5 2 7 10 4 9 3 7 4 7 2 8 5 1 1 10 [176] 8 9 9 2 4 2 9 9 10 7 4 1 5 7 9 9 2 10 8 1 1 8 5 9 10 Now, to remove 1 from vector x4, add the following code to the above code − x4<-sample(1:10,200,replace=TRUE) x4<-x4[x4!=1] x4 If you execute all the above given codes as a single program, it generates the following output − [1] 10 2 5 6 8 10 5 8 4 5 6 5 8 5 10 3 6 7 9 8 7 9 9 4 6 [26] 10 3 6 6 9 8 5 2 8 2 8 3 5 9 7 2 2 10 3 10 2 6 9 4 10 [51] 2 4 4 10 8 3 3 4 10 3 4 7 10 10 10 10 7 6 3 4 4 9 9 7 7 [76] 2 9 7 2 6 2 9 4 10 5 5 2 3 10 4 5 6 3 7 4 5 9 3 10 6 [101] 2 2 2 9 3 3 9 5 8 9 10 2 7 6 8 10 4 10 4 2 9 2 10 8 9 [126] 6 4 7 8 2 9 7 3 3 7 5 10 10 2 7 2 10 6 6 9 7 10 6 5 2 [151] 7 10 4 9 3 7 4 7 2 8 5 10 8 9 9 2 4 2 9 9 10 7 4 5 7 [176] 9 9 2 10 8 8 5 9 10 Consider the code given below for vector x5 − x5<-rpois(200,1) x5 If you execute the above given code, it generates the following output − [1] 2 1 1 1 4 1 0 0 1 2 0 0 1 2 1 0 1 1 3 0 0 3 0 2 3 0 1 0 1 2 1 0 0 2 0 0 0 [38] 1 3 2 1 0 0 1 0 4 1 0 0 3 2 1 1 1 1 2 2 1 2 0 0 0 0 1 1 1 0 0 3 0 2 1 0 0 [75] 0 1 1 2 3 1 0 3 0 0 0 0 0 3 0 3 0 0 0 0 2 0 0 1 1 1 2 2 1 1 0 0 0 1 1 1 0 [112] 2 1 2 2 1 2 1 0 0 3 0 1 2 3 0 1 0 1 0 0 1 0 1 1 1 2 0 2 1 1 0 2 1 1 2 0 2 [149] 0 0 0 3 3 3 2 0 0 2 0 1 1 1 0 3 0 1 0 1 0 3 1 1 0 2 4 2 0 0 1 2 0 0 0 1 1 [186] 0 0 1 1 2 0 0 3 1 0 0 2 1 1 1 Now to remove 0 from vector x5, add the following code to the above code − x5<-rpois(200,1) x5<-x5[x5!=0] x5 If you execute all the above given codes as a single program, it generates the following output − [1] 2 1 1 1 4 1 1 2 1 2 1 1 1 3 3 2 3 1 1 2 1 2 1 3 2 1 1 4 1 3 2 1 1 1 1 2 2 [38] 1 2 1 1 1 3 2 1 1 1 2 3 1 3 3 3 2 1 1 1 2 2 1 1 1 1 1 2 1 2 2 1 2 1 3 1 2 [75] 3 1 1 1 1 1 1 2 2 1 1 2 1 1 2 2 3 3 3 2 2 1 1 1 3 1 1 3 1 1 2 4 2 1 2 1 1 [112] 1 1 2 3 1 2 1 1 1
[ { "code": null, "e": 1136, "s": 1062, "text": "To remove a particular value from a vector, we can use negation of value." }, { "code": null, "e": 1314, "s": 1136, "text": "For example, if we have a vector called V that contains repetitive values starting from 1 to 10 and if we want to remove all 10s from V then we can use the command given below −" }, { "code": null, "e": 1326, "s": 1314, "text": "V<-V[V!=10]" }, { "code": null, "e": 1390, "s": 1326, "text": "In order to remove 0 from vector x1, use the code given below −" }, { "code": null, "e": 1410, "s": 1390, "text": "x1<-rpois(100,2)\nx1" }, { "code": null, "e": 1483, "s": 1410, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 1697, "s": 1483, "text": "[1] 1 1 1 1 3 1 1 2 3 4 2 2 1 2 2 5 2 1 4 1 2 1 2 3 1 3 1 1 4 4 3 3 4 2 0 1 1\n[38] 2 1 0 0 2 5 1 1 3 1 1 2 1 1 4 1 4 0 1 0 2 2 1 2 2 1 4 2 2 2 5 4 2 0 0 1 8\n[75] 1 2 4 1 2 0 0 1 0 0 2 4 1 3 1 1 3 1 3 0 2 3 1 2 8 4" }, { "code": null, "e": 1773, "s": 1697, "text": "Now, to remove 0 from vector x1, add the following code to the above code −" }, { "code": null, "e": 1807, "s": 1773, "text": "x1<-rpois(100,2)\nx1<-x1[x1!=0]\nx1" }, { "code": null, "e": 1905, "s": 1807, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 2095, "s": 1905, "text": "[1] 1 1 1 1 3 1 1 2 3 4 2 2 1 2 2 5 2 1 4 1 2 1 2 3 1 3 1 1 4 4 3 3 4 2 1 1 2 1\n[39] 2 5 1 1 3 1 1 2 1 1 4 1 4 1 2 2 1 2 2 1 4 2 2 2 5 4 2 1 8 1 2 4 1 2 1 2 4 1\n[77] 3 1 1 3 1 3 2 3 1 2 8 4" }, { "code": null, "e": 2141, "s": 2095, "text": "Consider the code given below for vector x2 −" }, { "code": null, "e": 2161, "s": 2141, "text": "x2<-rpois(200,5)\nx2" }, { "code": null, "e": 2234, "s": 2161, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 2686, "s": 2234, "text": "[1] 7 5 3 8 1 6 4 5 7 4 3 5 7 5 7 8 9 7 7 10 7 5 8 4 3\n[26] 3 7 9 2 4 3 4 5 5 4 8 6 6 6 2 3 5 2 3 10 2 8 11 8 7\n[51] 6 2 5 7 3 5 4 3 4 10 4 6 7 4 1 6 8 6 4 4 5 4 2 3 3\n[76] 6 6 5 6 8 4 15 3 4 4 5 6 6 4 2 7 3 1 8 1 10 5 8 4 6\n[101] 2 3 7 3 6 5 6 4 7 2 3 4 2 7 3 5 7 2 4 5 7 6 6 3 1\n[126] 9 5 5 2 8 4 6 5 5 6 5 8 7 6 2 3 7 2 1 8 5 6 10 6 4\n[151] 5 6 7 6 8 0 4 9 6 11 2 6 7 4 2 7 6 6 8 6 6 5 4 6 2\n[176] 9 7 5 6 9 2 6 7 10 4 3 5 3 3 8 3 2 5 6 9 6 3 4 4 8" }, { "code": null, "e": 2762, "s": 2686, "text": "Now, to remove 5 from vector x2, add the following code to the above code −" }, { "code": null, "e": 2779, "s": 2762, "text": "x2<-x2[x2!=5]\nx2" }, { "code": null, "e": 2877, "s": 2779, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 3267, "s": 2877, "text": "[1] 7 3 8 1 6 4 7 4 3 7 7 8 9 7 7 10 7 8 4 3 3 7 9 2 4\n[26] 3 4 4 8 6 6 6 2 3 2 3 10 2 8 11 8 7 6 2 7 3 4 3 4 10\n[51] 4 6 7 4 1 6 8 6 4 4 4 2 3 3 6 6 6 8 4 15 3 4 4 6 6\n[76] 4 2 7 3 1 8 1 10 8 4 6 2 3 7 3 6 6 4 7 2 3 4 2 7 3\n[101] 7 2 4 7 6 6 3 1 9 2 8 4 6 6 8 7 6 2 3 7 2 1 8 6 10\n[126] 6 4 6 7 6 8 0 4 9 6 11 2 6 7 4 2 7 6 6 8 6 6 4 6 2\n[151] 9 7 6 9 2 6 7 10 4 3 3 3 8 3 2 6 9 6 3 4 4 8" }, { "code": null, "e": 3313, "s": 3267, "text": "Consider the code given below for vector x3 −" }, { "code": null, "e": 3349, "s": 3313, "text": "x3<-sample(0:9,200,replace=TRUE)\nx3" }, { "code": null, "e": 3422, "s": 3349, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 3854, "s": 3422, "text": "[1] 4 9 7 6 3 9 8 6 2 8 0 2 7 1 3 0 8 6 2 3 4 9 9 0 5 2 4 6 3 0 3 4 3 1 3 0 3\n[38] 5 9 5 8 8 3 9 8 4 5 3 5 2 3 1 4 0 8 7 3 1 8 9 5 6 4 2 5 3 1 3 1 0 9 8 5 1\n[75] 8 4 4 1 5 6 8 1 5 7 0 4 3 7 0 1 4 5 4 5 2 0 5 8 8 3 0 4 0 2 0 5 6 9 8 8 6\n[112] 0 2 6 4 7 7 6 1 9 7 7 2 6 3 0 5 3 5 6 0 1 6 9 2 9 5 2 9 4 5 3 5 5 6 5 1 7\n[149] 6 3 4 8 2 0 0 2 7 0 1 4 1 1 6 6 2 7 2 3 7 7 9 7 6 7 3 8 1 2 2 9 8 7 8 9 2\n[186] 1 8 7 6 4 0 5 2 9 3 4 2 3 7 9" }, { "code": null, "e": 3930, "s": 3854, "text": "Now, to remove 4 from vector x3, add the following code to the above code −" }, { "code": null, "e": 3980, "s": 3930, "text": "x3<-sample(0:9,200,replace=TRUE)\nx3<-x3[x3!=4]\nx3" }, { "code": null, "e": 4078, "s": 3980, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 4466, "s": 4078, "text": "[1] 9 7 6 3 9 8 6 2 8 0 2 7 1 3 0 8 6 2 3 9 9 0 5 2 6 3 0 3 3 1 3 0 3 5 9 5 8\n[38] 8 3 9 8 5 3 5 2 3 1 0 8 7 3 1 8 9 5 6 2 5 3 1 3 1 0 9 8 5 1 8 1 5 6 8 1 5\n[75] 7 0 3 7 0 1 5 5 2 0 5 8 8 3 0 0 2 0 5 6 9 8 8 6 0 2 6 7 7 6 1 9 7 7 2 6 3\n[112] 0 5 3 5 6 0 1 6 9 2 9 5 2 9 5 3 5 5 6 5 1 7 6 3 8 2 0 0 2 7 0 1 1 1 6 6 2\n[149] 7 2 3 7 7 9 7 6 7 3 8 1 2 2 9 8 7 8 9 2 1 8 7 6 0 5 2 9 3 2 3 7 9" }, { "code": null, "e": 4512, "s": 4466, "text": "Consider the code given below for vector x4 −" }, { "code": null, "e": 4549, "s": 4512, "text": "x4<-sample(1:10,200,replace=TRUE)\nx4" }, { "code": null, "e": 4622, "s": 4549, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 5094, "s": 4622, "text": "[1] 10 2 5 6 8 10 1 5 8 4 5 6 5 8 5 10 1 1 3 6 7 9 8 7 9\n[26] 1 9 4 6 10 3 1 6 6 9 8 5 1 2 8 2 8 3 5 1 9 7 2 2 10\n[51] 3 10 2 6 9 4 10 2 4 4 10 8 3 3 4 10 3 4 7 1 10 10 10 10 7\n[76] 6 1 3 4 4 9 9 7 7 2 9 7 2 6 2 9 4 10 5 5 2 3 10 4 5\n[101] 6 3 7 4 5 9 3 10 6 2 2 2 9 3 3 9 5 8 9 10 1 2 7 6 8\n[126] 10 4 10 4 2 9 2 10 8 9 6 4 7 8 2 9 7 3 3 7 5 10 10 2 1\n[151] 7 2 10 6 6 9 7 10 6 5 2 7 10 4 9 3 7 4 7 2 8 5 1 1 10\n[176] 8 9 9 2 4 2 9 9 10 7 4 1 5 7 9 9 2 10 8 1 1 8 5 9 10" }, { "code": null, "e": 5170, "s": 5094, "text": "Now, to remove 1 from vector x4, add the following code to the above code −" }, { "code": null, "e": 5221, "s": 5170, "text": "x4<-sample(1:10,200,replace=TRUE)\nx4<-x4[x4!=1]\nx4" }, { "code": null, "e": 5319, "s": 5221, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 5759, "s": 5319, "text": "[1] 10 2 5 6 8 10 5 8 4 5 6 5 8 5 10 3 6 7 9 8 7 9 9 4 6\n[26] 10 3 6 6 9 8 5 2 8 2 8 3 5 9 7 2 2 10 3 10 2 6 9 4 10\n[51] 2 4 4 10 8 3 3 4 10 3 4 7 10 10 10 10 7 6 3 4 4 9 9 7 7\n[76] 2 9 7 2 6 2 9 4 10 5 5 2 3 10 4 5 6 3 7 4 5 9 3 10 6\n[101] 2 2 2 9 3 3 9 5 8 9 10 2 7 6 8 10 4 10 4 2 9 2 10 8 9\n[126] 6 4 7 8 2 9 7 3 3 7 5 10 10 2 7 2 10 6 6 9 7 10 6 5 2\n[151] 7 10 4 9 3 7 4 7 2 8 5 10 8 9 9 2 4 2 9 9 10 7 4 5 7\n[176] 9 9 2 10 8 8 5 9 10" }, { "code": null, "e": 5805, "s": 5759, "text": "Consider the code given below for vector x5 −" }, { "code": null, "e": 5825, "s": 5805, "text": "x5<-rpois(200,1)\nx5" }, { "code": null, "e": 5898, "s": 5825, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 6330, "s": 5898, "text": "[1] 2 1 1 1 4 1 0 0 1 2 0 0 1 2 1 0 1 1 3 0 0 3 0 2 3 0 1 0 1 2 1 0 0 2 0 0 0\n[38] 1 3 2 1 0 0 1 0 4 1 0 0 3 2 1 1 1 1 2 2 1 2 0 0 0 0 1 1 1 0 0 3 0 2 1 0 0\n[75] 0 1 1 2 3 1 0 3 0 0 0 0 0 3 0 3 0 0 0 0 2 0 0 1 1 1 2 2 1 1 0 0 0 1 1 1 0\n[112] 2 1 2 2 1 2 1 0 0 3 0 1 2 3 0 1 0 1 0 0 1 0 1 1 1 2 0 2 1 1 0 2 1 1 2 0 2\n[149] 0 0 0 3 3 3 2 0 0 2 0 1 1 1 0 3 0 1 0 1 0 3 1 1 0 2 4 2 0 0 1 2 0 0 0 1 1\n[186] 0 0 1 1 2 0 0 3 1 0 0 2 1 1 1" }, { "code": null, "e": 6405, "s": 6330, "text": "Now to remove 0 from vector x5, add the following code to the above code −" }, { "code": null, "e": 6439, "s": 6405, "text": "x5<-rpois(200,1)\nx5<-x5[x5!=0]\nx5" }, { "code": null, "e": 6537, "s": 6439, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 6797, "s": 6537, "text": "[1] 2 1 1 1 4 1 1 2 1 2 1 1 1 3 3 2 3 1 1 2 1 2 1 3 2 1 1 4 1 3 2 1 1 1 1 2 2\n[38] 1 2 1 1 1 3 2 1 1 1 2 3 1 3 3 3 2 1 1 1 2 2 1 1 1 1 1 2 1 2 2 1 2 1 3 1 2\n[75] 3 1 1 1 1 1 1 2 2 1 1 2 1 1 2 2 3 3 3 2 2 1 1 1 3 1 1 3 1 1 2 4 2 1 2 1 1\n[112] 1 1 2 3 1 2 1 1 1" } ]
CSS @font-face rule - GeeksforGeeks
25 Nov, 2021 The @font-face CSS at-rule rule is used to associate a font name that can be used in a style sheet. A font-family descriptor is used within the rule to name the font and an src descriptor is associated with an external font name. This can be used with downloadable fonts. This CSS @font-face rule can contain more than one property (max 24). Syntax: @font-face { font-family: fontName; src: url(fontFile path); font-stretch: font-stretch Property; font-weight: font-weight Property; font-style: font-style Property; } Parameter: The @font-face rule accepts four-parameter as described below: font-family: It specifies the font of an element. src: It is used to specify the location (URL) of the external resource ie., it holds the file path (url). font-stretch: It is used to set the text wider or narrower. font-weight: It is used to set the weight or thickness of the font being used with the HTML Text. font-style: It is used to style the given particular text in a normal, italic, or oblique face from its font-family. Few hosted font services: These services will provide you with various types of fonts. Fonts.com Google Fonts Typotheque Typography Example 1: This example illustrates the use of the @font-face rule to specify the different font properties to decorate the text accordingly. HTML <!DOCTYPE html><html> <head> <title>CSS @font-face rule</title> <style> @font-face { font-family: fontName; src: url(sansation_light.woff); } @font-face { font-family: fontName; src: url(sansation_bold.woff); font-weight: bold; } div { font-family: fontName; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div>A Computer Science Portal fo Geeks</div> </center></body> </html> Output: Example 2: This example illustrates the use of the @font-face rule by specifying the source of the file path along with its format. HTML <!DOCTYPE html><html lang="en"> <head> <title>CSS @font-face rule</title> <style type="text/css"> @font-face { font-family: "OpenSans"; src: url("/examples/fonts/OpenSans-Regular.eot"); src: url("/examples/fonts/OpenSans-Regular.ttf") format("truetype"); font-stretch: normal; font-weight: normal; font-style: normal; } @font-face { font-family: "OpenSansBold"; src: url("/examples/fonts/OpenSans-Bold.eot"); src: url("/examples/fonts/OpenSans-Bold.ttf") format("truetype"); font-stretch: normal; font-weight: normal; font-style: normal; } /* Specify the OpenSans bold font */ h1 { font-family: "OpenSansBold", Arial, sans-serif; color: green; } p { font-family: "OpenSans", Arial, sans-serif; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </center></body> </html> Output: Note: There is 5 Font format those are: TTF/OTF, WOFF, WOFF2, SVG, and EOT. Supported Browsers: The browsers supported by CSS @font-face rule are listed below: Google Chrome (TTF/OTF, WOFF, WOFF2 and SVG) Internet Explorer (TTF/OTF, WOFF and EOT) Firefox (TTF/OTF, WOFF and WOFF2) Safari TTF/OTF, WOFF and SVG) Opera TTF/OTF, WOFF, WOFF2 and SVG bhaskargeeksforgeeks varshagumber28 CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set div width to fit content using CSS ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24854, "s": 24826, "text": "\n25 Nov, 2021" }, { "code": null, "e": 25197, "s": 24854, "text": "The @font-face CSS at-rule rule is used to associate a font name that can be used in a style sheet. A font-family descriptor is used within the rule to name the font and an src descriptor is associated with an external font name. This can be used with downloadable fonts. This CSS @font-face rule can contain more than one property (max 24)." }, { "code": null, "e": 25205, "s": 25197, "text": "Syntax:" }, { "code": null, "e": 25383, "s": 25205, "text": "@font-face {\n font-family: fontName;\n src: url(fontFile path);\n font-stretch: font-stretch Property;\n font-weight: font-weight Property;\n font-style: font-style Property;\n}" }, { "code": null, "e": 25457, "s": 25383, "text": "Parameter: The @font-face rule accepts four-parameter as described below:" }, { "code": null, "e": 25507, "s": 25457, "text": "font-family: It specifies the font of an element." }, { "code": null, "e": 25613, "s": 25507, "text": "src: It is used to specify the location (URL) of the external resource ie., it holds the file path (url)." }, { "code": null, "e": 25673, "s": 25613, "text": "font-stretch: It is used to set the text wider or narrower." }, { "code": null, "e": 25771, "s": 25673, "text": "font-weight: It is used to set the weight or thickness of the font being used with the HTML Text." }, { "code": null, "e": 25888, "s": 25771, "text": "font-style: It is used to style the given particular text in a normal, italic, or oblique face from its font-family." }, { "code": null, "e": 25975, "s": 25888, "text": "Few hosted font services: These services will provide you with various types of fonts." }, { "code": null, "e": 25985, "s": 25975, "text": "Fonts.com" }, { "code": null, "e": 25998, "s": 25985, "text": "Google Fonts" }, { "code": null, "e": 26009, "s": 25998, "text": "Typotheque" }, { "code": null, "e": 26020, "s": 26009, "text": "Typography" }, { "code": null, "e": 26162, "s": 26020, "text": "Example 1: This example illustrates the use of the @font-face rule to specify the different font properties to decorate the text accordingly." }, { "code": null, "e": 26167, "s": 26162, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS @font-face rule</title> <style> @font-face { font-family: fontName; src: url(sansation_light.woff); } @font-face { font-family: fontName; src: url(sansation_bold.woff); font-weight: bold; } div { font-family: fontName; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div>A Computer Science Portal fo Geeks</div> </center></body> </html>", "e": 26692, "s": 26167, "text": null }, { "code": null, "e": 26700, "s": 26692, "text": "Output:" }, { "code": null, "e": 26832, "s": 26700, "text": "Example 2: This example illustrates the use of the @font-face rule by specifying the source of the file path along with its format." }, { "code": null, "e": 26837, "s": 26832, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>CSS @font-face rule</title> <style type=\"text/css\"> @font-face { font-family: \"OpenSans\"; src: url(\"/examples/fonts/OpenSans-Regular.eot\"); src: url(\"/examples/fonts/OpenSans-Regular.ttf\") format(\"truetype\"); font-stretch: normal; font-weight: normal; font-style: normal; } @font-face { font-family: \"OpenSansBold\"; src: url(\"/examples/fonts/OpenSans-Bold.eot\"); src: url(\"/examples/fonts/OpenSans-Bold.ttf\") format(\"truetype\"); font-stretch: normal; font-weight: normal; font-style: normal; } /* Specify the OpenSans bold font */ h1 { font-family: \"OpenSansBold\", Arial, sans-serif; color: green; } p { font-family: \"OpenSans\", Arial, sans-serif; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </center></body> </html>", "e": 27836, "s": 26837, "text": null }, { "code": null, "e": 27846, "s": 27836, "text": "Output: " }, { "code": null, "e": 27923, "s": 27846, "text": "Note: There is 5 Font format those are: TTF/OTF, WOFF, WOFF2, SVG, and EOT. " }, { "code": null, "e": 28007, "s": 27923, "text": "Supported Browsers: The browsers supported by CSS @font-face rule are listed below:" }, { "code": null, "e": 28052, "s": 28007, "text": "Google Chrome (TTF/OTF, WOFF, WOFF2 and SVG)" }, { "code": null, "e": 28094, "s": 28052, "text": "Internet Explorer (TTF/OTF, WOFF and EOT)" }, { "code": null, "e": 28128, "s": 28094, "text": "Firefox (TTF/OTF, WOFF and WOFF2)" }, { "code": null, "e": 28158, "s": 28128, "text": "Safari TTF/OTF, WOFF and SVG)" }, { "code": null, "e": 28193, "s": 28158, "text": "Opera TTF/OTF, WOFF, WOFF2 and SVG" }, { "code": null, "e": 28214, "s": 28193, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28229, "s": 28214, "text": "varshagumber28" }, { "code": null, "e": 28244, "s": 28229, "text": "CSS-Properties" }, { "code": null, "e": 28248, "s": 28244, "text": "CSS" }, { "code": null, "e": 28265, "s": 28248, "text": "Web Technologies" }, { "code": null, "e": 28363, "s": 28265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28427, "s": 28363, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28468, "s": 28427, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28505, "s": 28468, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28566, "s": 28505, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28614, "s": 28566, "text": "How to set div width to fit content using CSS ?" }, { "code": null, "e": 28656, "s": 28614, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28689, "s": 28656, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28732, "s": 28689, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28777, "s": 28732, "text": "Convert a string to an integer in JavaScript" } ]
Factorials of large numbers | Practice | GeeksforGeeks
Given an integer N, find its factorial. Example 1: Input: N = 5 Output: 120 Explanation : 5! = 1*2*3*4*5 = 120 Example 2: Input: N = 10 Output: 3628800 Explanation : 10! = 1*2*3*4*5*6*7*8*9*10 = 3628800 Your Task: You don't need to read input or print anything. Complete the function factorial() that takes integer N as input parameter and returns a list of integers denoting the digits that make up the factorial of N. Expected Time Complexity : O(N2) Expected Auxilliary Space : O(1) Constraints: 1 ≤ N ≤ 1000 0 hansrajsaran791 day ago Simple Python solution in less Time Complexity fact = 1 for i in range(2,N+1): fact = fact*i return str(fact) +2 vamsiipl1 day ago class Solution {public: vector<int> factorial(int N) { vector<int> v; for(int i = 1; i <= N; i++) { if(v.size() == 0) v.push_back(i); int carry = 0; for(int j = 0; j < v.size(); j++) { int m = v[j] * i; m += carry; v[j] = m % 10; carry = m / 10; } while(carry) { int r = carry % 10; v.push_back(r); carry /= 10; } } reverse(v.begin(), v.end()); return v; }}; -14 mahiratnaparkhe40522 weeks ago Easy Peasy ! fact=1 while N!=0: fact=fact*N N-=1 return [fact] +1 janvijindal052 weeks ago vector<int> ans; ans.push_back(1); for(int x=2;x<=N;x++){ int carry=0; for(int i=0;i<ans.size();i++){ int value=ans[i]*x + carry; ans[i]=value%10; carry=value/10; } while(carry!=0){ ans.push_back(carry%10); carry/=10; } } reverse(ans.begin(),ans.end()); return ans; +1 pratiksehjpal20002 weeks ago class Solution { static ArrayList<Integer> factorial(int N){ int size=0,carry=0; ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0,1); size = 1; int val=2; while(val<=N) { for(int i=list.size()-1;i>=0;i--) { int temp = list.get(i)*val+carry; list.set(i,temp%10); carry = temp/10; } while(carry!=0) { list.add(0,carry%10); carry=carry/10; // size++; } val++; } return list; } } +1 dabhideep443 weeks ago JAVA SOLUTION(0.93 SECONDS) static ArrayList<Integer> factorial (int N) { // Declare an arrayList ArrayList<Integer> list = new ArrayList<>(); int size = 0, c = 0; // adding 1 at 0th index list.add(0, 1); // Updating size size = 1; // Declare a variable to travers numbers from 2 to n int val = 2 ; while (val <= N) { // Traverse arrayList from right to left for(int i = size - 1; i >= 0; i--) { // Updating value in arrayList int temp = list.get(i) * val + c; // Store last digit at index and remaining to carry list.set(i, temp % 10); // Update carry c = temp / 10; } // Insert carry digit by digit to the beginning of the ArrayList while (c != 0) { list.add(0, c % 10); c = c / 10; size++; } val++; } return list; } 0 jotarokujo3 weeks ago static ArrayList<Integer> factorial(int n){ java.math.BigInteger[] fact = new java.math.BigInteger[n + 1]; fact[1] = java.math.BigInteger.valueOf(1); for (int i = 2; i <= n; i += 1) { fact[i] = fact[i - 1] .multiply(java.math.BigInteger.valueOf(i)); } char[] ans = fact[n].toString().toCharArray(); ArrayList<Integer> sol = new ArrayList<>(); for (int i = 0; i < ans.length; i += 1) { sol.add(ans[i] - '0'); } return sol; } +1 bhavinraichura283 weeks ago vector<int> factorial(int n){ // code here vector<int>digits; int val; for (int i =1;i<=n;i++){ int j =0; int carry = 0; if (i==1){ digits.push_back(1); continue; } while(j<digits.size()){ val = digits[j]*i + carry; digits[j]= val%10; carry = val/10; j++; } while(carry!=0){ digits.push_back(carry%10); carry=carry/10; } } reverse(digits.begin(),digits.end()); return digits; } -2 amiransarimy1 month ago Simple Python Solutions def factorial(self, N): res = self.factorialHelper(N) return list(str(res)) def factorialHelper(self,num): if num == 0 or num == 1: return 1 else: return num*self.factorialHelper(num-1) +1 kaustubhdwivedi17291 month ago The number of digits in 1000 factorial is 2568. vector<int> factorial(int N){ int arr[2568]; int n = 2568; arr[n-1] = 1; int res = 1; int carry = 0; for(int i = 2; i <= N; i++){ carry = 0; for(int j = n-1; j > n-1-res; j--){ int temp = arr[j]*i+carry; arr[j] = temp%10; carry = temp/10; } while(carry){ arr[n-1-res] = carry%10; carry /= 10; res++; } } vector<int> ans(res, 0); int j = 0; for(int i = n-res; i < n; i++) ans[j++] = arr[i]; return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 290, "s": 238, "text": "Given an integer N, find its factorial.\n\nExample 1:" }, { "code": null, "e": 351, "s": 290, "text": "Input: N = 5\nOutput: 120\nExplanation : 5! = 1*2*3*4*5 = 120\n" }, { "code": null, "e": 362, "s": 351, "text": "Example 2:" }, { "code": null, "e": 443, "s": 362, "text": "Input: N = 10\nOutput: 3628800\nExplanation :\n10! = 1*2*3*4*5*6*7*8*9*10 = 3628800" }, { "code": null, "e": 661, "s": 443, "text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function factorial() that takes integer N as input parameter and returns a list of integers denoting the digits that make up the factorial of N." }, { "code": null, "e": 728, "s": 661, "text": "\nExpected Time Complexity : O(N2)\nExpected Auxilliary Space : O(1)" }, { "code": null, "e": 755, "s": 728, "text": "\nConstraints:\n1 ≤ N ≤ 1000" }, { "code": null, "e": 757, "s": 755, "text": "0" }, { "code": null, "e": 781, "s": 757, "text": "hansrajsaran791 day ago" }, { "code": null, "e": 828, "s": 781, "text": "Simple Python solution in less Time Complexity" }, { "code": null, "e": 924, "s": 828, "text": " fact = 1\n for i in range(2,N+1):\n fact = fact*i\n return str(fact) " }, { "code": null, "e": 927, "s": 924, "text": "+2" }, { "code": null, "e": 945, "s": 927, "text": "vamsiipl1 day ago" }, { "code": null, "e": 1556, "s": 945, "text": "class Solution {public: vector<int> factorial(int N) { vector<int> v; for(int i = 1; i <= N; i++) { if(v.size() == 0) v.push_back(i); int carry = 0; for(int j = 0; j < v.size(); j++) { int m = v[j] * i; m += carry; v[j] = m % 10; carry = m / 10; } while(carry) { int r = carry % 10; v.push_back(r); carry /= 10; } } reverse(v.begin(), v.end()); return v; }};" }, { "code": null, "e": 1560, "s": 1556, "text": "-14" }, { "code": null, "e": 1591, "s": 1560, "text": "mahiratnaparkhe40522 weeks ago" }, { "code": null, "e": 1604, "s": 1591, "text": "Easy Peasy !" }, { "code": null, "e": 1686, "s": 1604, "text": "fact=1 while N!=0: fact=fact*N N-=1 return [fact]" }, { "code": null, "e": 1689, "s": 1686, "text": "+1" }, { "code": null, "e": 1714, "s": 1689, "text": "janvijindal052 weeks ago" }, { "code": null, "e": 2116, "s": 1714, "text": " vector<int> ans; ans.push_back(1); for(int x=2;x<=N;x++){ int carry=0; for(int i=0;i<ans.size();i++){ int value=ans[i]*x + carry; ans[i]=value%10; carry=value/10; } while(carry!=0){ ans.push_back(carry%10); carry/=10; } } reverse(ans.begin(),ans.end()); return ans;" }, { "code": null, "e": 2119, "s": 2116, "text": "+1" }, { "code": null, "e": 2148, "s": 2119, "text": "pratiksehjpal20002 weeks ago" }, { "code": null, "e": 2799, "s": 2148, "text": "class Solution {\n static ArrayList<Integer> factorial(int N){\n int size=0,carry=0;\n ArrayList<Integer> list = new ArrayList<Integer>();\n list.add(0,1);\n size = 1;\n int val=2;\n while(val<=N)\n {\n for(int i=list.size()-1;i>=0;i--)\n {\n int temp = list.get(i)*val+carry;\n list.set(i,temp%10);\n carry = temp/10;\n }\n while(carry!=0)\n {\n list.add(0,carry%10);\n carry=carry/10;\n // size++;\n }\n val++;\n }\n return list;\n }\n}" }, { "code": null, "e": 2802, "s": 2799, "text": "+1" }, { "code": null, "e": 2825, "s": 2802, "text": "dabhideep443 weeks ago" }, { "code": null, "e": 2853, "s": 2825, "text": "JAVA SOLUTION(0.93 SECONDS)" }, { "code": null, "e": 3814, "s": 2853, "text": "static ArrayList<Integer> factorial (int N) { // Declare an arrayList ArrayList<Integer> list = new ArrayList<>(); int size = 0, c = 0; // adding 1 at 0th index list.add(0, 1); // Updating size size = 1; // Declare a variable to travers numbers from 2 to n int val = 2 ; while (val <= N) { // Traverse arrayList from right to left for(int i = size - 1; i >= 0; i--) { // Updating value in arrayList int temp = list.get(i) * val + c; // Store last digit at index and remaining to carry list.set(i, temp % 10); // Update carry c = temp / 10; } // Insert carry digit by digit to the beginning of the ArrayList while (c != 0) { list.add(0, c % 10); c = c / 10; size++; } val++; } return list; }" }, { "code": null, "e": 3816, "s": 3814, "text": "0" }, { "code": null, "e": 3838, "s": 3816, "text": "jotarokujo3 weeks ago" }, { "code": null, "e": 4370, "s": 3838, "text": "static ArrayList<Integer> factorial(int n){\n java.math.BigInteger[] fact\n \t= new java.math.BigInteger[n + 1];\n fact[1] = java.math.BigInteger.valueOf(1);\n for (int i = 2; i <= n; i += 1) {\n fact[i] = fact[i - 1]\n \t.multiply(java.math.BigInteger.valueOf(i));\n }\n char[] ans = fact[n].toString().toCharArray();\n ArrayList<Integer> sol = new ArrayList<>();\n for (int i = 0; i < ans.length; i += 1) {\n sol.add(ans[i] - '0');\n }\n return sol;\n }" }, { "code": null, "e": 4373, "s": 4370, "text": "+1" }, { "code": null, "e": 4401, "s": 4373, "text": "bhavinraichura283 weeks ago" }, { "code": null, "e": 4478, "s": 4401, "text": "vector<int> factorial(int n){ // code here vector<int>digits; int val;" }, { "code": null, "e": 4764, "s": 4478, "text": " for (int i =1;i<=n;i++){ int j =0; int carry = 0; if (i==1){ digits.push_back(1); continue; } while(j<digits.size()){ val = digits[j]*i + carry; digits[j]= val%10; carry = val/10; j++; }" }, { "code": null, "e": 4925, "s": 4764, "text": " while(carry!=0){ digits.push_back(carry%10); carry=carry/10; } } reverse(digits.begin(),digits.end()); return digits; }" }, { "code": null, "e": 4928, "s": 4925, "text": "-2" }, { "code": null, "e": 4952, "s": 4928, "text": "amiransarimy1 month ago" }, { "code": null, "e": 4976, "s": 4952, "text": "Simple Python Solutions" }, { "code": null, "e": 5232, "s": 4978, "text": "def factorial(self, N):\n res = self.factorialHelper(N)\n return list(str(res))\n \n def factorialHelper(self,num):\n if num == 0 or num == 1:\n return 1 \n else:\n return num*self.factorialHelper(num-1) " }, { "code": null, "e": 5235, "s": 5232, "text": "+1" }, { "code": null, "e": 5266, "s": 5235, "text": "kaustubhdwivedi17291 month ago" }, { "code": null, "e": 5314, "s": 5266, "text": "The number of digits in 1000 factorial is 2568." }, { "code": null, "e": 5993, "s": 5314, "text": " vector<int> factorial(int N){\n \tint arr[2568];\n int n = 2568;\n arr[n-1] = 1;\n int res = 1;\n int carry = 0;\n \n for(int i = 2; i <= N; i++){\n carry = 0;\n for(int j = n-1; j > n-1-res; j--){\n int temp = arr[j]*i+carry;\n arr[j] = temp%10;\n carry = temp/10;\n }\n while(carry){\n arr[n-1-res] = carry%10;\n carry /= 10;\n res++;\n }\n }\n \n vector<int> ans(res, 0);\n int j = 0;\n for(int i = n-res; i < n; i++)\n ans[j++] = arr[i];\n return ans;\n }" }, { "code": null, "e": 6139, "s": 5993, "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": 6175, "s": 6139, "text": " Login to access your submissions. " }, { "code": null, "e": 6185, "s": 6175, "text": "\nProblem\n" }, { "code": null, "e": 6195, "s": 6185, "text": "\nContest\n" }, { "code": null, "e": 6258, "s": 6195, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6406, "s": 6258, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6614, "s": 6406, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6720, "s": 6614, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java Examples - Getting Thread Name
How to get the name of a running thread? Following example shows how to get the name of a running thread. public class TwoThreadGetName extends Thread { public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadGetName tt = new TwoThreadGetName(); tt.start(); for (int i = 0; i < 10; i++) { tt.printMsg(); } } } The above code sample will produce the following result. name = main name = main name = main name = main name = main name = thread name = thread name = thread name = thread Print Add Notes Bookmark this page
[ { "code": null, "e": 2109, "s": 2068, "text": "How to get the name of a running thread?" }, { "code": null, "e": 2174, "s": 2109, "text": "Following example shows how to get the name of a running thread." }, { "code": null, "e": 2655, "s": 2174, "text": "public class TwoThreadGetName extends Thread {\n public void run() {\n for (int i = 0; i < 10; i++) {\n printMsg();\n }\n }\n public void printMsg() {\n Thread t = Thread.currentThread();\n String name = t.getName();\n System.out.println(\"name=\" + name);\n } \n public static void main(String[] args) {\n TwoThreadGetName tt = new TwoThreadGetName();\n tt.start();\n for (int i = 0; i < 10; i++) {\n tt.printMsg();\n }\n }\n}" }, { "code": null, "e": 2712, "s": 2655, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2829, "s": 2712, "text": "name = main\nname = main\nname = main\nname = main\nname = main\nname = thread\nname = thread\nname = thread\nname = thread\n" }, { "code": null, "e": 2836, "s": 2829, "text": " Print" }, { "code": null, "e": 2847, "s": 2836, "text": " Add Notes" } ]
Completion time of a given process in round robin - GeeksforGeeks
30 Apr, 2021 We are given n-processes with their completion times in form of an array. We need to find the time instant when a given process p ends if the scheduling process is round robin and time slice is 1-sec. note : Array index start with 0.Examples : Input : arr[] = {3, 2, 4, 2}, p = 1 Output : Completion time = 6 Explanation : Snap of process for every second is as: Time | Process Array 0 | {3, 2, 4, 2} 1 | {2, 2, 4, 2} 2 | {2, 1, 4, 2} 3 | {2, 1, 3, 2} 4 | {2, 1, 3, 1} 5 | {1, 1, 3, 1} 6 | {1, 0, 3, 1} Input : arr[] = {2, 4, 1, 3}, p = 2 Output :Completion time = 3 Explanation : Snap of process for every second is as: Time | Process Array 0 | {2, 4, 1, 3} 1 | {1, 4, 1, 3} 2 | {1, 3, 1, 3} 3 | {1, 3, 0, 3} Brute Force :The basic approach for solving this problem is to apply round robin algorithm with time slice 1. But the time complexity of that approach will be O(ΣAi) i.e. summation of all process’s time, which is quite high.Efficient Approach: The idea is based on below observations. 1) All processes with CPU time less than arr[p] would complete before arr[p]. We simply need to add time of these processes. 2) We also need to add time of arr[p]. 3) For every process x with CPU time more than arr[p], two cases arise : .....(i) If x is on left of arr[p] (scheduled before arr[p]), then this process takes arr[p] time of CPU before p finishes. .....(ii) If x is on right of arr[p] (scheduled after arr[p]), then this process takes arr[p]-1 time of CPU before p finishes.Algorithm : time_req = 0; // Add time for process on left of p // (Scheduled before p in a round of // 1 unit time slice) for (int i=0; i<p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // step 2 : Add time of process p time_req += arr[p]; // Add time for process on right // of p (Scheduled after p in // a round of 1 unit time slice) for (int i=p+1; i<n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]-1; } C++ Java Python C# PHP Javascript // Program to find end time of a process// p in round robin scheduling with unit// time slice.#include <bits/stdc++.h>using namespace std; // Returns completion time of p.int completionTime(int arr[], int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req;} // driver programint main() { int arr[] = {3, 5, 2, 7, 6, 1}; int n = sizeof(arr) / sizeof(arr[0]); int p = 2; cout << "Completion time = " << completionTime(arr, n, p); return 0;} // Program to find end time of a process// p in round robin scheduling with unit// time slice.class GFG{ // Returns completion time of p. static int completionTime(int arr[], int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req; } // Driver code public static void main (String[] args) { int arr[] = {3, 5, 2, 7, 6, 1}; int n =arr.length;; int p = 2; System.out.print("Completion time = "+ completionTime(arr, n, p)); }} // This code is contributed by Anant Agarwal. # Program to find end time of a process# p in round robin scheduling with unit# time slice. # Returns completion time of p.def completionTime(arr, n, p) : # Initialize result time_req = 0 # Step 1 : Add time of processes on # left of p (Scheduled before p) for i in range(0, p): if (arr[i] < arr[p]): time_req += arr[i] else: time_req += arr[p] # Step 2 : Add time of p time_req += arr[p] # Step 3 : Add time of processes on # right of p (Scheduled after p) for i in range(p + 1, n): if (arr[i] < arr[p]): time_req += arr[i] else: time_req += arr[p] - 1 return time_req # driver programarr = [3, 5, 2, 7, 6, 1]n = len(arr)p = 2print("Completion time =", completionTime(arr, n, p)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find end time of a process// p in round robin scheduling with unit// time slice.using System; class GFG { // Returns completion time of p. static int completionTime(int []arr, int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes // on left of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on // right of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req; } // Driver code public static void Main () { int []arr = {3, 5, 2, 7, 6, 1}; int n =arr.Length;; int p = 2; Console.WriteLine("Completion time = "+ completionTime(arr, n, p)); }} // This code is contributed by vt_m. <?php// Program to find end time// of a process p in round// robin scheduling with// unit time slice. // Returns completion time of p.function completionTime($arr, $n, $p){ // Initialize result$time_req = 0; // Step 1 : Add time of processes on// left of p (Scheduled before p)for ($i = 0; $i < $p; $i++){ if ($arr[$i] < $arr[$p]) $time_req += $arr[$i]; else $time_req += $arr[$p];} // Step 2 : Add time of p$time_req += $arr[$p]; // Step 3 : Add time of processes on// right of p (Scheduled after p)for ($i = $p + 1; $i < $n; $i++){ if ($arr[$i] < $arr[$p]) $time_req += $arr[$i]; else $time_req += $arr[$p] - 1;} return $time_req;} // Driver Code$arr = array(3, 5, 2, 7, 6, 1);$n = count($arr);$p = 2;echo"Completion time = " , completionTime($arr, $n, $p); // This code is contributed by anuj_67.?> <script> // Program to find end time of a process// p in round robin scheduling with unit// time slice. // Returns completion time of p.function completionTime(arr, n, p) { // Initialize result var time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (var i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (var i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req;} // driver programvar arr = [3, 5, 2, 7, 6, 1];var n = arr.length;var p = 2;document.write( "Completion time = " + completionTime(arr, n, p)); // This code is contributed by noob2000.</script> Output : Completion time = 9 Time Complexity : O(n) vt_m noob2000 cpu-scheduling Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Program to find sum of elements in a given array Building Heap from Array Move all negative numbers to beginning and positive to end with constant extra space Find duplicates in O(n) time and O(1) extra space | Set 1 Count pairs with given sum Next Greater Element Remove duplicates from sorted array
[ { "code": null, "e": 24822, "s": 24794, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25068, "s": 24822, "text": "We are given n-processes with their completion times in form of an array. We need to find the time instant when a given process p ends if the scheduling process is round robin and time slice is 1-sec. note : Array index start with 0.Examples : " }, { "code": null, "e": 25633, "s": 25068, "text": "Input : arr[] = {3, 2, 4, 2}, p = 1\nOutput : Completion time = 6\nExplanation : Snap of process for every second is as:\nTime | Process Array\n0 | {3, 2, 4, 2}\n1 | {2, 2, 4, 2}\n2 | {2, 1, 4, 2}\n3 | {2, 1, 3, 2}\n4 | {2, 1, 3, 1}\n5 | {1, 1, 3, 1}\n6 | {1, 0, 3, 1}\n\nInput : arr[] = {2, 4, 1, 3}, p = 2\nOutput :Completion time = 3\nExplanation : Snap of process for every second is as:\nTime | Process Array\n0 | {2, 4, 1, 3}\n1 | {1, 4, 1, 3}\n2 | {1, 3, 1, 3}\n3 | {1, 3, 0, 3}" }, { "code": null, "e": 26419, "s": 25633, "text": "Brute Force :The basic approach for solving this problem is to apply round robin algorithm with time slice 1. But the time complexity of that approach will be O(ΣAi) i.e. summation of all process’s time, which is quite high.Efficient Approach: The idea is based on below observations. 1) All processes with CPU time less than arr[p] would complete before arr[p]. We simply need to add time of these processes. 2) We also need to add time of arr[p]. 3) For every process x with CPU time more than arr[p], two cases arise : .....(i) If x is on left of arr[p] (scheduled before arr[p]), then this process takes arr[p] time of CPU before p finishes. .....(ii) If x is on right of arr[p] (scheduled after arr[p]), then this process takes arr[p]-1 time of CPU before p finishes.Algorithm : " }, { "code": null, "e": 26924, "s": 26419, "text": "time_req = 0;\n\n// Add time for process on left of p \n// (Scheduled before p in a round of \n// 1 unit time slice)\nfor (int i=0; i<p; i++)\n{\n if (arr[i] < arr[p])\n time_req += arr[i];\n else\n time_req += arr[p];\n}\n\n// step 2 : Add time of process p\ntime_req += arr[p];\n\n// Add time for process on right\n// of p (Scheduled after p in\n// a round of 1 unit time slice)\nfor (int i=p+1; i<n; i++)\n{\n if (arr[i] < arr[p])\n time_req += arr[i];\n else\n time_req += arr[p]-1;\n}" }, { "code": null, "e": 26932, "s": 26928, "text": "C++" }, { "code": null, "e": 26937, "s": 26932, "text": "Java" }, { "code": null, "e": 26944, "s": 26937, "text": "Python" }, { "code": null, "e": 26947, "s": 26944, "text": "C#" }, { "code": null, "e": 26951, "s": 26947, "text": "PHP" }, { "code": null, "e": 26962, "s": 26951, "text": "Javascript" }, { "code": "// Program to find end time of a process// p in round robin scheduling with unit// time slice.#include <bits/stdc++.h>using namespace std; // Returns completion time of p.int completionTime(int arr[], int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req;} // driver programint main() { int arr[] = {3, 5, 2, 7, 6, 1}; int n = sizeof(arr) / sizeof(arr[0]); int p = 2; cout << \"Completion time = \" << completionTime(arr, n, p); return 0;}", "e": 27872, "s": 26962, "text": null }, { "code": "// Program to find end time of a process// p in round robin scheduling with unit// time slice.class GFG{ // Returns completion time of p. static int completionTime(int arr[], int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req; } // Driver code public static void main (String[] args) { int arr[] = {3, 5, 2, 7, 6, 1}; int n =arr.length;; int p = 2; System.out.print(\"Completion time = \"+ completionTime(arr, n, p)); }} // This code is contributed by Anant Agarwal.", "e": 29067, "s": 27872, "text": null }, { "code": "# Program to find end time of a process# p in round robin scheduling with unit# time slice. # Returns completion time of p.def completionTime(arr, n, p) : # Initialize result time_req = 0 # Step 1 : Add time of processes on # left of p (Scheduled before p) for i in range(0, p): if (arr[i] < arr[p]): time_req += arr[i] else: time_req += arr[p] # Step 2 : Add time of p time_req += arr[p] # Step 3 : Add time of processes on # right of p (Scheduled after p) for i in range(p + 1, n): if (arr[i] < arr[p]): time_req += arr[i] else: time_req += arr[p] - 1 return time_req # driver programarr = [3, 5, 2, 7, 6, 1]n = len(arr)p = 2print(\"Completion time =\", completionTime(arr, n, p)) # This code is contributed by# Smitha Dinesh Semwal", "e": 29944, "s": 29067, "text": null }, { "code": "// C# program to find end time of a process// p in round robin scheduling with unit// time slice.using System; class GFG { // Returns completion time of p. static int completionTime(int []arr, int n, int p) { // Initialize result int time_req = 0; // Step 1 : Add time of processes // on left of p (Scheduled before p) for (int i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on // right of p (Scheduled after p) for (int i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req; } // Driver code public static void Main () { int []arr = {3, 5, 2, 7, 6, 1}; int n =arr.Length;; int p = 2; Console.WriteLine(\"Completion time = \"+ completionTime(arr, n, p)); }} // This code is contributed by vt_m.", "e": 31179, "s": 29944, "text": null }, { "code": "<?php// Program to find end time// of a process p in round// robin scheduling with// unit time slice. // Returns completion time of p.function completionTime($arr, $n, $p){ // Initialize result$time_req = 0; // Step 1 : Add time of processes on// left of p (Scheduled before p)for ($i = 0; $i < $p; $i++){ if ($arr[$i] < $arr[$p]) $time_req += $arr[$i]; else $time_req += $arr[$p];} // Step 2 : Add time of p$time_req += $arr[$p]; // Step 3 : Add time of processes on// right of p (Scheduled after p)for ($i = $p + 1; $i < $n; $i++){ if ($arr[$i] < $arr[$p]) $time_req += $arr[$i]; else $time_req += $arr[$p] - 1;} return $time_req;} // Driver Code$arr = array(3, 5, 2, 7, 6, 1);$n = count($arr);$p = 2;echo\"Completion time = \" , completionTime($arr, $n, $p); // This code is contributed by anuj_67.?>", "e": 32010, "s": 31179, "text": null }, { "code": "<script> // Program to find end time of a process// p in round robin scheduling with unit// time slice. // Returns completion time of p.function completionTime(arr, n, p) { // Initialize result var time_req = 0; // Step 1 : Add time of processes on left // of p (Scheduled before p) for (var i = 0; i < p; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p]; } // Step 2 : Add time of p time_req += arr[p]; // Step 3 : Add time of processes on right // of p (Scheduled after p) for (var i = p + 1; i < n; i++) { if (arr[i] < arr[p]) time_req += arr[i]; else time_req += arr[p] - 1; } return time_req;} // driver programvar arr = [3, 5, 2, 7, 6, 1];var n = arr.length;var p = 2;document.write( \"Completion time = \" + completionTime(arr, n, p)); // This code is contributed by noob2000.</script>", "e": 32880, "s": 32010, "text": null }, { "code": null, "e": 32891, "s": 32880, "text": "Output : " }, { "code": null, "e": 32911, "s": 32891, "text": "Completion time = 9" }, { "code": null, "e": 32935, "s": 32911, "text": "Time Complexity : O(n) " }, { "code": null, "e": 32940, "s": 32935, "text": "vt_m" }, { "code": null, "e": 32949, "s": 32940, "text": "noob2000" }, { "code": null, "e": 32964, "s": 32949, "text": "cpu-scheduling" }, { "code": null, "e": 32971, "s": 32964, "text": "Arrays" }, { "code": null, "e": 32978, "s": 32971, "text": "Arrays" }, { "code": null, "e": 33076, "s": 32978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33101, "s": 33076, "text": "Window Sliding Technique" }, { "code": null, "e": 33121, "s": 33101, "text": "Trapping Rain Water" }, { "code": null, "e": 33159, "s": 33121, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33208, "s": 33159, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33233, "s": 33208, "text": "Building Heap from Array" }, { "code": null, "e": 33318, "s": 33233, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 33376, "s": 33318, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33403, "s": 33376, "text": "Count pairs with given sum" }, { "code": null, "e": 33424, "s": 33403, "text": "Next Greater Element" } ]
Disable Exit (or [ X ]) in Tkinter Window
The window manager implements the Tkinter window control icons. To hide and show the Tkinter window control icons, we can use the built-in function, which describes whether we want to disable control icons’ functionality. To disable the Exit or [X] control icon, we have to define the protocol() method. We can limit the control icon definition by specifying an empty function for disabling the state of the control icon. #Import the tkinter library from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame win= Tk() #Define the geometry of the function win.geometry("750x250") def close_win(): win.destroy() def disable_event(): pass #Create a button to close the window btn = ttk.Button(win, text ="Click here to Close",command=close_win) btn.pack() #Disable the Close Window Control Icon win.protocol("WM_DELETE_WINDOW", disable_event) win.mainloop() The above code will display a window that has a disabled [X] window close control. To close the window, click the button "Click here to Close."
[ { "code": null, "e": 1284, "s": 1062, "text": "The window manager implements the Tkinter window control icons. To hide and show the Tkinter window control icons, we can use the built-in function, which describes whether we want to disable control icons’ functionality." }, { "code": null, "e": 1484, "s": 1284, "text": "To disable the Exit or [X] control icon, we have to define the protocol() method. We can limit the control icon definition by specifying an empty function for disabling the state of the control icon." }, { "code": null, "e": 1948, "s": 1484, "text": "#Import the tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of Tkinter frame\nwin= Tk()\n#Define the geometry of the function\nwin.geometry(\"750x250\")\ndef close_win():\n win.destroy()\ndef disable_event():\n pass\n#Create a button to close the window\nbtn = ttk.Button(win, text =\"Click here to Close\",command=close_win)\nbtn.pack()\n#Disable the Close Window Control Icon\nwin.protocol(\"WM_DELETE_WINDOW\", disable_event)\nwin.mainloop()" }, { "code": null, "e": 2031, "s": 1948, "text": "The above code will display a window that has a disabled [X] window close control." }, { "code": null, "e": 2092, "s": 2031, "text": "To close the window, click the button \"Click here to Close.\"" } ]
Electron - Menus
The desktop apps come with two types of menus – the application menu(on the top bar) and a context menu(right-click menu). We will learn how to create both of these in this chapter. We will be using two modules – the Menu and the MenuItem modules. Note that the Menu and the MenuItem modules are only available in the main process. For using these modules in the renderer process, you need the remote module. We will come across this when we create a context menu. Now, let us create a new main.js file for the main process − const {app, BrowserWindow, Menu, MenuItem} = require('electron') const url = require('url') const path = require('path') let win function createWindow() { win = new BrowserWindow({width: 800, height: 600}) win.loadURL(url.format ({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } const template = [ { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' } ] }, { label: 'View', submenu: [ { role: 'reload' }, { role: 'toggledevtools' }, { type: 'separator' }, { role: 'resetzoom' }, { role: 'zoomin' }, { role: 'zoomout' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { role: 'window', submenu: [ { role: 'minimize' }, { role: 'close' } ] }, { role: 'help', submenu: [ { label: 'Learn More' } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) app.on('ready', createWindow) We are building a menu from a template here. This means that we provide the menu as a JSON to the function and it will take care of the rest. Now we have to set this menu as the Application menu. Now create an empty HTML file called index.html and run this application using − $ electron ./main.js On the normal position of application menus, you will see a menu based on the above template. We created this menu from the main process. Let us now create a context menu for our app. We will do this in our HTML file − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Menus</title> </head> <body> <script type = "text/javascript"> const {remote} = require('electron') const {Menu, MenuItem} = remote const menu = new Menu() // Build menu one item at a time, unlike menu.append(new MenuItem ({ label: 'MenuItem1', click() { console.log('item 1 clicked') } })) menu.append(new MenuItem({type: 'separator'})) menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true})) menu.append(new MenuItem ({ label: 'MenuItem3', click() { console.log('item 3 clicked') } })) // Prevent default action of right click in chromium. Replace with our menu. window.addEventListener('contextmenu', (e) => { e.preventDefault() menu.popup(remote.getCurrentWindow()) }, false) </script> </body> </html> We imported the Menu and MenuItem modules using the remote module; then, we created a menu and appended our menuitems to it one by one. Further, we prevented the default action of right-click in chromium and replaced it with our menu. The creation of menus in Electron is a very simple task. Now you can attach your event handlers to these items and handle the events according to your needs. 251 Lectures 35.5 hours Gowthami Swarna 9 Lectures 41 mins Ashraf Said 8 Lectures 32 mins Ashraf Said 25 Lectures 1 hours Ashraf Said 17 Lectures 1 hours Ashraf Said 8 Lectures 25 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2247, "s": 2065, "text": "The desktop apps come with two types of menus – the application menu(on the top bar) and a context menu(right-click menu). We will learn how to create both of these in this chapter." }, { "code": null, "e": 2530, "s": 2247, "text": "We will be using two modules – the Menu and the MenuItem modules. Note that the Menu and the MenuItem modules are only available in the main process. For using these modules in the renderer process, you need the remote module. We will come across this when we create a context menu." }, { "code": null, "e": 2591, "s": 2530, "text": "Now, let us create a new main.js file for the main process −" }, { "code": null, "e": 4178, "s": 2591, "text": "const {app, BrowserWindow, Menu, MenuItem} = require('electron')\nconst url = require('url')\nconst path = require('path')\n\nlet win\n\nfunction createWindow() {\n win = new BrowserWindow({width: 800, height: 600})\n win.loadURL(url.format ({\n pathname: path.join(__dirname, 'index.html'),\n protocol: 'file:',\n slashes: true\n }))\n}\n\nconst template = [\n {\n label: 'Edit',\n submenu: [\n {\n role: 'undo'\n },\n {\n role: 'redo'\n },\n {\n type: 'separator'\n },\n {\n role: 'cut'\n },\n {\n role: 'copy'\n },\n {\n role: 'paste'\n }\n ]\n },\n \n {\n label: 'View',\n submenu: [\n {\n role: 'reload'\n },\n {\n role: 'toggledevtools'\n },\n {\n type: 'separator'\n },\n {\n role: 'resetzoom'\n },\n {\n role: 'zoomin'\n },\n {\n role: 'zoomout'\n },\n {\n type: 'separator'\n },\n {\n role: 'togglefullscreen'\n }\n ]\n },\n \n {\n role: 'window',\n submenu: [\n {\n role: 'minimize'\n },\n {\n role: 'close'\n }\n ]\n },\n \n {\n role: 'help',\n submenu: [\n {\n label: 'Learn More'\n }\n ]\n }\n]\n\nconst menu = Menu.buildFromTemplate(template)\nMenu.setApplicationMenu(menu)\napp.on('ready', createWindow)" }, { "code": null, "e": 4374, "s": 4178, "text": "We are building a menu from a template here. This means that we provide the menu as a JSON to the function and it will take care of the rest. Now we have to set this menu as the Application menu." }, { "code": null, "e": 4455, "s": 4374, "text": "Now create an empty HTML file called index.html and run this application using −" }, { "code": null, "e": 4477, "s": 4455, "text": "$ electron ./main.js\n" }, { "code": null, "e": 4571, "s": 4477, "text": "On the normal position of application menus, you will see a menu based on the above template." }, { "code": null, "e": 4696, "s": 4571, "text": "We created this menu from the main process. Let us now create a context menu for our app. We will do this in our HTML file −" }, { "code": null, "e": 5786, "s": 4696, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Menus</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n const {remote} = require('electron')\n const {Menu, MenuItem} = remote\n\n const menu = new Menu()\n\n // Build menu one item at a time, unlike\n menu.append(new MenuItem ({\n label: 'MenuItem1',\n click() { \n console.log('item 1 clicked')\n }\n }))\n \n menu.append(new MenuItem({type: 'separator'}))\n menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))\n menu.append(new MenuItem ({\n label: 'MenuItem3',\n click() {\n console.log('item 3 clicked')\n }\n }))\n\n // Prevent default action of right click in chromium. Replace with our menu.\n window.addEventListener('contextmenu', (e) => {\n e.preventDefault()\n menu.popup(remote.getCurrentWindow())\n }, false)\n </script>\n </body>\n</html>" }, { "code": null, "e": 6021, "s": 5786, "text": "We imported the Menu and MenuItem modules using the remote module; then, we created a menu and appended our menuitems to it one by one. Further, we prevented the default action of right-click in chromium and replaced it with our menu." }, { "code": null, "e": 6179, "s": 6021, "text": "The creation of menus in Electron is a very simple task. Now you can attach your event handlers to these items and handle the events according to your needs." }, { "code": null, "e": 6216, "s": 6179, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 6233, "s": 6216, "text": " Gowthami Swarna" }, { "code": null, "e": 6264, "s": 6233, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 6277, "s": 6264, "text": " Ashraf Said" }, { "code": null, "e": 6308, "s": 6277, "text": "\n 8 Lectures \n 32 mins\n" }, { "code": null, "e": 6321, "s": 6308, "text": " Ashraf Said" }, { "code": null, "e": 6354, "s": 6321, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 6367, "s": 6354, "text": " Ashraf Said" }, { "code": null, "e": 6400, "s": 6367, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6413, "s": 6400, "text": " Ashraf Said" }, { "code": null, "e": 6444, "s": 6413, "text": "\n 8 Lectures \n 25 mins\n" }, { "code": null, "e": 6457, "s": 6444, "text": " Ashraf Said" }, { "code": null, "e": 6464, "s": 6457, "text": " Print" }, { "code": null, "e": 6475, "s": 6464, "text": " Add Notes" } ]
C++ String Library - append
It extends the string by appending additional characters at the end of its current value. Following is the declaration for std::string::append. string& append (const string& str); string& append (const string& str); string& append (const string& str); str − It is a string object. str − It is a string object. c − It is a character object. c − It is a character object. It returns *this. if an exception is thrown, there are no changes in the string. In below example for std::string::append. #include <iostream> #include <string> int main () { std::string str; std::string str2="Writing "; std::string str3="print 10 and then 5 more"; str.append(str2); str.append(str3,6,3); str.append("dots are cool",5); str.append("here: "); str.append(10u,'.'); str.append(str3.begin()+8,str3.end()); str.append<int>(5,0x2E); std::cout << str << '\n'; return 0; } Writing 10 dots here: .......... and then 5 more..... Print Add Notes Bookmark this page
[ { "code": null, "e": 2693, "s": 2603, "text": "It extends the string by appending additional characters at the end of its current value." }, { "code": null, "e": 2747, "s": 2693, "text": "Following is the declaration for std::string::append." }, { "code": null, "e": 2783, "s": 2747, "text": "string& append (const string& str);" }, { "code": null, "e": 2819, "s": 2783, "text": "string& append (const string& str);" }, { "code": null, "e": 2855, "s": 2819, "text": "string& append (const string& str);" }, { "code": null, "e": 2884, "s": 2855, "text": "str − It is a string object." }, { "code": null, "e": 2913, "s": 2884, "text": "str − It is a string object." }, { "code": null, "e": 2943, "s": 2913, "text": "c − It is a character object." }, { "code": null, "e": 2973, "s": 2943, "text": "c − It is a character object." }, { "code": null, "e": 2991, "s": 2973, "text": "It returns *this." }, { "code": null, "e": 3054, "s": 2991, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 3096, "s": 3054, "text": "In below example for std::string::append." }, { "code": null, "e": 3493, "s": 3096, "text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str;\n std::string str2=\"Writing \";\n std::string str3=\"print 10 and then 5 more\";\n\n str.append(str2);\n str.append(str3,6,3);\n str.append(\"dots are cool\",5);\n str.append(\"here: \");\n str.append(10u,'.');\n str.append(str3.begin()+8,str3.end());\n str.append<int>(5,0x2E);\n std::cout << str << '\\n';\n return 0;\n}" }, { "code": null, "e": 3548, "s": 3493, "text": "Writing 10 dots here: .......... and then 5 more.....\n" }, { "code": null, "e": 3555, "s": 3548, "text": " Print" }, { "code": null, "e": 3566, "s": 3555, "text": " Add Notes" } ]
How to delete all users from specific OU using PowerShell?
To remove all users from the specific OU, we need to first retrieve the users from that OU. For example, we have 3 users in the OU called LABDOMAIN and we need to delete them all. Get-ADUser -SearchBase "OU=LabUsers,DC=labdomain,DC=local" -Filter * The above command will retrieve users from the specific OU and then we can use the Remove-ADUser command to delete them all. Get-ADUser -SearchBase "OU=LabUsers,DC=labdomain,DC=local" -Filter * | Remove-ADUser -Confirm:$false -Verbose -Confirm switch has been added to bypass the confirmation for all the users. The default confirmation is true. VERBOSE: Performing the operation "Remove" on target "CN=JensonA,OU=LabUsers,DC=labdomain,DC=local". VERBOSE: Performing the operation "Remove" on target "CN=ChrisT,OU=LabUsers,DC=labdomain,DC=local". VERBOSE: Performing the operation "Remove" on target "CN=ChiragN,OU=LabUsers,DC=labdomain,DC=local".
[ { "code": null, "e": 1242, "s": 1062, "text": "To remove all users from the specific OU, we need to first retrieve the users from that OU. For example, we have 3 users in the OU called LABDOMAIN and we need to delete them all." }, { "code": null, "e": 1311, "s": 1242, "text": "Get-ADUser -SearchBase \"OU=LabUsers,DC=labdomain,DC=local\" -Filter *" }, { "code": null, "e": 1436, "s": 1311, "text": "The above command will retrieve users from the specific OU and then we can use the Remove-ADUser command to delete them all." }, { "code": null, "e": 1546, "s": 1436, "text": "Get-ADUser -SearchBase \"OU=LabUsers,DC=labdomain,DC=local\" -Filter * | Remove-ADUser -Confirm:$false -Verbose" }, { "code": null, "e": 1657, "s": 1546, "text": "-Confirm switch has been added to bypass the confirmation for all the users. The default confirmation is true." }, { "code": null, "e": 1959, "s": 1657, "text": "VERBOSE: Performing the operation \"Remove\" on target \"CN=JensonA,OU=LabUsers,DC=labdomain,DC=local\". VERBOSE: Performing the operation \"Remove\" on target \"CN=ChrisT,OU=LabUsers,DC=labdomain,DC=local\". VERBOSE: Performing the operation \"Remove\" on target \"CN=ChiragN,OU=LabUsers,DC=labdomain,DC=local\"." } ]
Custom Sort String in C++
Suppose we have S and T two strings these are composed of lowercase letters. In S, no letter occurs more than once. S was sorted in some custom order previously. We have to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x will occur before y in the returned string. So if the S = “cba” and T = “abcd”, then the output will be “cbad”. Here "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". As "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. To solve this, we will follow these steps − set ret as empty string set ret as empty string define a map m, and store the frequency of each character present in T into m define a map m, and store the frequency of each character present in T into m for i in range 0 to size of S – 1x := S[i]for j in range 0 to m[x] – 1ret := ret + xm[x] := 0 for i in range 0 to size of S – 1 x := S[i] x := S[i] for j in range 0 to m[x] – 1ret := ret + x for j in range 0 to m[x] – 1 ret := ret + x ret := ret + x m[x] := 0 m[x] := 0 for each pair it in m −if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it for each pair it in m − if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it if value of it is > 0, then for i in range 0 to value of it – 1ret := ret concatenate key of it for i in range 0 to value of it – 1 ret := ret concatenate key of it ret := ret concatenate key of it return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string customSortString(string S, string T) { string ret = ""; unordered_map <char, int> m; for(int i = 0; i < T.size(); i++){ m[T[i]]++; } for(int i = 0; i < S.size(); i++){ char x = S[i]; for(int j = 0; j < m[x]; j++){ ret += x; } m[x] = 0; } unordered_map <char, int> :: iterator it = m.begin(); while(it != m.end()){ if(it->second > 0){ for(int i = 0; i < it->second; i++)ret += it->first; } it++; } return ret; } }; main(){ Solution ob; cout << (ob.customSortString("cba", "abcd")); } "cba" "abcd" cbad
[ { "code": null, "e": 1408, "s": 1062, "text": "Suppose we have S and T two strings these are composed of lowercase letters. In S, no letter occurs more than once. S was sorted in some custom order previously. We have to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x will occur before y in the returned string." }, { "code": null, "e": 1675, "s": 1408, "text": "So if the S = “cba” and T = “abcd”, then the output will be “cbad”. Here \"a\", \"b\", \"c\" appear in S, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". As \"d\" does not appear in S, it can be at any position in T. \"dcba\", \"cdba\", \"cbda\" are also valid outputs." }, { "code": null, "e": 1719, "s": 1675, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1743, "s": 1719, "text": "set ret as empty string" }, { "code": null, "e": 1767, "s": 1743, "text": "set ret as empty string" }, { "code": null, "e": 1845, "s": 1767, "text": "define a map m, and store the frequency of each character present in T into m" }, { "code": null, "e": 1923, "s": 1845, "text": "define a map m, and store the frequency of each character present in T into m" }, { "code": null, "e": 2017, "s": 1923, "text": "for i in range 0 to size of S – 1x := S[i]for j in range 0 to m[x] – 1ret := ret + xm[x] := 0" }, { "code": null, "e": 2051, "s": 2017, "text": "for i in range 0 to size of S – 1" }, { "code": null, "e": 2061, "s": 2051, "text": "x := S[i]" }, { "code": null, "e": 2071, "s": 2061, "text": "x := S[i]" }, { "code": null, "e": 2114, "s": 2071, "text": "for j in range 0 to m[x] – 1ret := ret + x" }, { "code": null, "e": 2143, "s": 2114, "text": "for j in range 0 to m[x] – 1" }, { "code": null, "e": 2158, "s": 2143, "text": "ret := ret + x" }, { "code": null, "e": 2173, "s": 2158, "text": "ret := ret + x" }, { "code": null, "e": 2183, "s": 2173, "text": "m[x] := 0" }, { "code": null, "e": 2193, "s": 2183, "text": "m[x] := 0" }, { "code": null, "e": 2311, "s": 2193, "text": "for each pair it in m −if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it" }, { "code": null, "e": 2335, "s": 2311, "text": "for each pair it in m −" }, { "code": null, "e": 2430, "s": 2335, "text": "if value of it is > 0, thenfor i in range 0 to value of it – 1ret := ret concatenate key of it" }, { "code": null, "e": 2458, "s": 2430, "text": "if value of it is > 0, then" }, { "code": null, "e": 2526, "s": 2458, "text": "for i in range 0 to value of it – 1ret := ret concatenate key of it" }, { "code": null, "e": 2562, "s": 2526, "text": "for i in range 0 to value of it – 1" }, { "code": null, "e": 2595, "s": 2562, "text": "ret := ret concatenate key of it" }, { "code": null, "e": 2628, "s": 2595, "text": "ret := ret concatenate key of it" }, { "code": null, "e": 2639, "s": 2628, "text": "return ret" }, { "code": null, "e": 2650, "s": 2639, "text": "return ret" }, { "code": null, "e": 2722, "s": 2650, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2733, "s": 2722, "text": " Live Demo" }, { "code": null, "e": 3465, "s": 2733, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string customSortString(string S, string T) {\n string ret = \"\";\n unordered_map <char, int> m;\n for(int i = 0; i < T.size(); i++){\n m[T[i]]++;\n }\n for(int i = 0; i < S.size(); i++){\n char x = S[i];\n for(int j = 0; j < m[x]; j++){\n ret += x;\n }\n m[x] = 0;\n }\n unordered_map <char, int> :: iterator it = m.begin();\n while(it != m.end()){\n if(it->second > 0){\n for(int i = 0; i < it->second; i++)ret += it->first;\n }\n it++;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.customSortString(\"cba\", \"abcd\"));\n}" }, { "code": null, "e": 3478, "s": 3465, "text": "\"cba\"\n\"abcd\"" }, { "code": null, "e": 3483, "s": 3478, "text": "cbad" } ]
CICS - Handle condition
Handle condition is used to transfer the control of the program to a paragraph or a procedure label. If the condition name specified in the exception block arises, the particular para will be given control and then we can handle that condition. HANDLE CONDITION can handle only conditions related to CICS, not the ordinary program Abends like as data exceptions. It can handle conditions that are related only to CICS. It cannot handle the ordinary program Abends like as data exceptions. The syntax of Handle Condition is as follows − EXEC CICS HANDLE CONDITION CONDITION(Label) CONDITION(Label) ERROR(LABEL) END-EXEC. Following is the example of Handle condition − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. EXEC CICS HANDLE CONDITION DUPKEY(X0000-DUPKEY-ERR-PARA) NOTFND(X000-NOT-FOUND-PARA) ERROR(X0000-GEN-ERR-PARA) END-EXEC. X0000-DUPKEY-ERR-PARA. DISPLAY 'Duplicate Key Found'. X0000-NOT-FOUND-PARA. DISPLAY 'Record Not Found'. X0000-GEN-ERR-PARA. DISPLAY 'General Error'. Print Add Notes Bookmark this page
[ { "code": null, "e": 2171, "s": 1926, "text": "Handle condition is used to transfer the control of the program to a paragraph or a procedure label. If the condition name specified in the exception block arises, the particular para will be given control and then we can handle that condition." }, { "code": null, "e": 2462, "s": 2171, "text": "HANDLE CONDITION can handle only conditions related to CICS, not the ordinary program Abends like as data exceptions. It can handle conditions that are related only to CICS. It cannot handle the ordinary program Abends like as data exceptions. The syntax of Handle Condition is as follows −" }, { "code": null, "e": 2556, "s": 2462, "text": "EXEC CICS HANDLE CONDITION\n CONDITION(Label)\n CONDITION(Label)\n ERROR(LABEL)\nEND-EXEC.\n" }, { "code": null, "e": 2603, "s": 2556, "text": "Following is the example of Handle condition −" }, { "code": null, "e": 3038, "s": 2603, "text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nPROCEDURE DIVISION.\n\nEXEC CICS HANDLE CONDITION\n DUPKEY(X0000-DUPKEY-ERR-PARA)\n NOTFND(X000-NOT-FOUND-PARA)\n ERROR(X0000-GEN-ERR-PARA)\nEND-EXEC.\nX0000-DUPKEY-ERR-PARA.\n\nDISPLAY 'Duplicate Key Found'.\nX0000-NOT-FOUND-PARA.\n\nDISPLAY 'Record Not Found'.\nX0000-GEN-ERR-PARA.\n\nDISPLAY 'General Error'." }, { "code": null, "e": 3045, "s": 3038, "text": " Print" }, { "code": null, "e": 3056, "s": 3045, "text": " Add Notes" } ]
4 Jupyter Notebook Alternative for Data Scientist | by Cornellius Yudha Wijaya | Towards Data Science
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here. As modern Data scientists, programming is the main tool that we must master. Although, unlike software developers or engineers, we utilize programming language for data analysis and not for software development. That is why we data scientists are taught to use the data analysis IDE for our work. Jupyter Notebook is the main environment where many Data Scientists start from because it is the easiest to understood and integrated with the Anaconda environment (which many people use to set up the Data Science platform). However, there are few Jupyter Notebook alternatives that I want to introduce as a consideration once you have understood how Jupyter Notebook works. Here are my four Jupyter Notebook alternatives for Data scientists. Let’s get started on it. Visual Studio Code or VS Code is a free and open-source IDE designed for programmers to running and executing their codes seamlessly. VS Code is versatile because they include many customizable extensions, code debugging, and GIT integration for versioning purposes. In the past, VS Code is more suitable to developers or engineers because it did not have any capability for data analysis, but since 2020 VS Code team have worked together with the Jupyter team to bring an integrated notebook within the VS Code. The result is an amazing IDE workbook you could use for data analysis. Let me show you how the VS Code notebook integration works in the image below. As you can see in the image above, you are running your code on the left side (where it looks like a cell in the Jupyter Notebook), and the result is shown on the right side. Let’s try to dissect in more detail how the process works. First, to initialize the notebook cell, you need to type # %% on above the code you want to run as a cell similar to the Jupyter Notebook. When you do this, VS Code would automatically understand that you intended to initiate the Notebook and show up with the cell option. When you want to run the cell, you could run it using the shortcut shift + enter. When you run the cell code, it would automatically run in the interactive notebook—for example; I run the following code. In the image above, I load an mpg dataset and show up the dataset's head (top 5 rows). In the notebook, it would process similar to the image below. The capability is there, but why do we want to use VS Code notebook instead of the Jupyter Notebook? There are few reasons I could give you: If you are coming from a developer background, VS Code would feel familiar,VS Code is integrated with the GIT Versioning, which helps when you want to see your old code,Code Debugging exists in the VS Code, unlike in Jupyter Notebook. If you are coming from a developer background, VS Code would feel familiar, VS Code is integrated with the GIT Versioning, which helps when you want to see your old code, Code Debugging exists in the VS Code, unlike in Jupyter Notebook. There are many more reasons I could think of, but in the end, it would come back to your preferences. What is nteract? It is an open-source interactive environment designed for end-to-end data analysis workflow, including a notebook for data exploration, building applications, versioning, and more. In my opinion, the main selling point for nteract is the interactive part, where the UI allows you to control the notebook result and present it as an application. The nteract environment contains a desktop app that you could download here, and the kernel is automatically integrated with your Anaconda environment. Because of that, when you already installed the nteract, you could open your notebook without the need to initiate the Jupyter Notebook or go to the Jupyter Lab. For example, I would show you my old notebook and the folder. From the image above, you could see that the ipynb file is now, by default, could be open using the nteract. Let’s see what is it like when you open it. The nteract IDE is shown in the image above. The nteract environment is similar to the Jupyter Notebook but with more control in the cell placement and integrated as an app. Let’s see the usage of nteract in the GIF below. There are also various nteract libraries you could use to enhance your productivity, such as: Papermill is used for notebook parameterization, which could automatically save your notebook result to the cloud environment, Scrapbook is used to save all the data and images from your notebook by basically “Scrapping” it, Bookstore is used for versioning. Jupyterlite is an in-browser based Jupyter Notebook unofficially developed by the Jupyter developer. It utilizes many of the Jupyter Lab and Jupyter Notebook features and is made ready to use in the browser. The development is still ongoing so expect many changes and additional features would be added, but we could check out the Jupyterlite environment. You could try Jupyterlite in-browser using the demo in the Jupyter Lab style or the Retro Lab Style (Classic Jupyter Notebook). Either way, the basic environment have already contained few features such as: Pre-installed visualization packages such as altair, plotly, and matplotlib In-browser based notebook interaction for hosting, save, and export notebook Jupyterlite CLI Let’s try to check out the basic usage of Jupyterlite using the plotly notebook demo provided by Jupyterlite. From the GIF above, we could see that the environment is still similar to the Jupyter Notebook, but it seems more basic. Though, the UI is slightly more interactive — you could move the cell around, just like nteract. If you want to build Jupyterlite in your own environment, you could do that by installing Jupyterlite. python -m pip install --pre jupyterlite When you have finished installing the package, you need to run the following code. jupyter lite initjupyter lite buildjupyter lite serve Done. You now have built the Jupyterlite locally and could access it from your browser. However, just like I mentioned previously that Jupyterlite is still ongoing development, so I expect many things could be changed in the future. Google Colaboratory or Colab is an in-browser based notebook developed by the google team. The notebook environment is based on the Jupyter Notebook environment, so it would feel familiar for you who already use the Jupyter. The notebook is shown in the image below. As you can see from the image above, the environment is similar to the Jupyter Notebook. So, why do we want to use Google Colab? There are few reasons I could give you: It is perfect for any people who did not have any access to high-performance hardware/GPU. Because Colab is hosted in the cloud and provided you with free GPU, you could analyze bigger datasets that are not possible in-premise — especially if you are still in the learning phase, Easy integration with the Google database such as Google Sheet, Google Drive or Google BigQuery, Instant code snippets you could use for specific purposes. For example, camera capture from a webcam or creating a stacked chart. Google Colab is perfect for you who still learning or working closely with the Google environment as it is developed with the Google services integration. If you want to learn more about Google Colab, I suggest you visit their notebook tutorial. This tutorial provided all the basic Google Colab use cases and how to develop your own Neural Network using TensorFlow. Data people vastly use Jupyter Notebook because it is easy to use and developed specifically for data analysis. However, as you getting more familiar with the Jupyter Notebook, you might want to check another alternative. In this article, I have present you with four Jupyter Notebook alternatives you could use. They are: Visual Studio CodenteractJupyterliteGoogle Colab Visual Studio Code nteract Jupyterlite Google Colab I hope it helps! Visit me on my LinkedIn or Twitter. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 342, "s": 172, "text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here." }, { "code": null, "e": 639, "s": 342, "text": "As modern Data scientists, programming is the main tool that we must master. Although, unlike software developers or engineers, we utilize programming language for data analysis and not for software development. That is why we data scientists are taught to use the data analysis IDE for our work." }, { "code": null, "e": 1014, "s": 639, "text": "Jupyter Notebook is the main environment where many Data Scientists start from because it is the easiest to understood and integrated with the Anaconda environment (which many people use to set up the Data Science platform). However, there are few Jupyter Notebook alternatives that I want to introduce as a consideration once you have understood how Jupyter Notebook works." }, { "code": null, "e": 1107, "s": 1014, "text": "Here are my four Jupyter Notebook alternatives for Data scientists. Let’s get started on it." }, { "code": null, "e": 1374, "s": 1107, "text": "Visual Studio Code or VS Code is a free and open-source IDE designed for programmers to running and executing their codes seamlessly. VS Code is versatile because they include many customizable extensions, code debugging, and GIT integration for versioning purposes." }, { "code": null, "e": 1770, "s": 1374, "text": "In the past, VS Code is more suitable to developers or engineers because it did not have any capability for data analysis, but since 2020 VS Code team have worked together with the Jupyter team to bring an integrated notebook within the VS Code. The result is an amazing IDE workbook you could use for data analysis. Let me show you how the VS Code notebook integration works in the image below." }, { "code": null, "e": 2004, "s": 1770, "text": "As you can see in the image above, you are running your code on the left side (where it looks like a cell in the Jupyter Notebook), and the result is shown on the right side. Let’s try to dissect in more detail how the process works." }, { "code": null, "e": 2359, "s": 2004, "text": "First, to initialize the notebook cell, you need to type # %% on above the code you want to run as a cell similar to the Jupyter Notebook. When you do this, VS Code would automatically understand that you intended to initiate the Notebook and show up with the cell option. When you want to run the cell, you could run it using the shortcut shift + enter." }, { "code": null, "e": 2481, "s": 2359, "text": "When you run the cell code, it would automatically run in the interactive notebook—for example; I run the following code." }, { "code": null, "e": 2630, "s": 2481, "text": "In the image above, I load an mpg dataset and show up the dataset's head (top 5 rows). In the notebook, it would process similar to the image below." }, { "code": null, "e": 2771, "s": 2630, "text": "The capability is there, but why do we want to use VS Code notebook instead of the Jupyter Notebook? There are few reasons I could give you:" }, { "code": null, "e": 3006, "s": 2771, "text": "If you are coming from a developer background, VS Code would feel familiar,VS Code is integrated with the GIT Versioning, which helps when you want to see your old code,Code Debugging exists in the VS Code, unlike in Jupyter Notebook." }, { "code": null, "e": 3082, "s": 3006, "text": "If you are coming from a developer background, VS Code would feel familiar," }, { "code": null, "e": 3177, "s": 3082, "text": "VS Code is integrated with the GIT Versioning, which helps when you want to see your old code," }, { "code": null, "e": 3243, "s": 3177, "text": "Code Debugging exists in the VS Code, unlike in Jupyter Notebook." }, { "code": null, "e": 3345, "s": 3243, "text": "There are many more reasons I could think of, but in the end, it would come back to your preferences." }, { "code": null, "e": 3707, "s": 3345, "text": "What is nteract? It is an open-source interactive environment designed for end-to-end data analysis workflow, including a notebook for data exploration, building applications, versioning, and more. In my opinion, the main selling point for nteract is the interactive part, where the UI allows you to control the notebook result and present it as an application." }, { "code": null, "e": 4083, "s": 3707, "text": "The nteract environment contains a desktop app that you could download here, and the kernel is automatically integrated with your Anaconda environment. Because of that, when you already installed the nteract, you could open your notebook without the need to initiate the Jupyter Notebook or go to the Jupyter Lab. For example, I would show you my old notebook and the folder." }, { "code": null, "e": 4236, "s": 4083, "text": "From the image above, you could see that the ipynb file is now, by default, could be open using the nteract. Let’s see what is it like when you open it." }, { "code": null, "e": 4459, "s": 4236, "text": "The nteract IDE is shown in the image above. The nteract environment is similar to the Jupyter Notebook but with more control in the cell placement and integrated as an app. Let’s see the usage of nteract in the GIF below." }, { "code": null, "e": 4553, "s": 4459, "text": "There are also various nteract libraries you could use to enhance your productivity, such as:" }, { "code": null, "e": 4680, "s": 4553, "text": "Papermill is used for notebook parameterization, which could automatically save your notebook result to the cloud environment," }, { "code": null, "e": 4778, "s": 4680, "text": "Scrapbook is used to save all the data and images from your notebook by basically “Scrapping” it," }, { "code": null, "e": 4812, "s": 4778, "text": "Bookstore is used for versioning." }, { "code": null, "e": 5168, "s": 4812, "text": "Jupyterlite is an in-browser based Jupyter Notebook unofficially developed by the Jupyter developer. It utilizes many of the Jupyter Lab and Jupyter Notebook features and is made ready to use in the browser. The development is still ongoing so expect many changes and additional features would be added, but we could check out the Jupyterlite environment." }, { "code": null, "e": 5375, "s": 5168, "text": "You could try Jupyterlite in-browser using the demo in the Jupyter Lab style or the Retro Lab Style (Classic Jupyter Notebook). Either way, the basic environment have already contained few features such as:" }, { "code": null, "e": 5451, "s": 5375, "text": "Pre-installed visualization packages such as altair, plotly, and matplotlib" }, { "code": null, "e": 5528, "s": 5451, "text": "In-browser based notebook interaction for hosting, save, and export notebook" }, { "code": null, "e": 5544, "s": 5528, "text": "Jupyterlite CLI" }, { "code": null, "e": 5654, "s": 5544, "text": "Let’s try to check out the basic usage of Jupyterlite using the plotly notebook demo provided by Jupyterlite." }, { "code": null, "e": 5872, "s": 5654, "text": "From the GIF above, we could see that the environment is still similar to the Jupyter Notebook, but it seems more basic. Though, the UI is slightly more interactive — you could move the cell around, just like nteract." }, { "code": null, "e": 5975, "s": 5872, "text": "If you want to build Jupyterlite in your own environment, you could do that by installing Jupyterlite." }, { "code": null, "e": 6015, "s": 5975, "text": "python -m pip install --pre jupyterlite" }, { "code": null, "e": 6098, "s": 6015, "text": "When you have finished installing the package, you need to run the following code." }, { "code": null, "e": 6152, "s": 6098, "text": "jupyter lite initjupyter lite buildjupyter lite serve" }, { "code": null, "e": 6385, "s": 6152, "text": "Done. You now have built the Jupyterlite locally and could access it from your browser. However, just like I mentioned previously that Jupyterlite is still ongoing development, so I expect many things could be changed in the future." }, { "code": null, "e": 6652, "s": 6385, "text": "Google Colaboratory or Colab is an in-browser based notebook developed by the google team. The notebook environment is based on the Jupyter Notebook environment, so it would feel familiar for you who already use the Jupyter. The notebook is shown in the image below." }, { "code": null, "e": 6821, "s": 6652, "text": "As you can see from the image above, the environment is similar to the Jupyter Notebook. So, why do we want to use Google Colab? There are few reasons I could give you:" }, { "code": null, "e": 7101, "s": 6821, "text": "It is perfect for any people who did not have any access to high-performance hardware/GPU. Because Colab is hosted in the cloud and provided you with free GPU, you could analyze bigger datasets that are not possible in-premise — especially if you are still in the learning phase," }, { "code": null, "e": 7198, "s": 7101, "text": "Easy integration with the Google database such as Google Sheet, Google Drive or Google BigQuery," }, { "code": null, "e": 7328, "s": 7198, "text": "Instant code snippets you could use for specific purposes. For example, camera capture from a webcam or creating a stacked chart." }, { "code": null, "e": 7483, "s": 7328, "text": "Google Colab is perfect for you who still learning or working closely with the Google environment as it is developed with the Google services integration." }, { "code": null, "e": 7695, "s": 7483, "text": "If you want to learn more about Google Colab, I suggest you visit their notebook tutorial. This tutorial provided all the basic Google Colab use cases and how to develop your own Neural Network using TensorFlow." }, { "code": null, "e": 7917, "s": 7695, "text": "Data people vastly use Jupyter Notebook because it is easy to use and developed specifically for data analysis. However, as you getting more familiar with the Jupyter Notebook, you might want to check another alternative." }, { "code": null, "e": 8018, "s": 7917, "text": "In this article, I have present you with four Jupyter Notebook alternatives you could use. They are:" }, { "code": null, "e": 8067, "s": 8018, "text": "Visual Studio CodenteractJupyterliteGoogle Colab" }, { "code": null, "e": 8086, "s": 8067, "text": "Visual Studio Code" }, { "code": null, "e": 8094, "s": 8086, "text": "nteract" }, { "code": null, "e": 8106, "s": 8094, "text": "Jupyterlite" }, { "code": null, "e": 8119, "s": 8106, "text": "Google Colab" }, { "code": null, "e": 8136, "s": 8119, "text": "I hope it helps!" }, { "code": null, "e": 8172, "s": 8136, "text": "Visit me on my LinkedIn or Twitter." } ]
Creating a Slider / Carousel with CSS Flexbox (with infinite repeating items in loop)
We can create an infinitely scrolling slider using CSS Flexbox with the help of JavaScript. The following examples illustrate carousel using CSS. Live Demo <!DOCTYPE html> <html> <head> <style> img { width: 100%; } .container { max-width: 600px; position: relative; margin: 6% auto; } .prevbtn, .nextbtn { position: absolute; top: 50%; padding: 12px; margin-top: -20px; color: white; font-weight: bold; cursor: pointer; transition: 0.2s ease-in; border-radius: 50%; } .prevbtn:hover, .nextbtn:hover { background-color: darkgrey; color: rgb(0,0,0); } .nextbtn { right: 0; } </style> </head> <body> <div class="container"> <div class="slide"> <img src="https://images.unsplash.com/photo-1609517904792-bac493d55556?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700" /> </div> <div class="slide"> <img src="https://images.unsplash.com/photo-1609883475382-c4c9378569e5?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700" /> </div> <div class="slide"> <img src="https://images.unsplash.com/photo-1610258648552-fe6407d664a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700" /> </div> <div class="slide"> <img src="https://images.unsplash.com/photo-1610258648552-fe6407d664a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700" /> </div> <div class="slide"> <img src="https://images.unsplash.com/photo-1611094607507-8c8173e5cf33?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700" /> </div> <a class="prevbtn" onclick="changeSlide(-1)">❮</a> <a class="nextbtn" onclick="changeSlide(1)">❯</a> </div> <script> let slideIndex = [1,1]; viewSlides(1); function changeSlide(n) { viewSlides(slideIndex[0] += n); } function viewSlides(n) { let ele = document.getElementsByClassName("slide"); if (n > ele.length) { slideIndex[0] = 1 } if (n < 1) { slideIndex[0] = ele.length } for (i = 0; i < ele.length; i++) { ele[i].style.display = "none"; } ele[slideIndex[0]-1].style.display = "block"; } </script> </body> </html> This gives the following output Live Demo <!DOCTYPE html> <html> <head> <style> .container { height: 120px; max-width: 600px; margin: 12px auto; position: relative; overflow: hidden; transform: translate3d(0, 0, 0); border: 4px ridge rgba(20,30,240,0.6); } .container > div { height: 120px; width: 2400px; background: url(https://images.unsplash.com/photo-1611485916153-fce531587fe0?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb-1.2.1&q=80&w=120); position: absolute; height: 100%; transform: translate3d(0, 0, 0); } .container .slider { animation: slideshow 20s linear infinite; } @keyframes slideshow { 100% { transform: translateX(-33.33%); } } </style> </head> <body> <div class="container"> <div class="slider"></div> </div> </body> </html> This gives the following output
[ { "code": null, "e": 1154, "s": 1062, "text": "We can create an infinitely scrolling slider using CSS Flexbox with the help of JavaScript." }, { "code": null, "e": 1208, "s": 1154, "text": "The following examples illustrate carousel using CSS." }, { "code": null, "e": 1219, "s": 1208, "text": " Live Demo" }, { "code": null, "e": 3783, "s": 1219, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n img {\n width: 100%;\n }\n .container {\n max-width: 600px;\n position: relative;\n margin: 6% auto;\n }\n .prevbtn, .nextbtn {\n position: absolute;\n top: 50%;\n padding: 12px;\n margin-top: -20px;\n color: white;\n font-weight: bold;\n cursor: pointer;\n transition: 0.2s ease-in;\n border-radius: 50%;\n }\n .prevbtn:hover, .nextbtn:hover {\n background-color: darkgrey;\n color: rgb(0,0,0);\n }\n .nextbtn {\n right: 0;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"slide\">\n <img src=\"https://images.unsplash.com/photo-1609517904792-bac493d55556?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700\" />\n </div>\n <div class=\"slide\">\n <img src=\"https://images.unsplash.com/photo-1609883475382-c4c9378569e5?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700\" />\n </div>\n <div class=\"slide\">\n <img src=\"https://images.unsplash.com/photo-1610258648552-fe6407d664a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700\" />\n </div>\n <div class=\"slide\">\n <img src=\"https://images.unsplash.com/photo-1610258648552-fe6407d664a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700\" />\n </div>\n <div class=\"slide\">\n <img src=\"https://images.unsplash.com/photo-1611094607507-8c8173e5cf33?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=700\" />\n </div>\n <a class=\"prevbtn\" onclick=\"changeSlide(-1)\">❮</a>\n <a class=\"nextbtn\" onclick=\"changeSlide(1)\">❯</a>\n </div>\n <script>\n let slideIndex = [1,1];\n viewSlides(1);\n function changeSlide(n) {\n viewSlides(slideIndex[0] += n);\n }\n function viewSlides(n) {\n let ele = document.getElementsByClassName(\"slide\");\n if (n > ele.length) {\n slideIndex[0] = 1\n }\n if (n < 1) {\n slideIndex[0] = ele.length\n }\n for (i = 0; i < ele.length; i++) {\n ele[i].style.display = \"none\";\n }\n ele[slideIndex[0]-1].style.display = \"block\";\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 3815, "s": 3783, "text": "This gives the following output" }, { "code": null, "e": 3826, "s": 3815, "text": " Live Demo" }, { "code": null, "e": 4864, "s": 3826, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n height: 120px;\n max-width: 600px;\n margin: 12px auto;\n position: relative;\n overflow: hidden;\n transform: translate3d(0, 0, 0);\n border: 4px ridge rgba(20,30,240,0.6);\n }\n .container > div {\n height: 120px;\n width: 2400px;\n background: url(https://images.unsplash.com/photo-1611485916153-fce531587fe0?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb-1.2.1&q=80&w=120);\n position: absolute;\n height: 100%;\n transform: translate3d(0, 0, 0);\n }\n .container .slider {\n animation: slideshow 20s linear infinite;\n }\n @keyframes slideshow {\n 100% {\n transform: translateX(-33.33%);\n }\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"slider\"></div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4896, "s": 4864, "text": "This gives the following output" } ]
How to apply an id attribute to a child element of a ReactJS component ? - GeeksforGeeks
07 Apr, 2021 We can get the ID attribute of a ReactJS component from the props of the ReactJS component. As we are inside a ReactJS component here we are going to use this.props instead of props. If the ID attribute has been passed as id to the ReactJS component then we can use the following to get the ID attribute passed: this.props.id Once we get the ID attribute we can easily pass it to any child element to which we wish to pass it as shown below. <child_element_name id = {this.props.id}> 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: 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 BodyComponent from './Bodycomponent.js'; function App() { return ( <div> <header>Hello and Welcome</header> <BodyComponent id='childid' /> </div> );} export default App; Bodycomponent.js import React from 'react'; function BodyComponent(props) { return ( <p id={props.id}> This is the content with the ID 'childid'. It has been supplied with the ID attribute of the React component. </p> );} export default BodyComponent; 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 JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to filter object array based on attributes? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25256, "s": 25228, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25568, "s": 25256, "text": "We can get the ID attribute of a ReactJS component from the props of the ReactJS component. As we are inside a ReactJS component here we are going to use this.props instead of props. If the ID attribute has been passed as id to the ReactJS component then we can use the following to get the ID attribute passed:" }, { "code": null, "e": 25582, "s": 25568, "text": "this.props.id" }, { "code": null, "e": 25698, "s": 25582, "text": "Once we get the ID attribute we can easily pass it to any child element to which we wish to pass it as shown below." }, { "code": null, "e": 25740, "s": 25698, "text": "<child_element_name id = {this.props.id}>" }, { "code": null, "e": 25768, "s": 25740, "text": "Creating React Application:" }, { "code": null, "e": 25863, "s": 25768, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 25927, "s": 25863, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25959, "s": 25927, "text": "npx create-react-app foldername" }, { "code": null, "e": 26072, "s": 25959, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 26172, "s": 26072, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26186, "s": 26172, "text": "cd foldername" }, { "code": null, "e": 26238, "s": 26186, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26368, "s": 26238, "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": 26375, "s": 26368, "text": "App.js" }, { "code": "import BodyComponent from './Bodycomponent.js'; function App() { return ( <div> <header>Hello and Welcome</header> <BodyComponent id='childid' /> </div> );} export default App;", "e": 26596, "s": 26375, "text": null }, { "code": null, "e": 26613, "s": 26596, "text": "Bodycomponent.js" }, { "code": "import React from 'react'; function BodyComponent(props) { return ( <p id={props.id}> This is the content with the ID 'childid'. It has been supplied with the ID attribute of the React component. </p> );} export default BodyComponent;", "e": 26906, "s": 26613, "text": null }, { "code": null, "e": 27019, "s": 26906, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27029, "s": 27019, "text": "npm start" }, { "code": null, "e": 27128, "s": 27029, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27135, "s": 27128, "text": "Picked" }, { "code": null, "e": 27151, "s": 27135, "text": "React-Questions" }, { "code": null, "e": 27162, "s": 27151, "text": "JavaScript" }, { "code": null, "e": 27170, "s": 27162, "text": "ReactJS" }, { "code": null, "e": 27187, "s": 27170, "text": "Web Technologies" }, { "code": null, "e": 27285, "s": 27187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27294, "s": 27285, "text": "Comments" }, { "code": null, "e": 27307, "s": 27294, "text": "Old Comments" }, { "code": null, "e": 27368, "s": 27307, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27409, "s": 27368, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27457, "s": 27409, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27519, "s": 27457, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27576, "s": 27519, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27619, "s": 27576, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27664, "s": 27619, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27729, "s": 27664, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27797, "s": 27729, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Visualizing the Central Limit Theorem with Python | by Valentina Alto | Towards Data Science
Whenever you are dealing with data and want to gather some information about them, the very first thing you are likely to check is whether they follow a known distribution. Why is it so important knowing data distribution? The answer to this question relies on the goal of many statistical types of research, that is, knowing something more about an objective, which is generally referred to as population. The caveat is that it is often impractical (or even impossible) to observe the whole population of your project. Imagine, namely, you want to know the average weight of men aged between 40 and 50 years-old. Do you think you might be able to interview all men around the world who have these features? The impossibility of observing the whole population is the reason why we need samples. The sampling procedure consists of selecting from the whole population a subset which, ideally, should be representative of the initial population. By doing so, we want to make inferences about our objective population starting from the information contained in our sample. In the previous example (finding the average weight of men), a way of resolution is collecting data from a subset or sample of men, considering different nationalities so that the sample is not biased. So we will obtain a sample mean which should approximate the population mean. However, how can we be sure about the accuracy of that result? By definitions, statisticians are never sure, that’s why we need to test the robustness of our results, running the so-called hypothesis tests. Those latter allow us to state whether we can reject or not reject our null hypothesis (in our case, that would be ‘ the sample mean is a good estimate of the real parameter’). And, to do so, we need to know the distribution of our data. That’s why the Central Limit Theorem (CLT) is so important. The idea of CLT is the following: let’s collect x samples each of size n and let’s compute the sample mean for each sample. Then, (under some assumptions we are going to see in a minute) if we plot all the sample means, they should be following a Normal distribution. Furthermore, the mean of all the sample means should be almost equal to the real parameter of the whole population. Which are those assumptions I mentioned? The sampling procedure must be randomly executed Samples have to be independent among each other Sample size should be no more than 10% of the population when sampling is done without replacement The sample size should be sufficiently large (normally, a size of n=30 is considered to be sufficiently large, even though it really depends on the initial population) If those assumptions are considered true, the CLT allows you to make inferences about your initial population. Furthermore, the larger the size of your samples, the more evident will be the bell-shape of your sample mean distribution. To fully appreciate this theorem, let’s visualize it in Python. What I’m about to do is creating random samples of men’s weights (imagining they range between 60 and 90 kg), each of size n=50. Then, I will run this simulation multiple times and see whether the sample means distribution resembles a Normal distribution. from numpy.random import seedfrom numpy.random import randintfrom numpy import mean# seed the random number generator, so that the experiment is #replicableseed(1)# generate a sample of men's weightsweights = randint(60, 90, 50)print(weights)print('The average weight is {} kg'.format(mean(weights))) Now let’s repeat the sampling simulation for 1000 times: import matplotlib.pyplot as plt# seed the random number generator, so that the experiment is replicableseed(1)# calculate the mean of 50 men's weights 1000 timesmeans = [mean(randint(60, 90, 50)) for _i in range(1000)]# plot the distribution of sample meansplt.hist(means)plt.show()print('The mean of the sample means is {}'.format(mean(means))) According to the CLT, the mean of the sample means (74.54) should be a good estimate of the real parameter (which is unknown). To be sure of our result, let’s run a normality test on our data. For this purpose, I’m going to use the Shapiro-Wilk normality test (you can read more about this test here), where the hypotheses are: H0: data follow a Normal distribution H1: data do not follow a Normal distribution So if our sample means follow a normal distribution, we are going to not reject the null. from scipy.stats import shapirostat, p = shapiro(means)print('Statistics={}, p={}'.format(stat, p))alpha = 0.05if p > alpha: print('Sample looks Normal (do not reject H0)')else: print('Sample does not look Normal (reject H0)') Since the p-value is far greater than our confidence level alpha (specifically, it is greater of any significant level of alpha), we do not reject H0. Now let’s see what happens if we increase the sample size from 50 to, respectively, 80, 90 and 100: As you can see, the higher the sample size n, the higher the p-value, the higher the confidence with which we do not reject the null hypothesis of normality.
[ { "code": null, "e": 344, "s": 171, "text": "Whenever you are dealing with data and want to gather some information about them, the very first thing you are likely to check is whether they follow a known distribution." }, { "code": null, "e": 394, "s": 344, "text": "Why is it so important knowing data distribution?" }, { "code": null, "e": 879, "s": 394, "text": "The answer to this question relies on the goal of many statistical types of research, that is, knowing something more about an objective, which is generally referred to as population. The caveat is that it is often impractical (or even impossible) to observe the whole population of your project. Imagine, namely, you want to know the average weight of men aged between 40 and 50 years-old. Do you think you might be able to interview all men around the world who have these features?" }, { "code": null, "e": 1240, "s": 879, "text": "The impossibility of observing the whole population is the reason why we need samples. The sampling procedure consists of selecting from the whole population a subset which, ideally, should be representative of the initial population. By doing so, we want to make inferences about our objective population starting from the information contained in our sample." }, { "code": null, "e": 1520, "s": 1240, "text": "In the previous example (finding the average weight of men), a way of resolution is collecting data from a subset or sample of men, considering different nationalities so that the sample is not biased. So we will obtain a sample mean which should approximate the population mean." }, { "code": null, "e": 1904, "s": 1520, "text": "However, how can we be sure about the accuracy of that result? By definitions, statisticians are never sure, that’s why we need to test the robustness of our results, running the so-called hypothesis tests. Those latter allow us to state whether we can reject or not reject our null hypothesis (in our case, that would be ‘ the sample mean is a good estimate of the real parameter’)." }, { "code": null, "e": 2025, "s": 1904, "text": "And, to do so, we need to know the distribution of our data. That’s why the Central Limit Theorem (CLT) is so important." }, { "code": null, "e": 2409, "s": 2025, "text": "The idea of CLT is the following: let’s collect x samples each of size n and let’s compute the sample mean for each sample. Then, (under some assumptions we are going to see in a minute) if we plot all the sample means, they should be following a Normal distribution. Furthermore, the mean of all the sample means should be almost equal to the real parameter of the whole population." }, { "code": null, "e": 2450, "s": 2409, "text": "Which are those assumptions I mentioned?" }, { "code": null, "e": 2499, "s": 2450, "text": "The sampling procedure must be randomly executed" }, { "code": null, "e": 2547, "s": 2499, "text": "Samples have to be independent among each other" }, { "code": null, "e": 2646, "s": 2547, "text": "Sample size should be no more than 10% of the population when sampling is done without replacement" }, { "code": null, "e": 2814, "s": 2646, "text": "The sample size should be sufficiently large (normally, a size of n=30 is considered to be sufficiently large, even though it really depends on the initial population)" }, { "code": null, "e": 3049, "s": 2814, "text": "If those assumptions are considered true, the CLT allows you to make inferences about your initial population. Furthermore, the larger the size of your samples, the more evident will be the bell-shape of your sample mean distribution." }, { "code": null, "e": 3369, "s": 3049, "text": "To fully appreciate this theorem, let’s visualize it in Python. What I’m about to do is creating random samples of men’s weights (imagining they range between 60 and 90 kg), each of size n=50. Then, I will run this simulation multiple times and see whether the sample means distribution resembles a Normal distribution." }, { "code": null, "e": 3670, "s": 3369, "text": "from numpy.random import seedfrom numpy.random import randintfrom numpy import mean# seed the random number generator, so that the experiment is #replicableseed(1)# generate a sample of men's weightsweights = randint(60, 90, 50)print(weights)print('The average weight is {} kg'.format(mean(weights)))" }, { "code": null, "e": 3727, "s": 3670, "text": "Now let’s repeat the sampling simulation for 1000 times:" }, { "code": null, "e": 4073, "s": 3727, "text": "import matplotlib.pyplot as plt# seed the random number generator, so that the experiment is replicableseed(1)# calculate the mean of 50 men's weights 1000 timesmeans = [mean(randint(60, 90, 50)) for _i in range(1000)]# plot the distribution of sample meansplt.hist(means)plt.show()print('The mean of the sample means is {}'.format(mean(means)))" }, { "code": null, "e": 4200, "s": 4073, "text": "According to the CLT, the mean of the sample means (74.54) should be a good estimate of the real parameter (which is unknown)." }, { "code": null, "e": 4401, "s": 4200, "text": "To be sure of our result, let’s run a normality test on our data. For this purpose, I’m going to use the Shapiro-Wilk normality test (you can read more about this test here), where the hypotheses are:" }, { "code": null, "e": 4439, "s": 4401, "text": "H0: data follow a Normal distribution" }, { "code": null, "e": 4484, "s": 4439, "text": "H1: data do not follow a Normal distribution" }, { "code": null, "e": 4574, "s": 4484, "text": "So if our sample means follow a normal distribution, we are going to not reject the null." }, { "code": null, "e": 4807, "s": 4574, "text": "from scipy.stats import shapirostat, p = shapiro(means)print('Statistics={}, p={}'.format(stat, p))alpha = 0.05if p > alpha: print('Sample looks Normal (do not reject H0)')else: print('Sample does not look Normal (reject H0)')" }, { "code": null, "e": 4958, "s": 4807, "text": "Since the p-value is far greater than our confidence level alpha (specifically, it is greater of any significant level of alpha), we do not reject H0." }, { "code": null, "e": 5058, "s": 4958, "text": "Now let’s see what happens if we increase the sample size from 50 to, respectively, 80, 90 and 100:" } ]
How can I override the 'Home' button in my Android App?
This example demonstrates how do I in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:text="Press Home Button" android:textSize="16sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onUserLeaveHint(){ Toast.makeText(getApplicationContext(), "Home Button is Pressed", Toast.LENGTH_SHORT).show(); super.onUserLeaveHint(); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1109, "s": 1062, "text": "This example demonstrates how do I in android." }, { "code": null, "e": 1238, "s": 1109, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1303, "s": 1238, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1838, "s": 1303, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:text=\"Press Home Button\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 1895, "s": 1838, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2403, "s": 1895, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n @Override\n protected void onUserLeaveHint(){\n Toast.makeText(getApplicationContext(), \"Home Button is Pressed\", Toast.LENGTH_SHORT).show();\n super.onUserLeaveHint();\n }\n}" }, { "code": null, "e": 2458, "s": 2403, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3131, "s": 2458, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3479, "s": 3131, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3519, "s": 3479, "text": "Click here to download the project code" } ]
Replace part of string in MySQL table column?
To replace part of string in MySQL table column, you can use REPLACE(). Following is the syntax − update yourTableName set yourColumnName = REPLACE(yourColumnName ,'yourOldValue','yourNewValue'); Let us first create a table − mysql> create table replacePartOfStringDemo -> ( -> WebsiteURL varchar(100) -> ); Query OK, 0 rows affected (0.47 sec) Following is the query to insert records in the table using insert command − mysql> insert into replacePartOfStringDemo(WebsiteURL) values('www.mysqlQuestion.com'); Query OK, 1 row affected (0.14 sec) Following is the query to display all records from the table using select statement − mysql> select * from replacePartOfStringDemo; This will produce the following output − +-----------------------+ | WebsiteURL | +-----------------------+ | www.mysqlQuestion.com | +-----------------------+ 1 row in set (0.00 sec) Let us now replace part of a string in MySQL table column. Here, “mysqlQuestion“ is replaced with “mysql” − mysql> update replacePartOfStringDemo set WebsiteURL=REPLACE(WebsiteURL,'www.mysqlQuestion.com','www.mysql.com'); Query OK, 1 row affected (0.20 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check the table record once again − mysql> select * from replacePartOfStringDemo; This will produce the following output − +---------------+ | WebsiteURL | +---------------+ | www.mysql.com | +---------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "To replace part of string in MySQL table column, you can use REPLACE(). Following is the syntax −" }, { "code": null, "e": 1258, "s": 1160, "text": "update yourTableName set yourColumnName = REPLACE(yourColumnName ,'yourOldValue','yourNewValue');" }, { "code": null, "e": 1288, "s": 1258, "text": "Let us first create a table −" }, { "code": null, "e": 1416, "s": 1288, "text": "mysql> create table replacePartOfStringDemo\n -> (\n -> WebsiteURL varchar(100)\n -> );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1493, "s": 1416, "text": "Following is the query to insert records in the table using insert command −" }, { "code": null, "e": 1617, "s": 1493, "text": "mysql> insert into replacePartOfStringDemo(WebsiteURL) values('www.mysqlQuestion.com');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1703, "s": 1617, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1749, "s": 1703, "text": "mysql> select * from replacePartOfStringDemo;" }, { "code": null, "e": 1790, "s": 1749, "text": "This will produce the following output −" }, { "code": null, "e": 1944, "s": 1790, "text": "+-----------------------+\n| WebsiteURL |\n+-----------------------+\n| www.mysqlQuestion.com |\n+-----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2052, "s": 1944, "text": "Let us now replace part of a string in MySQL table column. Here, “mysqlQuestion“ is replaced with “mysql” −" }, { "code": null, "e": 2241, "s": 2052, "text": "mysql> update replacePartOfStringDemo set\nWebsiteURL=REPLACE(WebsiteURL,'www.mysqlQuestion.com','www.mysql.com');\nQuery OK, 1 row affected (0.20 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2284, "s": 2241, "text": "Let us check the table record once again −" }, { "code": null, "e": 2330, "s": 2284, "text": "mysql> select * from replacePartOfStringDemo;" }, { "code": null, "e": 2371, "s": 2330, "text": "This will produce the following output −" }, { "code": null, "e": 2485, "s": 2371, "text": "+---------------+\n| WebsiteURL |\n+---------------+\n| www.mysql.com |\n+---------------+\n1 row in set (0.00 sec)" } ]