title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Different ways to access HTML elements using JavaScript - GeeksforGeeks
|
06 Dec, 2021
Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structure of the web page.
From the DOM, users can access HTML elements in five different ways in JavaScript.
Get HTML element by Id
Get HTML element by className
Get HTML element by Name
Get HTML element by tagName
Get HTML element by CSS Selector
At below, users can see the demonstration of the above methods with the sample code.
Get HTML element by Id: Generally, most developers use unique ids in the whole HTML document. The user has to add the id to the particular HTML element before accessing the HTML element with the id. Users can use getElementById() method to access HTML element using the id. If any element doesn’t exist with the passed id into the getElementById method, it returns the null value.
Syntax:
document.getElementById(element_ID);
Parameter: It takes the id of the element which the user wants to access.
Return value: It returns the object with the particular id. If the element with the particular id doesn’t found, it returns the NULL value.
Example: This example demonstrates the use of the getElementsById method. Also, it prints the inner HTML of a returned object into the console of the browser. Users can open the console into the chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html><html> <head> <title>DOM getElementById() Method</title></head> <body> <!-- Heading element with GeeksforGeeks id--> <h1 id="Geeksforgeeks"> GeeksforGeeks </h1> <p>DOM getElementById() Method</p> <script> // Accessing the element by getElementById method var temp = document.getElementById("Geeksforgeeks"); console.log(temp); console.log(temp.innerHTML); </script></body> </html>
Output:
Get HTML element by className: In javascript, getElementsByClassName() method is useful to access the HTML elements using the className. The developers can use single className multiple times in a particular HTML document. When users try to access an element using the className, it returns the collection of all objects that include a particular class.
Syntax:
document.getElementsByClassName(element_classnames);
Parameter: It takes the multiple class names of the element which the user wants to access.
Return value: It returns the collection of objects that have a particular class name. Users can get every element from the collection object using the index that starts from 0.
Example 1: This example demonstrates the use of the getElementsByClassName() method. It prints every element of the returned collection object into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html><html> <head> <title>DOM getElementsByClassName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks class name --> <h1 class="GeeksforGeeks">GeeksforGeeks sample 1</h1> <h1 class="GeeksforGeeks">GeeksforGeeks sample 2</h1> <h1 class="GeeksforGeeks">GeeksforGeeks sample 3</h1> <p>DOM getElementsByclassName() Method</p> <script> // Accessing the element by getElementsByclassName method var temp = document.getElementsByClassName("GeeksforGeeks"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>
Output:
Example 2: If a particular element contains more than one class, users can access it by passing space-separated names of the classes as a parameter of the method. Users can open the console into the chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks class name --> <h1 class="GeeksforGeeks geeks">GeeksforGeeks sample 1</h1> <h1 class="GeeksforGeeks">GeeksforGeeks sample 2</h1> <h1 class="GeeksforGeeks">GeeksforGeeks sample 3</h1> <p>DOM getElementsByclassName() Method</p> <script> // Accessing the element by getElementsByclassName // method with multiple class var temp = document.getElementsByClassName( "GeeksforGeeks geeks"); console.log(temp[0]); </script></body> </html>
Output:
Get HTML element by Name: In javascript, getElementsByName() method is useful to access the HTML elements using the name. Here, the name suggests the name attribute of the HTML element. This method returns the collection of HTML elements that includes the particular name. Users can get the length of the collection using the build-in length method.
Syntax:
document.getElementsByName(element_name);
Parameter: It takes the name of the element which the user wants to access.
Return value: It returns the collection of elements that have a particular name.
Example: This example demonstrates the use of the getElementsByName method. It prints every element with a particular name into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html><html> <head> <title>DOM getElementByName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks name --> <h1 name="GeeksforGeeks">GeeksforGeeks sample 1</h1> <h1 name="GeeksforGeeks">GeeksforGeeks sample 2</h1> <h1 name="GeeksforGeeks">GeeksforGeeks sample 3</h1> <p>DOM getElementsByName() Method</p> <script> // Accessing the element by getElementsByName method var temp = document.getElementsByName("GeeksforGeeks"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>
Output:
Get HTML elements by TagName: In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.
Syntax:
document.getElementsByTagName(Tag_name);
Parameter: It takes a single parameter which is the tag name.
Return value: It returns the collection of elements that includes the tag which passed as a parameter.
Example: This example demonstrates the use of the getElementsByTagName method. It prints every element with a particular tag into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I.
HTML
<!DOCTYPE html><html> <head> <title>DOM getElementByTagName() Method</title></head> <body> <!-- Multiple html element with h1 tag --> <h1>GeeksforGeeks sample 1</h1> <h1>GeeksforGeeks sample 2</h1> <h1>GeeksforGeeks sample 3</h1> <p>DOM getElementsByTagName() Method</p> <script> // Accessing the element by // getElementsByTagName method var temp = document.getElementsByTagName("h1"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>
Output:
Get HTML elements by CSS Selector: Users can select the HTML elements using the different CSS selectors such as class, id, and tag name at a single time. HTML elements can be retrieved using CSS selectors in two ways. The querySelector() method returns the first element that matches the particular CSS selector. The querySelectorAll() method returns all element that matches the particular CSS selector.
To use id/class as a parameter users have to add the ‘#‘/’.‘ sign before it. Users can pass directly the tag name into the above 2 methods. Users don’t need to separate CSS selectors when passing multiple CSS selectors as parameters.
Syntax:
document.querySelector(selectors);
document.querySelectorAll(selectors);
parameter: As a parameter, it accepts different CSS selectors such as class, tag name, and id.
Return value: The querySelector() method returns the first object that matches the CSS selectors, while the querySelectorAll() method returns a collection of all objects that match the CSS selectors.
Example 1: This example demonstrates the use of the querySelector method. In the below, code we have used the different CSS selectors to access the HTML elements from the DOM.
HTML
<!DOCTYPE html><html> <head> <title>DOM querySelector() Method</title></head> <body> <!-- html element with classnames and id --> <h1 class="gfg1" id="g1">GeeksforGeeks sample 1</h1> <h1 class="gfg1" id="g2">GeeksforGeeks sample 2</h1> <p class="gfg1">GeeksforGeeks sample 3</p> <script> // Accessing the element by class name // using querySelector var temp = document.querySelector(".gfg1"); console.log(temp); // Accessing the element by id using querySelector temp = document.querySelector("#g2"); console.log(temp); // Accessing the element by class name and // id using querySelector temp = document.querySelector(".gfg1#g2"); console.log(temp); // Accessing the element by tag name that // includes the particular class temp = document.querySelector("p.gfg1"); console.log(temp); </script></body> </html>
Output:
Example 2: This example demonstrates the use of the querySelectorAll method. The querySelectorAll() method returns the node list of all objects that match with the CSS selectors. Users can access all elements of the CSS node list using the index that starts from 0.
HTML
<!DOCTYPE html><html> <head> <title>DOM querySelectorAll() Method</title></head> <body> <!-- html element with classnames and id --> <h1 class="gfg1" id="g1">GeeksforGeeks sample 1</h1> <h1 class="gfg1" id="g2">GeeksforGeeks sample 2</h1> <p class="gfg1">GeeksforGeeks sample 3</p> <p class="gfg1">GeeksforGeeks sample 4</p> <script> // Accessing the element by class name, id and // tag name using querySelectorAll var temp = document.querySelectorAll("h1.gfg1#g2"); console.log(temp[0]); // Accessing the element by tag name using // querySelectorAll temp = document.querySelectorAll("p"); console.log(temp[0]); console.log(temp[1]); </script></body> </html>
Output:
JavaScript-Questions
Picked
JavaScript
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 get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 25670,
"s": 25300,
"text": "Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structure of the web page. "
},
{
"code": null,
"e": 25753,
"s": 25670,
"text": "From the DOM, users can access HTML elements in five different ways in JavaScript."
},
{
"code": null,
"e": 25776,
"s": 25753,
"text": "Get HTML element by Id"
},
{
"code": null,
"e": 25806,
"s": 25776,
"text": "Get HTML element by className"
},
{
"code": null,
"e": 25831,
"s": 25806,
"text": "Get HTML element by Name"
},
{
"code": null,
"e": 25859,
"s": 25831,
"text": "Get HTML element by tagName"
},
{
"code": null,
"e": 25892,
"s": 25859,
"text": "Get HTML element by CSS Selector"
},
{
"code": null,
"e": 25978,
"s": 25892,
"text": "At below, users can see the demonstration of the above methods with the sample code. "
},
{
"code": null,
"e": 26359,
"s": 25978,
"text": "Get HTML element by Id: Generally, most developers use unique ids in the whole HTML document. The user has to add the id to the particular HTML element before accessing the HTML element with the id. Users can use getElementById() method to access HTML element using the id. If any element doesn’t exist with the passed id into the getElementById method, it returns the null value."
},
{
"code": null,
"e": 26367,
"s": 26359,
"text": "Syntax:"
},
{
"code": null,
"e": 26404,
"s": 26367,
"text": "document.getElementById(element_ID);"
},
{
"code": null,
"e": 26478,
"s": 26404,
"text": "Parameter: It takes the id of the element which the user wants to access."
},
{
"code": null,
"e": 26618,
"s": 26478,
"text": "Return value: It returns the object with the particular id. If the element with the particular id doesn’t found, it returns the NULL value."
},
{
"code": null,
"e": 26862,
"s": 26618,
"text": "Example: This example demonstrates the use of the getElementsById method. Also, it prints the inner HTML of a returned object into the console of the browser. Users can open the console into the chrome web browser by pressing ctrl + shift + I."
},
{
"code": null,
"e": 26867,
"s": 26862,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM getElementById() Method</title></head> <body> <!-- Heading element with GeeksforGeeks id--> <h1 id=\"Geeksforgeeks\"> GeeksforGeeks </h1> <p>DOM getElementById() Method</p> <script> // Accessing the element by getElementById method var temp = document.getElementById(\"Geeksforgeeks\"); console.log(temp); console.log(temp.innerHTML); </script></body> </html>",
"e": 27352,
"s": 26867,
"text": null
},
{
"code": null,
"e": 27360,
"s": 27352,
"text": "Output:"
},
{
"code": null,
"e": 27714,
"s": 27360,
"text": "Get HTML element by className: In javascript, getElementsByClassName() method is useful to access the HTML elements using the className. The developers can use single className multiple times in a particular HTML document. When users try to access an element using the className, it returns the collection of all objects that include a particular class."
},
{
"code": null,
"e": 27722,
"s": 27714,
"text": "Syntax:"
},
{
"code": null,
"e": 27775,
"s": 27722,
"text": "document.getElementsByClassName(element_classnames);"
},
{
"code": null,
"e": 27867,
"s": 27775,
"text": "Parameter: It takes the multiple class names of the element which the user wants to access."
},
{
"code": null,
"e": 28044,
"s": 27867,
"text": "Return value: It returns the collection of objects that have a particular class name. Users can get every element from the collection object using the index that starts from 0."
},
{
"code": null,
"e": 28290,
"s": 28044,
"text": "Example 1: This example demonstrates the use of the getElementsByClassName() method. It prints every element of the returned collection object into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I."
},
{
"code": null,
"e": 28295,
"s": 28290,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM getElementsByClassName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks class name --> <h1 class=\"GeeksforGeeks\">GeeksforGeeks sample 1</h1> <h1 class=\"GeeksforGeeks\">GeeksforGeeks sample 2</h1> <h1 class=\"GeeksforGeeks\">GeeksforGeeks sample 3</h1> <p>DOM getElementsByclassName() Method</p> <script> // Accessing the element by getElementsByclassName method var temp = document.getElementsByClassName(\"GeeksforGeeks\"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>",
"e": 28956,
"s": 28295,
"text": null
},
{
"code": null,
"e": 28964,
"s": 28956,
"text": "Output:"
},
{
"code": null,
"e": 29212,
"s": 28964,
"text": "Example 2: If a particular element contains more than one class, users can access it by passing space-separated names of the classes as a parameter of the method. Users can open the console into the chrome web browser by pressing ctrl + shift + I."
},
{
"code": null,
"e": 29217,
"s": 29212,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks class name --> <h1 class=\"GeeksforGeeks geeks\">GeeksforGeeks sample 1</h1> <h1 class=\"GeeksforGeeks\">GeeksforGeeks sample 2</h1> <h1 class=\"GeeksforGeeks\">GeeksforGeeks sample 3</h1> <p>DOM getElementsByclassName() Method</p> <script> // Accessing the element by getElementsByclassName // method with multiple class var temp = document.getElementsByClassName( \"GeeksforGeeks geeks\"); console.log(temp[0]); </script></body> </html>",
"e": 29895,
"s": 29217,
"text": null
},
{
"code": null,
"e": 29903,
"s": 29895,
"text": "Output:"
},
{
"code": null,
"e": 30253,
"s": 29903,
"text": "Get HTML element by Name: In javascript, getElementsByName() method is useful to access the HTML elements using the name. Here, the name suggests the name attribute of the HTML element. This method returns the collection of HTML elements that includes the particular name. Users can get the length of the collection using the build-in length method."
},
{
"code": null,
"e": 30261,
"s": 30253,
"text": "Syntax:"
},
{
"code": null,
"e": 30303,
"s": 30261,
"text": "document.getElementsByName(element_name);"
},
{
"code": null,
"e": 30379,
"s": 30303,
"text": "Parameter: It takes the name of the element which the user wants to access."
},
{
"code": null,
"e": 30460,
"s": 30379,
"text": "Return value: It returns the collection of elements that have a particular name."
},
{
"code": null,
"e": 30687,
"s": 30460,
"text": "Example: This example demonstrates the use of the getElementsByName method. It prints every element with a particular name into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I."
},
{
"code": null,
"e": 30692,
"s": 30687,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM getElementByName() Method</title></head> <body> <!-- Multiple html element with GeeksforGeeks name --> <h1 name=\"GeeksforGeeks\">GeeksforGeeks sample 1</h1> <h1 name=\"GeeksforGeeks\">GeeksforGeeks sample 2</h1> <h1 name=\"GeeksforGeeks\">GeeksforGeeks sample 3</h1> <p>DOM getElementsByName() Method</p> <script> // Accessing the element by getElementsByName method var temp = document.getElementsByName(\"GeeksforGeeks\"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>",
"e": 31323,
"s": 30692,
"text": null
},
{
"code": null,
"e": 31331,
"s": 31323,
"text": "Output:"
},
{
"code": null,
"e": 31618,
"s": 31331,
"text": "Get HTML elements by TagName: In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element."
},
{
"code": null,
"e": 31626,
"s": 31618,
"text": "Syntax:"
},
{
"code": null,
"e": 31667,
"s": 31626,
"text": "document.getElementsByTagName(Tag_name);"
},
{
"code": null,
"e": 31729,
"s": 31667,
"text": "Parameter: It takes a single parameter which is the tag name."
},
{
"code": null,
"e": 31832,
"s": 31729,
"text": "Return value: It returns the collection of elements that includes the tag which passed as a parameter."
},
{
"code": null,
"e": 32060,
"s": 31832,
"text": "Example: This example demonstrates the use of the getElementsByTagName method. It prints every element with a particular tag into the console. Users can open the console into the chrome web browser by pressing ctrl + shift + I."
},
{
"code": null,
"e": 32065,
"s": 32060,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM getElementByTagName() Method</title></head> <body> <!-- Multiple html element with h1 tag --> <h1>GeeksforGeeks sample 1</h1> <h1>GeeksforGeeks sample 2</h1> <h1>GeeksforGeeks sample 3</h1> <p>DOM getElementsByTagName() Method</p> <script> // Accessing the element by // getElementsByTagName method var temp = document.getElementsByTagName(\"h1\"); console.log(temp[0]); console.log(temp[1]); console.log(temp[2]); </script></body> </html>",
"e": 32633,
"s": 32065,
"text": null
},
{
"code": null,
"e": 32641,
"s": 32633,
"text": "Output:"
},
{
"code": null,
"e": 33047,
"s": 32641,
"text": "Get HTML elements by CSS Selector: Users can select the HTML elements using the different CSS selectors such as class, id, and tag name at a single time. HTML elements can be retrieved using CSS selectors in two ways. The querySelector() method returns the first element that matches the particular CSS selector. The querySelectorAll() method returns all element that matches the particular CSS selector. "
},
{
"code": null,
"e": 33281,
"s": 33047,
"text": "To use id/class as a parameter users have to add the ‘#‘/’.‘ sign before it. Users can pass directly the tag name into the above 2 methods. Users don’t need to separate CSS selectors when passing multiple CSS selectors as parameters."
},
{
"code": null,
"e": 33289,
"s": 33281,
"text": "Syntax:"
},
{
"code": null,
"e": 33362,
"s": 33289,
"text": "document.querySelector(selectors);\ndocument.querySelectorAll(selectors);"
},
{
"code": null,
"e": 33457,
"s": 33362,
"text": "parameter: As a parameter, it accepts different CSS selectors such as class, tag name, and id."
},
{
"code": null,
"e": 33657,
"s": 33457,
"text": "Return value: The querySelector() method returns the first object that matches the CSS selectors, while the querySelectorAll() method returns a collection of all objects that match the CSS selectors."
},
{
"code": null,
"e": 33833,
"s": 33657,
"text": "Example 1: This example demonstrates the use of the querySelector method. In the below, code we have used the different CSS selectors to access the HTML elements from the DOM."
},
{
"code": null,
"e": 33838,
"s": 33833,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM querySelector() Method</title></head> <body> <!-- html element with classnames and id --> <h1 class=\"gfg1\" id=\"g1\">GeeksforGeeks sample 1</h1> <h1 class=\"gfg1\" id=\"g2\">GeeksforGeeks sample 2</h1> <p class=\"gfg1\">GeeksforGeeks sample 3</p> <script> // Accessing the element by class name // using querySelector var temp = document.querySelector(\".gfg1\"); console.log(temp); // Accessing the element by id using querySelector temp = document.querySelector(\"#g2\"); console.log(temp); // Accessing the element by class name and // id using querySelector temp = document.querySelector(\".gfg1#g2\"); console.log(temp); // Accessing the element by tag name that // includes the particular class temp = document.querySelector(\"p.gfg1\"); console.log(temp); </script></body> </html>",
"e": 34794,
"s": 33838,
"text": null
},
{
"code": null,
"e": 34802,
"s": 34794,
"text": "Output:"
},
{
"code": null,
"e": 35069,
"s": 34802,
"text": "Example 2: This example demonstrates the use of the querySelectorAll method. The querySelectorAll() method returns the node list of all objects that match with the CSS selectors. Users can access all elements of the CSS node list using the index that starts from 0. "
},
{
"code": null,
"e": 35074,
"s": 35069,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM querySelectorAll() Method</title></head> <body> <!-- html element with classnames and id --> <h1 class=\"gfg1\" id=\"g1\">GeeksforGeeks sample 1</h1> <h1 class=\"gfg1\" id=\"g2\">GeeksforGeeks sample 2</h1> <p class=\"gfg1\">GeeksforGeeks sample 3</p> <p class=\"gfg1\">GeeksforGeeks sample 4</p> <script> // Accessing the element by class name, id and // tag name using querySelectorAll var temp = document.querySelectorAll(\"h1.gfg1#g2\"); console.log(temp[0]); // Accessing the element by tag name using // querySelectorAll temp = document.querySelectorAll(\"p\"); console.log(temp[0]); console.log(temp[1]); </script></body> </html>",
"e": 35842,
"s": 35074,
"text": null
},
{
"code": null,
"e": 35850,
"s": 35842,
"text": "Output:"
},
{
"code": null,
"e": 35871,
"s": 35850,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 35878,
"s": 35871,
"text": "Picked"
},
{
"code": null,
"e": 35889,
"s": 35878,
"text": "JavaScript"
},
{
"code": null,
"e": 35906,
"s": 35889,
"text": "Web Technologies"
},
{
"code": null,
"e": 36004,
"s": 35906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36013,
"s": 36004,
"text": "Comments"
},
{
"code": null,
"e": 36026,
"s": 36013,
"text": "Old Comments"
},
{
"code": null,
"e": 36087,
"s": 36026,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 36128,
"s": 36087,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 36182,
"s": 36128,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 36244,
"s": 36182,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 36301,
"s": 36244,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 36343,
"s": 36301,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 36376,
"s": 36343,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36419,
"s": 36376,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 36481,
"s": 36419,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Dart Programming - Lists
|
A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists.
The logical representation of a list in Dart is given below −
test_list − is the identifier that references the collection.
test_list − is the identifier that references the collection.
The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements.
The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements.
Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript.
Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript.
Lists can be classified as −
Fixed Length List
Growable List
Let us now discuss these two types of lists in detail.
A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below −
Step 1 − Declaring a list
The syntax for declaring a fixed length list is given below −
var list_name = new List(initial_size)
The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception.
Step 2 − Initializing a list
The syntax for initializing a list is as given below −
lst_name[index] = value;
void main() {
var lst = new List(3);
lst[0] = 12;
lst[1] = 13;
lst[2] = 11;
print(lst);
}
It will produce the following output −
[12, 13, 11]
A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below −
Step 1 − Declaring a List
var list_name = [val1,val2,val3]
--- creates a list containing the specified values
OR
var list_name = new List()
--- creates a list of size zero
Step 2 − Initializing a List
The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below −
list_name[index] = value;
The following example shows how to create a list of 3 elements.
void main() {
var num_list = [1,2,3];
print(num_list);
}
It will produce the following output −
[1, 2, 3]
The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list.
void main() {
var lst = new List();
lst.add(12);
lst.add(13);
print(lst);
}
It will produce the following output −
[12, 13]
The following table lists some commonly used properties of the List class in the dart:core library.
Returns the first element in the list.
Returns true if the collection has no elements.
Returns true if the collection has at least one element.
Returns the size of the list.
Returns the last element in the list.
Returns an iterable object containing the lists values in the reverse order.
Checks if the list has only one element and returns it.
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2778,
"s": 2525,
"text": "A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists."
},
{
"code": null,
"e": 2840,
"s": 2778,
"text": "The logical representation of a list in Dart is given below −"
},
{
"code": null,
"e": 2902,
"s": 2840,
"text": "test_list − is the identifier that references the collection."
},
{
"code": null,
"e": 2964,
"s": 2902,
"text": "test_list − is the identifier that references the collection."
},
{
"code": null,
"e": 3077,
"s": 2964,
"text": "The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements."
},
{
"code": null,
"e": 3190,
"s": 3077,
"text": "The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements."
},
{
"code": null,
"e": 3416,
"s": 3190,
"text": "Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript."
},
{
"code": null,
"e": 3642,
"s": 3416,
"text": "Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript."
},
{
"code": null,
"e": 3671,
"s": 3642,
"text": "Lists can be classified as −"
},
{
"code": null,
"e": 3689,
"s": 3671,
"text": "Fixed Length List"
},
{
"code": null,
"e": 3703,
"s": 3689,
"text": "Growable List"
},
{
"code": null,
"e": 3758,
"s": 3703,
"text": "Let us now discuss these two types of lists in detail."
},
{
"code": null,
"e": 3877,
"s": 3758,
"text": "A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below −"
},
{
"code": null,
"e": 3904,
"s": 3877,
"text": "Step 1 − Declaring a list"
},
{
"code": null,
"e": 3966,
"s": 3904,
"text": "The syntax for declaring a fixed length list is given below −"
},
{
"code": null,
"e": 4006,
"s": 3966,
"text": "var list_name = new List(initial_size)\n"
},
{
"code": null,
"e": 4164,
"s": 4006,
"text": "The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception."
},
{
"code": null,
"e": 4193,
"s": 4164,
"text": "Step 2 − Initializing a list"
},
{
"code": null,
"e": 4248,
"s": 4193,
"text": "The syntax for initializing a list is as given below −"
},
{
"code": null,
"e": 4274,
"s": 4248,
"text": "lst_name[index] = value;\n"
},
{
"code": null,
"e": 4385,
"s": 4274,
"text": "void main() { \n var lst = new List(3); \n lst[0] = 12; \n lst[1] = 13; \n lst[2] = 11; \n print(lst); \n}"
},
{
"code": null,
"e": 4424,
"s": 4385,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4438,
"s": 4424,
"text": "[12, 13, 11]\n"
},
{
"code": null,
"e": 4565,
"s": 4438,
"text": "A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below −"
},
{
"code": null,
"e": 4591,
"s": 4565,
"text": "Step 1 − Declaring a List"
},
{
"code": null,
"e": 4747,
"s": 4591,
"text": "var list_name = [val1,val2,val3] \n--- creates a list containing the specified values \nOR \nvar list_name = new List() \n--- creates a list of size zero \n"
},
{
"code": null,
"e": 4776,
"s": 4747,
"text": "Step 2 − Initializing a List"
},
{
"code": null,
"e": 4925,
"s": 4776,
"text": "The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below −"
},
{
"code": null,
"e": 4952,
"s": 4925,
"text": "list_name[index] = value;\n"
},
{
"code": null,
"e": 5016,
"s": 4952,
"text": "The following example shows how to create a list of 3 elements."
},
{
"code": null,
"e": 5082,
"s": 5016,
"text": "void main() { \n var num_list = [1,2,3]; \n print(num_list); \n}"
},
{
"code": null,
"e": 5121,
"s": 5082,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5132,
"s": 5121,
"text": "[1, 2, 3]\n"
},
{
"code": null,
"e": 5303,
"s": 5132,
"text": "The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list."
},
{
"code": null,
"e": 5397,
"s": 5303,
"text": "void main() { \n var lst = new List(); \n lst.add(12); \n lst.add(13); \n print(lst); \n} "
},
{
"code": null,
"e": 5436,
"s": 5397,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5447,
"s": 5436,
"text": "[12, 13] \n"
},
{
"code": null,
"e": 5547,
"s": 5447,
"text": "The following table lists some commonly used properties of the List class in the dart:core library."
},
{
"code": null,
"e": 5586,
"s": 5547,
"text": "Returns the first element in the list."
},
{
"code": null,
"e": 5634,
"s": 5586,
"text": "Returns true if the collection has no elements."
},
{
"code": null,
"e": 5691,
"s": 5634,
"text": "Returns true if the collection has at least one element."
},
{
"code": null,
"e": 5721,
"s": 5691,
"text": "Returns the size of the list."
},
{
"code": null,
"e": 5759,
"s": 5721,
"text": "Returns the last element in the list."
},
{
"code": null,
"e": 5836,
"s": 5759,
"text": "Returns an iterable object containing the lists values in the reverse order."
},
{
"code": null,
"e": 5892,
"s": 5836,
"text": "Checks if the list has only one element and returns it."
},
{
"code": null,
"e": 5927,
"s": 5892,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5947,
"s": 5927,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 5980,
"s": 5947,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6000,
"s": 5980,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 6033,
"s": 6000,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6050,
"s": 6033,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6085,
"s": 6050,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6102,
"s": 6085,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6137,
"s": 6102,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6157,
"s": 6137,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6190,
"s": 6157,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6210,
"s": 6190,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6217,
"s": 6210,
"text": " Print"
},
{
"code": null,
"e": 6228,
"s": 6217,
"text": " Add Notes"
}
] |
Number of Submatrices That Sum to Target in C++
|
Suppose we have a matrix, and a target value, we have to find the number of non-empty
submatrices that sum is same as target. Here a submatrix [(x1, y1), (x2, y2)] is the set of all cells matrix[x][y] with x in range x1 and x2 and y in range y1 and y2. Two submatrices [(x1, y1), (x2, y2)] and [(x1', y1'), (x2', y2')] are different if they have some coordinate that is different: like, if x1 is not same as x1'.
So, if the input is like
and target = 0, then the output will be 4, this is because four 1x1 submatrices that only contain 0.
To solve this, we will follow these steps −
ans := 0
ans := 0
col := number of columns
col := number of columns
row := number of rows
row := number of rows
for initialize i := 0, when i < row, update (increase i by 1), do −for initialize j := 1, when j < col, update (increase j by 1), do −matrix[i, j] := matrix[i, j] + matrix[i, j - 1]
for initialize i := 0, when i < row, update (increase i by 1), do −
for initialize j := 1, when j < col, update (increase j by 1), do −matrix[i, j] := matrix[i, j] + matrix[i, j - 1]
for initialize j := 1, when j < col, update (increase j by 1), do −
matrix[i, j] := matrix[i, j] + matrix[i, j - 1]
matrix[i, j] := matrix[i, j] + matrix[i, j - 1]
Define one map m
Define one map m
for initialize i := 0, when i < col, update (increase i by 1), do −for initialize j := i, when j < col, update (increase j by 1), do −clear the map mm[0] := 1sum := 0for initialize k := 0, when k < row, update (increase k by 1), do −current := matrix[k, j]if i - 1 >= 0, then −current := current - matrix[k, i - 1]sum := sum + currentans := ans + m[target - sum]increase m[-sum] by 1
for initialize i := 0, when i < col, update (increase i by 1), do −
for initialize j := i, when j < col, update (increase j by 1), do −clear the map mm[0] := 1sum := 0
for initialize j := i, when j < col, update (increase j by 1), do −
clear the map m
clear the map m
m[0] := 1
m[0] := 1
sum := 0
sum := 0
for initialize k := 0, when k < row, update (increase k by 1), do −current := matrix[k, j]if i - 1 >= 0, then −current := current - matrix[k, i - 1]sum := sum + currentans := ans + m[target - sum]increase m[-sum] by 1
for initialize k := 0, when k < row, update (increase k by 1), do −
current := matrix[k, j]
current := matrix[k, j]
if i - 1 >= 0, then −current := current - matrix[k, i - 1]
if i - 1 >= 0, then −
current := current - matrix[k, i - 1]
current := current - matrix[k, i - 1]
sum := sum + current
sum := sum + current
ans := ans + m[target - sum]
ans := ans + m[target - sum]
increase m[-sum] by 1
increase m[-sum] by 1
return ans
return ans
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int
target) {
int ans = 0;
int col = matrix[0].size();
int row = matrix.size();
for(int i = 0; i < row; i++){
for(int j = 1; j < col; j++){
matrix[i][j] += matrix[i][j - 1];
}
}
unordered_map <int, int> m;
for(int i = 0; i < col; i++){
for(int j = i; j < col; j++){
m.clear();
m[0] = 1;
int sum = 0;
for(int k = 0; k < row; k++){
int current = matrix[k][j];
if(i - 1 >= 0)current -= matrix[k][i - 1];
sum += current;
ans += m[target - sum];
m[-sum]++;
}
}
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{0,1,0},{1,1,1},{0,1,0}};
cout << (ob.numSubmatrixSumTarget(v, 0));
}
{{0,1,0},{1,1,1},{0,1,0}}, 0
4
|
[
{
"code": null,
"e": 1475,
"s": 1062,
"text": "Suppose we have a matrix, and a target value, we have to find the number of non-empty\nsubmatrices that sum is same as target. Here a submatrix [(x1, y1), (x2, y2)] is the set of all cells matrix[x][y] with x in range x1 and x2 and y in range y1 and y2. Two submatrices [(x1, y1), (x2, y2)] and [(x1', y1'), (x2', y2')] are different if they have some coordinate that is different: like, if x1 is not same as x1'."
},
{
"code": null,
"e": 1500,
"s": 1475,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1601,
"s": 1500,
"text": "and target = 0, then the output will be 4, this is because four 1x1 submatrices that only contain 0."
},
{
"code": null,
"e": 1645,
"s": 1601,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1654,
"s": 1645,
"text": "ans := 0"
},
{
"code": null,
"e": 1663,
"s": 1654,
"text": "ans := 0"
},
{
"code": null,
"e": 1688,
"s": 1663,
"text": "col := number of columns"
},
{
"code": null,
"e": 1713,
"s": 1688,
"text": "col := number of columns"
},
{
"code": null,
"e": 1735,
"s": 1713,
"text": "row := number of rows"
},
{
"code": null,
"e": 1757,
"s": 1735,
"text": "row := number of rows"
},
{
"code": null,
"e": 1939,
"s": 1757,
"text": "for initialize i := 0, when i < row, update (increase i by 1), do −for initialize j := 1, when j < col, update (increase j by 1), do −matrix[i, j] := matrix[i, j] + matrix[i, j - 1]"
},
{
"code": null,
"e": 2007,
"s": 1939,
"text": "for initialize i := 0, when i < row, update (increase i by 1), do −"
},
{
"code": null,
"e": 2122,
"s": 2007,
"text": "for initialize j := 1, when j < col, update (increase j by 1), do −matrix[i, j] := matrix[i, j] + matrix[i, j - 1]"
},
{
"code": null,
"e": 2190,
"s": 2122,
"text": "for initialize j := 1, when j < col, update (increase j by 1), do −"
},
{
"code": null,
"e": 2238,
"s": 2190,
"text": "matrix[i, j] := matrix[i, j] + matrix[i, j - 1]"
},
{
"code": null,
"e": 2286,
"s": 2238,
"text": "matrix[i, j] := matrix[i, j] + matrix[i, j - 1]"
},
{
"code": null,
"e": 2303,
"s": 2286,
"text": "Define one map m"
},
{
"code": null,
"e": 2320,
"s": 2303,
"text": "Define one map m"
},
{
"code": null,
"e": 2704,
"s": 2320,
"text": "for initialize i := 0, when i < col, update (increase i by 1), do −for initialize j := i, when j < col, update (increase j by 1), do −clear the map mm[0] := 1sum := 0for initialize k := 0, when k < row, update (increase k by 1), do −current := matrix[k, j]if i - 1 >= 0, then −current := current - matrix[k, i - 1]sum := sum + currentans := ans + m[target - sum]increase m[-sum] by 1"
},
{
"code": null,
"e": 2772,
"s": 2704,
"text": "for initialize i := 0, when i < col, update (increase i by 1), do −"
},
{
"code": null,
"e": 2872,
"s": 2772,
"text": "for initialize j := i, when j < col, update (increase j by 1), do −clear the map mm[0] := 1sum := 0"
},
{
"code": null,
"e": 2940,
"s": 2872,
"text": "for initialize j := i, when j < col, update (increase j by 1), do −"
},
{
"code": null,
"e": 2956,
"s": 2940,
"text": "clear the map m"
},
{
"code": null,
"e": 2972,
"s": 2956,
"text": "clear the map m"
},
{
"code": null,
"e": 2982,
"s": 2972,
"text": "m[0] := 1"
},
{
"code": null,
"e": 2992,
"s": 2982,
"text": "m[0] := 1"
},
{
"code": null,
"e": 3001,
"s": 2992,
"text": "sum := 0"
},
{
"code": null,
"e": 3010,
"s": 3001,
"text": "sum := 0"
},
{
"code": null,
"e": 3228,
"s": 3010,
"text": "for initialize k := 0, when k < row, update (increase k by 1), do −current := matrix[k, j]if i - 1 >= 0, then −current := current - matrix[k, i - 1]sum := sum + currentans := ans + m[target - sum]increase m[-sum] by 1"
},
{
"code": null,
"e": 3296,
"s": 3228,
"text": "for initialize k := 0, when k < row, update (increase k by 1), do −"
},
{
"code": null,
"e": 3320,
"s": 3296,
"text": "current := matrix[k, j]"
},
{
"code": null,
"e": 3344,
"s": 3320,
"text": "current := matrix[k, j]"
},
{
"code": null,
"e": 3403,
"s": 3344,
"text": "if i - 1 >= 0, then −current := current - matrix[k, i - 1]"
},
{
"code": null,
"e": 3425,
"s": 3403,
"text": "if i - 1 >= 0, then −"
},
{
"code": null,
"e": 3463,
"s": 3425,
"text": "current := current - matrix[k, i - 1]"
},
{
"code": null,
"e": 3501,
"s": 3463,
"text": "current := current - matrix[k, i - 1]"
},
{
"code": null,
"e": 3522,
"s": 3501,
"text": "sum := sum + current"
},
{
"code": null,
"e": 3543,
"s": 3522,
"text": "sum := sum + current"
},
{
"code": null,
"e": 3572,
"s": 3543,
"text": "ans := ans + m[target - sum]"
},
{
"code": null,
"e": 3601,
"s": 3572,
"text": "ans := ans + m[target - sum]"
},
{
"code": null,
"e": 3623,
"s": 3601,
"text": "increase m[-sum] by 1"
},
{
"code": null,
"e": 3645,
"s": 3623,
"text": "increase m[-sum] by 1"
},
{
"code": null,
"e": 3656,
"s": 3645,
"text": "return ans"
},
{
"code": null,
"e": 3667,
"s": 3656,
"text": "return ans"
},
{
"code": null,
"e": 3737,
"s": 3667,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3748,
"s": 3737,
"text": " Live Demo"
},
{
"code": null,
"e": 4723,
"s": 3748,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int\n target) {\n int ans = 0;\n int col = matrix[0].size();\n int row = matrix.size();\n for(int i = 0; i < row; i++){\n for(int j = 1; j < col; j++){\n matrix[i][j] += matrix[i][j - 1];\n }\n }\n unordered_map <int, int> m;\n for(int i = 0; i < col; i++){\n for(int j = i; j < col; j++){\n m.clear();\n m[0] = 1;\n int sum = 0;\n for(int k = 0; k < row; k++){\n int current = matrix[k][j];\n if(i - 1 >= 0)current -= matrix[k][i - 1];\n sum += current;\n ans += m[target - sum];\n m[-sum]++;\n }\n }\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{0,1,0},{1,1,1},{0,1,0}};\n cout << (ob.numSubmatrixSumTarget(v, 0));\n}"
},
{
"code": null,
"e": 4752,
"s": 4723,
"text": "{{0,1,0},{1,1,1},{0,1,0}}, 0"
},
{
"code": null,
"e": 4754,
"s": 4752,
"text": "4"
}
] |
Introduction to Tailwind CSS - GeeksforGeeks
|
03 Jul, 2021
Tailwind CSS can be used to make websites in the fastest and the easiest way.
Tailwind CSS is basically a utility-first CSS framework for rapidly building custom user interfaces. It is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override. The beauty of this thing called tailwind is it doesn’t impose design specification or how your site should look like, you simply bring tiny components together to construct a user interface that is unique. What Tailwind simply does is take a ‘raw’ CSS file, processes this CSS file over a configuration file, and produces an output.Why Tailwind CSS?
Faster UI building process
It is a utility-first CSS framework which means we can use utility classes to build custom designs without writing CSS as in traditional approach.
Advantages of Tailwind CSS:
No more silly names for CSS classes and Id’s.
Minimum lines of Code in CSS file.
We can customize the designs to make the components.
Makes the website responsive.
Makes the changes in the desired manner. CSS is global in nature and if make changes in the file the property is changed in all the HTML files linked to it. But with the help of Tailwind CSS we can use utility classes and make local changes.
Installation: Method 1: Install Tailwind via npm
Step 1:npm init -y
Step 2:npm install tailwindcss
Step 3:Use the @tailwind directive to inject Tailwind’s base, components, and utilities styles into your CSS file. @tailwind base; @tailwind components; @tailwind utilities;
Step 4:npx tailwindcss init This is used to create a config file to customize the designs. It is an optional step.
Step 5:npx tailwindcss build styles.css -o output.css This command is used to compile style.css is the file which has to be compiled and output.css is the file on which it has to be compiled.If the file output.css is not created earlier then it will automatically created.
Method 2: Using Tailwind via CDN
html
<!-- add it to the head section of the html file --><link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
But there are some limitations when CDN is used. Some of them are:
Customize Tailwind’s default theme can’t be used
Directives like @apply, @variants, etc can’t be used
Can’t install third-party plugins
Example:
html
<!-- Write HTML code here --><!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Tailwind CSS</title> <link rel="stylesheet" href="./style.css" /> </head> <body> <!-- font size --> <h1 class="text-lg">Large font size</h1> <!-- font weight --> <h1 class="font-bold">Bold fond weight</h1> <!-- Typography --> <h1 class="tracking-widest">Spacing between words</h1> <!-- Transform --> <h1 class="uppercase">Uppercase word</h1> <!-- line height align color background width padding margin border opacity shadow--> <div class="leading-9 text-right text-red-700 bg-red-500 w-1/2 h-1/3 p-5 my-10 border-t-2 border-solid border-green-500 opacity-40 shadow-2xl"> <p>GeeksforGeeks</p> </div> <!-- focus pseudo class --> <input class="border focus:border-red-500 focus:outline-none p-5 m-5 placeholder-red-500" type="text" name="" value="" placeholder="name" /> <!-- layout --> <div class="md:flex md:flex-wrap m-5"> <div class="bg-blue-500 p-5 md:w-1/3 md:bg-pink-600"> GeeksforGeeks </div> <div class="bg-teal-500 p-5 md:w-1/3"> GeeksforGeeks </div> <div class="bg-yellow-500 p-5 md:w-1/3"> GeeksforGeeks </div> </div> </body></html>
Output:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ysachin2314
CSS-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 36166,
"s": 36138,
"text": "\n03 Jul, 2021"
},
{
"code": null,
"e": 36244,
"s": 36166,
"text": "Tailwind CSS can be used to make websites in the fastest and the easiest way."
},
{
"code": null,
"e": 36895,
"s": 36244,
"text": "Tailwind CSS is basically a utility-first CSS framework for rapidly building custom user interfaces. It is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override. The beauty of this thing called tailwind is it doesn’t impose design specification or how your site should look like, you simply bring tiny components together to construct a user interface that is unique. What Tailwind simply does is take a ‘raw’ CSS file, processes this CSS file over a configuration file, and produces an output.Why Tailwind CSS?"
},
{
"code": null,
"e": 36922,
"s": 36895,
"text": "Faster UI building process"
},
{
"code": null,
"e": 37071,
"s": 36922,
"text": "It is a utility-first CSS framework which means we can use utility classes to build custom designs without writing CSS as in traditional approach. "
},
{
"code": null,
"e": 37099,
"s": 37071,
"text": "Advantages of Tailwind CSS:"
},
{
"code": null,
"e": 37145,
"s": 37099,
"text": "No more silly names for CSS classes and Id’s."
},
{
"code": null,
"e": 37180,
"s": 37145,
"text": "Minimum lines of Code in CSS file."
},
{
"code": null,
"e": 37233,
"s": 37180,
"text": "We can customize the designs to make the components."
},
{
"code": null,
"e": 37263,
"s": 37233,
"text": "Makes the website responsive."
},
{
"code": null,
"e": 37505,
"s": 37263,
"text": "Makes the changes in the desired manner. CSS is global in nature and if make changes in the file the property is changed in all the HTML files linked to it. But with the help of Tailwind CSS we can use utility classes and make local changes."
},
{
"code": null,
"e": 37554,
"s": 37505,
"text": "Installation: Method 1: Install Tailwind via npm"
},
{
"code": null,
"e": 37573,
"s": 37554,
"text": "Step 1:npm init -y"
},
{
"code": null,
"e": 37604,
"s": 37573,
"text": "Step 2:npm install tailwindcss"
},
{
"code": null,
"e": 37778,
"s": 37604,
"text": "Step 3:Use the @tailwind directive to inject Tailwind’s base, components, and utilities styles into your CSS file. @tailwind base; @tailwind components; @tailwind utilities;"
},
{
"code": null,
"e": 37893,
"s": 37778,
"text": "Step 4:npx tailwindcss init This is used to create a config file to customize the designs. It is an optional step."
},
{
"code": null,
"e": 38166,
"s": 37893,
"text": "Step 5:npx tailwindcss build styles.css -o output.css This command is used to compile style.css is the file which has to be compiled and output.css is the file on which it has to be compiled.If the file output.css is not created earlier then it will automatically created."
},
{
"code": null,
"e": 38199,
"s": 38166,
"text": "Method 2: Using Tailwind via CDN"
},
{
"code": null,
"e": 38204,
"s": 38199,
"text": "html"
},
{
"code": "<!-- add it to the head section of the html file --><link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\">",
"e": 38349,
"s": 38204,
"text": null
},
{
"code": null,
"e": 38416,
"s": 38349,
"text": "But there are some limitations when CDN is used. Some of them are:"
},
{
"code": null,
"e": 38465,
"s": 38416,
"text": "Customize Tailwind’s default theme can’t be used"
},
{
"code": null,
"e": 38518,
"s": 38465,
"text": "Directives like @apply, @variants, etc can’t be used"
},
{
"code": null,
"e": 38552,
"s": 38518,
"text": "Can’t install third-party plugins"
},
{
"code": null,
"e": 38561,
"s": 38552,
"text": "Example:"
},
{
"code": null,
"e": 38566,
"s": 38561,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Tailwind CSS</title> <link rel=\"stylesheet\" href=\"./style.css\" /> </head> <body> <!-- font size --> <h1 class=\"text-lg\">Large font size</h1> <!-- font weight --> <h1 class=\"font-bold\">Bold fond weight</h1> <!-- Typography --> <h1 class=\"tracking-widest\">Spacing between words</h1> <!-- Transform --> <h1 class=\"uppercase\">Uppercase word</h1> <!-- line height align color background width padding margin border opacity shadow--> <div class=\"leading-9 text-right text-red-700 bg-red-500 w-1/2 h-1/3 p-5 my-10 border-t-2 border-solid border-green-500 opacity-40 shadow-2xl\"> <p>GeeksforGeeks</p> </div> <!-- focus pseudo class --> <input class=\"border focus:border-red-500 focus:outline-none p-5 m-5 placeholder-red-500\" type=\"text\" name=\"\" value=\"\" placeholder=\"name\" /> <!-- layout --> <div class=\"md:flex md:flex-wrap m-5\"> <div class=\"bg-blue-500 p-5 md:w-1/3 md:bg-pink-600\"> GeeksforGeeks </div> <div class=\"bg-teal-500 p-5 md:w-1/3\"> GeeksforGeeks </div> <div class=\"bg-yellow-500 p-5 md:w-1/3\"> GeeksforGeeks </div> </div> </body></html>",
"e": 40394,
"s": 38566,
"text": null
},
{
"code": null,
"e": 40402,
"s": 40394,
"text": "Output:"
},
{
"code": null,
"e": 40421,
"s": 40402,
"text": "Supported Browser:"
},
{
"code": null,
"e": 40435,
"s": 40421,
"text": "Google Chrome"
},
{
"code": null,
"e": 40450,
"s": 40435,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 40458,
"s": 40450,
"text": "Firefox"
},
{
"code": null,
"e": 40465,
"s": 40458,
"text": "Safari"
},
{
"code": null,
"e": 40602,
"s": 40465,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 40614,
"s": 40602,
"text": "ysachin2314"
},
{
"code": null,
"e": 40623,
"s": 40614,
"text": "CSS-Misc"
},
{
"code": null,
"e": 40627,
"s": 40623,
"text": "CSS"
},
{
"code": null,
"e": 40632,
"s": 40627,
"text": "HTML"
},
{
"code": null,
"e": 40649,
"s": 40632,
"text": "Web Technologies"
},
{
"code": null,
"e": 40654,
"s": 40649,
"text": "HTML"
},
{
"code": null,
"e": 40752,
"s": 40654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40761,
"s": 40752,
"text": "Comments"
},
{
"code": null,
"e": 40774,
"s": 40761,
"text": "Old Comments"
},
{
"code": null,
"e": 40836,
"s": 40774,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 40886,
"s": 40836,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 40934,
"s": 40886,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 40992,
"s": 40934,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 41042,
"s": 40992,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 41104,
"s": 41042,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41154,
"s": 41104,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 41202,
"s": 41154,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 41262,
"s": 41202,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Peewee - Using MySQL
|
As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql.
First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/.
You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html ).
Next, we install pymysql module, DB-API compatible Python driver.
pip install pymysql
The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP.
If you choose to create database programmatically, use following Python script −
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='')
conn.cursor().execute('CREATE DATABASE mydatabase')
conn.close()
Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it.
The MySQLDatabase object requires server credentials such as host, port, user name and password.
from peewee import *
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
class Meta:
database=db
db_table='MyUser'
db.connect()
db.create_tables([MyUser])
The Phpmyadmin web interface now shows myuser table created.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2635,
"s": 2384,
"text": "As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql."
},
{
"code": null,
"e": 2793,
"s": 2635,
"text": "First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/."
},
{
"code": null,
"e": 2932,
"s": 2793,
"text": "You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html )."
},
{
"code": null,
"e": 2998,
"s": 2932,
"text": "Next, we install pymysql module, DB-API compatible Python driver."
},
{
"code": null,
"e": 3019,
"s": 2998,
"text": "pip install pymysql\n"
},
{
"code": null,
"e": 3117,
"s": 3019,
"text": "The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP."
},
{
"code": null,
"e": 3198,
"s": 3117,
"text": "If you choose to create database programmatically, use following Python script −"
},
{
"code": null,
"e": 3346,
"s": 3198,
"text": "import pymysql\n\nconn = pymysql.connect(host='localhost', user='root', password='')\nconn.cursor().execute('CREATE DATABASE mydatabase')\nconn.close()"
},
{
"code": null,
"e": 3457,
"s": 3346,
"text": "Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it."
},
{
"code": null,
"e": 3554,
"s": 3457,
"text": "The MySQLDatabase object requires server credentials such as host, port, user name and password."
},
{
"code": null,
"e": 3881,
"s": 3554,
"text": "from peewee import *\ndb = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n class Meta:\n database=db\n db_table='MyUser'\ndb.connect()\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 3942,
"s": 3881,
"text": "The Phpmyadmin web interface now shows myuser table created."
},
{
"code": null,
"e": 3949,
"s": 3942,
"text": " Print"
},
{
"code": null,
"e": 3960,
"s": 3949,
"text": " Add Notes"
}
] |
How to set python environment variable PYTHONPATH on Linux?
|
To set the PYTHONPATH on linux to point Python to look in other directories for module and package imports, export the PYTHONPATH variable as follows:
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
In this case we are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "To set the PYTHONPATH on linux to point Python to look in other directories for module and package imports, export the PYTHONPATH variable as follows:"
},
{
"code": null,
"e": 1259,
"s": 1213,
"text": "$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo"
},
{
"code": null,
"e": 1535,
"s": 1259,
"text": "In this case we are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble."
}
] |
Kotlin Tutorial
|
Kotlin is a modern, trending programming language.
Kotlin is easy to learn, especially if you already know Java (it is
100% compatible with Java).
Kotlin is used to develop Android apps, server side apps, and much more.
Our "Try it Yourself" editor makes it easy to learn Kotlin. You can edit the
code and view the result in your browser:
fun main() {
println("Hello World")
}
Click on the "Try it Yourself" button to see how it works.
We recommend reading this tutorial, in the sequence listed in the left menu.
Insert the missing part of the code below to output "Hello World".
() {
println("Hello World")
}
Start the Exercise
Learn by taking a quiz! This quiz will give you a signal of how much you know about Kotlin.
Take the Kotlin Quiz
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All Kotlin Examples
Download Kotlin from github:
https://github.com/JetBrains/kotlin
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 51,
"s": 0,
"text": "Kotlin is a modern, trending programming language."
},
{
"code": null,
"e": 150,
"s": 51,
"text": "Kotlin is easy to learn, especially if you already know Java (it is \n 100% compatible with Java)."
},
{
"code": null,
"e": 223,
"s": 150,
"text": "Kotlin is used to develop Android apps, server side apps, and much more."
},
{
"code": null,
"e": 343,
"s": 223,
"text": "Our \"Try it Yourself\" editor makes it easy to learn Kotlin. You can edit the \ncode and view the result in your browser:"
},
{
"code": null,
"e": 383,
"s": 343,
"text": "fun main() {\n println(\"Hello World\")\n}"
},
{
"code": null,
"e": 442,
"s": 383,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 519,
"s": 442,
"text": "We recommend reading this tutorial, in the sequence listed in the left menu."
},
{
"code": null,
"e": 586,
"s": 519,
"text": "Insert the missing part of the code below to output \"Hello World\"."
},
{
"code": null,
"e": 620,
"s": 586,
"text": " () {\n println(\"Hello World\")\n}\n"
},
{
"code": null,
"e": 639,
"s": 620,
"text": "Start the Exercise"
},
{
"code": null,
"e": 731,
"s": 639,
"text": "Learn by taking a quiz! This quiz will give you a signal of how much you know about Kotlin."
},
{
"code": null,
"e": 752,
"s": 731,
"text": "Take the Kotlin Quiz"
},
{
"code": null,
"e": 840,
"s": 752,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 864,
"s": 840,
"text": "See All Kotlin Examples"
},
{
"code": null,
"e": 929,
"s": 864,
"text": "Download Kotlin from github:\nhttps://github.com/JetBrains/kotlin"
},
{
"code": null,
"e": 962,
"s": 929,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1004,
"s": 962,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1111,
"s": 1004,
"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": 1130,
"s": 1111,
"text": "[email protected]"
}
] |
time.Time.Hour() Function in Golang With Examples - GeeksforGeeks
|
19 Apr, 2020
The Time.Hour() function in Go language is used to check the hour within the day in which the stated “t” presents itself in the range [0, 23]. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Hour() int
Here, “t” is the stated time.
Return Value: It returns the hour within the day in which the stated “t” occurs.
Example 1:
// Golang program to illustrate the usage of// Time.Hour() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 36, 11, 45, 04, 0, time.UTC) // Calling Hour method hr := t.Hour() // Prints hour as specified fmt.Printf("The stated hour "+ "within the day is: %v\n", hr)}
Output:
The stated hour within the day is: 11
Example 2:
// Golang program to illustrate the usage of// Time.Hour() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 36, 29, 45, 04, 0, time.UTC) // Calling Hour method hr := t.Hour() // Prints hour as specified fmt.Printf("The stated hour"+ " within the day is: %v\n", hr)}
Output:
The stated hour within the day is: 5
Here, the stated hour is out of usual range but it is normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
|
[
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 24348,
"s": 24069,
"text": "The Time.Hour() function in Go language is used to check the hour within the day in which the stated “t” presents itself in the range [0, 23]. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 24356,
"s": 24348,
"text": "Syntax:"
},
{
"code": null,
"e": 24382,
"s": 24356,
"text": "func (t Time) Hour() int\n"
},
{
"code": null,
"e": 24412,
"s": 24382,
"text": "Here, “t” is the stated time."
},
{
"code": null,
"e": 24493,
"s": 24412,
"text": "Return Value: It returns the hour within the day in which the stated “t” occurs."
},
{
"code": null,
"e": 24504,
"s": 24493,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Hour() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 36, 11, 45, 04, 0, time.UTC) // Calling Hour method hr := t.Hour() // Prints hour as specified fmt.Printf(\"The stated hour \"+ \"within the day is: %v\\n\", hr)}",
"e": 24932,
"s": 24504,
"text": null
},
{
"code": null,
"e": 24940,
"s": 24932,
"text": "Output:"
},
{
"code": null,
"e": 24979,
"s": 24940,
"text": "The stated hour within the day is: 11\n"
},
{
"code": null,
"e": 24990,
"s": 24979,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Hour() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 36, 29, 45, 04, 0, time.UTC) // Calling Hour method hr := t.Hour() // Prints hour as specified fmt.Printf(\"The stated hour\"+ \" within the day is: %v\\n\", hr)}",
"e": 25417,
"s": 24990,
"text": null
},
{
"code": null,
"e": 25425,
"s": 25417,
"text": "Output:"
},
{
"code": null,
"e": 25463,
"s": 25425,
"text": "The stated hour within the day is: 5\n"
},
{
"code": null,
"e": 25546,
"s": 25463,
"text": "Here, the stated hour is out of usual range but it is normalized while conversion."
},
{
"code": null,
"e": 25558,
"s": 25546,
"text": "GoLang-time"
},
{
"code": null,
"e": 25570,
"s": 25558,
"text": "Go Language"
},
{
"code": null,
"e": 25668,
"s": 25570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25677,
"s": 25668,
"text": "Comments"
},
{
"code": null,
"e": 25690,
"s": 25677,
"text": "Old Comments"
},
{
"code": null,
"e": 25719,
"s": 25690,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 25743,
"s": 25719,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 25758,
"s": 25743,
"text": "Rune in Golang"
},
{
"code": null,
"e": 25792,
"s": 25758,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 25813,
"s": 25792,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 25840,
"s": 25813,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 25861,
"s": 25840,
"text": "Structures in Golang"
},
{
"code": null,
"e": 25886,
"s": 25861,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 25904,
"s": 25886,
"text": "Strings in Golang"
}
] |
Explain the MUL() function in JavaScript ? - GeeksforGeeks
|
25 Jul, 2021
The MUL function is a miniature of the multiplication function. In this function, we call the function that required an argument as a first number, and that function calls another function that required another argument and this step goes on.
The first function’s argument is x, the second function argument is y and the third is z, so the return value will be xyz.
Syntax:
function mul(x) {
return function (y) {
return function (z) {
return x * y * z;
};
};
}
Example: Below example illustrates the MUL() function in JavaScript.
Javascript
<script>function mul(x) { return function(y) { return function(z) { return x*y*z; }; }} console.log(mul(2)(3)(5));console.log(mul(2)(3)(4));</script>
Output:
30
24
javascript-functions
JavaScript-Questions
Picked
JavaScript
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 detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n25 Jul, 2021"
},
{
"code": null,
"e": 25464,
"s": 25220,
"text": "The MUL function is a miniature of the multiplication function. In this function, we call the function that required an argument as a first number, and that function calls another function that required another argument and this step goes on. "
},
{
"code": null,
"e": 25587,
"s": 25464,
"text": "The first function’s argument is x, the second function argument is y and the third is z, so the return value will be xyz."
},
{
"code": null,
"e": 25595,
"s": 25587,
"text": "Syntax:"
},
{
"code": null,
"e": 25701,
"s": 25595,
"text": "function mul(x) {\n return function (y) {\n return function (z) {\n return x * y * z;\n };\n };\n}"
},
{
"code": null,
"e": 25770,
"s": 25701,
"text": "Example: Below example illustrates the MUL() function in JavaScript."
},
{
"code": null,
"e": 25781,
"s": 25770,
"text": "Javascript"
},
{
"code": "<script>function mul(x) { return function(y) { return function(z) { return x*y*z; }; }} console.log(mul(2)(3)(5));console.log(mul(2)(3)(4));</script>",
"e": 25945,
"s": 25781,
"text": null
},
{
"code": null,
"e": 25953,
"s": 25945,
"text": "Output:"
},
{
"code": null,
"e": 25959,
"s": 25953,
"text": "30\n24"
},
{
"code": null,
"e": 25980,
"s": 25959,
"text": "javascript-functions"
},
{
"code": null,
"e": 26001,
"s": 25980,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 26008,
"s": 26001,
"text": "Picked"
},
{
"code": null,
"e": 26019,
"s": 26008,
"text": "JavaScript"
},
{
"code": null,
"e": 26036,
"s": 26019,
"text": "Web Technologies"
},
{
"code": null,
"e": 26134,
"s": 26036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26143,
"s": 26134,
"text": "Comments"
},
{
"code": null,
"e": 26156,
"s": 26143,
"text": "Old Comments"
},
{
"code": null,
"e": 26217,
"s": 26156,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26258,
"s": 26217,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26311,
"s": 26258,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 26365,
"s": 26311,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26413,
"s": 26365,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 26455,
"s": 26413,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26488,
"s": 26455,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26550,
"s": 26488,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26593,
"s": 26550,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to sort elements in the ListBox in C#? - GeeksforGeeks
|
17 Jul, 2019
In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to sort the elements present in the ListBox using Sorted Property of the ListBox. This property always sorts the string type elements in the alphabetical order and integer type elements in ascending order. The default value of this property is false. You can set this property in two different ways:
1. Design-Time: It is the easiest way to sort the elements present in the ListBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ListBox control to sort the elements of the ListBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the ListBox control programmatically with the help of given syntax:
public bool Sorted { get; set; }
Here, the value of this property is of System.Boolean type. If you want to sort the elements present in the Listbox, then set the value of this property to true. Otherwise, false. The following steps show how to set the Sorted property of the ListBox dynamically:
Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor
ListBox lstbox = new ListBox();
// Creating ListBox using ListBox class constructor
ListBox lstbox = new ListBox();
Step 2: After creating ListBox, set the Sorted property of the ListBox provided by the ListBox class.// Sorting the elements of the listbox
lstbox.Sorted = true;
// Sorting the elements of the listbox
lstbox.Sorted = true;
Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form
this.Controls.Add(lstbox);
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 WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = "Select post"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Sorted = true; lstbox.Items.Add("Intern"); lstbox.Items.Add("Software Engineer"); lstbox.Items.Add("Project Manager"); lstbox.Items.Add("HR"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}Output:Before sorting:After sorting:
// Add this ListBox to the form
this.Controls.Add(lstbox);
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 WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = "Select post"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Sorted = true; lstbox.Items.Add("Intern"); lstbox.Items.Add("Software Engineer"); lstbox.Items.Add("Project Manager"); lstbox.Items.Add("HR"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}
Output:
Before sorting:
After sorting:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 23737,
"s": 23709,
"text": "\n17 Jul, 2019"
},
{
"code": null,
"e": 24256,
"s": 23737,
"text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to sort the elements present in the ListBox using Sorted Property of the ListBox. This property always sorts the string type elements in the alphabetical order and integer type elements in ascending order. The default value of this property is false. You can set this property in two different ways:"
},
{
"code": null,
"e": 24371,
"s": 24256,
"text": "1. Design-Time: It is the easiest way to sort the elements present in the ListBox as shown in the following steps:"
},
{
"code": null,
"e": 24487,
"s": 24371,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24666,
"s": 24487,
"text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 24791,
"s": 24666,
"text": "Step 3: After drag and drop you will go to the properties of the ListBox control to sort the elements of the ListBox.Output:"
},
{
"code": null,
"e": 24799,
"s": 24791,
"text": "Output:"
},
{
"code": null,
"e": 24984,
"s": 24799,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the ListBox control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25017,
"s": 24984,
"text": "public bool Sorted { get; set; }"
},
{
"code": null,
"e": 25281,
"s": 25017,
"text": "Here, the value of this property is of System.Boolean type. If you want to sort the elements present in the Listbox, then set the value of this property to true. Otherwise, false. The following steps show how to set the Sorted property of the ListBox dynamically:"
},
{
"code": null,
"e": 25457,
"s": 25281,
"text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor\nListBox lstbox = new ListBox();\n"
},
{
"code": null,
"e": 25542,
"s": 25457,
"text": "// Creating ListBox using ListBox class constructor\nListBox lstbox = new ListBox();\n"
},
{
"code": null,
"e": 25705,
"s": 25542,
"text": "Step 2: After creating ListBox, set the Sorted property of the ListBox provided by the ListBox class.// Sorting the elements of the listbox\nlstbox.Sorted = true;\n"
},
{
"code": null,
"e": 25767,
"s": 25705,
"text": "// Sorting the elements of the listbox\nlstbox.Sorted = true;\n"
},
{
"code": null,
"e": 27015,
"s": 25767,
"text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(lstbox);\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 WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = \"Select post\"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Sorted = true; lstbox.Items.Add(\"Intern\"); lstbox.Items.Add(\"Software Engineer\"); lstbox.Items.Add(\"Project Manager\"); lstbox.Items.Add(\"HR\"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}Output:Before sorting:After sorting:"
},
{
"code": null,
"e": 27075,
"s": 27015,
"text": "// Add this ListBox to the form\nthis.Controls.Add(lstbox);\n"
},
{
"code": null,
"e": 27084,
"s": 27075,
"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 WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = \"Select post\"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Sorted = true; lstbox.Items.Add(\"Intern\"); lstbox.Items.Add(\"Software Engineer\"); lstbox.Items.Add(\"Project Manager\"); lstbox.Items.Add(\"HR\"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}",
"e": 28156,
"s": 27084,
"text": null
},
{
"code": null,
"e": 28164,
"s": 28156,
"text": "Output:"
},
{
"code": null,
"e": 28180,
"s": 28164,
"text": "Before sorting:"
},
{
"code": null,
"e": 28195,
"s": 28180,
"text": "After sorting:"
},
{
"code": null,
"e": 28198,
"s": 28195,
"text": "C#"
},
{
"code": null,
"e": 28296,
"s": 28198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28305,
"s": 28296,
"text": "Comments"
},
{
"code": null,
"e": 28318,
"s": 28305,
"text": "Old Comments"
},
{
"code": null,
"e": 28341,
"s": 28318,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28369,
"s": 28341,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28415,
"s": 28369,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28430,
"s": 28415,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28470,
"s": 28430,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28501,
"s": 28470,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28519,
"s": 28501,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28542,
"s": 28519,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28564,
"s": 28542,
"text": "C# | Class and Object"
}
] |
Find maximum xor of k elements in an array - GeeksforGeeks
|
22 Dec, 2021
Given an array arr[] of N integers and an integer K. The task is to find the maximum xor subset of size K of the given array.Examples:
Input: arr[] = {2, 5, 4, 1, 3, 7, 6, 8}, K = 3 Output: 15 We obtain 15 by selecting 4, 5, 6, 8Input: arr[] = {3, 4, 7, 7, 9}, K = 3 Output: 14
Naive approach: Iterate over all subsets of size K of the array and find maximum xor among them.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum xor for a// subset of size k from the given arrayint Max_Xor(int arr[], int n, int k){ // Initialize result int maxXor = INT_MIN; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (__builtin_popcount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if (i & (1 << j)) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = max(maxXor, cur_xor); } } return maxXor;} // Driver codeint main(){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = sizeof(arr) / sizeof(int); int k = 3; cout << Max_Xor(arr, n, k); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum xor for a// subset of size k from the given arraystatic int Max_Xor(int arr[], int n, int k){ // Initialize result int maxXor = Integer.MIN_VALUE; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (Integer.bitCount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if ((i & (1 << j)) == 0) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.max(maxXor, cur_xor); } } return maxXor;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.length; int k = 3; System.out.println(Max_Xor(arr, n, k));}} // This code is contributed by PrinciRaj1992
# Python implementation of the approach MAX = 10000MAX_ELEMENT = 50 dp =[[[-1 for i in range(MAX)] for j in range(MAX_ELEMENT)] for k in range(MAX_ELEMENT)] # Function to return the maximum xor for a# subset of size j from the given arraydef Max_Xor(arr, i, j, mask, n): if (i >= n): # If the subset is complete then return # the xor value of the selected elements if (j == 0): return mask else: return 0 # Return if already calculated for some # mask and j at the i'th index if (dp[i][j][mask] != -1): return dp[i][j][mask] # Initialize answer to 0 ans = 0 # If we can still include elements in our subset # include the i'th element if (j > 0): ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n) # Exclude the i'th element # ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)) dp[i][j][mask] = ans return ans # Driver codearr = [2, 5, 4, 1, 3, 7, 6, 8]n = len(arr)k = 3 print(Max_Xor(arr, 0, k, 0, n)) # This code is contributed by shubhamsingh10
// C# implementation of the approachusing System; class GFG{ // Function to return the maximum xor for a// subset of size k from the given arraystatic int Max_Xor(int []arr, int n, int k){ // Initialize result int maxXor = int.MinValue; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (bitCount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if ((i & (1 << j)) == 0) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.Max(maxXor, cur_xor); } } return maxXor;} static int bitCount(long x){ int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.Length; int k = 3; Console.WriteLine(Max_Xor(arr, n, k));}} // This code is contributed by Princi Singh
<script> // Javascript implementation of the approach // Function to return the maximum xor for a// subset of size k from the given arrayfunction Max_Xor(arr, n, k){ // Initialize result let maxXor = Number.MIN_VALUE; // Traverse all subsets of the array for (let i = 0; i < (1 << n); i++) { // bitCount() returns the number // of sets bits in an integer if (bitCount(i) == k) { // Initialize current xor as 0 let cur_xor = 0; for (let j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if (i & (1 << j)) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.max(maxXor, cur_xor); } } return maxXor;} function bitCount(x){ let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver code let arr = [ 2, 5, 4, 1, 3, 7, 6, 8 ]; let n = arr.length; let k = 3; document.write(Max_Xor(arr, n, k)); </script>
15
Efficient approach: The problem can be solved using dynamic programming. Create a dp table dp[i][j][mask] which stores the maximum xor possible at the ith index (with or without including it) and j denotes the number of remaining elements we can include in our subset of K elements. Mask is the xor of all the elements selected till the ith index. Note: This approach will only work for smaller arrays due to space requirements for the dp array.Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 10000#define MAX_ELEMENT 50 int dp[MAX_ELEMENT][MAX_ELEMENT][MAX]; // Function to return the maximum xor for a// subset of size j from the given arrayint Max_Xor(int arr[], int i, int j, int mask, int n){ if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i][j][mask] != -1) return dp[i][j][mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i][j][mask] = ans;} // Driver codeint main(){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = sizeof(arr) / sizeof(int); int k = 3; memset(dp, -1, sizeof(dp)); cout << Max_Xor(arr, 0, k, 0, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 10000;static int MAX_ELEMENT = 50; static int [][][] dp = new int[MAX_ELEMENT][MAX_ELEMENT][MAX]; // Function to return the maximum xor for a// subset of size j from the given arraystatic int Max_Xor(int arr[], int i, int j, int mask, int n){ if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i][j][mask] != -1) return dp[i][j][mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = Math.max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i][j][mask] = ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.length; int k = 3; for(int i = 0; i < MAX_ELEMENT; i++) { for(int j = 0; j < MAX_ELEMENT; j++) { for(int l = 0; l < MAX; l++) dp[i][j][l] = -1; } } System.out.println(Max_Xor(arr, 0, k, 0, n));}} // This code is contributed by Princi Singh
# Python implementation of the approach MAX = 10000MAX_ELEMENT = 50 dp =[[[-1 for i in range(MAX)] for j in range(MAX_ELEMENT)] for k in range(MAX_ELEMENT)] # Function to return the maximum xor for a# subset of size j from the given arraydef Max_Xor(arr, i, j, mask, n): if (i >= n): # If the subset is complete then return # the xor value of the selected elements if (j == 0): return mask else: return 0 # Return if already calculated for some # mask and j at the i'th index if (dp[i][j][mask] != -1): return dp[i][j][mask] # Initialize answer to 0 ans = 0 # If we can still include elements in our subset # include the i'th element if (j > 0): ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n) # Exclude the i'th element # ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)) dp[i][j][mask] = ans return ans # Driver code arr = [2, 5, 4, 1, 3, 7, 6, 8]n = len(arr)k = 3 print(Max_Xor(arr, 0, k, 0, n)) # This code is contributed by shubhamsingh10
// C# implementation of the approachusing System; class GFG{ static int MAX = 10000; static int MAX_ELEMENT = 50; static int [,,] dp = new int[MAX_ELEMENT, MAX_ELEMENT, MAX]; // Function to return the maximum xor for a // subset of size j from the given array static int Max_Xor(int[] arr, int i, int j, int mask, int n) { if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i,j,mask] != -1) return dp[i,j,mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = Math.Max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i,j,mask] = ans; } // Driver code public static void Main () { int[] arr = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.Length; int k = 3; for(int i = 0; i < MAX_ELEMENT; i++) { for(int j = 0; j < MAX_ELEMENT; j++) { for(int l = 0; l < MAX; l++) dp[i,j,l] = -1; } } Console.WriteLine(Max_Xor(arr, 0, k, 0, n)); }} // This code is contributed by target_2.
15
princiraj1992
princi singh
AlexPeter
SHUBHAMSINGH10
subham348
target_2
Bitwise-XOR
Arrays
Bit Magic
Competitive Programming
Mathematical
Arrays
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division
|
[
{
"code": null,
"e": 25071,
"s": 25043,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25208,
"s": 25071,
"text": "Given an array arr[] of N integers and an integer K. The task is to find the maximum xor subset of size K of the given array.Examples: "
},
{
"code": null,
"e": 25353,
"s": 25208,
"text": "Input: arr[] = {2, 5, 4, 1, 3, 7, 6, 8}, K = 3 Output: 15 We obtain 15 by selecting 4, 5, 6, 8Input: arr[] = {3, 4, 7, 7, 9}, K = 3 Output: 14 "
},
{
"code": null,
"e": 25503,
"s": 25355,
"text": "Naive approach: Iterate over all subsets of size K of the array and find maximum xor among them.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25507,
"s": 25503,
"text": "C++"
},
{
"code": null,
"e": 25512,
"s": 25507,
"text": "Java"
},
{
"code": null,
"e": 25520,
"s": 25512,
"text": "Python3"
},
{
"code": null,
"e": 25523,
"s": 25520,
"text": "C#"
},
{
"code": null,
"e": 25534,
"s": 25523,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum xor for a// subset of size k from the given arrayint Max_Xor(int arr[], int n, int k){ // Initialize result int maxXor = INT_MIN; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (__builtin_popcount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if (i & (1 << j)) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = max(maxXor, cur_xor); } } return maxXor;} // Driver codeint main(){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = sizeof(arr) / sizeof(int); int k = 3; cout << Max_Xor(arr, n, k); return 0;}",
"e": 26590,
"s": 25534,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum xor for a// subset of size k from the given arraystatic int Max_Xor(int arr[], int n, int k){ // Initialize result int maxXor = Integer.MIN_VALUE; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (Integer.bitCount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if ((i & (1 << j)) == 0) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.max(maxXor, cur_xor); } } return maxXor;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.length; int k = 3; System.out.println(Max_Xor(arr, n, k));}} // This code is contributed by PrinciRaj1992",
"e": 27738,
"s": 26590,
"text": null
},
{
"code": "# Python implementation of the approach MAX = 10000MAX_ELEMENT = 50 dp =[[[-1 for i in range(MAX)] for j in range(MAX_ELEMENT)] for k in range(MAX_ELEMENT)] # Function to return the maximum xor for a# subset of size j from the given arraydef Max_Xor(arr, i, j, mask, n): if (i >= n): # If the subset is complete then return # the xor value of the selected elements if (j == 0): return mask else: return 0 # Return if already calculated for some # mask and j at the i'th index if (dp[i][j][mask] != -1): return dp[i][j][mask] # Initialize answer to 0 ans = 0 # If we can still include elements in our subset # include the i'th element if (j > 0): ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n) # Exclude the i'th element # ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)) dp[i][j][mask] = ans return ans # Driver codearr = [2, 5, 4, 1, 3, 7, 6, 8]n = len(arr)k = 3 print(Max_Xor(arr, 0, k, 0, n)) # This code is contributed by shubhamsingh10",
"e": 28864,
"s": 27738,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum xor for a// subset of size k from the given arraystatic int Max_Xor(int []arr, int n, int k){ // Initialize result int maxXor = int.MinValue; // Traverse all subsets of the array for (int i = 0; i < (1 << n); i++) { // __builtin_popcount() returns the number // of sets bits in an integer if (bitCount(i) == k) { // Initialize current xor as 0 int cur_xor = 0; for (int j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if ((i & (1 << j)) == 0) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.Max(maxXor, cur_xor); } } return maxXor;} static int bitCount(long x){ int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.Length; int k = 3; Console.WriteLine(Max_Xor(arr, n, k));}} // This code is contributed by Princi Singh",
"e": 30132,
"s": 28864,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the maximum xor for a// subset of size k from the given arrayfunction Max_Xor(arr, n, k){ // Initialize result let maxXor = Number.MIN_VALUE; // Traverse all subsets of the array for (let i = 0; i < (1 << n); i++) { // bitCount() returns the number // of sets bits in an integer if (bitCount(i) == k) { // Initialize current xor as 0 let cur_xor = 0; for (let j = 0; j < n; j++) { // If jth bit is set in i then include // jth element in the current xor if (i & (1 << j)) cur_xor = cur_xor ^ arr[j]; } // Update maximum xor so far maxXor = Math.max(maxXor, cur_xor); } } return maxXor;} function bitCount(x){ let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Driver code let arr = [ 2, 5, 4, 1, 3, 7, 6, 8 ]; let n = arr.length; let k = 3; document.write(Max_Xor(arr, n, k)); </script>",
"e": 31252,
"s": 30132,
"text": null
},
{
"code": null,
"e": 31255,
"s": 31252,
"text": "15"
},
{
"code": null,
"e": 31755,
"s": 31257,
"text": "Efficient approach: The problem can be solved using dynamic programming. Create a dp table dp[i][j][mask] which stores the maximum xor possible at the ith index (with or without including it) and j denotes the number of remaining elements we can include in our subset of K elements. Mask is the xor of all the elements selected till the ith index. Note: This approach will only work for smaller arrays due to space requirements for the dp array.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31759,
"s": 31755,
"text": "C++"
},
{
"code": null,
"e": 31764,
"s": 31759,
"text": "Java"
},
{
"code": null,
"e": 31772,
"s": 31764,
"text": "Python3"
},
{
"code": null,
"e": 31775,
"s": 31772,
"text": "C#"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 10000#define MAX_ELEMENT 50 int dp[MAX_ELEMENT][MAX_ELEMENT][MAX]; // Function to return the maximum xor for a// subset of size j from the given arrayint Max_Xor(int arr[], int i, int j, int mask, int n){ if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i][j][mask] != -1) return dp[i][j][mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i][j][mask] = ans;} // Driver codeint main(){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = sizeof(arr) / sizeof(int); int k = 3; memset(dp, -1, sizeof(dp)); cout << Max_Xor(arr, 0, k, 0, n); return 0;}",
"e": 32980,
"s": 31775,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 10000;static int MAX_ELEMENT = 50; static int [][][] dp = new int[MAX_ELEMENT][MAX_ELEMENT][MAX]; // Function to return the maximum xor for a// subset of size j from the given arraystatic int Max_Xor(int arr[], int i, int j, int mask, int n){ if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i][j][mask] != -1) return dp[i][j][mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = Math.max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i][j][mask] = ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.length; int k = 3; for(int i = 0; i < MAX_ELEMENT; i++) { for(int j = 0; j < MAX_ELEMENT; j++) { for(int l = 0; l < MAX; l++) dp[i][j][l] = -1; } } System.out.println(Max_Xor(arr, 0, k, 0, n));}} // This code is contributed by Princi Singh",
"e": 34498,
"s": 32980,
"text": null
},
{
"code": "# Python implementation of the approach MAX = 10000MAX_ELEMENT = 50 dp =[[[-1 for i in range(MAX)] for j in range(MAX_ELEMENT)] for k in range(MAX_ELEMENT)] # Function to return the maximum xor for a# subset of size j from the given arraydef Max_Xor(arr, i, j, mask, n): if (i >= n): # If the subset is complete then return # the xor value of the selected elements if (j == 0): return mask else: return 0 # Return if already calculated for some # mask and j at the i'th index if (dp[i][j][mask] != -1): return dp[i][j][mask] # Initialize answer to 0 ans = 0 # If we can still include elements in our subset # include the i'th element if (j > 0): ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n) # Exclude the i'th element # ans store the max of both operations ans = max(ans, Max_Xor(arr, i + 1, j, mask, n)) dp[i][j][mask] = ans return ans # Driver code arr = [2, 5, 4, 1, 3, 7, 6, 8]n = len(arr)k = 3 print(Max_Xor(arr, 0, k, 0, n)) # This code is contributed by shubhamsingh10",
"e": 35620,
"s": 34498,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 10000; static int MAX_ELEMENT = 50; static int [,,] dp = new int[MAX_ELEMENT, MAX_ELEMENT, MAX]; // Function to return the maximum xor for a // subset of size j from the given array static int Max_Xor(int[] arr, int i, int j, int mask, int n) { if (i >= n) { // If the subset is complete then return // the xor value of the selected elements if (j == 0) return mask; else return 0; } // Return if already calculated for some // mask and j at the i'th index if (dp[i,j,mask] != -1) return dp[i,j,mask]; // Initialize answer to 0 int ans = 0; // If we can still include elements in our subset // include the i'th element if (j > 0) ans = Max_Xor(arr, i + 1, j - 1, mask ^ arr[i], n); // Exclude the i'th element // ans store the max of both operations ans = Math.Max(ans, Max_Xor(arr, i + 1, j, mask, n)); return dp[i,j,mask] = ans; } // Driver code public static void Main () { int[] arr = { 2, 5, 4, 1, 3, 7, 6, 8 }; int n = arr.Length; int k = 3; for(int i = 0; i < MAX_ELEMENT; i++) { for(int j = 0; j < MAX_ELEMENT; j++) { for(int l = 0; l < MAX; l++) dp[i,j,l] = -1; } } Console.WriteLine(Max_Xor(arr, 0, k, 0, n)); }} // This code is contributed by target_2.",
"e": 37095,
"s": 35620,
"text": null
},
{
"code": null,
"e": 37098,
"s": 37095,
"text": "15"
},
{
"code": null,
"e": 37114,
"s": 37100,
"text": "princiraj1992"
},
{
"code": null,
"e": 37127,
"s": 37114,
"text": "princi singh"
},
{
"code": null,
"e": 37137,
"s": 37127,
"text": "AlexPeter"
},
{
"code": null,
"e": 37152,
"s": 37137,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37162,
"s": 37152,
"text": "subham348"
},
{
"code": null,
"e": 37171,
"s": 37162,
"text": "target_2"
},
{
"code": null,
"e": 37183,
"s": 37171,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 37190,
"s": 37183,
"text": "Arrays"
},
{
"code": null,
"e": 37200,
"s": 37190,
"text": "Bit Magic"
},
{
"code": null,
"e": 37224,
"s": 37200,
"text": "Competitive Programming"
},
{
"code": null,
"e": 37237,
"s": 37224,
"text": "Mathematical"
},
{
"code": null,
"e": 37244,
"s": 37237,
"text": "Arrays"
},
{
"code": null,
"e": 37257,
"s": 37244,
"text": "Mathematical"
},
{
"code": null,
"e": 37267,
"s": 37257,
"text": "Bit Magic"
},
{
"code": null,
"e": 37365,
"s": 37267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37374,
"s": 37365,
"text": "Comments"
},
{
"code": null,
"e": 37387,
"s": 37374,
"text": "Old Comments"
},
{
"code": null,
"e": 37410,
"s": 37387,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37442,
"s": 37410,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37527,
"s": 37442,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37548,
"s": 37527,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37593,
"s": 37548,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 37620,
"s": 37593,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 37666,
"s": 37620,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 37734,
"s": 37666,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 37763,
"s": 37734,
"text": "Count set bits in an integer"
}
] |
Custom Chips using Jetpack Compose in Android - GeeksforGeeks
|
21 Nov, 2021
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.Buttonimport androidx.compose.material.MaterialThemeimport androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using // the 'background' color from the theme Surface(color = Color.White) { Column(modifier = Modifier.padding(10.dp)) { // call the function which // contains all the chips Chips() } } } } }} // Function for Custom Chip// Later we will reuse it to// create chips wherever needed// selected : Boolean - to Check// whether it is checked or not// text - To show the data@Composablefun CustomChip( selected: Boolean, text: String, modifier: Modifier = Modifier) { // define properties to the chip // such as color, shape, width Surface( color = when { selected -> MaterialTheme.colors.onSurface else -> Color.Transparent }, contentColor = when { selected -> MaterialTheme.colors.onPrimary else -> Color.LightGray }, shape = CircleShape, border = BorderStroke( width = 1.dp, color = when { selected -> MaterialTheme.colors.primary else -> Color.LightGray } ), modifier = modifier ) { // Add text to show the data that we passed Text( text = text, textAlign = TextAlign.Center, style = MaterialTheme.typography.body2, modifier = Modifier.padding(8.dp) ) }} // Function to create a Custom Image Chip with text// text - For showing data on the chip// imageId - For showing the image that we want to use// selected : Boolean - to check if it is selected or not@Composableprivate fun CustomImageChip( text: String, imageId: Int, selected: Boolean, modifier: Modifier = Modifier) { // define properties to the chip // such as color, shape, width Surface( color = when { selected -> MaterialTheme.colors.primary else -> Color.Transparent }, contentColor = when { selected -> MaterialTheme.colors.onPrimary else -> Color.LightGray }, shape = RoundedCornerShape(16.dp), border = BorderStroke( width = 1.dp, color = when { selected -> MaterialTheme.colors.primary else -> Color.LightGray } ), modifier = modifier ) { // Inside a Row pack the Image and text together to // show inside the chip Row(modifier = Modifier) { Image( painter = painterResource(imageId), contentDescription = null, modifier = Modifier .padding(8.dp) .size(20.dp) .clip(CircleShape) ) Text( text = text, style = typography.body2, modifier = Modifier.padding(end = 8.dp, top = 8.dp, bottom = 8.dp) ) } }} @Preview@Composablefun Chips() { Text(text = "Custom Chips", style = typography.h6, modifier = Modifier.padding(8.dp)) SubtitleText(subtitle = "Custom chips with surface") // Call the functions that we defined // above and pass the actual data Column { Row(modifier = Modifier.padding(8.dp)) { // creates a custom chip for active state CustomChip( selected = true, text = "Chip", modifier = Modifier.padding(horizontal = 8.dp) ) // Creates a custom chip for inactive state CustomChip( selected = false, text = "Inactive", modifier = Modifier.padding(horizontal = 8.dp) ) // Create a custom image chip whose state is active CustomImageChip( text = "custom", imageId = R.drawable.gfg_logo, selected = true ) Spacer(modifier = Modifier.padding(8.dp)) // Create a custom image chip whose state is inactive CustomImageChip( text = "custom2", imageId = R.drawable.gfg_logo, selected = false ) } SubtitleText(subtitle = "Buttons with circle clipping.") // We can also use a circular shape button as a chip Row(modifier = Modifier.padding(8.dp)) { // Creates an active state chip using button Button( onClick = {}, modifier = Modifier .padding(8.dp) .clip(CircleShape) ) { Text(text = "Chip button") } // Creates an inactive state chip using button Button( onClick = {}, enabled = false, modifier = Modifier .padding(8.dp) .clip(CircleShape) ) { Text(text = "Disabled chip") } } }} // Function to show a text message@Composablefun SubtitleText(subtitle: String, modifier: Modifier = Modifier) { Text(text = subtitle, style = typography.subtitle2, modifier = modifier.padding(8.dp))}
Output:
sagar0719kumar
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 25130,
"s": 24725,
"text": "Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 25159,
"s": 25130,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25319,
"s": 25159,
"text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 25365,
"s": 25319,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 25570,
"s": 25365,
"text": "Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 25577,
"s": 25570,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.Buttonimport androidx.compose.material.MaterialThemeimport androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using // the 'background' color from the theme Surface(color = Color.White) { Column(modifier = Modifier.padding(10.dp)) { // call the function which // contains all the chips Chips() } } } } }} // Function for Custom Chip// Later we will reuse it to// create chips wherever needed// selected : Boolean - to Check// whether it is checked or not// text - To show the data@Composablefun CustomChip( selected: Boolean, text: String, modifier: Modifier = Modifier) { // define properties to the chip // such as color, shape, width Surface( color = when { selected -> MaterialTheme.colors.onSurface else -> Color.Transparent }, contentColor = when { selected -> MaterialTheme.colors.onPrimary else -> Color.LightGray }, shape = CircleShape, border = BorderStroke( width = 1.dp, color = when { selected -> MaterialTheme.colors.primary else -> Color.LightGray } ), modifier = modifier ) { // Add text to show the data that we passed Text( text = text, textAlign = TextAlign.Center, style = MaterialTheme.typography.body2, modifier = Modifier.padding(8.dp) ) }} // Function to create a Custom Image Chip with text// text - For showing data on the chip// imageId - For showing the image that we want to use// selected : Boolean - to check if it is selected or not@Composableprivate fun CustomImageChip( text: String, imageId: Int, selected: Boolean, modifier: Modifier = Modifier) { // define properties to the chip // such as color, shape, width Surface( color = when { selected -> MaterialTheme.colors.primary else -> Color.Transparent }, contentColor = when { selected -> MaterialTheme.colors.onPrimary else -> Color.LightGray }, shape = RoundedCornerShape(16.dp), border = BorderStroke( width = 1.dp, color = when { selected -> MaterialTheme.colors.primary else -> Color.LightGray } ), modifier = modifier ) { // Inside a Row pack the Image and text together to // show inside the chip Row(modifier = Modifier) { Image( painter = painterResource(imageId), contentDescription = null, modifier = Modifier .padding(8.dp) .size(20.dp) .clip(CircleShape) ) Text( text = text, style = typography.body2, modifier = Modifier.padding(end = 8.dp, top = 8.dp, bottom = 8.dp) ) } }} @Preview@Composablefun Chips() { Text(text = \"Custom Chips\", style = typography.h6, modifier = Modifier.padding(8.dp)) SubtitleText(subtitle = \"Custom chips with surface\") // Call the functions that we defined // above and pass the actual data Column { Row(modifier = Modifier.padding(8.dp)) { // creates a custom chip for active state CustomChip( selected = true, text = \"Chip\", modifier = Modifier.padding(horizontal = 8.dp) ) // Creates a custom chip for inactive state CustomChip( selected = false, text = \"Inactive\", modifier = Modifier.padding(horizontal = 8.dp) ) // Create a custom image chip whose state is active CustomImageChip( text = \"custom\", imageId = R.drawable.gfg_logo, selected = true ) Spacer(modifier = Modifier.padding(8.dp)) // Create a custom image chip whose state is inactive CustomImageChip( text = \"custom2\", imageId = R.drawable.gfg_logo, selected = false ) } SubtitleText(subtitle = \"Buttons with circle clipping.\") // We can also use a circular shape button as a chip Row(modifier = Modifier.padding(8.dp)) { // Creates an active state chip using button Button( onClick = {}, modifier = Modifier .padding(8.dp) .clip(CircleShape) ) { Text(text = \"Chip button\") } // Creates an inactive state chip using button Button( onClick = {}, enabled = false, modifier = Modifier .padding(8.dp) .clip(CircleShape) ) { Text(text = \"Disabled chip\") } } }} // Function to show a text message@Composablefun SubtitleText(subtitle: String, modifier: Modifier = Modifier) { Text(text = subtitle, style = typography.subtitle2, modifier = modifier.padding(8.dp))}",
"e": 32033,
"s": 25577,
"text": null
},
{
"code": null,
"e": 32045,
"s": 32037,
"text": "Output:"
},
{
"code": null,
"e": 32064,
"s": 32049,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 32080,
"s": 32064,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 32088,
"s": 32080,
"text": "Android"
},
{
"code": null,
"e": 32095,
"s": 32088,
"text": "Kotlin"
},
{
"code": null,
"e": 32103,
"s": 32095,
"text": "Android"
},
{
"code": null,
"e": 32201,
"s": 32103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32210,
"s": 32201,
"text": "Comments"
},
{
"code": null,
"e": 32223,
"s": 32210,
"text": "Old Comments"
},
{
"code": null,
"e": 32262,
"s": 32223,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32312,
"s": 32262,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32350,
"s": 32312,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32401,
"s": 32350,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32443,
"s": 32401,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32462,
"s": 32443,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 32475,
"s": 32462,
"text": "Kotlin Array"
},
{
"code": null,
"e": 32517,
"s": 32475,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
What are transformers and how can you use them? | Towards Data Science
|
One innovation that has taken natural language processing to new heights in the last three years was the development of transformers. And no, I’m not talking about the giant robots that turn into cars in the famous science-fiction film series directed by Michael Bay.
Transformers are semi-supervised machine learning models that are primarily used with text data and have replaced recurrent neural networks in natural language processing tasks. The goal of this article is to explain how transformers work and to show you how you can use them in your own machine learning projects.
Transformers were originally introduced by researchers at Google in the 2017 NIPS paper Attention is All You Need. Transformers are designed to work on sequence data and will take an input sequence and use it to generate an output sequence one element at a time.
For example, a transformer could be used to translate a sentence in English into a sentence in French. In this case, a sentence is basically treated as a sequence of words. A transformer has two main segments, the first is an encoder that operates primarily on the input sequence and the second is a decoder that operates on the target output sequence during training and predicts the next item in the sequence. In a machine translation problem, for example, the transformer may take a sequence of words in English and iteratively predict the next French word in the proper translation until the sentence has been completely translated. The diagram below demonstrates how a transformer is put together, with the encoder on the left and the decoder on the right.
It looks like there’s a lot going on in the diagram above, so let’s take a look at each component separately. The parts of a transformer that are particularly important are the embeddings, the positional encoding block, and the multi-head attention blocks.
If you have ever worked with word embeddings using the Word2Vec algorithm, the input and output embeddings are basically just embedding layers. The embedding layer takes a sequence of words and learns a vector representation for each word.
In the image above, a word embedding has been created for the sentence “the quick brown fox jumped over the lazy dog”. Notice how the sentence with nine words has been transformed into a 9 x 5 embedding matrix.
The Word2Vec algorithm uses a large sample of text as training data and learns word embeddings using one of two algorithms:
Continuous bag of words (CBOW) — in this case, the algorithm tries to predict a center word in the middle of the sentence using the surrounding context words.
Skip-gram model — in this case, the algorithm does the opposite of CBOW and predicts the distribution of context words from a center word.
Word2Vec uses a shallow neural network with just one hidden layer to make these predictions. The word vectors come from the weights learned in the hidden layer and are used to represent the semantic meaning of each word in relation to other words. The idea behind Word2Vec is that words with similar meanings will have similar embedding vectors. For a more comprehensive explanation of this algorithm, please see these lecture notes from Stanford’s NLP class.
What’s important to understand from this description is that the input and output embeddings both take a text document and produce an embedding matrix with an embedding vector for each word.
The positional encoding block applies a function to the embedding matrix that allows a neural network to understand the relative position of each word vector even if the matrix was shuffled. This might seem insignificant, but you will see why it’s important when I describe the attention blocks in detail.
The positional encoding blocks inject information about the position of each word vector by concatenating sine and cosine functions of different wavelengths/frequencies to these vectors as demonstrated in the equations below.
Given the equations below, if we consider an input with 10,000 possible positions, the positional encoding block will add sine and cosine values with wavelengths that increase geometrically from 2π to 10000*2π. This allows us to mathematically represent the relative position of word vectors such that a neural network can learn to recognize differences in position.
The multi-head attention block is the main innovation behind transformers. The question that the attention block aims to answer is what parts of the text should the model focus on? This is exactly why it is called an attention block. Each attention block takes three input matrices:
A query matrix, Q, of dimension n.
A key matrix, K, of dimension n.
And a value matrix, V, m.
This concept is best explained through a practical example. Let’s say the query matrix has values that represent a sentence in English such as “the quick brown fox jumped”. Let’s say that our goal is to translate this sentence into French. In this case, the transformer will have learned weights for individual English words in a key matrix and the query matrix will represent the actual input sentence. Computing the dot product of the query and key matrix is known as self-attention and will produce an output that looks something like this.
Note that the key matrix contains representations of each word and the dot product is essentially a matrix of similarity scores between the query matrix and the key matrix. These scores are later scaled by dividing the dot product matrix by the square root of the number of dimensions in the key and query matrices. A softmax activation function is applied to the scaled scores to convert them into probabilities. These probabilities are referred to as the attention weights, which are then multiplied by the value matrix to produce the final output of the attention block. The final output of the attention block is defined using the equation below:
Note that n was previously defined as the number of dimensions in the query matrix (Q) and the key matrix (K). The key and value matrices are learned parameters while the query matrix is defined by the input word vectors. It is also important to note that the words of a sentence are passed into the transformer at the same time and the concept of a sequential order present in LSTMs is not that apparent with transformers. This is why the positional encoding blocks mentioned earlier are important. They allow attention block to understand the relative position of words in sentences.
A single attention block can tell a model to pay attention to something specific such as the tense in a sentence. Adding multiple attention blocks allows the model to pay attention to different linguistic elements such as part of speech, tense, nouns, verbs, and so on.
This layer simply takes the outputs from the multi-head attention block, adds them together, and normalizes the result with layer normalization. If you have heard of batch normalization, layer normalization is similar but instead of normalizing the input features across the batch dimensions, it normalizes the inputs to a layer across all features.
This layer needs very little explanation. It is simply a single fully-connected layer of a feed-forward neural network. The feed-forward layer operates on the output attention vectors and learns to recognize patterns within them.
Now that we have covered each of the building blocks of a transformer, we can see how they fit together in the encoder and decoder segments.
The encoder is the part of the transformer that chooses what parts of the input to focus on. The encoder can take a sentence such as “the quick brown fox jumped”, computes the embedding matrix, and then converts it into a series of attention vectors. The multi-head attention block initially produces these attention vectors, which are then added and normalized, passed into a fully-connected layer (Feed Forward in the diagram above), and normalized again before being passed over to the decoder.
During training, the decoder operates directly on the target output sequence. As per our example, let’s assume the target output is the French translation of the English sentence “the quick brown fox jumped”, which translates to “le renard brun rapide a sauté” in French. In the decoder, separate embedding vectors are computed for each French word in the sentence, and the positional encoding is also applied in the form of sine and cosine functions.
However, a masked attention block is used, meaning that only the previous word in the French sentence is used and the other words are masked. This allows the transformer to learn to predict the next French word. The outputs of this masked attention block are added and normalized before being passed to another attention block that also receives the attention vectors produced by the encoder.
A feed-forward network receives the final attention vectors and uses them to produce a single vector with a dimension equal to the number of unique words in the model’s vocabulary. Applying the softmax activation function to this vector produces a set of probabilities corresponding to each word. In the context of our example, these probabilities predict the likelihood of each French word appearing next in the translation. This is how a transformer performs tasks such as machine translation and text generation. Just as demonstrated in the figure below, a transformer iteratively predicts the next word in a translated sentence when performing translation tasks.
In the last few years, several architectures based on the basic transformer introduced in the 2017 paper have been developed and trained for complex natural language processing tasks. Some of the most common transformer models that were created recently are listed below:
BERT
DistilBERT
T5
GPT-2
Transformers are definitely useful and as of 2020, are considered state-of-the-art NLP models. But implementing them seems quite difficult for the average machine learning practitioner. Luckily, HuggingFace has implemented a Python package for transformers that is really easy to use. It is open-source and you can find it on GitHub.
To install the transformers package run the following pip command:
pip install transformers
Make sure to install the library in a virtual environment as per the instructions provided in the GitHub repository. This package allows you to not only use pre-trained state-of-the-art transformers such as BERT and GPT for standard tasks but also lets you finetune them for your own tasks. Consider some of the examples below.
The transformers package from HuggingFace has a really simple interface provided through the pipeline module that makes it easy to use pre-trained transformers for standard tasks such as sentiment analysis. Consider the example below.
from transformers import pipelineclassifier = pipeline('sentiment-analysis')classifier('Batman Begins is a great movie! Truly a classic!')
Running this code produces a dictionary indicating the sentiment of the text.
[{'label': 'POSITIVE', 'score': 0.9998838305473328}]
We can also use the pipeline module for answering questions given some context information as demonstrated in the example below.
from transformers import pipelinequestion_answerer = pipeline('question-answering')question_answerer({ 'question': 'What is the name of my dog?', 'context': 'I have a dog named Sam. He likes to chase cats in the neighborhood.'})
Running the code produces the output shown below.
{'score': 0.9907370805740356, 'start': 19, 'end': 22, 'answer': 'Sam'}
Interestingly, the transformer not only gives us the answer to the question about the name of the dog but also tells us where we can find the answer in the context string.
In this article, I gave the example of translating English sentences to French in order to demonstrate how transformers work. The pipeline module, as expected, allows us to use transformer models to translate text from one language to another as demonstrated below.
from transformers import pipelinetranslator = pipeline('translation_en_to_fr')translator("The quick brown fox jumped.")
Running the code above produces the French translation shown below.
[{'translation_text': 'Le renard brun rapide saute.'}]
We can also use transformers for text summarization. In the example below, I used the T5 transformer to summarize Winston Churchill’s famous “Never Give In” speech in 1941 during one of the darkest times in World War II.
from transformers import pipelinesummarizer = pipeline('summarization', model="t5-base", tokenizer="t5-base", framework="tf")speech = open('./data/never_give_in.txt').read()summarizer(speech, min_length=50, max_length=100)
Running the code above produces this concise and beautifully worded summary below.
[{'summary_text': 'a year ago, we stood all alone, and to many countries it seemed that our account was closed, we were finished and liquidated . today, we can be sure that we have only to persevere to conquer . do not let us speak of dark days; these are great days - the greatest days our country has ever lived .'}]
We can also fine-tune pre-trained transformers for text classification tasks using transfer learning. In one of my previous articles, I used recurrent convolutional neural networks for classifying fake news articles.
towardsdatascience.com
In the example below, I used a preprocessed version of the same fake news dataset to train a BERT transformer model to detect fake news. Fine-tuning models requires a few extra steps so the sample code I provided is understandable but a bit more complicated than the previous examples. We not only have to import the transformer model, but also a tokenizer that can transform a text document into a series of integer tokens corresponding to different words as demonstrated in the image below.
Please note that I ran the code below on a GPU instance in AWS SageMaker because the training process is computationally expensive. If you plan on running this code yourself, I would recommend using a GPU.
There’s a lot going on in the code above so here’s an overview of the steps that I performed in the process of fine-tuning the BERT transformer:
Loaded the pre-trained BERT transformer model and initialized it for binary classification problems.Loaded the BERT tokenizer for encoding the text data as a series of integer tokens corresponding to each word.Read the fake news dataset using pandas and split it into training and validation sets.Encoded the text for the training and validation data using the BERT tokenizer and used this data to create TensorFlow datasets for training and validation.Set the parameters for the model and trained it for a single epoch on the training dataset.
Loaded the pre-trained BERT transformer model and initialized it for binary classification problems.
Loaded the BERT tokenizer for encoding the text data as a series of integer tokens corresponding to each word.
Read the fake news dataset using pandas and split it into training and validation sets.
Encoded the text for the training and validation data using the BERT tokenizer and used this data to create TensorFlow datasets for training and validation.
Set the parameters for the model and trained it for a single epoch on the training dataset.
The code produced the following output after the training process was complete:
3238/3238 [==============================] - 3420s 1s/step - loss: 0.1627 - accuracy: 0.9368 - val_loss: 0.1179 - val_accuracy: 0.9581<tensorflow.python.keras.callbacks.History at 0x7f12f39dc080>
The finetuned BERT model achieved a validation accuracy of 95.81 percent after just one training epoch, which is quite impressive. With more training epochs, it may achieve an even higher validation accuracy.
Transformers are powerful deep learning models that can be used for a wide variety of natural language processing tasks.
The transformers package provided by HuggingFace makes it very easy for developers to use state-of-the-art transformers for standard tasks such as sentiment analysis, question-answering, and text-summarization.
You can also finetune pre-trained transformers for your own natural language processing tasks.
As usual, I have made the full code for this article available on GitHub.
A. Vaswani, N. Shazeer, et. al, Attention Is All You Need, (2017), 31st Conference on Neural Information Processing Systems.F. Chaubard, M. Fang, et. al, Word Vectors I: Introduction, SVD and Word2Vec, (2019), CS224n: Natural Language Processing with Deep Learning lecture notes, Stanford University.J. Devlin, M. W. Chang, K. Lee, and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, (2018), arXiv.org.V. Sanh, L. Debut, J. Chaumond, and T. Wolf, DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter, (2019), arXiv.org.C. Raffel, N. Shazeer, et. al, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, (2019), arXiv.org.A. Radford, J.Wu, et. al, Language Models are Unsupervised Multitask Learners, (2019), OpenAI.
A. Vaswani, N. Shazeer, et. al, Attention Is All You Need, (2017), 31st Conference on Neural Information Processing Systems.
F. Chaubard, M. Fang, et. al, Word Vectors I: Introduction, SVD and Word2Vec, (2019), CS224n: Natural Language Processing with Deep Learning lecture notes, Stanford University.
J. Devlin, M. W. Chang, K. Lee, and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, (2018), arXiv.org.
V. Sanh, L. Debut, J. Chaumond, and T. Wolf, DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter, (2019), arXiv.org.
C. Raffel, N. Shazeer, et. al, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, (2019), arXiv.org.
A. Radford, J.Wu, et. al, Language Models are Unsupervised Multitask Learners, (2019), OpenAI.
|
[
{
"code": null,
"e": 439,
"s": 171,
"text": "One innovation that has taken natural language processing to new heights in the last three years was the development of transformers. And no, I’m not talking about the giant robots that turn into cars in the famous science-fiction film series directed by Michael Bay."
},
{
"code": null,
"e": 754,
"s": 439,
"text": "Transformers are semi-supervised machine learning models that are primarily used with text data and have replaced recurrent neural networks in natural language processing tasks. The goal of this article is to explain how transformers work and to show you how you can use them in your own machine learning projects."
},
{
"code": null,
"e": 1017,
"s": 754,
"text": "Transformers were originally introduced by researchers at Google in the 2017 NIPS paper Attention is All You Need. Transformers are designed to work on sequence data and will take an input sequence and use it to generate an output sequence one element at a time."
},
{
"code": null,
"e": 1779,
"s": 1017,
"text": "For example, a transformer could be used to translate a sentence in English into a sentence in French. In this case, a sentence is basically treated as a sequence of words. A transformer has two main segments, the first is an encoder that operates primarily on the input sequence and the second is a decoder that operates on the target output sequence during training and predicts the next item in the sequence. In a machine translation problem, for example, the transformer may take a sequence of words in English and iteratively predict the next French word in the proper translation until the sentence has been completely translated. The diagram below demonstrates how a transformer is put together, with the encoder on the left and the decoder on the right."
},
{
"code": null,
"e": 2036,
"s": 1779,
"text": "It looks like there’s a lot going on in the diagram above, so let’s take a look at each component separately. The parts of a transformer that are particularly important are the embeddings, the positional encoding block, and the multi-head attention blocks."
},
{
"code": null,
"e": 2276,
"s": 2036,
"text": "If you have ever worked with word embeddings using the Word2Vec algorithm, the input and output embeddings are basically just embedding layers. The embedding layer takes a sequence of words and learns a vector representation for each word."
},
{
"code": null,
"e": 2487,
"s": 2276,
"text": "In the image above, a word embedding has been created for the sentence “the quick brown fox jumped over the lazy dog”. Notice how the sentence with nine words has been transformed into a 9 x 5 embedding matrix."
},
{
"code": null,
"e": 2611,
"s": 2487,
"text": "The Word2Vec algorithm uses a large sample of text as training data and learns word embeddings using one of two algorithms:"
},
{
"code": null,
"e": 2770,
"s": 2611,
"text": "Continuous bag of words (CBOW) — in this case, the algorithm tries to predict a center word in the middle of the sentence using the surrounding context words."
},
{
"code": null,
"e": 2909,
"s": 2770,
"text": "Skip-gram model — in this case, the algorithm does the opposite of CBOW and predicts the distribution of context words from a center word."
},
{
"code": null,
"e": 3369,
"s": 2909,
"text": "Word2Vec uses a shallow neural network with just one hidden layer to make these predictions. The word vectors come from the weights learned in the hidden layer and are used to represent the semantic meaning of each word in relation to other words. The idea behind Word2Vec is that words with similar meanings will have similar embedding vectors. For a more comprehensive explanation of this algorithm, please see these lecture notes from Stanford’s NLP class."
},
{
"code": null,
"e": 3560,
"s": 3369,
"text": "What’s important to understand from this description is that the input and output embeddings both take a text document and produce an embedding matrix with an embedding vector for each word."
},
{
"code": null,
"e": 3866,
"s": 3560,
"text": "The positional encoding block applies a function to the embedding matrix that allows a neural network to understand the relative position of each word vector even if the matrix was shuffled. This might seem insignificant, but you will see why it’s important when I describe the attention blocks in detail."
},
{
"code": null,
"e": 4092,
"s": 3866,
"text": "The positional encoding blocks inject information about the position of each word vector by concatenating sine and cosine functions of different wavelengths/frequencies to these vectors as demonstrated in the equations below."
},
{
"code": null,
"e": 4459,
"s": 4092,
"text": "Given the equations below, if we consider an input with 10,000 possible positions, the positional encoding block will add sine and cosine values with wavelengths that increase geometrically from 2π to 10000*2π. This allows us to mathematically represent the relative position of word vectors such that a neural network can learn to recognize differences in position."
},
{
"code": null,
"e": 4742,
"s": 4459,
"text": "The multi-head attention block is the main innovation behind transformers. The question that the attention block aims to answer is what parts of the text should the model focus on? This is exactly why it is called an attention block. Each attention block takes three input matrices:"
},
{
"code": null,
"e": 4777,
"s": 4742,
"text": "A query matrix, Q, of dimension n."
},
{
"code": null,
"e": 4810,
"s": 4777,
"text": "A key matrix, K, of dimension n."
},
{
"code": null,
"e": 4836,
"s": 4810,
"text": "And a value matrix, V, m."
},
{
"code": null,
"e": 5380,
"s": 4836,
"text": "This concept is best explained through a practical example. Let’s say the query matrix has values that represent a sentence in English such as “the quick brown fox jumped”. Let’s say that our goal is to translate this sentence into French. In this case, the transformer will have learned weights for individual English words in a key matrix and the query matrix will represent the actual input sentence. Computing the dot product of the query and key matrix is known as self-attention and will produce an output that looks something like this."
},
{
"code": null,
"e": 6031,
"s": 5380,
"text": "Note that the key matrix contains representations of each word and the dot product is essentially a matrix of similarity scores between the query matrix and the key matrix. These scores are later scaled by dividing the dot product matrix by the square root of the number of dimensions in the key and query matrices. A softmax activation function is applied to the scaled scores to convert them into probabilities. These probabilities are referred to as the attention weights, which are then multiplied by the value matrix to produce the final output of the attention block. The final output of the attention block is defined using the equation below:"
},
{
"code": null,
"e": 6617,
"s": 6031,
"text": "Note that n was previously defined as the number of dimensions in the query matrix (Q) and the key matrix (K). The key and value matrices are learned parameters while the query matrix is defined by the input word vectors. It is also important to note that the words of a sentence are passed into the transformer at the same time and the concept of a sequential order present in LSTMs is not that apparent with transformers. This is why the positional encoding blocks mentioned earlier are important. They allow attention block to understand the relative position of words in sentences."
},
{
"code": null,
"e": 6887,
"s": 6617,
"text": "A single attention block can tell a model to pay attention to something specific such as the tense in a sentence. Adding multiple attention blocks allows the model to pay attention to different linguistic elements such as part of speech, tense, nouns, verbs, and so on."
},
{
"code": null,
"e": 7237,
"s": 6887,
"text": "This layer simply takes the outputs from the multi-head attention block, adds them together, and normalizes the result with layer normalization. If you have heard of batch normalization, layer normalization is similar but instead of normalizing the input features across the batch dimensions, it normalizes the inputs to a layer across all features."
},
{
"code": null,
"e": 7467,
"s": 7237,
"text": "This layer needs very little explanation. It is simply a single fully-connected layer of a feed-forward neural network. The feed-forward layer operates on the output attention vectors and learns to recognize patterns within them."
},
{
"code": null,
"e": 7608,
"s": 7467,
"text": "Now that we have covered each of the building blocks of a transformer, we can see how they fit together in the encoder and decoder segments."
},
{
"code": null,
"e": 8106,
"s": 7608,
"text": "The encoder is the part of the transformer that chooses what parts of the input to focus on. The encoder can take a sentence such as “the quick brown fox jumped”, computes the embedding matrix, and then converts it into a series of attention vectors. The multi-head attention block initially produces these attention vectors, which are then added and normalized, passed into a fully-connected layer (Feed Forward in the diagram above), and normalized again before being passed over to the decoder."
},
{
"code": null,
"e": 8559,
"s": 8106,
"text": "During training, the decoder operates directly on the target output sequence. As per our example, let’s assume the target output is the French translation of the English sentence “the quick brown fox jumped”, which translates to “le renard brun rapide a sauté” in French. In the decoder, separate embedding vectors are computed for each French word in the sentence, and the positional encoding is also applied in the form of sine and cosine functions."
},
{
"code": null,
"e": 8952,
"s": 8559,
"text": "However, a masked attention block is used, meaning that only the previous word in the French sentence is used and the other words are masked. This allows the transformer to learn to predict the next French word. The outputs of this masked attention block are added and normalized before being passed to another attention block that also receives the attention vectors produced by the encoder."
},
{
"code": null,
"e": 9619,
"s": 8952,
"text": "A feed-forward network receives the final attention vectors and uses them to produce a single vector with a dimension equal to the number of unique words in the model’s vocabulary. Applying the softmax activation function to this vector produces a set of probabilities corresponding to each word. In the context of our example, these probabilities predict the likelihood of each French word appearing next in the translation. This is how a transformer performs tasks such as machine translation and text generation. Just as demonstrated in the figure below, a transformer iteratively predicts the next word in a translated sentence when performing translation tasks."
},
{
"code": null,
"e": 9891,
"s": 9619,
"text": "In the last few years, several architectures based on the basic transformer introduced in the 2017 paper have been developed and trained for complex natural language processing tasks. Some of the most common transformer models that were created recently are listed below:"
},
{
"code": null,
"e": 9896,
"s": 9891,
"text": "BERT"
},
{
"code": null,
"e": 9907,
"s": 9896,
"text": "DistilBERT"
},
{
"code": null,
"e": 9910,
"s": 9907,
"text": "T5"
},
{
"code": null,
"e": 9916,
"s": 9910,
"text": "GPT-2"
},
{
"code": null,
"e": 10250,
"s": 9916,
"text": "Transformers are definitely useful and as of 2020, are considered state-of-the-art NLP models. But implementing them seems quite difficult for the average machine learning practitioner. Luckily, HuggingFace has implemented a Python package for transformers that is really easy to use. It is open-source and you can find it on GitHub."
},
{
"code": null,
"e": 10317,
"s": 10250,
"text": "To install the transformers package run the following pip command:"
},
{
"code": null,
"e": 10342,
"s": 10317,
"text": "pip install transformers"
},
{
"code": null,
"e": 10670,
"s": 10342,
"text": "Make sure to install the library in a virtual environment as per the instructions provided in the GitHub repository. This package allows you to not only use pre-trained state-of-the-art transformers such as BERT and GPT for standard tasks but also lets you finetune them for your own tasks. Consider some of the examples below."
},
{
"code": null,
"e": 10905,
"s": 10670,
"text": "The transformers package from HuggingFace has a really simple interface provided through the pipeline module that makes it easy to use pre-trained transformers for standard tasks such as sentiment analysis. Consider the example below."
},
{
"code": null,
"e": 11044,
"s": 10905,
"text": "from transformers import pipelineclassifier = pipeline('sentiment-analysis')classifier('Batman Begins is a great movie! Truly a classic!')"
},
{
"code": null,
"e": 11122,
"s": 11044,
"text": "Running this code produces a dictionary indicating the sentiment of the text."
},
{
"code": null,
"e": 11175,
"s": 11122,
"text": "[{'label': 'POSITIVE', 'score': 0.9998838305473328}]"
},
{
"code": null,
"e": 11304,
"s": 11175,
"text": "We can also use the pipeline module for answering questions given some context information as demonstrated in the example below."
},
{
"code": null,
"e": 11535,
"s": 11304,
"text": "from transformers import pipelinequestion_answerer = pipeline('question-answering')question_answerer({ 'question': 'What is the name of my dog?', 'context': 'I have a dog named Sam. He likes to chase cats in the neighborhood.'})"
},
{
"code": null,
"e": 11585,
"s": 11535,
"text": "Running the code produces the output shown below."
},
{
"code": null,
"e": 11656,
"s": 11585,
"text": "{'score': 0.9907370805740356, 'start': 19, 'end': 22, 'answer': 'Sam'}"
},
{
"code": null,
"e": 11828,
"s": 11656,
"text": "Interestingly, the transformer not only gives us the answer to the question about the name of the dog but also tells us where we can find the answer in the context string."
},
{
"code": null,
"e": 12094,
"s": 11828,
"text": "In this article, I gave the example of translating English sentences to French in order to demonstrate how transformers work. The pipeline module, as expected, allows us to use transformer models to translate text from one language to another as demonstrated below."
},
{
"code": null,
"e": 12214,
"s": 12094,
"text": "from transformers import pipelinetranslator = pipeline('translation_en_to_fr')translator(\"The quick brown fox jumped.\")"
},
{
"code": null,
"e": 12282,
"s": 12214,
"text": "Running the code above produces the French translation shown below."
},
{
"code": null,
"e": 12337,
"s": 12282,
"text": "[{'translation_text': 'Le renard brun rapide saute.'}]"
},
{
"code": null,
"e": 12558,
"s": 12337,
"text": "We can also use transformers for text summarization. In the example below, I used the T5 transformer to summarize Winston Churchill’s famous “Never Give In” speech in 1941 during one of the darkest times in World War II."
},
{
"code": null,
"e": 12781,
"s": 12558,
"text": "from transformers import pipelinesummarizer = pipeline('summarization', model=\"t5-base\", tokenizer=\"t5-base\", framework=\"tf\")speech = open('./data/never_give_in.txt').read()summarizer(speech, min_length=50, max_length=100)"
},
{
"code": null,
"e": 12864,
"s": 12781,
"text": "Running the code above produces this concise and beautifully worded summary below."
},
{
"code": null,
"e": 13183,
"s": 12864,
"text": "[{'summary_text': 'a year ago, we stood all alone, and to many countries it seemed that our account was closed, we were finished and liquidated . today, we can be sure that we have only to persevere to conquer . do not let us speak of dark days; these are great days - the greatest days our country has ever lived .'}]"
},
{
"code": null,
"e": 13400,
"s": 13183,
"text": "We can also fine-tune pre-trained transformers for text classification tasks using transfer learning. In one of my previous articles, I used recurrent convolutional neural networks for classifying fake news articles."
},
{
"code": null,
"e": 13423,
"s": 13400,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13916,
"s": 13423,
"text": "In the example below, I used a preprocessed version of the same fake news dataset to train a BERT transformer model to detect fake news. Fine-tuning models requires a few extra steps so the sample code I provided is understandable but a bit more complicated than the previous examples. We not only have to import the transformer model, but also a tokenizer that can transform a text document into a series of integer tokens corresponding to different words as demonstrated in the image below."
},
{
"code": null,
"e": 14122,
"s": 13916,
"text": "Please note that I ran the code below on a GPU instance in AWS SageMaker because the training process is computationally expensive. If you plan on running this code yourself, I would recommend using a GPU."
},
{
"code": null,
"e": 14267,
"s": 14122,
"text": "There’s a lot going on in the code above so here’s an overview of the steps that I performed in the process of fine-tuning the BERT transformer:"
},
{
"code": null,
"e": 14812,
"s": 14267,
"text": "Loaded the pre-trained BERT transformer model and initialized it for binary classification problems.Loaded the BERT tokenizer for encoding the text data as a series of integer tokens corresponding to each word.Read the fake news dataset using pandas and split it into training and validation sets.Encoded the text for the training and validation data using the BERT tokenizer and used this data to create TensorFlow datasets for training and validation.Set the parameters for the model and trained it for a single epoch on the training dataset."
},
{
"code": null,
"e": 14913,
"s": 14812,
"text": "Loaded the pre-trained BERT transformer model and initialized it for binary classification problems."
},
{
"code": null,
"e": 15024,
"s": 14913,
"text": "Loaded the BERT tokenizer for encoding the text data as a series of integer tokens corresponding to each word."
},
{
"code": null,
"e": 15112,
"s": 15024,
"text": "Read the fake news dataset using pandas and split it into training and validation sets."
},
{
"code": null,
"e": 15269,
"s": 15112,
"text": "Encoded the text for the training and validation data using the BERT tokenizer and used this data to create TensorFlow datasets for training and validation."
},
{
"code": null,
"e": 15361,
"s": 15269,
"text": "Set the parameters for the model and trained it for a single epoch on the training dataset."
},
{
"code": null,
"e": 15441,
"s": 15361,
"text": "The code produced the following output after the training process was complete:"
},
{
"code": null,
"e": 15637,
"s": 15441,
"text": "3238/3238 [==============================] - 3420s 1s/step - loss: 0.1627 - accuracy: 0.9368 - val_loss: 0.1179 - val_accuracy: 0.9581<tensorflow.python.keras.callbacks.History at 0x7f12f39dc080>"
},
{
"code": null,
"e": 15846,
"s": 15637,
"text": "The finetuned BERT model achieved a validation accuracy of 95.81 percent after just one training epoch, which is quite impressive. With more training epochs, it may achieve an even higher validation accuracy."
},
{
"code": null,
"e": 15967,
"s": 15846,
"text": "Transformers are powerful deep learning models that can be used for a wide variety of natural language processing tasks."
},
{
"code": null,
"e": 16178,
"s": 15967,
"text": "The transformers package provided by HuggingFace makes it very easy for developers to use state-of-the-art transformers for standard tasks such as sentiment analysis, question-answering, and text-summarization."
},
{
"code": null,
"e": 16273,
"s": 16178,
"text": "You can also finetune pre-trained transformers for your own natural language processing tasks."
},
{
"code": null,
"e": 16347,
"s": 16273,
"text": "As usual, I have made the full code for this article available on GitHub."
},
{
"code": null,
"e": 17166,
"s": 16347,
"text": "A. Vaswani, N. Shazeer, et. al, Attention Is All You Need, (2017), 31st Conference on Neural Information Processing Systems.F. Chaubard, M. Fang, et. al, Word Vectors I: Introduction, SVD and Word2Vec, (2019), CS224n: Natural Language Processing with Deep Learning lecture notes, Stanford University.J. Devlin, M. W. Chang, K. Lee, and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, (2018), arXiv.org.V. Sanh, L. Debut, J. Chaumond, and T. Wolf, DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter, (2019), arXiv.org.C. Raffel, N. Shazeer, et. al, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, (2019), arXiv.org.A. Radford, J.Wu, et. al, Language Models are Unsupervised Multitask Learners, (2019), OpenAI."
},
{
"code": null,
"e": 17291,
"s": 17166,
"text": "A. Vaswani, N. Shazeer, et. al, Attention Is All You Need, (2017), 31st Conference on Neural Information Processing Systems."
},
{
"code": null,
"e": 17468,
"s": 17291,
"text": "F. Chaubard, M. Fang, et. al, Word Vectors I: Introduction, SVD and Word2Vec, (2019), CS224n: Natural Language Processing with Deep Learning lecture notes, Stanford University."
},
{
"code": null,
"e": 17619,
"s": 17468,
"text": "J. Devlin, M. W. Chang, K. Lee, and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, (2018), arXiv.org."
},
{
"code": null,
"e": 17762,
"s": 17619,
"text": "V. Sanh, L. Debut, J. Chaumond, and T. Wolf, DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter, (2019), arXiv.org."
},
{
"code": null,
"e": 17895,
"s": 17762,
"text": "C. Raffel, N. Shazeer, et. al, Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, (2019), arXiv.org."
}
] |
Convert string to bool in C#
|
To convert a string to a bool, use the Bool.parse method in C# −
Firstly, set a string −
string str = "false";
Now, convert it to bool −
bool.Parse(str);
Here is the complete code −
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
string str = "false";
bool res = bool.Parse(str);
Console.WriteLine(res);
}
}
False
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "To convert a string to a bool, use the Bool.parse method in C# −"
},
{
"code": null,
"e": 1151,
"s": 1127,
"text": "Firstly, set a string −"
},
{
"code": null,
"e": 1173,
"s": 1151,
"text": "string str = \"false\";"
},
{
"code": null,
"e": 1199,
"s": 1173,
"text": "Now, convert it to bool −"
},
{
"code": null,
"e": 1216,
"s": 1199,
"text": "bool.Parse(str);"
},
{
"code": null,
"e": 1244,
"s": 1216,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1255,
"s": 1244,
"text": " Live Demo"
},
{
"code": null,
"e": 1424,
"s": 1255,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n string str = \"false\";\n bool res = bool.Parse(str);\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 1430,
"s": 1424,
"text": "False"
}
] |
Minimum number of operations on an array to make all elements 0 using C++.
|
Given an array of size N and each element is either 1 or 0. The task is to calculated the minimum number of operations to be performed to convert all elements to zero. One can perform below operations −
If an element is 1, You can change its value equal to 0 then −
If the next consecutive element is 1, it will automatically get converted to 0
If the next consecutive element is 1, it will automatically get converted to 0
If the next consecutive element is already 0, nothing will happen.
If the next consecutive element is already 0, nothing will happen.
If arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1} then 4
operation are required to make all elements zero
1.If the current element is 1 then increment the count and search for the next 0 as all consecutive 1’s will be automatically converted to 0.
2. Return final count
#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int performMinOperation(int *arr, int n){
int i, cnt = 0;
for (i = 0; i < n; ++i) {
if (arr[i] == 1) {
int j;
for (j = i + 1; j < n; ++j) {
if (arr[j] == 0) {
break;
}
}
i = j - 1;
++cnt;
}
}
return cnt;
}
int main(){
int arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1};
cout << "Minimum required operations = " << performMinOperation(arr, SIZE(arr)) << endl;
return 0;
}
When you compile and execute the above program. It generates the following output −
Minimum required operations = 4
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "Given an array of size N and each element is either 1 or 0. The task is to calculated the minimum number of operations to be performed to convert all elements to zero. One can perform below operations −"
},
{
"code": null,
"e": 1328,
"s": 1265,
"text": "If an element is 1, You can change its value equal to 0 then −"
},
{
"code": null,
"e": 1407,
"s": 1328,
"text": "If the next consecutive element is 1, it will automatically get converted to 0"
},
{
"code": null,
"e": 1486,
"s": 1407,
"text": "If the next consecutive element is 1, it will automatically get converted to 0"
},
{
"code": null,
"e": 1553,
"s": 1486,
"text": "If the next consecutive element is already 0, nothing will happen."
},
{
"code": null,
"e": 1620,
"s": 1553,
"text": "If the next consecutive element is already 0, nothing will happen."
},
{
"code": null,
"e": 1733,
"s": 1620,
"text": "If arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1} then 4\noperation are required to make all elements zero"
},
{
"code": null,
"e": 1897,
"s": 1733,
"text": "1.If the current element is 1 then increment the count and search for the next 0 as all consecutive 1’s will be automatically converted to 0.\n2. Return final count"
},
{
"code": null,
"e": 2482,
"s": 1897,
"text": "#include <iostream>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nint performMinOperation(int *arr, int n){\n int i, cnt = 0;\n for (i = 0; i < n; ++i) {\n if (arr[i] == 1) {\n int j;\n for (j = i + 1; j < n; ++j) {\n if (arr[j] == 0) {\n break;\n }\n }\n i = j - 1;\n ++cnt;\n }\n }\n return cnt;\n}\nint main(){\n int arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1};\n cout << \"Minimum required operations = \" << performMinOperation(arr, SIZE(arr)) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2566,
"s": 2482,
"text": "When you compile and execute the above program. It generates the following output −"
},
{
"code": null,
"e": 2598,
"s": 2566,
"text": "Minimum required operations = 4"
}
] |
Queries to minimize sum added to given ranges in an array to make their Bitwise AND non-zero - GeeksforGeeks
|
19 Sep, 2021
Given an array arr[] consisting of N integers an array Q[][] consisting of queries of the form {l, r}. For each query {l, r}, the task is to determine the minimum sum of all values that must be added to each array element in that range such that the Bitwise AND of all numbers in that range exceeds 0. Note: Different values can be added to different integers in the given range.
Examples:
Input: arr[] = {1, 2, 4, 8}, Q[][] = {{1, 4}, {2, 3}, {1, 3}}Output: 3 2 2Explanation: Binary representation of array elements are as follows:1 – 00012 – 00104 – 01008 – 1000For first query {1, 4}, add 1 to all numbers present in the range except the first number. Therefore, Bitwise AND = (1 & 3 & 5 & 9) = 1 and minimum sum of elements added = 3.For second query {2, 3}, add 2 to 3rd element. Therefore, Bitwise AND = (2 & 6) = 2 and minimum sum of elements added = 2.For third query {1, 3}, add 1 to 2nd and 3rd elements. Therefore, Bitwise AND = (1 & 3 & 5) = 1 and minimum sum of elements added = 2.
Input: arr[] = {4, 6, 5, 3}, Q[][] = {{1, 4}}Output: 1Explanation: Optimal way to make the Bitwise AND non-zero is to add 1 to the last element. Therefore, bitwise AND = (4 & 6 & 5 & 4) = 4 and minimum sum of elements added = 1.
Approach: The idea is to first observe that the Bitwise AND of all the integers in the range [l, r] can only be non-zero if a bit at a particular index is set for each integer in that range. Follow the steps below to solve the problem:
Initialize a 2D vector pre where pre[i][j] stores the minimum sum of integers to be added to all integers from index 0 to index i such that, for each of them, their jth bit is set.For each element at index i, check for each of its bit from j = 0 to 31.Initialize a variable sum with 0.If jth bit is set, update pre[i][j] as pre[i][j]=pre[i-1][j] and increment sum by 2j. Otherwise, update pre[i][j] = pre[i-1][j] + 2j – sum where (2j-sum) is the value that must be added to set the jth bit of arr[i].Now, for each query {l, r}, the minimum sum required to set jth bit of all elements in the given range is pre[r][j] – pre[l-1][j].For each query {l, r}, find the answer for each bit from j = 0 to 31 and print the minimum amongst them.
Initialize a 2D vector pre where pre[i][j] stores the minimum sum of integers to be added to all integers from index 0 to index i such that, for each of them, their jth bit is set.
For each element at index i, check for each of its bit from j = 0 to 31.
Initialize a variable sum with 0.
If jth bit is set, update pre[i][j] as pre[i][j]=pre[i-1][j] and increment sum by 2j. Otherwise, update pre[i][j] = pre[i-1][j] + 2j – sum where (2j-sum) is the value that must be added to set the jth bit of arr[i].
Now, for each query {l, r}, the minimum sum required to set jth bit of all elements in the given range is pre[r][j] – pre[l-1][j].
For each query {l, r}, find the answer for each bit from j = 0 to 31 and print the minimum amongst them.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the min sum required// to set the jth bit of all integervoid processing(vector<int> v, vector<vector<long long int> >& pre){ // Number of elements int N = v.size(); // Traverse all elements for (int i = 0; i < N; i++) { // Binary representation bitset<32> b(v[i]); long long int sum = 0; // Take previous values if (i != 0) { pre[i] = pre[i - 1]; } // Processing each bit and // store it in 2d vector for (int j = 0; j < 32; j++) { if (b[j] == 1) { sum += 1ll << j; } else { pre[i][j] += (1ll << j) - sum; } } }} // Function to print the minimum// sum for each querylong long intprocess_query(vector<vector<int> > Q, vector<vector<long long int> >& pre){ // Stores the sum for each query vector<int> ans; for (int i = 0; i < Q.size(); i++) { // Update wrt 0-based index --Q[i][0], --Q[i][1]; // Initizlize answer long long int min1 = INT_MAX; // Find minimum sum for each bit if (Q[i][0] == 0) { for (int j = 0; j < 32; j++) { min1 = min(pre[Q[i][1]][j], min1); } } else { for (int j = 0; j < 32; j++) { min1 = min(pre[Q[i][1]][j] - pre[Q[i][0] - 1][j], min1); } } // Store the answer for // each query ans.push_back(min1); } // Print the answer vector for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; }} // Driver Codeint main(){ // Given array vector<int> arr = { 1, 2, 4, 8 }; // Given Queries vector<vector<int> > Q = { { 1, 4 }, { 2, 3 }, { 1, 3 } }; // 2d Prefix vector vector<vector<long long int> > pre( 100001, vector<long long int>(32, 0)); // Preprocessing processing(arr, pre); // Function call for queries process_query(Q, pre); return 0;}
3 2 2
Time Complexity: O(N*32 + sizeof(Q)*32) Auxiliary Space: O(N*32)
surinderdawra388
array-range-queries
Bitwise-AND
CPP-bitset
prefix-sum
Arrays
Bit Magic
Mathematical
prefix-sum
Arrays
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 24786,
"s": 24405,
"text": "Given an array arr[] consisting of N integers an array Q[][] consisting of queries of the form {l, r}. For each query {l, r}, the task is to determine the minimum sum of all values that must be added to each array element in that range such that the Bitwise AND of all numbers in that range exceeds 0. Note: Different values can be added to different integers in the given range. "
},
{
"code": null,
"e": 24796,
"s": 24786,
"text": "Examples:"
},
{
"code": null,
"e": 25401,
"s": 24796,
"text": "Input: arr[] = {1, 2, 4, 8}, Q[][] = {{1, 4}, {2, 3}, {1, 3}}Output: 3 2 2Explanation: Binary representation of array elements are as follows:1 – 00012 – 00104 – 01008 – 1000For first query {1, 4}, add 1 to all numbers present in the range except the first number. Therefore, Bitwise AND = (1 & 3 & 5 & 9) = 1 and minimum sum of elements added = 3.For second query {2, 3}, add 2 to 3rd element. Therefore, Bitwise AND = (2 & 6) = 2 and minimum sum of elements added = 2.For third query {1, 3}, add 1 to 2nd and 3rd elements. Therefore, Bitwise AND = (1 & 3 & 5) = 1 and minimum sum of elements added = 2."
},
{
"code": null,
"e": 25630,
"s": 25401,
"text": "Input: arr[] = {4, 6, 5, 3}, Q[][] = {{1, 4}}Output: 1Explanation: Optimal way to make the Bitwise AND non-zero is to add 1 to the last element. Therefore, bitwise AND = (4 & 6 & 5 & 4) = 4 and minimum sum of elements added = 1."
},
{
"code": null,
"e": 25866,
"s": 25630,
"text": "Approach: The idea is to first observe that the Bitwise AND of all the integers in the range [l, r] can only be non-zero if a bit at a particular index is set for each integer in that range. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26601,
"s": 25866,
"text": "Initialize a 2D vector pre where pre[i][j] stores the minimum sum of integers to be added to all integers from index 0 to index i such that, for each of them, their jth bit is set.For each element at index i, check for each of its bit from j = 0 to 31.Initialize a variable sum with 0.If jth bit is set, update pre[i][j] as pre[i][j]=pre[i-1][j] and increment sum by 2j. Otherwise, update pre[i][j] = pre[i-1][j] + 2j – sum where (2j-sum) is the value that must be added to set the jth bit of arr[i].Now, for each query {l, r}, the minimum sum required to set jth bit of all elements in the given range is pre[r][j] – pre[l-1][j].For each query {l, r}, find the answer for each bit from j = 0 to 31 and print the minimum amongst them."
},
{
"code": null,
"e": 26782,
"s": 26601,
"text": "Initialize a 2D vector pre where pre[i][j] stores the minimum sum of integers to be added to all integers from index 0 to index i such that, for each of them, their jth bit is set."
},
{
"code": null,
"e": 26855,
"s": 26782,
"text": "For each element at index i, check for each of its bit from j = 0 to 31."
},
{
"code": null,
"e": 26889,
"s": 26855,
"text": "Initialize a variable sum with 0."
},
{
"code": null,
"e": 27105,
"s": 26889,
"text": "If jth bit is set, update pre[i][j] as pre[i][j]=pre[i-1][j] and increment sum by 2j. Otherwise, update pre[i][j] = pre[i-1][j] + 2j – sum where (2j-sum) is the value that must be added to set the jth bit of arr[i]."
},
{
"code": null,
"e": 27236,
"s": 27105,
"text": "Now, for each query {l, r}, the minimum sum required to set jth bit of all elements in the given range is pre[r][j] – pre[l-1][j]."
},
{
"code": null,
"e": 27341,
"s": 27236,
"text": "For each query {l, r}, find the answer for each bit from j = 0 to 31 and print the minimum amongst them."
},
{
"code": null,
"e": 27392,
"s": 27341,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27396,
"s": 27392,
"text": "C++"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the min sum required// to set the jth bit of all integervoid processing(vector<int> v, vector<vector<long long int> >& pre){ // Number of elements int N = v.size(); // Traverse all elements for (int i = 0; i < N; i++) { // Binary representation bitset<32> b(v[i]); long long int sum = 0; // Take previous values if (i != 0) { pre[i] = pre[i - 1]; } // Processing each bit and // store it in 2d vector for (int j = 0; j < 32; j++) { if (b[j] == 1) { sum += 1ll << j; } else { pre[i][j] += (1ll << j) - sum; } } }} // Function to print the minimum// sum for each querylong long intprocess_query(vector<vector<int> > Q, vector<vector<long long int> >& pre){ // Stores the sum for each query vector<int> ans; for (int i = 0; i < Q.size(); i++) { // Update wrt 0-based index --Q[i][0], --Q[i][1]; // Initizlize answer long long int min1 = INT_MAX; // Find minimum sum for each bit if (Q[i][0] == 0) { for (int j = 0; j < 32; j++) { min1 = min(pre[Q[i][1]][j], min1); } } else { for (int j = 0; j < 32; j++) { min1 = min(pre[Q[i][1]][j] - pre[Q[i][0] - 1][j], min1); } } // Store the answer for // each query ans.push_back(min1); } // Print the answer vector for (int i = 0; i < ans.size(); i++) { cout << ans[i] << \" \"; }} // Driver Codeint main(){ // Given array vector<int> arr = { 1, 2, 4, 8 }; // Given Queries vector<vector<int> > Q = { { 1, 4 }, { 2, 3 }, { 1, 3 } }; // 2d Prefix vector vector<vector<long long int> > pre( 100001, vector<long long int>(32, 0)); // Preprocessing processing(arr, pre); // Function call for queries process_query(Q, pre); return 0;}",
"e": 29598,
"s": 27396,
"text": null
},
{
"code": null,
"e": 29604,
"s": 29598,
"text": "3 2 2"
},
{
"code": null,
"e": 29671,
"s": 29606,
"text": "Time Complexity: O(N*32 + sizeof(Q)*32) Auxiliary Space: O(N*32)"
},
{
"code": null,
"e": 29688,
"s": 29671,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29708,
"s": 29688,
"text": "array-range-queries"
},
{
"code": null,
"e": 29720,
"s": 29708,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 29731,
"s": 29720,
"text": "CPP-bitset"
},
{
"code": null,
"e": 29742,
"s": 29731,
"text": "prefix-sum"
},
{
"code": null,
"e": 29749,
"s": 29742,
"text": "Arrays"
},
{
"code": null,
"e": 29759,
"s": 29749,
"text": "Bit Magic"
},
{
"code": null,
"e": 29772,
"s": 29759,
"text": "Mathematical"
},
{
"code": null,
"e": 29783,
"s": 29772,
"text": "prefix-sum"
},
{
"code": null,
"e": 29790,
"s": 29783,
"text": "Arrays"
},
{
"code": null,
"e": 29803,
"s": 29790,
"text": "Mathematical"
},
{
"code": null,
"e": 29813,
"s": 29803,
"text": "Bit Magic"
},
{
"code": null,
"e": 29911,
"s": 29813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29920,
"s": 29911,
"text": "Comments"
},
{
"code": null,
"e": 29933,
"s": 29920,
"text": "Old Comments"
},
{
"code": null,
"e": 29954,
"s": 29933,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29979,
"s": 29954,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30006,
"s": 29979,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30055,
"s": 30006,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30093,
"s": 30055,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30120,
"s": 30093,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30166,
"s": 30120,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 30234,
"s": 30166,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 30263,
"s": 30234,
"text": "Count set bits in an integer"
}
] |
Python GUI App In No Time by Lazar Gugleta | Towards Data Science
|
One of the most important parts of today's applications is GUI (Graphical User Interface) itself.
That is because the market is so competitive and oversaturated that it is not even about the functionality anymore, but who can make it look prettier and simpler to use.
Today we will be learning how to create and build GUI applications in one of the most popular programming languages Python.
This short tutorial will be explained line by line and will be very easy to follow although you might not have much experience with Python or programming in general.
For the development of this app, you will not need much, If you are already familiar with Python, you can skip until the next chapter of this article.
My personal choice for code and software development is Visual Studio Code.
Next up we will need Python installed and so if you are on the Ubuntu or similar Linux distributions, Python comes pre-installed.
If that is not the case, you can install it like this:
sudo apt-get install software-properties-commonsudo add-apt-repository ppa:deadsnakes/ppasudo apt-get updatesudo apt-get install python3.8
*at the time of writing this article the Python 3.8 is the latest stable version and deadsnakes is recommended PPA to use.
On other operating systems like windows or mac, you are going to install it by downloading the executable installation and simply running it.
We also have to install the Tkinter library for development:
sudo apt-get install python3-tk
The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit.
At the beginning of our coding with importing the required libraries:
import tkinter
Once we imported them, we are able to use them in our code and usually, your code editor will be able to recognize keywords from those libraries and make typing easier for you as much as possible.
Next up is creating the window, that we will be using to add elements to and have as the main window of our GUI app.
window = tkinter.Tk()
Top-level widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter.
After you initialized the window all you have to do is call the main loop of Tk and it will execute all the commands you set for GUI.
window.mainloop()
Mainloop takes care of any events, like button clicks or text box entries that come after it from running until the window is closed.
Run your Python file using the command:
python3 GUI.py
Here is our first window!
This is just the beginning of our app and what we have to do next is customize our window!
Adding a title to our window is very simple:
window.title("Python GUI")
An important thing to note here is that every single command that we want to be executed for our window has to be before “window.mainloop()” because otherwise it won’t be shown in GUI.
Setting a specific window size is rather important because you might want more space for your elements that we are going to add later on!
Way to do it:
window.geometry("450x250")
The first part is width followed by separation as “x” and height number.
After setting basic window settings, we are ready to add elements to our GUI app.
There are different kinds of elements we could use here and that are provided to us by the Tkinter library, but we will focus on the four most essential to every GUI application.Those are: Label, Button, Entry(Input), and Text
In every GUI it is essential to create some sort of text display to the user that is using the program.
label = tkinter.Label(window, text="Some label text",width = 50)
We save our label under the variable named ‘variable’ and define it that it belongs to our main ‘window’, contains some text and it is possible to define extra parameters like width, etc.
An important step after defining the label we have to pack it and set it into the window. There is a function called pack() for exactly that:
label.pack()
This geometry manager organizes widgets in blocks before placing them in the parent widget.
We use buttons to execute some type of command or a backend functionality that our app might require.
Since we need some kind of function, we define ‘clicked’ to create a new label every time the button is clicked.
def clicked(): label = tkinter.Label(window, text="Button label",width = 50) label.pack()butt = tkinter.Button(window, text="Click button!", command=clicked,width = 10)butt.pack()
Every time you click the button, it will create a new object with a type Label, which will be displayed under the previous one.
This element is called Entry in Tkinkter library, but is also familiar under the term Text Box for many other programming languages.
Let’s see how we can implement it:
entry = tkinter.Entry(window, width=10)entry.pack()
Useful function of the Entry element is that we can retrieve what the user has written in it, but more about that in the example of the binary convertor.
Specialized Text Box, which is much more customizable than the regular Entry.
And here is how we use it:
text = tkinter.Text(window, width=20, height=5)text.insert(tkinter.INSERT, "Hello")text.insert(tkinter.END, "World")text.pack()
We have parameters like INSERT and END so we can specify the position of the text we want. For more information go here.
Once we are done with covering all the essential elements, let’s build an actually app with what we just learned.
We should create something that would make sense and is useful to us.
My first though is simple calculator so we can utilize all elements we were talking about during the tutorial.
Let’s take a look at the complete code I have written here:
We basically use all elements that we talked about and I crated simple Text and Entry manipulations inside the add and sub functions.
Every time you click to add two numbers, the Text element gets cleared and new value is inserted.There is also ValueError handling, which will catch anything else but numbers, which are fine.
Here is the complete code for both tutorial and calculator example.
github.com
That is all for today my beautiful people.
This is just a really simple GUI in Python, that in my opinion everyone is able to do If they follow along!
Although simple it is a very powerful software that could be used to create real world apps!
Stay creative and follow me for more tutorials like this one!
|
[
{
"code": null,
"e": 270,
"s": 172,
"text": "One of the most important parts of today's applications is GUI (Graphical User Interface) itself."
},
{
"code": null,
"e": 440,
"s": 270,
"text": "That is because the market is so competitive and oversaturated that it is not even about the functionality anymore, but who can make it look prettier and simpler to use."
},
{
"code": null,
"e": 564,
"s": 440,
"text": "Today we will be learning how to create and build GUI applications in one of the most popular programming languages Python."
},
{
"code": null,
"e": 730,
"s": 564,
"text": "This short tutorial will be explained line by line and will be very easy to follow although you might not have much experience with Python or programming in general."
},
{
"code": null,
"e": 881,
"s": 730,
"text": "For the development of this app, you will not need much, If you are already familiar with Python, you can skip until the next chapter of this article."
},
{
"code": null,
"e": 957,
"s": 881,
"text": "My personal choice for code and software development is Visual Studio Code."
},
{
"code": null,
"e": 1087,
"s": 957,
"text": "Next up we will need Python installed and so if you are on the Ubuntu or similar Linux distributions, Python comes pre-installed."
},
{
"code": null,
"e": 1142,
"s": 1087,
"text": "If that is not the case, you can install it like this:"
},
{
"code": null,
"e": 1281,
"s": 1142,
"text": "sudo apt-get install software-properties-commonsudo add-apt-repository ppa:deadsnakes/ppasudo apt-get updatesudo apt-get install python3.8"
},
{
"code": null,
"e": 1404,
"s": 1281,
"text": "*at the time of writing this article the Python 3.8 is the latest stable version and deadsnakes is recommended PPA to use."
},
{
"code": null,
"e": 1546,
"s": 1404,
"text": "On other operating systems like windows or mac, you are going to install it by downloading the executable installation and simply running it."
},
{
"code": null,
"e": 1607,
"s": 1546,
"text": "We also have to install the Tkinter library for development:"
},
{
"code": null,
"e": 1639,
"s": 1607,
"text": "sudo apt-get install python3-tk"
},
{
"code": null,
"e": 1732,
"s": 1639,
"text": "The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit."
},
{
"code": null,
"e": 1802,
"s": 1732,
"text": "At the beginning of our coding with importing the required libraries:"
},
{
"code": null,
"e": 1817,
"s": 1802,
"text": "import tkinter"
},
{
"code": null,
"e": 2014,
"s": 1817,
"text": "Once we imported them, we are able to use them in our code and usually, your code editor will be able to recognize keywords from those libraries and make typing easier for you as much as possible."
},
{
"code": null,
"e": 2131,
"s": 2014,
"text": "Next up is creating the window, that we will be using to add elements to and have as the main window of our GUI app."
},
{
"code": null,
"e": 2153,
"s": 2131,
"text": "window = tkinter.Tk()"
},
{
"code": null,
"e": 2273,
"s": 2153,
"text": "Top-level widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter."
},
{
"code": null,
"e": 2407,
"s": 2273,
"text": "After you initialized the window all you have to do is call the main loop of Tk and it will execute all the commands you set for GUI."
},
{
"code": null,
"e": 2425,
"s": 2407,
"text": "window.mainloop()"
},
{
"code": null,
"e": 2559,
"s": 2425,
"text": "Mainloop takes care of any events, like button clicks or text box entries that come after it from running until the window is closed."
},
{
"code": null,
"e": 2599,
"s": 2559,
"text": "Run your Python file using the command:"
},
{
"code": null,
"e": 2614,
"s": 2599,
"text": "python3 GUI.py"
},
{
"code": null,
"e": 2640,
"s": 2614,
"text": "Here is our first window!"
},
{
"code": null,
"e": 2731,
"s": 2640,
"text": "This is just the beginning of our app and what we have to do next is customize our window!"
},
{
"code": null,
"e": 2776,
"s": 2731,
"text": "Adding a title to our window is very simple:"
},
{
"code": null,
"e": 2803,
"s": 2776,
"text": "window.title(\"Python GUI\")"
},
{
"code": null,
"e": 2988,
"s": 2803,
"text": "An important thing to note here is that every single command that we want to be executed for our window has to be before “window.mainloop()” because otherwise it won’t be shown in GUI."
},
{
"code": null,
"e": 3126,
"s": 2988,
"text": "Setting a specific window size is rather important because you might want more space for your elements that we are going to add later on!"
},
{
"code": null,
"e": 3140,
"s": 3126,
"text": "Way to do it:"
},
{
"code": null,
"e": 3167,
"s": 3140,
"text": "window.geometry(\"450x250\")"
},
{
"code": null,
"e": 3240,
"s": 3167,
"text": "The first part is width followed by separation as “x” and height number."
},
{
"code": null,
"e": 3322,
"s": 3240,
"text": "After setting basic window settings, we are ready to add elements to our GUI app."
},
{
"code": null,
"e": 3549,
"s": 3322,
"text": "There are different kinds of elements we could use here and that are provided to us by the Tkinter library, but we will focus on the four most essential to every GUI application.Those are: Label, Button, Entry(Input), and Text"
},
{
"code": null,
"e": 3653,
"s": 3549,
"text": "In every GUI it is essential to create some sort of text display to the user that is using the program."
},
{
"code": null,
"e": 3718,
"s": 3653,
"text": "label = tkinter.Label(window, text=\"Some label text\",width = 50)"
},
{
"code": null,
"e": 3906,
"s": 3718,
"text": "We save our label under the variable named ‘variable’ and define it that it belongs to our main ‘window’, contains some text and it is possible to define extra parameters like width, etc."
},
{
"code": null,
"e": 4048,
"s": 3906,
"text": "An important step after defining the label we have to pack it and set it into the window. There is a function called pack() for exactly that:"
},
{
"code": null,
"e": 4061,
"s": 4048,
"text": "label.pack()"
},
{
"code": null,
"e": 4153,
"s": 4061,
"text": "This geometry manager organizes widgets in blocks before placing them in the parent widget."
},
{
"code": null,
"e": 4255,
"s": 4153,
"text": "We use buttons to execute some type of command or a backend functionality that our app might require."
},
{
"code": null,
"e": 4368,
"s": 4255,
"text": "Since we need some kind of function, we define ‘clicked’ to create a new label every time the button is clicked."
},
{
"code": null,
"e": 4550,
"s": 4368,
"text": "def clicked(): label = tkinter.Label(window, text=\"Button label\",width = 50) label.pack()butt = tkinter.Button(window, text=\"Click button!\", command=clicked,width = 10)butt.pack()"
},
{
"code": null,
"e": 4678,
"s": 4550,
"text": "Every time you click the button, it will create a new object with a type Label, which will be displayed under the previous one."
},
{
"code": null,
"e": 4811,
"s": 4678,
"text": "This element is called Entry in Tkinkter library, but is also familiar under the term Text Box for many other programming languages."
},
{
"code": null,
"e": 4846,
"s": 4811,
"text": "Let’s see how we can implement it:"
},
{
"code": null,
"e": 4898,
"s": 4846,
"text": "entry = tkinter.Entry(window, width=10)entry.pack()"
},
{
"code": null,
"e": 5052,
"s": 4898,
"text": "Useful function of the Entry element is that we can retrieve what the user has written in it, but more about that in the example of the binary convertor."
},
{
"code": null,
"e": 5130,
"s": 5052,
"text": "Specialized Text Box, which is much more customizable than the regular Entry."
},
{
"code": null,
"e": 5157,
"s": 5130,
"text": "And here is how we use it:"
},
{
"code": null,
"e": 5285,
"s": 5157,
"text": "text = tkinter.Text(window, width=20, height=5)text.insert(tkinter.INSERT, \"Hello\")text.insert(tkinter.END, \"World\")text.pack()"
},
{
"code": null,
"e": 5406,
"s": 5285,
"text": "We have parameters like INSERT and END so we can specify the position of the text we want. For more information go here."
},
{
"code": null,
"e": 5520,
"s": 5406,
"text": "Once we are done with covering all the essential elements, let’s build an actually app with what we just learned."
},
{
"code": null,
"e": 5590,
"s": 5520,
"text": "We should create something that would make sense and is useful to us."
},
{
"code": null,
"e": 5701,
"s": 5590,
"text": "My first though is simple calculator so we can utilize all elements we were talking about during the tutorial."
},
{
"code": null,
"e": 5761,
"s": 5701,
"text": "Let’s take a look at the complete code I have written here:"
},
{
"code": null,
"e": 5895,
"s": 5761,
"text": "We basically use all elements that we talked about and I crated simple Text and Entry manipulations inside the add and sub functions."
},
{
"code": null,
"e": 6087,
"s": 5895,
"text": "Every time you click to add two numbers, the Text element gets cleared and new value is inserted.There is also ValueError handling, which will catch anything else but numbers, which are fine."
},
{
"code": null,
"e": 6155,
"s": 6087,
"text": "Here is the complete code for both tutorial and calculator example."
},
{
"code": null,
"e": 6166,
"s": 6155,
"text": "github.com"
},
{
"code": null,
"e": 6209,
"s": 6166,
"text": "That is all for today my beautiful people."
},
{
"code": null,
"e": 6317,
"s": 6209,
"text": "This is just a really simple GUI in Python, that in my opinion everyone is able to do If they follow along!"
},
{
"code": null,
"e": 6410,
"s": 6317,
"text": "Although simple it is a very powerful software that could be used to create real world apps!"
}
] |
Conversion Functions in SQL
|
There may be times when the SQL query was expecting some data type but it got another. In that case type conversion is done by SQL. This is implicit type conversion. However, sometimes the programmer explicitly converts one data type into another in a query. This is known as explicit type conversion. Both of these in detail are given as follows:
In implicit data type conversion, the SQL programmer does not specify anything. Rather the system converts one type of data to another as per its requirements. For example - a numeric data type can be converted to character if required and vice versa.
Implicit DataType Conversion only occurs if the data types used in the query are valid so that the system can recognise them and convert them as required. This is not possible with invalid or wrongly provided data types.
If the programmer wants,they can explicitly convert data types from one form to another. There are SQL functions provided for this express purpose. These SQL functions are −
This function is used to explicitly convert a number or date data type to char.
The syntax of this function is given as follows −
TO_CHAR(number,format,parameters)
This function changes number to char with the specific format as provided according to the syntax. The parameters can be used to specify decimal characters, group separators etc.
For example −
SELECT CHAR(sysdate, “Month DD,YYYY”) FROM DUAL;
This returns the system date in the form of 31 July, 2018
This function is used to explicitly convert a string to number. If the string to be converted does not contain numeric characters then TO_NUMBER shows an error.
The syntax of this function is given as follows −
TO_NUMBER(number,format,parameters)
This function changes the given string to number with the specific format as provided according to the syntax.
The parameters and format are optional so to convert a string to a number
For example,
TO_NUMBER (‘353.78’);
This returns the string 353.78 in numerical format.
This function takes character values and returns the output in the date format.
The syntax of this function is given as follows −
TO_DATE(number, format, parameters)
This function changes the given string to number with the specific format as provided according to the syntax.
SELECT TO_DATE(‘2018/07/31’,’yyyy/mm/dd’) FROM DUAL;
This takes the values in character format and returns them in date format as specified.
|
[
{
"code": null,
"e": 1410,
"s": 1062,
"text": "There may be times when the SQL query was expecting some data type but it got another. In that case type conversion is done by SQL. This is implicit type conversion. However, sometimes the programmer explicitly converts one data type into another in a query. This is known as explicit type conversion. Both of these in detail are given as follows:"
},
{
"code": null,
"e": 1662,
"s": 1410,
"text": "In implicit data type conversion, the SQL programmer does not specify anything. Rather the system converts one type of data to another as per its requirements. For example - a numeric data type can be converted to character if required and vice versa."
},
{
"code": null,
"e": 1883,
"s": 1662,
"text": "Implicit DataType Conversion only occurs if the data types used in the query are valid so that the system can recognise them and convert them as required. This is not possible with invalid or wrongly provided data types."
},
{
"code": null,
"e": 2058,
"s": 1883,
"text": "If the programmer wants,they can explicitly convert data types from one form to another. There are SQL functions provided for this express purpose. These SQL functions are −"
},
{
"code": null,
"e": 2138,
"s": 2058,
"text": "This function is used to explicitly convert a number or date data type to char."
},
{
"code": null,
"e": 2188,
"s": 2138,
"text": "The syntax of this function is given as follows −"
},
{
"code": null,
"e": 2222,
"s": 2188,
"text": "TO_CHAR(number,format,parameters)"
},
{
"code": null,
"e": 2401,
"s": 2222,
"text": "This function changes number to char with the specific format as provided according to the syntax. The parameters can be used to specify decimal characters, group separators etc."
},
{
"code": null,
"e": 2415,
"s": 2401,
"text": "For example −"
},
{
"code": null,
"e": 2464,
"s": 2415,
"text": "SELECT CHAR(sysdate, “Month DD,YYYY”) FROM DUAL;"
},
{
"code": null,
"e": 2522,
"s": 2464,
"text": "This returns the system date in the form of 31 July, 2018"
},
{
"code": null,
"e": 2683,
"s": 2522,
"text": "This function is used to explicitly convert a string to number. If the string to be converted does not contain numeric characters then TO_NUMBER shows an error."
},
{
"code": null,
"e": 2733,
"s": 2683,
"text": "The syntax of this function is given as follows −"
},
{
"code": null,
"e": 2769,
"s": 2733,
"text": "TO_NUMBER(number,format,parameters)"
},
{
"code": null,
"e": 2880,
"s": 2769,
"text": "This function changes the given string to number with the specific format as provided according to the syntax."
},
{
"code": null,
"e": 2954,
"s": 2880,
"text": "The parameters and format are optional so to convert a string to a number"
},
{
"code": null,
"e": 2967,
"s": 2954,
"text": "For example,"
},
{
"code": null,
"e": 2989,
"s": 2967,
"text": "TO_NUMBER (‘353.78’);"
},
{
"code": null,
"e": 3041,
"s": 2989,
"text": "This returns the string 353.78 in numerical format."
},
{
"code": null,
"e": 3121,
"s": 3041,
"text": "This function takes character values and returns the output in the date format."
},
{
"code": null,
"e": 3171,
"s": 3121,
"text": "The syntax of this function is given as follows −"
},
{
"code": null,
"e": 3207,
"s": 3171,
"text": "TO_DATE(number, format, parameters)"
},
{
"code": null,
"e": 3318,
"s": 3207,
"text": "This function changes the given string to number with the specific format as provided according to the syntax."
},
{
"code": null,
"e": 3371,
"s": 3318,
"text": "SELECT TO_DATE(‘2018/07/31’,’yyyy/mm/dd’) FROM DUAL;"
},
{
"code": null,
"e": 3459,
"s": 3371,
"text": "This takes the values in character format and returns them in date format as specified."
}
] |
Disarium Number | Practice | GeeksforGeeks
|
Given a number N, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself. Output 1 if it's Disarium, and 0 if not.
Example 1:
Input:
N = 89
Output:
1
Explanation:
8^1+9^2 = 89 thus output is 1.
Example 2:
Input:
N = 81
Output:
0
Explanation:
8^1+1^2 = 9 thus output is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isDisarium() which takes an Integer N as input and returns the answer.
Expected Time Complexity: O(log(N))
Expected Auxiliary Space: O(1)
Constraints:
0 <= N <= 108
0
ayushnautiyal11103 months ago
C++ Implementation:)
Time 0.0/1.5
int isDisarium(int N) { string n=to_string(N); int res=0; for(int i=0;i<n.length();i++){ int m=n[i]-'0'; res+=pow(m,i+1); } return res==N?1:0; }
+1
pketul22125 months ago
class Solution {
static int isDisarium(int N) {
int k = N, sum = 0, count = 0;
while(k != 0) {
count++;
k /= 10;
}
k = N;
while(k != 0) {
sum += Math.pow((k % 10), count);
k /= 10;
count--;
}
if(sum == N)
return 1;
return 0;
}
}
0
Ashutosh Patel8 months ago
Ashutosh Patel
//Straight forward/simple approach --> count the no. of digits-->Summation of digits^power(count) from last ---> decrement count.//Code in C++//int isDisarium(int N) { int count=0; int num=N,n=N; while(N!=0){ count++; N=N/10; } int sum=0; while(n!=0){ int rem=n%10; sum=sum+pow(rem,count); count--; n=n/10; } if(sum==num) return 1; else return 0; }
0
Nitin Gangwar9 months ago
Nitin Gangwar
def isDisarium(self, N): # code here sum=0 j=1 s=str(N) for i in s: sum+=pow(int(i),j) j+=1 if(sum==N): return 1 return 0
0
martial9 months ago
martial
https://uploads.disquscdn.c... https://uploads.disquscdn.c...
0
Raushan Kumar10 months ago
Raushan Kumar
class Solution { static int isDisarium(int N) { // code here int sum=0; int temp=N; int v=N; int count=0; int i=1; while(temp!=0) { count++; temp/=10; } // System.out.println(count); while(count!=0){ count-=1; int m=(int)(v/(Math.pow(10,count))); v=(int)(v%(Math.pow(10,count))); // System.out.print(v+" "); sum=(int)(sum+Math.pow(m,i)); i++;
} // System.out.println(sum); if(N==sum) return 1; else return 0; }};
0
Gurucharan Rajput1 year ago
Gurucharan Rajput
java simple solution
static int isDisarium(int N) { int c=0; int y,res; int num = N; int temp=N;; int sum = 0; while(N>0) { res=N%10; c++; N/=10; }
while(num > 0) { y=num%10; sum =(int)(sum+Math.pow(y,c)); c--; num /= 10; }
return sum == temp ? 1 : 0; }};
0
Annanya Mathur1 year ago
Annanya Mathur
int isDisarium(int n) { int c=floor(log10(n)+1); int num=n,s=0; while(num) { s+=pow((num%10),c--); num=num/10; } return s==n; }
0
Drigger1 year ago
Drigger
Sol in Java: https://ide.geeksforgeeks.o...
0
Myron Dsilva1 year ago
Myron Dsilva
cop=N l=0 while(cop!=0): r=cop%10 l=l+1 cop=cop//10 copy=N dis=0 while(copy>0): rem=copy%10 dis=dis+int(rem**l) l=l-1 copy=copy//10 if(dis==N): return 1 else: return 0
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": 448,
"s": 238,
"text": "Given a number N, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself. Output 1 if it's Disarium, and 0 if not."
},
{
"code": null,
"e": 461,
"s": 450,
"text": "Example 1:"
},
{
"code": null,
"e": 529,
"s": 461,
"text": "Input:\nN = 89\nOutput:\n1\nExplanation:\n8^1+9^2 = 89 thus output is 1."
},
{
"code": null,
"e": 540,
"s": 529,
"text": "Example 2:"
},
{
"code": null,
"e": 608,
"s": 540,
"text": "Input:\nN = 81\nOutput:\n0\nExplanation:\n8^1+1^2 = 9 thus output is 0. "
},
{
"code": null,
"e": 778,
"s": 610,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isDisarium() which takes an Integer N as input and returns the answer."
},
{
"code": null,
"e": 847,
"s": 780,
"text": "Expected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 876,
"s": 849,
"text": "Constraints:\n0 <= N <= 108"
},
{
"code": null,
"e": 878,
"s": 876,
"text": "0"
},
{
"code": null,
"e": 908,
"s": 878,
"text": "ayushnautiyal11103 months ago"
},
{
"code": null,
"e": 929,
"s": 908,
"text": "C++ Implementation:)"
},
{
"code": null,
"e": 942,
"s": 929,
"text": "Time 0.0/1.5"
},
{
"code": null,
"e": 1141,
"s": 944,
"text": "int isDisarium(int N) { string n=to_string(N); int res=0; for(int i=0;i<n.length();i++){ int m=n[i]-'0'; res+=pow(m,i+1); } return res==N?1:0; }"
},
{
"code": null,
"e": 1144,
"s": 1141,
"text": "+1"
},
{
"code": null,
"e": 1167,
"s": 1144,
"text": "pketul22125 months ago"
},
{
"code": null,
"e": 1585,
"s": 1167,
"text": "class Solution {\n static int isDisarium(int N) {\n \n int k = N, sum = 0, count = 0;\n \n while(k != 0) {\n count++;\n k /= 10;\n }\n \n k = N;\n \n while(k != 0) {\n sum += Math.pow((k % 10), count);\n k /= 10;\n count--;\n }\n \n if(sum == N)\n return 1;\n return 0;\n }\n}"
},
{
"code": null,
"e": 1587,
"s": 1585,
"text": "0"
},
{
"code": null,
"e": 1614,
"s": 1587,
"text": "Ashutosh Patel8 months ago"
},
{
"code": null,
"e": 1629,
"s": 1614,
"text": "Ashutosh Patel"
},
{
"code": null,
"e": 2120,
"s": 1629,
"text": "//Straight forward/simple approach --> count the no. of digits-->Summation of digits^power(count) from last ---> decrement count.//Code in C++//int isDisarium(int N) { int count=0; int num=N,n=N; while(N!=0){ count++; N=N/10; } int sum=0; while(n!=0){ int rem=n%10; sum=sum+pow(rem,count); count--; n=n/10; } if(sum==num) return 1; else return 0; }"
},
{
"code": null,
"e": 2122,
"s": 2120,
"text": "0"
},
{
"code": null,
"e": 2148,
"s": 2122,
"text": "Nitin Gangwar9 months ago"
},
{
"code": null,
"e": 2162,
"s": 2148,
"text": "Nitin Gangwar"
},
{
"code": null,
"e": 2368,
"s": 2162,
"text": "def isDisarium(self, N): # code here sum=0 j=1 s=str(N) for i in s: sum+=pow(int(i),j) j+=1 if(sum==N): return 1 return 0"
},
{
"code": null,
"e": 2370,
"s": 2368,
"text": "0"
},
{
"code": null,
"e": 2390,
"s": 2370,
"text": "martial9 months ago"
},
{
"code": null,
"e": 2398,
"s": 2390,
"text": "martial"
},
{
"code": null,
"e": 2460,
"s": 2398,
"text": "https://uploads.disquscdn.c... https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2462,
"s": 2460,
"text": "0"
},
{
"code": null,
"e": 2489,
"s": 2462,
"text": "Raushan Kumar10 months ago"
},
{
"code": null,
"e": 2503,
"s": 2489,
"text": "Raushan Kumar"
},
{
"code": null,
"e": 2994,
"s": 2503,
"text": "class Solution { static int isDisarium(int N) { // code here int sum=0; int temp=N; int v=N; int count=0; int i=1; while(temp!=0) { count++; temp/=10; } // System.out.println(count); while(count!=0){ count-=1; int m=(int)(v/(Math.pow(10,count))); v=(int)(v%(Math.pow(10,count))); // System.out.print(v+\" \"); sum=(int)(sum+Math.pow(m,i)); i++;"
},
{
"code": null,
"e": 3133,
"s": 2994,
"text": " } // System.out.println(sum); if(N==sum) return 1; else return 0; }};"
},
{
"code": null,
"e": 3135,
"s": 3133,
"text": "0"
},
{
"code": null,
"e": 3163,
"s": 3135,
"text": "Gurucharan Rajput1 year ago"
},
{
"code": null,
"e": 3181,
"s": 3163,
"text": "Gurucharan Rajput"
},
{
"code": null,
"e": 3202,
"s": 3181,
"text": "java simple solution"
},
{
"code": null,
"e": 3414,
"s": 3202,
"text": "static int isDisarium(int N) { int c=0; int y,res; int num = N; int temp=N;; int sum = 0; while(N>0) { res=N%10; c++; N/=10; }"
},
{
"code": null,
"e": 3557,
"s": 3414,
"text": " while(num > 0) { y=num%10; sum =(int)(sum+Math.pow(y,c)); c--; num /= 10; }"
},
{
"code": null,
"e": 3600,
"s": 3557,
"text": " return sum == temp ? 1 : 0; }};"
},
{
"code": null,
"e": 3602,
"s": 3600,
"text": "0"
},
{
"code": null,
"e": 3627,
"s": 3602,
"text": "Annanya Mathur1 year ago"
},
{
"code": null,
"e": 3642,
"s": 3627,
"text": "Annanya Mathur"
},
{
"code": null,
"e": 3837,
"s": 3642,
"text": "int isDisarium(int n) { int c=floor(log10(n)+1); int num=n,s=0; while(num) { s+=pow((num%10),c--); num=num/10; } return s==n; }"
},
{
"code": null,
"e": 3839,
"s": 3837,
"text": "0"
},
{
"code": null,
"e": 3857,
"s": 3839,
"text": "Drigger1 year ago"
},
{
"code": null,
"e": 3865,
"s": 3857,
"text": "Drigger"
},
{
"code": null,
"e": 3909,
"s": 3865,
"text": "Sol in Java: https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3911,
"s": 3909,
"text": "0"
},
{
"code": null,
"e": 3934,
"s": 3911,
"text": "Myron Dsilva1 year ago"
},
{
"code": null,
"e": 3947,
"s": 3934,
"text": "Myron Dsilva"
},
{
"code": null,
"e": 4272,
"s": 3947,
"text": " cop=N l=0 while(cop!=0): r=cop%10 l=l+1 cop=cop//10 copy=N dis=0 while(copy>0): rem=copy%10 dis=dis+int(rem**l) l=l-1 copy=copy//10 if(dis==N): return 1 else: return 0"
},
{
"code": null,
"e": 4418,
"s": 4272,
"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": 4454,
"s": 4418,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4464,
"s": 4454,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4474,
"s": 4464,
"text": "\nContest\n"
},
{
"code": null,
"e": 4537,
"s": 4474,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4685,
"s": 4537,
"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": 4893,
"s": 4685,
"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": 4999,
"s": 4893,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to determine the user IP address using node.js ? - GeeksforGeeks
|
05 Feb, 2021
Node.js is an open-source, back-end JavaScript runtime environment that runs on the web engine and executes JavaScript code. There are various platforms such as Windows, Linux, Mac OS where Node.js can run. The Domain Name System is a hierarchical and decentralized naming system for computers etc that are connected to the Internet. To find the IP address of the user in Node.js we use dns.lookup() method of dns module.
dns.lookup() function:
dns.lookup(hostname[, options], callback)
Parameters:
Hostname: It consists website link which is valid or active.Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error.
Hostname: It consists website link which is valid or active.
Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.
Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error.
Approach to determine IP address:
Import dns module in the node.js file.Use dns.lookup() function to search for addresses and family of the client.Display address and family.
Import dns module in the node.js file.
Use dns.lookup() function to search for addresses and family of the client.
Display address and family.
Implementation:
index.js
// Import fileconst dns = require('dns'); // dns.lookup() function searches// for user IP address and family// if there is no errordns.lookup('www.geeksforgeeks.org', (err, addresses, family) => { // Print the address found of user console.log('addresses:', addresses); // Print the family found of user console.log('family:', family);});
Run index.js file using the below command:
node client_ip.js
Output:
Reference:https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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": 24531,
"s": 24503,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 24954,
"s": 24531,
"text": "Node.js is an open-source, back-end JavaScript runtime environment that runs on the web engine and executes JavaScript code. There are various platforms such as Windows, Linux, Mac OS where Node.js can run. The Domain Name System is a hierarchical and decentralized naming system for computers etc that are connected to the Internet. To find the IP address of the user in Node.js we use dns.lookup() method of dns module."
},
{
"code": null,
"e": 24977,
"s": 24954,
"text": "dns.lookup() function:"
},
{
"code": null,
"e": 25019,
"s": 24977,
"text": "dns.lookup(hostname[, options], callback)"
},
{
"code": null,
"e": 25031,
"s": 25019,
"text": "Parameters:"
},
{
"code": null,
"e": 25267,
"s": 25031,
"text": "Hostname: It consists website link which is valid or active.Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error."
},
{
"code": null,
"e": 25328,
"s": 25267,
"text": "Hostname: It consists website link which is valid or active."
},
{
"code": null,
"e": 25417,
"s": 25328,
"text": "Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses."
},
{
"code": null,
"e": 25505,
"s": 25417,
"text": "Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error."
},
{
"code": null,
"e": 25539,
"s": 25505,
"text": "Approach to determine IP address:"
},
{
"code": null,
"e": 25680,
"s": 25539,
"text": "Import dns module in the node.js file.Use dns.lookup() function to search for addresses and family of the client.Display address and family."
},
{
"code": null,
"e": 25719,
"s": 25680,
"text": "Import dns module in the node.js file."
},
{
"code": null,
"e": 25795,
"s": 25719,
"text": "Use dns.lookup() function to search for addresses and family of the client."
},
{
"code": null,
"e": 25823,
"s": 25795,
"text": "Display address and family."
},
{
"code": null,
"e": 25839,
"s": 25823,
"text": "Implementation:"
},
{
"code": null,
"e": 25848,
"s": 25839,
"text": "index.js"
},
{
"code": "// Import fileconst dns = require('dns'); // dns.lookup() function searches// for user IP address and family// if there is no errordns.lookup('www.geeksforgeeks.org', (err, addresses, family) => { // Print the address found of user console.log('addresses:', addresses); // Print the family found of user console.log('family:', family);});",
"e": 26206,
"s": 25848,
"text": null
},
{
"code": null,
"e": 26250,
"s": 26206,
"text": "Run index.js file using the below command:"
},
{
"code": null,
"e": 26268,
"s": 26250,
"text": "node client_ip.js"
},
{
"code": null,
"e": 26276,
"s": 26268,
"text": "Output:"
},
{
"code": null,
"e": 26359,
"s": 26276,
"text": "Reference:https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback"
},
{
"code": null,
"e": 26366,
"s": 26359,
"text": "Picked"
},
{
"code": null,
"e": 26390,
"s": 26366,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26398,
"s": 26390,
"text": "Node.js"
},
{
"code": null,
"e": 26417,
"s": 26398,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26434,
"s": 26417,
"text": "Web Technologies"
},
{
"code": null,
"e": 26532,
"s": 26434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26541,
"s": 26532,
"text": "Comments"
},
{
"code": null,
"e": 26554,
"s": 26541,
"text": "Old Comments"
},
{
"code": null,
"e": 26611,
"s": 26554,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 26650,
"s": 26611,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 26677,
"s": 26650,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 26708,
"s": 26677,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 26783,
"s": 26708,
"text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?"
},
{
"code": null,
"e": 26839,
"s": 26783,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26901,
"s": 26839,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26944,
"s": 26901,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26994,
"s": 26944,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Can we call methods of the superclass from a static method in java?
|
Inheritance can be defined as the process where one (parent/super) class acquires the properties (methods and fields) of another (child/sub). With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties is known as a subclass and the class whose properties are inherited is called superclass. In short, in inheritance, you can access the members (variables and methods) of the superclass using the subclass object.
Live Demo
class SuperClass {
public void display(){
System.out.println("Hello this is the method of the superclass");
}
}
public class SubClass extends SuperClass {
public void greet(){
System.out.println("Hello this is the method of the subclass");
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.display();
obj.greet();
}
}
Hello this is the method of the superclass
Hello this is the method of the subclass
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
Live Demo
class SuperClass{
public void display() {
System.out.println("This is a static method of the superclass");
}
}
public class SubClass extends SuperClass{
public static void main(String args[]){
//Calling methods of the superclass
new SuperClass().display(); //superclass constructor
new SubClass().display(); //subclass constructor
}
}
This is a static method of the superclass
This is a static method of the superclass
|
[
{
"code": null,
"e": 1546,
"s": 1062,
"text": "Inheritance can be defined as the process where one (parent/super) class acquires the properties (methods and fields) of another (child/sub). With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties is known as a subclass and the class whose properties are inherited is called superclass. In short, in inheritance, you can access the members (variables and methods) of the superclass using the subclass object."
},
{
"code": null,
"e": 1557,
"s": 1546,
"text": " Live Demo"
},
{
"code": null,
"e": 1950,
"s": 1557,
"text": "class SuperClass {\n public void display(){\n System.out.println(\"Hello this is the method of the superclass\");\n }\n}\npublic class SubClass extends SuperClass {\n public void greet(){\n System.out.println(\"Hello this is the method of the subclass\");\n }\n public static void main(String args[]){\n SubClass obj = new SubClass();\n obj.display();\n obj.greet();\n }\n}"
},
{
"code": null,
"e": 2034,
"s": 1950,
"text": "Hello this is the method of the superclass\nHello this is the method of the subclass"
},
{
"code": null,
"e": 2182,
"s": 2034,
"text": "Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass)."
},
{
"code": null,
"e": 2193,
"s": 2182,
"text": " Live Demo"
},
{
"code": null,
"e": 2564,
"s": 2193,
"text": "class SuperClass{\n public void display() {\n System.out.println(\"This is a static method of the superclass\");\n }\n}\npublic class SubClass extends SuperClass{\n public static void main(String args[]){\n //Calling methods of the superclass\n new SuperClass().display(); //superclass constructor\n new SubClass().display(); //subclass constructor\n }\n}"
},
{
"code": null,
"e": 2648,
"s": 2564,
"text": "This is a static method of the superclass\nThis is a static method of the superclass"
}
] |
3-way Merge Sort in C++
|
Merge sort involves recursively dividing the array into 2 parts, sorting and finally merging them. A variant of merge sort is treated as 3-way merge sort where instead of dividing the array into 2 parts we divide it into 3 parts.
Merge sort breaks down the arrays to subarrays of size half in recursive manner. In the same way, 3-way Merge sort breaks down the arrays to subarrays of size one third.
Input : 46, -1, -44, 79, 31, -41, 11, 20 , 74, 94
Output : -44 -41 -1 11 20 31 46 74 79 94
Input : 24, -18
Output : -18 24
The time complexity of 3 way merge sort is nlog3n.
// C++ Program for performing 3 way Merge Sort
#include <bits/stdc++.h>
usingnamespacestd;
voidmerge1(intgArray1[], intlow1, intmid1,
intmid2, inthigh1, intdestArray1[]){
inti = low1, j = mid1, k = mid2, l = low1;
// choose smaller of the smallest in the three ranges
while((i < mid1) && (j < mid2) && (k < high1)){
if(gArray1[i] < gArray1[j]){
if(gArray1[i] < gArray1[k]){
destArray1[l++] = gArray1[i++];
}
else{
destArray1[l++] = gArray1[k++];
}
}
else{
if(gArray1[j] < gArray1[k]){
destArray1[l++] = gArray1[j++];
}
else{
destArray1[l++] = gArray1[k++];
}
}
}
while((i < mid1) && (j < mid2)){
if(gArray1[i] < gArray1[j]){
destArray1[l++] = gArray1[i++];
}
else{
destArray1[l++] = gArray1[j++];
}
}
while((j < mid2) && (k < high1)){
if(gArray1[j] < gArray1[k]){
destArray1[l++] = gArray1[j++];
}
else{
destArray1[l++] = gArray1[k++];
}
}
while((i < mid1) && (k < high1)){
if(gArray1[i] < gArray1[k]){
destArray1[l++] = gArray1[i++];
}
else{
destArray1[l++] = gArray1[k++];
}
}
while(i < mid1)
destArray1[l++] = gArray1[i++];
while(j < mid2)
destArray1[l++] = gArray1[j++];
while(k < high)
destArray1[l++] = gArray1[k++];
}
voidmergeSort3WayRec(intgArray1[], intlow1,
inthigh1, intdestArray1[]){
if(high1 - low1 < 2)
return;
intmid1 = low1 + ((high1 - low1) / 3);
intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1;
mergeSort3WayRec(destArray1, low1, mid1, gArray1);
mergeSort3WayRec(destArray1, mid1, mid2, gArray1);
mergeSort3WayRec(destArray1, mid2, high1, gArray1);
merge(destArray1, low1, mid1, mid2, high1, gArray1);
}
voidmergeSort3Way(intgArray1[], intn1){
if(n1 == 0)
return;
intfArray1[n];
for(inti = 0; i < n1; i++)
fArray1[i] = gArray1[i];
// sort function
mergeSort3WayRec(fArray1, 0, n, gArray1);
for(inti = 0; i < n1; i++)
gArray1[i] = fArray1[i];
}
// Driver Code
intmain(){
intdata1[] = {46, -1, -44, 79, 31,
-41, 11, 20, 74, 94};
mergeSort3Way(data1,10);
cout<< "After 3 way merge sort: ";
for(inti = 0; i < 10; i++){
cout<< data1[i] << " ";
}
return0;
}
After 3 way merge sort: -44 -41 -1 11 20 31 46 74 79 94
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "Merge sort involves recursively dividing the array into 2 parts, sorting and finally merging them. A variant of merge sort is treated as 3-way merge sort where instead of dividing the array into 2 parts we divide it into 3 parts."
},
{
"code": null,
"e": 1462,
"s": 1292,
"text": "Merge sort breaks down the arrays to subarrays of size half in recursive manner. In the same way, 3-way Merge sort breaks down the arrays to subarrays of size one third."
},
{
"code": null,
"e": 1586,
"s": 1462,
"text": "Input : 46, -1, -44, 79, 31, -41, 11, 20 , 74, 94\nOutput : -44 -41 -1 11 20 31 46 74 79 94\n\nInput : 24, -18\nOutput : -18 24"
},
{
"code": null,
"e": 1637,
"s": 1586,
"text": "The time complexity of 3 way merge sort is nlog3n."
},
{
"code": null,
"e": 3939,
"s": 1637,
"text": "// C++ Program for performing 3 way Merge Sort\n#include <bits/stdc++.h>\nusingnamespacestd;\nvoidmerge1(intgArray1[], intlow1, intmid1,\nintmid2, inthigh1, intdestArray1[]){\n inti = low1, j = mid1, k = mid2, l = low1;\n // choose smaller of the smallest in the three ranges\n while((i < mid1) && (j < mid2) && (k < high1)){\n if(gArray1[i] < gArray1[j]){\n if(gArray1[i] < gArray1[k]){\n destArray1[l++] = gArray1[i++];\n }\n else{\n destArray1[l++] = gArray1[k++];\n }\n }\n else{\n if(gArray1[j] < gArray1[k]){\n destArray1[l++] = gArray1[j++];\n }\n else{\n destArray1[l++] = gArray1[k++];\n }\n }\n}\nwhile((i < mid1) && (j < mid2)){\n if(gArray1[i] < gArray1[j]){\n destArray1[l++] = gArray1[i++];\n }\n else{\n destArray1[l++] = gArray1[j++];\n }\n}\nwhile((j < mid2) && (k < high1)){\n if(gArray1[j] < gArray1[k]){\n destArray1[l++] = gArray1[j++];\n}\nelse{\n destArray1[l++] = gArray1[k++];\n }\n}\nwhile((i < mid1) && (k < high1)){\n if(gArray1[i] < gArray1[k]){\n destArray1[l++] = gArray1[i++];\n }\n else{\n destArray1[l++] = gArray1[k++];\n }\n }\n while(i < mid1)\n destArray1[l++] = gArray1[i++];\n while(j < mid2)\n destArray1[l++] = gArray1[j++];\n while(k < high)\n destArray1[l++] = gArray1[k++];\n}\nvoidmergeSort3WayRec(intgArray1[], intlow1,\ninthigh1, intdestArray1[]){\n if(high1 - low1 < 2)\n return;\n intmid1 = low1 + ((high1 - low1) / 3);\n intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1;\n mergeSort3WayRec(destArray1, low1, mid1, gArray1);\n mergeSort3WayRec(destArray1, mid1, mid2, gArray1);\n mergeSort3WayRec(destArray1, mid2, high1, gArray1);\n merge(destArray1, low1, mid1, mid2, high1, gArray1);\n}\nvoidmergeSort3Way(intgArray1[], intn1){\n if(n1 == 0)\n return;\n intfArray1[n];\n for(inti = 0; i < n1; i++)\n fArray1[i] = gArray1[i];\n // sort function\n mergeSort3WayRec(fArray1, 0, n, gArray1);\n for(inti = 0; i < n1; i++)\n gArray1[i] = fArray1[i];\n}\n// Driver Code\nintmain(){\n intdata1[] = {46, -1, -44, 79, 31,\n -41, 11, 20, 74, 94};\n mergeSort3Way(data1,10);\n cout<< \"After 3 way merge sort: \";\n for(inti = 0; i < 10; i++){\n cout<< data1[i] << \" \";\n }\n return0;\n}"
},
{
"code": null,
"e": 3995,
"s": 3939,
"text": "After 3 way merge sort: -44 -41 -1 11 20 31 46 74 79 94"
}
] |
Modelling Coronavirus: Beyond the SIR Model | Towards Data Science
|
My last article explains the background and provides an introduction to the topic of modelling infectious diseases. You might want to read that first to understand this one if you don’t already have a solid grasp of the SIR equations. This article is focused on more elaborate variants of the basic SIR model and will enable you to implement and code your own variants and ideas. The next article will be concerned with fitting a model to real-world data and includes Covid-19 as a case study.
You can find the python notebook for the whole article here.
First, we’ll quickly explore the SIR model from a slightly different — more visual — angle. Afterwards, we derive and implement the following extensions:
a “Dead” state for individuals that passed away from the disease
an “Exposed” state for individuals that have contracted the disease but are not yet infectious (this is known as the SEIR-model)
time-dependent R0-values that will allow us to model quarantines, lockdowns, ...
resource- and age-dependent fatality rates that will enable us to model overcrowded hospitals, populations with lots of young people, ...
As a quick recap, take a look at the variables we defined:
N: total population
S(t): number of people susceptible on day t
I(t): number of people infected on day t
R(t): number of people recovered on day t
β: expected amount of people an infected person infects per day
D: number of days an infected person has and can spread the disease
γ: the proportion of infected recovering per day (γ = 1/D)
R0: the total number of people an infected person infects (R0 = β / γ)
And here are the basic equations again:
When deriving the equations, we already intuitively thought of them as “directions” that tell us what happens to the population the next day (for example, when 10 people are infected and recovery takes place at the rate 1/5 (that’s gamma), then the number of recovered individuals the next day should increase by 1/5 * 10 = 2). We now solidify this understanding of the equations as “directions” or “transitions” from one compartment S, I or R to another — this will greatly simplify things when we introduce more compartments later on and the equations get messy.
Here’s the notation we need:
Compartments are boxes (the “states”), like this:
Transitions from one compartment to another are represented by arrows, with the following labeling:
The rate describes how long the transition takes, population is the group of individuals that this transition applies to, and probability is the probability of the transition taking place for an individual.
As an example, let’s look at the transition from Susceptibles to Infected in our SIR equations, with beta=2, a total population of 100, 10 infected and 90 susceptible. The rate is 1, as the infections happen immediately; the population the transition applies to is 2 * 10 = 20 individuals, as the 10 infected each infect 2 people; the probability is 90%, as 90/100 people can still be infected. It corresponds to this intuitive notation:
And more generally, now for the whole model (for I → R, the rate is γ and the probability is 1 as everyone recovers):
As you can see, arrows pointing towards a compartment get added in the equation; arrows pointing away from a compartment get subtracted. That’s not too bad, is it? Take a moment to really understand the new notation and see how it is just another way of writing the equations.
Right, we now understand the SIR model and can code it in python, but is it already useful? Can it tell us anything about real-world infectious diseases? The answer is no. In its current state, the model is more of a toy than a useful tool. Let’s change that!
Many infectious diseases have an incubation period before being infectious during which the host cannot yet spread the disease. We’ll call such individuals — and the whole compartment — Exposed.
Intuitively, we’ll have transitions of the form S → E → I → R: Susceptible people can contract the virus and thus become exposed, then infected, then recovered. The new transition S → E will have the same arrow as the current S → I transition, as the probability is the same (all susceptibles can be exposed), the rate is the same (“exposition” happens immediately) and the population is the same (the infectious individuals can spread the disease and each exposes β new individuals per day). There’s also no reason for the transition from I to R to change. The only new transition is the one from E to I: the probability is 1 (everyone that’s exposed becomes infected), the population is E (all exposed will become infected), and the rate gets a new variable, δ (delta). We arrive at these transitions:
From these transitions, we can immediately derive these equations (again, compare the state transitions and the equations until it makes sense to you):
This should not be too hard, we just have to change a few lines of code from the last article (again, the full code is here to read along, I’m just showcasing the important bits here). We’ll model a highly infectious (R0 =5.0) disease in a population of 1 million, with an incubation period of 5 days and a recovery taking 7 days.
Imports needed: from scipy.integrate import odeintimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline
The equations and initial values now look like this:
We calculate S, E, I, and R over time:
And (after plotting) get this:
We are now able to model real diseases a little more realistically, though one compartment is definitely still missing; we’ll add it now:
For very deadly diseases, this compartment is very important. For some other situations, you might want to add completely different compartments and dynamics (such as births and non-disease-related deaths when studying a disease over a long time); these models can get as complex as you want!
Let’s think about how we can take our current transitions and add a Dead state. When can people die from the disease? Only while they are infected! That means that we’ll have to add a transition I → D. Of course, people don’t die immediately; We define a new variable ρ (rho) for the rate at which people die (e.g. when it takes 6 days to die, ρ will be 1/6). There’s no reason for the rate of recovery, γ, to change. So our new model will look somehow like this:
The only thing that’s missing are the probabilities of going from infected to recovered and from infected to dead. That’ll be one more variable (the last one for now!), the death rate α. For example, if α=5%, ρ = 1 and γ = 1 (so people die or recover in 1 day, that makes for an easier example) and 100 people are infected, then 5% ⋅ 100 = 5 people will die. That leaves 95% ⋅ 100 = 95 people recovering. So all in all, the probability for I → D is α and thus the probability for I → R is 1-α. We finally arrive at this model:
Which naturally translates to these equations:
We only need to make some slight changes to the code (and we’ll set α to 20% and ρ to 1/9)...
... and we arrive at this:
Note that I added a “total” that adds up S, E, I, R, and D for every time step as a “sanity check”: The compartments always have to sum up to N; this can give you a hint as to whether your equations are correct.
You should now know how you can add a new compartment to the model: Think about what transitions need to be added and changed; think about the probabilities, populations and rates of these new transitions; draw the diagram; and finally write down the equations. The coding is definitively not the hard part for these models!
For example, you might want to add a “ICU” compartment for infected individuals that need to go to an ICU (we’ll do that in the next article). Think about from which compartment people can go to the ICU, where they can go after the ICU, etc.
Here’s an updated list of the variables we currently use:
N: total population
S(t): number of people susceptible on day t
E(t): number of people exposed on day t
I(t): number of people infected on day t
R(t): number of people recovered on day t
D(t): number of people dead on day t
β: expected amount of people an infected person infects per day
D: number of days an infected person has and can spread the disease
γ: the proportion of infected recovering per day (γ = 1/D)
R0: the total number of people an infected person infects (R0 = β / γ)
δ: length of incubation period
α: fatality rate
ρ: rate at which people die (= 1/days from infected until death)
As you can see, only the compartments change over time (they are not constant). Of course, this is highly unrealistic! As an example, why should the R0-value be constant? Surely, nationwide lockdowns reduce the number of people an infected person infects, that’s what they’re all about! Naturally, to get closer to modelling real-world developments, we have to make our variables change over time.
First, we implement a simple change: on day L, a strict “lockdown” is enforced, pushing R0 to 0.9. In the equations, we use β and not R0, but we know that R0 = β / γ, so β = R0 ⋅ γ. That means that we define a function
def R_0(t): return 5.0 if t < L else 0.9
and another function for beta that calls this function:
def beta(t): return R_0(t) * gamma
Right, seems easy enough; We just change the code accordingly:
Let’s plot this for some different values of L:
A few days can make a huge difference in the overall spread of the disease!
In reality, R0 probably never “jumps” from one value to another. Rather, it (more or less quickly) continuously changes (and might go up and down several times, e.g. if social distancing measures are loosened and then tightened again). You can choose any function you want for R0, I just want to present one common choice to model the initial impact of social distancing: a logistic function.
The function (adopted for our purposes) looks like this:
And here’s what the parameters actually do:
R_0_start and R_0_end are the values of R_0 on the first and the last day
x_0 is the x-value of the inflection point (i.e. the date of the steepest decline in R_0, this could be thought of as the main “lockdown” date)
k lets us vary how quickly R_0 declines
These plots might help you understand the parameters:
Again, changing the code accordingly:
We let R0 decline quickly from 5.0 to 0.5 around day 50 and can now really see the curves flattening after day 50:
Similarly to R0, the fatality rate α is probably not constant for most real diseases. It might depend on a variety of things; We’ll focus on dependency on resources and age.
First, let’s look at resource dependency. We want the fatality rate to be higher when more people are infected. Think about how this could be put into a function: we probably need a “base” or “optimal” fatality rate for the case that only few people are infected (and thus receive optimal treatment) and some factor that takes into account what proportion of the population is currently infected. This is one example of a function that implements these ideas:
Here, s is some arbitrary but fixed (that means we choose it freely once for a model and then it stays constant over time) scaling factor that controls how big of an influence the proportion of infected should have; α_OPT is the optimal fatality rate. For example, if s=1 and half the population is infected on one day, then s ⋅ I(t) / N = 1/2, so the fatality rate α(t) on that day is 50% + α_OPT. Or maybe most people barely have any symptoms and thus many people being infected does not clog the hospitals. Then a scaling factor of 0.1 might be appropriate (in the same scenario, the fatality rate would only be 5% + α_OPT).
More elaborate models might make the fatality rate depend on the number of ICU beds or ventilators available, etc. We’ll do that in the next article when modelling Coronavirus.
Age dependency is a little more difficult. To fully implement it, we’d have to include separate compartments for every age group (e.g. an Infected-compartment for people aged 0–9, another one for people aged 10–19, ...). That’s doable with a simple for-loop in python, but the equations get a little messy. A simpler approach that still is able to produce good results is the following:
We need 2 things for the simpler approach: Fatality rates by age group and proportion of the total population that is in that age group. For example, we might have the following fatality rates and number of individuals by age group (in Python dictionaries):
alpha_by_agegroup = { "0-29": 0.01, "30-59": 0.05, "60-89": 0.20, "89+": 0.30}proportion_of_agegroup = { "0-29": 0.1, "30-59": 0.3, "60-89": 0.4, "89+": 0.2}
(This would be an extremely old population with 40% being in the 60–89 range and 20% being in the 89+ range). Now we calculate the overall average fatality rate by adding up the age group fatality rate multiplied with the proportion of the population in that age group:
α = 0.01 ⋅ 0.1 + 0.05 ⋅ 0.3 + 0.2 ⋅ 0.4 + 0.3 ⋅ 0.2 = 15.6%. Or in code:
alpha = sum(alpha_by_agegroup[i] * proportion_of_agegroup[i] for i in list(alpha_by_agegroup.keys()))
A rather young population with the following proportions ...
proportion_of_agegroup = { "0-29": 0.4, "30-59": 0.4, "60-89": 0.1, "89+": 0.1}
... would only have an average fatality rate of 7.4%!
If we want to use both our formulas for resource- and age-dependency, we could use the resource-formula we just used to calculate α_OPT and use that in our resource-dependent formula from above.
There are certainly more elaborate ways to implement fatality rates over time. For example, we’re not taking into account that only critical cases needing intensive care fill up the hospitals and might increase fatality rates; or that deaths change the population structure that we used to calculate the fatality rate in the first place; or that the impact of infected on fatality rates should take place several days later as people don’t usually die immediately, which would result in a Delay Differential Equation, and that’s annoying to deal with in Python! Again, get as creative as you want!
This is rather straightforward, we don’t even have to change our main equations (we define alpha inside the equations as we need access to the current value I(t)).
With the fatality rates by age group and the older population from above (and a scaling factor s of 1, so many people being infected has a high impact on fatality rates), we arrive at this plot:
For the younger population (around 80k instead of 150k deaths):
And now with a scaling factor of only 0.01:
For the older population (note how the fatality rate only rises very slightly over time) ...
... and the younger population:
That’s all! You should now be able to add your own compartments (maybe a compartment for individuals that can get infected again, or a compartment for a special risk group such as diabetics), first graphically through the state transition notation, then formally through the equations, and finally programmatically in Python! Also, you saw some examples of implementing time-dependent variables, making the models much more versatile.
All this should allow you to design SIR models that come quite close to the real world. Of course, many scientists are working on these models currently (this link can help you find some current articles— be warned, they can get quite complex, but it’s nonetheless a great way to get insights into the current state of the field). In the next article, we’ll focus on designing and fitting models to real-world data, with Coronavirus as a case-study.
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
|
[
{
"code": null,
"e": 666,
"s": 172,
"text": "My last article explains the background and provides an introduction to the topic of modelling infectious diseases. You might want to read that first to understand this one if you don’t already have a solid grasp of the SIR equations. This article is focused on more elaborate variants of the basic SIR model and will enable you to implement and code your own variants and ideas. The next article will be concerned with fitting a model to real-world data and includes Covid-19 as a case study."
},
{
"code": null,
"e": 727,
"s": 666,
"text": "You can find the python notebook for the whole article here."
},
{
"code": null,
"e": 881,
"s": 727,
"text": "First, we’ll quickly explore the SIR model from a slightly different — more visual — angle. Afterwards, we derive and implement the following extensions:"
},
{
"code": null,
"e": 946,
"s": 881,
"text": "a “Dead” state for individuals that passed away from the disease"
},
{
"code": null,
"e": 1075,
"s": 946,
"text": "an “Exposed” state for individuals that have contracted the disease but are not yet infectious (this is known as the SEIR-model)"
},
{
"code": null,
"e": 1156,
"s": 1075,
"text": "time-dependent R0-values that will allow us to model quarantines, lockdowns, ..."
},
{
"code": null,
"e": 1294,
"s": 1156,
"text": "resource- and age-dependent fatality rates that will enable us to model overcrowded hospitals, populations with lots of young people, ..."
},
{
"code": null,
"e": 1353,
"s": 1294,
"text": "As a quick recap, take a look at the variables we defined:"
},
{
"code": null,
"e": 1373,
"s": 1353,
"text": "N: total population"
},
{
"code": null,
"e": 1417,
"s": 1373,
"text": "S(t): number of people susceptible on day t"
},
{
"code": null,
"e": 1458,
"s": 1417,
"text": "I(t): number of people infected on day t"
},
{
"code": null,
"e": 1500,
"s": 1458,
"text": "R(t): number of people recovered on day t"
},
{
"code": null,
"e": 1564,
"s": 1500,
"text": "β: expected amount of people an infected person infects per day"
},
{
"code": null,
"e": 1632,
"s": 1564,
"text": "D: number of days an infected person has and can spread the disease"
},
{
"code": null,
"e": 1691,
"s": 1632,
"text": "γ: the proportion of infected recovering per day (γ = 1/D)"
},
{
"code": null,
"e": 1762,
"s": 1691,
"text": "R0: the total number of people an infected person infects (R0 = β / γ)"
},
{
"code": null,
"e": 1802,
"s": 1762,
"text": "And here are the basic equations again:"
},
{
"code": null,
"e": 2367,
"s": 1802,
"text": "When deriving the equations, we already intuitively thought of them as “directions” that tell us what happens to the population the next day (for example, when 10 people are infected and recovery takes place at the rate 1/5 (that’s gamma), then the number of recovered individuals the next day should increase by 1/5 * 10 = 2). We now solidify this understanding of the equations as “directions” or “transitions” from one compartment S, I or R to another — this will greatly simplify things when we introduce more compartments later on and the equations get messy."
},
{
"code": null,
"e": 2396,
"s": 2367,
"text": "Here’s the notation we need:"
},
{
"code": null,
"e": 2446,
"s": 2396,
"text": "Compartments are boxes (the “states”), like this:"
},
{
"code": null,
"e": 2546,
"s": 2446,
"text": "Transitions from one compartment to another are represented by arrows, with the following labeling:"
},
{
"code": null,
"e": 2753,
"s": 2546,
"text": "The rate describes how long the transition takes, population is the group of individuals that this transition applies to, and probability is the probability of the transition taking place for an individual."
},
{
"code": null,
"e": 3191,
"s": 2753,
"text": "As an example, let’s look at the transition from Susceptibles to Infected in our SIR equations, with beta=2, a total population of 100, 10 infected and 90 susceptible. The rate is 1, as the infections happen immediately; the population the transition applies to is 2 * 10 = 20 individuals, as the 10 infected each infect 2 people; the probability is 90%, as 90/100 people can still be infected. It corresponds to this intuitive notation:"
},
{
"code": null,
"e": 3309,
"s": 3191,
"text": "And more generally, now for the whole model (for I → R, the rate is γ and the probability is 1 as everyone recovers):"
},
{
"code": null,
"e": 3586,
"s": 3309,
"text": "As you can see, arrows pointing towards a compartment get added in the equation; arrows pointing away from a compartment get subtracted. That’s not too bad, is it? Take a moment to really understand the new notation and see how it is just another way of writing the equations."
},
{
"code": null,
"e": 3846,
"s": 3586,
"text": "Right, we now understand the SIR model and can code it in python, but is it already useful? Can it tell us anything about real-world infectious diseases? The answer is no. In its current state, the model is more of a toy than a useful tool. Let’s change that!"
},
{
"code": null,
"e": 4041,
"s": 3846,
"text": "Many infectious diseases have an incubation period before being infectious during which the host cannot yet spread the disease. We’ll call such individuals — and the whole compartment — Exposed."
},
{
"code": null,
"e": 4845,
"s": 4041,
"text": "Intuitively, we’ll have transitions of the form S → E → I → R: Susceptible people can contract the virus and thus become exposed, then infected, then recovered. The new transition S → E will have the same arrow as the current S → I transition, as the probability is the same (all susceptibles can be exposed), the rate is the same (“exposition” happens immediately) and the population is the same (the infectious individuals can spread the disease and each exposes β new individuals per day). There’s also no reason for the transition from I to R to change. The only new transition is the one from E to I: the probability is 1 (everyone that’s exposed becomes infected), the population is E (all exposed will become infected), and the rate gets a new variable, δ (delta). We arrive at these transitions:"
},
{
"code": null,
"e": 4997,
"s": 4845,
"text": "From these transitions, we can immediately derive these equations (again, compare the state transitions and the equations until it makes sense to you):"
},
{
"code": null,
"e": 5328,
"s": 4997,
"text": "This should not be too hard, we just have to change a few lines of code from the last article (again, the full code is here to read along, I’m just showcasing the important bits here). We’ll model a highly infectious (R0 =5.0) disease in a population of 1 million, with an incubation period of 5 days and a recovery taking 7 days."
},
{
"code": null,
"e": 5446,
"s": 5328,
"text": "Imports needed: from scipy.integrate import odeintimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 5499,
"s": 5446,
"text": "The equations and initial values now look like this:"
},
{
"code": null,
"e": 5538,
"s": 5499,
"text": "We calculate S, E, I, and R over time:"
},
{
"code": null,
"e": 5569,
"s": 5538,
"text": "And (after plotting) get this:"
},
{
"code": null,
"e": 5707,
"s": 5569,
"text": "We are now able to model real diseases a little more realistically, though one compartment is definitely still missing; we’ll add it now:"
},
{
"code": null,
"e": 6000,
"s": 5707,
"text": "For very deadly diseases, this compartment is very important. For some other situations, you might want to add completely different compartments and dynamics (such as births and non-disease-related deaths when studying a disease over a long time); these models can get as complex as you want!"
},
{
"code": null,
"e": 6464,
"s": 6000,
"text": "Let’s think about how we can take our current transitions and add a Dead state. When can people die from the disease? Only while they are infected! That means that we’ll have to add a transition I → D. Of course, people don’t die immediately; We define a new variable ρ (rho) for the rate at which people die (e.g. when it takes 6 days to die, ρ will be 1/6). There’s no reason for the rate of recovery, γ, to change. So our new model will look somehow like this:"
},
{
"code": null,
"e": 6991,
"s": 6464,
"text": "The only thing that’s missing are the probabilities of going from infected to recovered and from infected to dead. That’ll be one more variable (the last one for now!), the death rate α. For example, if α=5%, ρ = 1 and γ = 1 (so people die or recover in 1 day, that makes for an easier example) and 100 people are infected, then 5% ⋅ 100 = 5 people will die. That leaves 95% ⋅ 100 = 95 people recovering. So all in all, the probability for I → D is α and thus the probability for I → R is 1-α. We finally arrive at this model:"
},
{
"code": null,
"e": 7038,
"s": 6991,
"text": "Which naturally translates to these equations:"
},
{
"code": null,
"e": 7132,
"s": 7038,
"text": "We only need to make some slight changes to the code (and we’ll set α to 20% and ρ to 1/9)..."
},
{
"code": null,
"e": 7159,
"s": 7132,
"text": "... and we arrive at this:"
},
{
"code": null,
"e": 7371,
"s": 7159,
"text": "Note that I added a “total” that adds up S, E, I, R, and D for every time step as a “sanity check”: The compartments always have to sum up to N; this can give you a hint as to whether your equations are correct."
},
{
"code": null,
"e": 7696,
"s": 7371,
"text": "You should now know how you can add a new compartment to the model: Think about what transitions need to be added and changed; think about the probabilities, populations and rates of these new transitions; draw the diagram; and finally write down the equations. The coding is definitively not the hard part for these models!"
},
{
"code": null,
"e": 7938,
"s": 7696,
"text": "For example, you might want to add a “ICU” compartment for infected individuals that need to go to an ICU (we’ll do that in the next article). Think about from which compartment people can go to the ICU, where they can go after the ICU, etc."
},
{
"code": null,
"e": 7996,
"s": 7938,
"text": "Here’s an updated list of the variables we currently use:"
},
{
"code": null,
"e": 8016,
"s": 7996,
"text": "N: total population"
},
{
"code": null,
"e": 8060,
"s": 8016,
"text": "S(t): number of people susceptible on day t"
},
{
"code": null,
"e": 8100,
"s": 8060,
"text": "E(t): number of people exposed on day t"
},
{
"code": null,
"e": 8141,
"s": 8100,
"text": "I(t): number of people infected on day t"
},
{
"code": null,
"e": 8183,
"s": 8141,
"text": "R(t): number of people recovered on day t"
},
{
"code": null,
"e": 8220,
"s": 8183,
"text": "D(t): number of people dead on day t"
},
{
"code": null,
"e": 8284,
"s": 8220,
"text": "β: expected amount of people an infected person infects per day"
},
{
"code": null,
"e": 8352,
"s": 8284,
"text": "D: number of days an infected person has and can spread the disease"
},
{
"code": null,
"e": 8411,
"s": 8352,
"text": "γ: the proportion of infected recovering per day (γ = 1/D)"
},
{
"code": null,
"e": 8482,
"s": 8411,
"text": "R0: the total number of people an infected person infects (R0 = β / γ)"
},
{
"code": null,
"e": 8513,
"s": 8482,
"text": "δ: length of incubation period"
},
{
"code": null,
"e": 8530,
"s": 8513,
"text": "α: fatality rate"
},
{
"code": null,
"e": 8595,
"s": 8530,
"text": "ρ: rate at which people die (= 1/days from infected until death)"
},
{
"code": null,
"e": 8993,
"s": 8595,
"text": "As you can see, only the compartments change over time (they are not constant). Of course, this is highly unrealistic! As an example, why should the R0-value be constant? Surely, nationwide lockdowns reduce the number of people an infected person infects, that’s what they’re all about! Naturally, to get closer to modelling real-world developments, we have to make our variables change over time."
},
{
"code": null,
"e": 9212,
"s": 8993,
"text": "First, we implement a simple change: on day L, a strict “lockdown” is enforced, pushing R0 to 0.9. In the equations, we use β and not R0, but we know that R0 = β / γ, so β = R0 ⋅ γ. That means that we define a function"
},
{
"code": null,
"e": 9256,
"s": 9212,
"text": "def R_0(t): return 5.0 if t < L else 0.9"
},
{
"code": null,
"e": 9312,
"s": 9256,
"text": "and another function for beta that calls this function:"
},
{
"code": null,
"e": 9350,
"s": 9312,
"text": "def beta(t): return R_0(t) * gamma"
},
{
"code": null,
"e": 9413,
"s": 9350,
"text": "Right, seems easy enough; We just change the code accordingly:"
},
{
"code": null,
"e": 9461,
"s": 9413,
"text": "Let’s plot this for some different values of L:"
},
{
"code": null,
"e": 9537,
"s": 9461,
"text": "A few days can make a huge difference in the overall spread of the disease!"
},
{
"code": null,
"e": 9930,
"s": 9537,
"text": "In reality, R0 probably never “jumps” from one value to another. Rather, it (more or less quickly) continuously changes (and might go up and down several times, e.g. if social distancing measures are loosened and then tightened again). You can choose any function you want for R0, I just want to present one common choice to model the initial impact of social distancing: a logistic function."
},
{
"code": null,
"e": 9987,
"s": 9930,
"text": "The function (adopted for our purposes) looks like this:"
},
{
"code": null,
"e": 10031,
"s": 9987,
"text": "And here’s what the parameters actually do:"
},
{
"code": null,
"e": 10105,
"s": 10031,
"text": "R_0_start and R_0_end are the values of R_0 on the first and the last day"
},
{
"code": null,
"e": 10249,
"s": 10105,
"text": "x_0 is the x-value of the inflection point (i.e. the date of the steepest decline in R_0, this could be thought of as the main “lockdown” date)"
},
{
"code": null,
"e": 10289,
"s": 10249,
"text": "k lets us vary how quickly R_0 declines"
},
{
"code": null,
"e": 10343,
"s": 10289,
"text": "These plots might help you understand the parameters:"
},
{
"code": null,
"e": 10381,
"s": 10343,
"text": "Again, changing the code accordingly:"
},
{
"code": null,
"e": 10496,
"s": 10381,
"text": "We let R0 decline quickly from 5.0 to 0.5 around day 50 and can now really see the curves flattening after day 50:"
},
{
"code": null,
"e": 10670,
"s": 10496,
"text": "Similarly to R0, the fatality rate α is probably not constant for most real diseases. It might depend on a variety of things; We’ll focus on dependency on resources and age."
},
{
"code": null,
"e": 11130,
"s": 10670,
"text": "First, let’s look at resource dependency. We want the fatality rate to be higher when more people are infected. Think about how this could be put into a function: we probably need a “base” or “optimal” fatality rate for the case that only few people are infected (and thus receive optimal treatment) and some factor that takes into account what proportion of the population is currently infected. This is one example of a function that implements these ideas:"
},
{
"code": null,
"e": 11758,
"s": 11130,
"text": "Here, s is some arbitrary but fixed (that means we choose it freely once for a model and then it stays constant over time) scaling factor that controls how big of an influence the proportion of infected should have; α_OPT is the optimal fatality rate. For example, if s=1 and half the population is infected on one day, then s ⋅ I(t) / N = 1/2, so the fatality rate α(t) on that day is 50% + α_OPT. Or maybe most people barely have any symptoms and thus many people being infected does not clog the hospitals. Then a scaling factor of 0.1 might be appropriate (in the same scenario, the fatality rate would only be 5% + α_OPT)."
},
{
"code": null,
"e": 11935,
"s": 11758,
"text": "More elaborate models might make the fatality rate depend on the number of ICU beds or ventilators available, etc. We’ll do that in the next article when modelling Coronavirus."
},
{
"code": null,
"e": 12322,
"s": 11935,
"text": "Age dependency is a little more difficult. To fully implement it, we’d have to include separate compartments for every age group (e.g. an Infected-compartment for people aged 0–9, another one for people aged 10–19, ...). That’s doable with a simple for-loop in python, but the equations get a little messy. A simpler approach that still is able to produce good results is the following:"
},
{
"code": null,
"e": 12580,
"s": 12322,
"text": "We need 2 things for the simpler approach: Fatality rates by age group and proportion of the total population that is in that age group. For example, we might have the following fatality rates and number of individuals by age group (in Python dictionaries):"
},
{
"code": null,
"e": 12744,
"s": 12580,
"text": "alpha_by_agegroup = { \"0-29\": 0.01, \"30-59\": 0.05, \"60-89\": 0.20, \"89+\": 0.30}proportion_of_agegroup = { \"0-29\": 0.1, \"30-59\": 0.3, \"60-89\": 0.4, \"89+\": 0.2}"
},
{
"code": null,
"e": 13014,
"s": 12744,
"text": "(This would be an extremely old population with 40% being in the 60–89 range and 20% being in the 89+ range). Now we calculate the overall average fatality rate by adding up the age group fatality rate multiplied with the proportion of the population in that age group:"
},
{
"code": null,
"e": 13087,
"s": 13014,
"text": "α = 0.01 ⋅ 0.1 + 0.05 ⋅ 0.3 + 0.2 ⋅ 0.4 + 0.3 ⋅ 0.2 = 15.6%. Or in code:"
},
{
"code": null,
"e": 13201,
"s": 13087,
"text": "alpha = sum(alpha_by_agegroup[i] * proportion_of_agegroup[i] for i in list(alpha_by_agegroup.keys()))"
},
{
"code": null,
"e": 13262,
"s": 13201,
"text": "A rather young population with the following proportions ..."
},
{
"code": null,
"e": 13345,
"s": 13262,
"text": "proportion_of_agegroup = { \"0-29\": 0.4, \"30-59\": 0.4, \"60-89\": 0.1, \"89+\": 0.1}"
},
{
"code": null,
"e": 13399,
"s": 13345,
"text": "... would only have an average fatality rate of 7.4%!"
},
{
"code": null,
"e": 13594,
"s": 13399,
"text": "If we want to use both our formulas for resource- and age-dependency, we could use the resource-formula we just used to calculate α_OPT and use that in our resource-dependent formula from above."
},
{
"code": null,
"e": 14192,
"s": 13594,
"text": "There are certainly more elaborate ways to implement fatality rates over time. For example, we’re not taking into account that only critical cases needing intensive care fill up the hospitals and might increase fatality rates; or that deaths change the population structure that we used to calculate the fatality rate in the first place; or that the impact of infected on fatality rates should take place several days later as people don’t usually die immediately, which would result in a Delay Differential Equation, and that’s annoying to deal with in Python! Again, get as creative as you want!"
},
{
"code": null,
"e": 14356,
"s": 14192,
"text": "This is rather straightforward, we don’t even have to change our main equations (we define alpha inside the equations as we need access to the current value I(t))."
},
{
"code": null,
"e": 14551,
"s": 14356,
"text": "With the fatality rates by age group and the older population from above (and a scaling factor s of 1, so many people being infected has a high impact on fatality rates), we arrive at this plot:"
},
{
"code": null,
"e": 14615,
"s": 14551,
"text": "For the younger population (around 80k instead of 150k deaths):"
},
{
"code": null,
"e": 14659,
"s": 14615,
"text": "And now with a scaling factor of only 0.01:"
},
{
"code": null,
"e": 14752,
"s": 14659,
"text": "For the older population (note how the fatality rate only rises very slightly over time) ..."
},
{
"code": null,
"e": 14784,
"s": 14752,
"text": "... and the younger population:"
},
{
"code": null,
"e": 15219,
"s": 14784,
"text": "That’s all! You should now be able to add your own compartments (maybe a compartment for individuals that can get infected again, or a compartment for a special risk group such as diabetics), first graphically through the state transition notation, then formally through the equations, and finally programmatically in Python! Also, you saw some examples of implementing time-dependent variables, making the models much more versatile."
},
{
"code": null,
"e": 15669,
"s": 15219,
"text": "All this should allow you to design SIR models that come quite close to the real world. Of course, many scientists are working on these models currently (this link can help you find some current articles— be warned, they can get quite complex, but it’s nonetheless a great way to get insights into the current state of the field). In the next article, we’ll focus on designing and fitting models to real-world data, with Coronavirus as a case-study."
}
] |
Print first m multiples of n without using any loop in Python
|
21 Nov, 2018
Given n and m, print first m multiples of a m number without using any loops in Python.
Examples:
Input : n = 2, m = 3
Output : 2 4 6
Input : n = 3, m = 4
Output : 3 6 9 12
We can use range() function in Python to store the multiples in a range.First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop.
Below is the Python implementation of the above approach:
# function to print the first m multiple# of a number n without using loop.def multiple(m, n): # inserts all elements from n to # (m * n)+1 incremented by n. a = range(n, (m * n)+1, n) print(*a) # driver code m = 4n = 3multiple(m, n)
Output:
3 6 9 12
Note : In Python 3, print(*(range(x)) is equivalent to print(" ".join([str(i) for i in range(x)]))
Python list-programs
python-list
python-puzzle
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 141,
"s": 53,
"text": "Given n and m, print first m multiples of a m number without using any loops in Python."
},
{
"code": null,
"e": 151,
"s": 141,
"text": "Examples:"
},
{
"code": null,
"e": 230,
"s": 151,
"text": "Input : n = 2, m = 3\nOutput : 2 4 6 \n\nInput : n = 3, m = 4\nOutput : 3 6 9 12 \n"
},
{
"code": null,
"e": 465,
"s": 230,
"text": "We can use range() function in Python to store the multiples in a range.First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop."
},
{
"code": null,
"e": 523,
"s": 465,
"text": "Below is the Python implementation of the above approach:"
},
{
"code": "# function to print the first m multiple# of a number n without using loop.def multiple(m, n): # inserts all elements from n to # (m * n)+1 incremented by n. a = range(n, (m * n)+1, n) print(*a) # driver code m = 4n = 3multiple(m, n)",
"e": 779,
"s": 523,
"text": null
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Output:"
},
{
"code": null,
"e": 797,
"s": 787,
"text": "3 6 9 12\n"
},
{
"code": null,
"e": 896,
"s": 797,
"text": "Note : In Python 3, print(*(range(x)) is equivalent to print(\" \".join([str(i) for i in range(x)]))"
},
{
"code": null,
"e": 917,
"s": 896,
"text": "Python list-programs"
},
{
"code": null,
"e": 929,
"s": 917,
"text": "python-list"
},
{
"code": null,
"e": 943,
"s": 929,
"text": "python-puzzle"
},
{
"code": null,
"e": 950,
"s": 943,
"text": "Python"
},
{
"code": null,
"e": 962,
"s": 950,
"text": "python-list"
}
] |
Operating Systems | Process Synchronization | Question 5
|
02 Feb, 2013
The atomic fetch-and-set x, y instruction unconditionally sets the memory location x to 1 and fetches the old value of x in y without allowing any intervening access to the memory location x. consider the following implementation of P and V functions on a binary semaphore .
void P (binary_semaphore *s) {
unsigned y;
unsigned *x = &(s->value);
do {
fetch-and-set x, y;
} while (y);
}
void V (binary_semaphore *s) {
S->value = 0;
}
Which one of the following is true?(A) The implementation may not work if context switching is disabled in P.(B) Instead of using fetch-and-set, a pair of normal load/store can be used(C) The implementation of V is wrong(D) The code does not implement a binary semaphoreAnswer: (A)Explanation: Let us talk about the operation P(). It stores the value of s in x, then it fetches the old value of x, stores it in y and sets x as 1. The while loop of a process will continue forever if some other process doesn’t execute V() and sets the value of s as 0. If context switching is disabled in P, the while loop will run forever as no other process will be able to execute V().
Operating Systems-Process Management
Process Management
Operating Systems Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operating Systems | Input Output Systems | Question 5
Operating Systems | Input Output Systems | Question 2
CPU Scheduling Numerical Questions
Operating Systems | Deadlock | Question 1
File System Inconsistency
Operating Systems | CPU Scheduling | Question 7
Operating Systems | CPU Scheduling | Question 6
Program to show that Linux provides time sharing environment to processes
Get to know Ubuntu 18.04 LTS | Welcome Bionic Beaver!!
Operating Systems | Deadlock | Question 2
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Feb, 2013"
},
{
"code": null,
"e": 327,
"s": 52,
"text": "The atomic fetch-and-set x, y instruction unconditionally sets the memory location x to 1 and fetches the old value of x in y without allowing any intervening access to the memory location x. consider the following implementation of P and V functions on a binary semaphore ."
},
{
"code": null,
"e": 501,
"s": 327,
"text": "void P (binary_semaphore *s) {\n unsigned y;\n unsigned *x = &(s->value);\n do {\n fetch-and-set x, y;\n } while (y);\n}\n\nvoid V (binary_semaphore *s) {\n S->value = 0;\n}\n"
},
{
"code": null,
"e": 1173,
"s": 501,
"text": "Which one of the following is true?(A) The implementation may not work if context switching is disabled in P.(B) Instead of using fetch-and-set, a pair of normal load/store can be used(C) The implementation of V is wrong(D) The code does not implement a binary semaphoreAnswer: (A)Explanation: Let us talk about the operation P(). It stores the value of s in x, then it fetches the old value of x, stores it in y and sets x as 1. The while loop of a process will continue forever if some other process doesn’t execute V() and sets the value of s as 0. If context switching is disabled in P, the while loop will run forever as no other process will be able to execute V()."
},
{
"code": null,
"e": 1210,
"s": 1173,
"text": "Operating Systems-Process Management"
},
{
"code": null,
"e": 1229,
"s": 1210,
"text": "Process Management"
},
{
"code": null,
"e": 1257,
"s": 1229,
"text": "Operating Systems Questions"
},
{
"code": null,
"e": 1355,
"s": 1257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1409,
"s": 1355,
"text": "Operating Systems | Input Output Systems | Question 5"
},
{
"code": null,
"e": 1463,
"s": 1409,
"text": "Operating Systems | Input Output Systems | Question 2"
},
{
"code": null,
"e": 1498,
"s": 1463,
"text": "CPU Scheduling Numerical Questions"
},
{
"code": null,
"e": 1540,
"s": 1498,
"text": "Operating Systems | Deadlock | Question 1"
},
{
"code": null,
"e": 1566,
"s": 1540,
"text": "File System Inconsistency"
},
{
"code": null,
"e": 1614,
"s": 1566,
"text": "Operating Systems | CPU Scheduling | Question 7"
},
{
"code": null,
"e": 1662,
"s": 1614,
"text": "Operating Systems | CPU Scheduling | Question 6"
},
{
"code": null,
"e": 1736,
"s": 1662,
"text": "Program to show that Linux provides time sharing environment to processes"
},
{
"code": null,
"e": 1791,
"s": 1736,
"text": "Get to know Ubuntu 18.04 LTS | Welcome Bionic Beaver!!"
}
] |
Text to Voice conversion using Web Speech API of Google Chrome
|
06 Jun, 2022
Creating a web app that converts text to speech incorporated to it sounds pretty cool, and if all these facilities are available without the interference of any third party library then it is even more easy to implement. The web speech API provides with basic tools that can be used to create interactive web apps with voice data enabled. We have created a basic interface that has a simple box that contains our text input section where we will write the text, and two sliders which manipulate the rate of the voice and also its pitch. Then we have a drop-down menu that contains all the supported languages with regions mentioned with it. index.html This HTML file contains the layout of the web page.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Text to speech!</title> <!-- CSS Links --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous"> <!-- Giving links to jquery and bootstraps js libraries --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script> <!-- Custom JS that contains all the main functions --> <script src="main.js"></script> <link rel="stylesheet" href="style.css"></head> <body> <form class="container text-center"> <div class="row"> <div class="col-sm-6 mx-auto"> <div class="form-group"> <div id="front-text" class="text-success"> GeeksforGeeks Text-to-Speech Conversion </div> <!-- Input box text area --> <textarea id="maintext" class="form-control form-control-lg" style="max-lines: 2" placeholder="Enter the text..."> </textarea> </div> </div> </div> <!-- Rate of voice which we will be updated by user --> <div class="row"> <div class="col-sm-6 mx-auto"> <div class="form-group"> <label for="rate">Rate</label> <div id="rate-value" class="badge badge-primary" >5</div> <input class="custom-range" type="range" id="rate" max="1" min="0.2" value="0.5" step="0.1"> </div> </div> </div> <!-- Pitch of voice which we will be updated by user --> <div class="row"> <div class="col-sm-6 mx-auto"> <div class="form-group"> <label for="pitch">Pitch</label> <div id="pitch-value" class="badge badge-primary" >5</div> <input class="custom-range" type="range" id="pitch" max="1" min="0.2" value="0.5" step="0.1"> </div> </div> </div> <!-- The different types of voice along with country and language --> <div class="row"> <div class="col-sm-6 mx-auto"> <div class="form-group"> <!-- This section will be dynamically loaded from the API so we left it blank for now--> <select class="form-control form-control-lg" id="voice-select" ></select> </div> <!-- Button to enable the speech from the text given in the input box --> <button id="submit" class="btn btn-success btn-lg"> Speak it </button> </div> </div> </form></body> </html>
style.css This file is used to add some CSS style to the HTML file.
html
body { background: url('images/background.jpg'); background-size: cover; background-repeat: no-repeat; height: 100vh; background-attachment: fixed;} #front-text { font-size: 35px; color: white; font-weight: bolder; text-shadow: 1px 1px 1px black; display: block; position: relative; margin-bottom: 5%; margin-top: 15%;} #rate-value { float: right;} #pitch-value { float: right;} #foot { font-size: 20px; color: white; font-weight: bolder; display: block; position: relative; margin-top: 1%;}
main.js The JavaScript file is used to convert the text file into voice.
javascript
// Initialising the speech APIconst synth = window.speechSynthesis; // Element initialization sectionconst form = document.querySelector('form');const textarea = document.getElementById('maintext');const voice_select = document.getElementById('voice-select');const rate = document.getElementById('rate');const pitch = document.getElementById('pitch');const rateval = document.getElementById('rate-value');const pitchval = document.getElementById('pitch-value'); // Retrieving the different voices and putting them as// options in our speech selection sectionlet voices = [];const getVoice = () => { // This method retrieves voices and is asynchronously loaded voices = synth.getVoices(); var option_string = ""; voices.forEach(value => { var option = value.name + ' (' + value.lang + ') '; var newOption = "<option data-name='" + value.name + "' data-lang='" + value.lang + "'>" + option + "</option>\n"; option_string += newOption; }); voice_select.innerHTML = option_string;} // Since synth.getVoices() is loaded asynchronously, this// event gets fired when the return object of that// function has changedsynth.onvoiceschanged = function() { getVoice();}; const speak = () => { // If the speech mode is on we dont want to load // another speech if(synth.speaking) { alert('Already speaking....'); return; } // If the text area is not empty that is if the input // is not empty if(textarea.value !== '') { // Creating an object of SpeechSynthesisUtterance with // the input value that represents a speech request const speakText = new SpeechSynthesisUtterance(textarea.value); // When the speaking is ended this method is fired speakText.onend = e => { console.log('Speaking is done!'); }; // When any error occurs this method is fired speakText.error = e=> { console.error('Error occurred...'); }; // Selecting the voice for the speech from the selection DOM const id = voice_select.selectedIndex; const selectedVoice = voice_select.selectedOptions[0].getAttribute('data-name'); // Checking which voices has been chosen from the selection // and setting the voice to the chosen voice voices.forEach(voice => { if(voice.name === selectedVoice) { speakText.voice = voice; } }); // Setting the rate and pitch of the voice speakText.rate = rate.value; speakText.pitch = pitch.value; // Finally calling the speech function that enables speech synth.speak(speakText); }}; // This function updates the rate and pitch value to the// value to displayrate.addEventListener('change', evt => rateval.innerHTML = (Number.parseFloat(rate.value) * 10) + ""); pitch.addEventListener('change', evt => pitchval.innerHTML = (Number.parseFloat(pitch.value) * 10) + ""); // This is the section when we assign the speak button, the// speech functionform.addEventListener('submit', evt => { evt.preventDefault(); speak(); textarea.blur();});
Output:
nikhatkhan11
Bootstrap
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to Add Image into Dropdown List for each items ?
How to change the background color of the active nav-item?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 734,
"s": 28,
"text": " Creating a web app that converts text to speech incorporated to it sounds pretty cool, and if all these facilities are available without the interference of any third party library then it is even more easy to implement. The web speech API provides with basic tools that can be used to create interactive web apps with voice data enabled. We have created a basic interface that has a simple box that contains our text input section where we will write the text, and two sliders which manipulate the rate of the voice and also its pitch. Then we have a drop-down menu that contains all the supported languages with regions mentioned with it. index.html This HTML file contains the layout of the web page. "
},
{
"code": null,
"e": 739,
"s": 734,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Text to speech!</title> <!-- CSS Links --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" crossorigin=\"anonymous\"> <!-- Giving links to jquery and bootstraps js libraries --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" crossorigin=\"anonymous\"></script> <!-- Custom JS that contains all the main functions --> <script src=\"main.js\"></script> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <form class=\"container text-center\"> <div class=\"row\"> <div class=\"col-sm-6 mx-auto\"> <div class=\"form-group\"> <div id=\"front-text\" class=\"text-success\"> GeeksforGeeks Text-to-Speech Conversion </div> <!-- Input box text area --> <textarea id=\"maintext\" class=\"form-control form-control-lg\" style=\"max-lines: 2\" placeholder=\"Enter the text...\"> </textarea> </div> </div> </div> <!-- Rate of voice which we will be updated by user --> <div class=\"row\"> <div class=\"col-sm-6 mx-auto\"> <div class=\"form-group\"> <label for=\"rate\">Rate</label> <div id=\"rate-value\" class=\"badge badge-primary\" >5</div> <input class=\"custom-range\" type=\"range\" id=\"rate\" max=\"1\" min=\"0.2\" value=\"0.5\" step=\"0.1\"> </div> </div> </div> <!-- Pitch of voice which we will be updated by user --> <div class=\"row\"> <div class=\"col-sm-6 mx-auto\"> <div class=\"form-group\"> <label for=\"pitch\">Pitch</label> <div id=\"pitch-value\" class=\"badge badge-primary\" >5</div> <input class=\"custom-range\" type=\"range\" id=\"pitch\" max=\"1\" min=\"0.2\" value=\"0.5\" step=\"0.1\"> </div> </div> </div> <!-- The different types of voice along with country and language --> <div class=\"row\"> <div class=\"col-sm-6 mx-auto\"> <div class=\"form-group\"> <!-- This section will be dynamically loaded from the API so we left it blank for now--> <select class=\"form-control form-control-lg\" id=\"voice-select\" ></select> </div> <!-- Button to enable the speech from the text given in the input box --> <button id=\"submit\" class=\"btn btn-success btn-lg\"> Speak it </button> </div> </div> </form></body> </html>",
"e": 3868,
"s": 739,
"text": null
},
{
"code": null,
"e": 3937,
"s": 3868,
"text": "style.css This file is used to add some CSS style to the HTML file. "
},
{
"code": null,
"e": 3942,
"s": 3937,
"text": "html"
},
{
"code": "body { background: url('images/background.jpg'); background-size: cover; background-repeat: no-repeat; height: 100vh; background-attachment: fixed;} #front-text { font-size: 35px; color: white; font-weight: bolder; text-shadow: 1px 1px 1px black; display: block; position: relative; margin-bottom: 5%; margin-top: 15%;} #rate-value { float: right;} #pitch-value { float: right;} #foot { font-size: 20px; color: white; font-weight: bolder; display: block; position: relative; margin-top: 1%;}",
"e": 4497,
"s": 3942,
"text": null
},
{
"code": null,
"e": 4571,
"s": 4497,
"text": "main.js The JavaScript file is used to convert the text file into voice. "
},
{
"code": null,
"e": 4582,
"s": 4571,
"text": "javascript"
},
{
"code": "// Initialising the speech APIconst synth = window.speechSynthesis; // Element initialization sectionconst form = document.querySelector('form');const textarea = document.getElementById('maintext');const voice_select = document.getElementById('voice-select');const rate = document.getElementById('rate');const pitch = document.getElementById('pitch');const rateval = document.getElementById('rate-value');const pitchval = document.getElementById('pitch-value'); // Retrieving the different voices and putting them as// options in our speech selection sectionlet voices = [];const getVoice = () => { // This method retrieves voices and is asynchronously loaded voices = synth.getVoices(); var option_string = \"\"; voices.forEach(value => { var option = value.name + ' (' + value.lang + ') '; var newOption = \"<option data-name='\" + value.name + \"' data-lang='\" + value.lang + \"'>\" + option + \"</option>\\n\"; option_string += newOption; }); voice_select.innerHTML = option_string;} // Since synth.getVoices() is loaded asynchronously, this// event gets fired when the return object of that// function has changedsynth.onvoiceschanged = function() { getVoice();}; const speak = () => { // If the speech mode is on we dont want to load // another speech if(synth.speaking) { alert('Already speaking....'); return; } // If the text area is not empty that is if the input // is not empty if(textarea.value !== '') { // Creating an object of SpeechSynthesisUtterance with // the input value that represents a speech request const speakText = new SpeechSynthesisUtterance(textarea.value); // When the speaking is ended this method is fired speakText.onend = e => { console.log('Speaking is done!'); }; // When any error occurs this method is fired speakText.error = e=> { console.error('Error occurred...'); }; // Selecting the voice for the speech from the selection DOM const id = voice_select.selectedIndex; const selectedVoice = voice_select.selectedOptions[0].getAttribute('data-name'); // Checking which voices has been chosen from the selection // and setting the voice to the chosen voice voices.forEach(voice => { if(voice.name === selectedVoice) { speakText.voice = voice; } }); // Setting the rate and pitch of the voice speakText.rate = rate.value; speakText.pitch = pitch.value; // Finally calling the speech function that enables speech synth.speak(speakText); }}; // This function updates the rate and pitch value to the// value to displayrate.addEventListener('change', evt => rateval.innerHTML = (Number.parseFloat(rate.value) * 10) + \"\"); pitch.addEventListener('change', evt => pitchval.innerHTML = (Number.parseFloat(pitch.value) * 10) + \"\"); // This is the section when we assign the speak button, the// speech functionform.addEventListener('submit', evt => { evt.preventDefault(); speak(); textarea.blur();});",
"e": 7810,
"s": 4582,
"text": null
},
{
"code": null,
"e": 7818,
"s": 7810,
"text": "Output:"
},
{
"code": null,
"e": 7831,
"s": 7818,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 7841,
"s": 7831,
"text": "Bootstrap"
},
{
"code": null,
"e": 7845,
"s": 7841,
"text": "CSS"
},
{
"code": null,
"e": 7850,
"s": 7845,
"text": "HTML"
},
{
"code": null,
"e": 7867,
"s": 7850,
"text": "Web Technologies"
},
{
"code": null,
"e": 7894,
"s": 7867,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 7899,
"s": 7894,
"text": "HTML"
},
{
"code": null,
"e": 7997,
"s": 7899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8038,
"s": 7997,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 8101,
"s": 8038,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 8134,
"s": 8101,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 8187,
"s": 8134,
"text": "How to Add Image into Dropdown List for each items ?"
},
{
"code": null,
"e": 8246,
"s": 8187,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 8308,
"s": 8246,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8358,
"s": 8308,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 8416,
"s": 8358,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 8466,
"s": 8416,
"text": "CSS to put icon inside an input element in a form"
}
] |
Minimum count of numbers required from given array to represent S
|
25 May, 2021
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that any element of the array can be chosen any number of times to get sum S.
Examples:
Input: arr[] = {25, 10, 5}, S = 30 Output: 2 Explanation: In the given array there are many possible solutions such as – 5 + 5 + 5 + 5 + 5 + 5 = 30, or 10 + 10 + 10 = 30, or 25 + 5 = 30 Hence, the minimum possible solution is 2
Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6 Output: 1 Explanation: In the given array there are many possible solutions such as – 2 + 2 + 2 = 6, or 2 + 4 = 6, or 6 = 6, Hence, the minimum possible solution is 1
Approach: The idea is to find every possible sequence recursively such that their sum is equal to the given S and also keep track of the minimum sequence such that their sum is given S. In this way, the minimum possible solution can be calculated easily.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S #include <bits/stdc++.h>using namespace std; // Function to find the// minimum elements required to// get the sum of given value Sint printAllSubsetsRec(int arr[], int n, vector<int> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return (int)v.size(); } if (sum < 0) return INT_MAX; // Condition when no // such sequence found if (n == 0) return INT_MAX; // Calling for without choosing // the current index value int x = printAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.push_back(arr[n - 1]); int y = printAllSubsetsRec( arr, n, v, sum - arr[n - 1]); return min(x, y);} // Function for every arrayint printAllSubsets(int arr[], int n, int sum){ vector<int> v; return printAllSubsetsRec(arr, n, v, sum);} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << printAllSubsets(arr, n, sum) << endl; return 0;}
// Java implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Simport java.util.*;import java.lang.*; class GFG{ // Function to find the// minimum elements required to// get the sum of given value Sstatic int printAllSubsetsRec(int arr[], int n, ArrayList<Integer> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return (int)v.size(); } if (sum < 0) return Integer.MAX_VALUE; // Condition when no // such sequence found if (n == 0) return Integer.MAX_VALUE; // Calling for without choosing // the current index value int x = printAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.add(arr[n - 1]); int y = printAllSubsetsRec( arr, n, v, sum - arr[n - 1]); v.remove(v.size() - 1); return Math.min(x, y);} // Function for every arraystatic int printAllSubsets(int arr[], int n, int sum){ ArrayList<Integer> v = new ArrayList<>(); return printAllSubsetsRec(arr, n, v, sum);} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = arr.length; System.out.println(printAllSubsets(arr, n, sum));}} // This code is contributed by offbeat
# Python3 implementation to find the# minimum number of sequence# required from array such that# their sum is equal to given Simport sys # Function to find the# minimum elements required to# get the sum of given value Sdef printAllSubsetsRec(arr, n, v, Sum): # Condition if the # sequence is found if (Sum == 0): return len(v) if (Sum < 0): return sys.maxsize # Condition when no # such sequence found if (n == 0): return sys.maxsize # Calling for without choosing # the current index value x = printAllSubsetsRec(arr, n - 1, v, Sum) # Calling for after choosing # the current index value v.append(arr[n - 1]) y = printAllSubsetsRec(arr, n, v, Sum - arr[n - 1]) v.pop(len(v) - 1) return min(x, y) # Function for every arraydef printAllSubsets(arr, n, Sum): v = [] return printAllSubsetsRec(arr, n, v, Sum) # Driver codearr = [ 2, 1, 4, 3, 5, 6 ]Sum = 6n = len(arr) print(printAllSubsets(arr, n, Sum)) # This code is contributed by avanitrachhadiya2155
// C# implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Susing System;using System.Collections.Generic; class GFG{ // Function to find the// minimum elements required to// get the sum of given value Sstatic int printAllSubsetsRec(int[] arr, int n, List<int> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return v.Count; } if (sum < 0) return Int32.MaxValue; // Condition when no // such sequence found if (n == 0) return Int32.MaxValue; // Calling for without choosing // the current index value int x = printAllSubsetsRec(arr, n - 1, v, sum); // Calling for after choosing // the current index value v.Add(arr[n - 1]); int y = printAllSubsetsRec(arr, n, v, sum - arr[n - 1]); v.RemoveAt(v.Count - 1); return Math.Min(x, y);} // Function for every arraystatic int printAllSubsets(int[] arr, int n, int sum){ List<int> v = new List<int>(); return printAllSubsetsRec(arr, n, v, sum);} // Driver code static void Main(){ int[] arr = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = arr.Length; Console.WriteLine(printAllSubsets(arr, n, sum));}} // This code is contributed by divyeshrabadiya07
<script>// Javascript implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S // Function to find the// minimum elements required to// get the sum of given value Sfunction prletAllSubsetsRec(arr, n, v, sum){ // Condition if the // sequence is found if (sum == 0) { return v.length; } if (sum < 0) return Number.MAX_VALUE; // Condition when no // such sequence found if (n == 0) return Number.MAX_VALUE; // Calling for without choosing // the current index value let x = prletAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.push(arr[n - 1]); let y = prletAllSubsetsRec( arr, n, v, sum - arr[n - 1]); v.pop(v.length - 1); return Math.min(x, y);} // Function for every arrayfunction prletAllSubsets(arr, n, sum){ let v = []; return prletAllSubsetsRec(arr, n, v, sum);} // Driver Code let arr = [ 2, 1, 4, 3, 5, 6 ]; let sum = 6; let n = arr.length; document.write(prletAllSubsets(arr, n, sum)); </script>
1
Performance Analysis:
Time Complexity: As in the above approach, there are two choose for every number in each step which takes O(2N) time, Hence the Time Complexity will be O(2N).
Space Complexity: As in the above approach, there is no extra space used, Hence the space complexity will be O(1).
Efficient Approach: As in the above approach there is overlapping subproblems, So the idea is to use Dynamic Programming paradigm to solve this problem. Create a DP table of N * S to store the pre-computed answer for the previous sequence that is the minimum length sequence required to get the sum as S – arr[i] and in this way the finally after calculating for every value of the array, the answer to the problem will be dp[N][S], where m is the length of the array and S is the given sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S #include <bits/stdc++.h>using namespace std; // Function to find the count of// minimum length of the sequenceint Count(int S[], int m, int n){ vector<vector<int> > table( m + 1, vector<int>( n + 1, 0)); // Loop to initialize the array // as infinite in the row 0 for (int i = 1; i <= n; i++) { table[0][i] = INT_MAX - 1; } // Loop to find the solution // by pre-computation for the // sequence for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible // for the previous // minimum value // of the sequence table[i][j] = min( table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codeint main(){ int arr[] = { 9, 6, 5, 1 }; int m = sizeof(arr) / sizeof(arr[0]); cout << Count(arr, m, 11); return 0;}
// Java implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Simport java.util.*; class GFG{ // Function to find the count of// minimum length of the sequencestatic int Count(int S[], int m, int n){ int [][]table = new int[m + 1][n + 1]; // Loop to initialize the array // as infinite in the row 0 for(int i = 1; i <= n; i++) { table[0][i] = Integer.MAX_VALUE - 1; } // Loop to find the solution // by pre-computation for the // sequence for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible for the // previous minimum value // of the sequence table[i][j] = Math.min(table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codepublic static void main(String[] args){ int arr[] = { 9, 6, 5, 1 }; int m = arr.length; System.out.print(Count(arr, m, 11));}} // This code is contributed by gauravrajput1
# Python3 implementation to find the# minimum number of sequence# required from array such that# their sum is equal to given S # Function to find the count of# minimum length of the sequencedef Count(S, m, n): table = [[0 for i in range(n + 1)] for i in range(m + 1)] # Loop to initialize the array # as infinite in the row 0 for i in range(1, n + 1): table[0][i] = 10**9 - 1 # Loop to find the solution # by pre-computation for the # sequence for i in range(1, m + 1): for j in range(1, n + 1): if (S[i - 1] > j): table[i][j] = table[i - 1][j] else: # Minimum possible # for the previous # minimum value # of the sequence table[i][j] = min(table[i - 1][j], table[i][j - S[i - 1]] + 1) return table[m][n] # Driver Codeif __name__ == '__main__': arr= [9, 6, 5, 1] m = len(arr) print(Count(arr, m, 11)) # This code is contributed by Mohit Kumar
// C# implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Susing System; class GFG{ // Function to find the count of// minimum length of the sequencestatic int Count(int[] S, int m, int n){ int[,] table = new int[m + 1, n + 1]; // Loop to initialize the array // as infinite in the row 0 for(int i = 1; i <= n; i++) { table[0, i] = int.MaxValue - 1; } // Loop to find the solution // by pre-computation for the // sequence for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i, j] = table[i - 1, j]; } else { // Minimum possible for the // previous minimum value // of the sequence table[i, j] = Math.Min(table[i - 1, j], table[i, j - S[i - 1]] + 1); } } } return table[m, n];} // Driver Codepublic static void Main(String[] args){ int[] arr = { 9, 6, 5, 1 }; int m = 4; Console.WriteLine(Count(arr, m, 11));}} // This code is contributed by jrishabh99
<script> // JavaScript implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S // Function to find the count of// minimum length of the sequencefunction Count(S, m, n){ let table = []; for(let i = 0;i<m+1;i++){ table[i] = []; for(let j = 0;j<n+1;j++){ table[i][j] = 0; } } // Loop to initialize the array // as infinite in the row 0 for (let i = 1; i <= n; i++) { table[0][i] = Number.MAX_VALUE - 1; } // Loop to find the solution // by pre-computation for the // sequence for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible // for the previous // minimum value // of the sequence table[i][j] = Math.min( table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codelet arr = [ 9, 6, 5, 1 ];let m = arr.length;document.write(Count(arr, m, 11)); </script>
2
Performance Analysis:
Time Complexity: As in the above approach, there are two loop for the calculation of the minimum length sequence required which takes O(N2) time, Hence the Time Complexity will be O(N2).
Space Complexity: As in the above approach, there is a extra dp table used, Hence the space complexity will be O(N2).
mohit kumar 29
GauravRajput1
jrishabh99
offbeat
khushboogoyal499
divyeshrabadiya07
avanitrachhadiya2155
simmytarika5
Akanksha_Rai
splevel62
rohitsingh07052
Arrays
Backtracking
Dynamic Programming
Mathematical
Recursion
Arrays
Dynamic Programming
Mathematical
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
Subset Sum Problem | DP-25
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
N Queen Problem | Backtracking-3
The Knight's tour problem | Backtracking-1
Backtracking | Introduction
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 241,
"s": 52,
"text": "Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that any element of the array can be chosen any number of times to get sum S."
},
{
"code": null,
"e": 252,
"s": 241,
"text": "Examples: "
},
{
"code": null,
"e": 480,
"s": 252,
"text": "Input: arr[] = {25, 10, 5}, S = 30 Output: 2 Explanation: In the given array there are many possible solutions such as – 5 + 5 + 5 + 5 + 5 + 5 = 30, or 10 + 10 + 10 = 30, or 25 + 5 = 30 Hence, the minimum possible solution is 2"
},
{
"code": null,
"e": 691,
"s": 480,
"text": "Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6 Output: 1 Explanation: In the given array there are many possible solutions such as – 2 + 2 + 2 = 6, or 2 + 4 = 6, or 6 = 6, Hence, the minimum possible solution is 1 "
},
{
"code": null,
"e": 947,
"s": 691,
"text": "Approach: The idea is to find every possible sequence recursively such that their sum is equal to the given S and also keep track of the minimum sequence such that their sum is given S. In this way, the minimum possible solution can be calculated easily. "
},
{
"code": null,
"e": 999,
"s": 947,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1003,
"s": 999,
"text": "C++"
},
{
"code": null,
"e": 1008,
"s": 1003,
"text": "Java"
},
{
"code": null,
"e": 1016,
"s": 1008,
"text": "Python3"
},
{
"code": null,
"e": 1019,
"s": 1016,
"text": "C#"
},
{
"code": null,
"e": 1030,
"s": 1019,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S #include <bits/stdc++.h>using namespace std; // Function to find the// minimum elements required to// get the sum of given value Sint printAllSubsetsRec(int arr[], int n, vector<int> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return (int)v.size(); } if (sum < 0) return INT_MAX; // Condition when no // such sequence found if (n == 0) return INT_MAX; // Calling for without choosing // the current index value int x = printAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.push_back(arr[n - 1]); int y = printAllSubsetsRec( arr, n, v, sum - arr[n - 1]); return min(x, y);} // Function for every arrayint printAllSubsets(int arr[], int n, int sum){ vector<int> v; return printAllSubsetsRec(arr, n, v, sum);} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << printAllSubsets(arr, n, sum) << endl; return 0;}",
"e": 2336,
"s": 1030,
"text": null
},
{
"code": "// Java implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Simport java.util.*;import java.lang.*; class GFG{ // Function to find the// minimum elements required to// get the sum of given value Sstatic int printAllSubsetsRec(int arr[], int n, ArrayList<Integer> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return (int)v.size(); } if (sum < 0) return Integer.MAX_VALUE; // Condition when no // such sequence found if (n == 0) return Integer.MAX_VALUE; // Calling for without choosing // the current index value int x = printAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.add(arr[n - 1]); int y = printAllSubsetsRec( arr, n, v, sum - arr[n - 1]); v.remove(v.size() - 1); return Math.min(x, y);} // Function for every arraystatic int printAllSubsets(int arr[], int n, int sum){ ArrayList<Integer> v = new ArrayList<>(); return printAllSubsetsRec(arr, n, v, sum);} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = arr.length; System.out.println(printAllSubsets(arr, n, sum));}} // This code is contributed by offbeat",
"e": 3868,
"s": 2336,
"text": null
},
{
"code": "# Python3 implementation to find the# minimum number of sequence# required from array such that# their sum is equal to given Simport sys # Function to find the# minimum elements required to# get the sum of given value Sdef printAllSubsetsRec(arr, n, v, Sum): # Condition if the # sequence is found if (Sum == 0): return len(v) if (Sum < 0): return sys.maxsize # Condition when no # such sequence found if (n == 0): return sys.maxsize # Calling for without choosing # the current index value x = printAllSubsetsRec(arr, n - 1, v, Sum) # Calling for after choosing # the current index value v.append(arr[n - 1]) y = printAllSubsetsRec(arr, n, v, Sum - arr[n - 1]) v.pop(len(v) - 1) return min(x, y) # Function for every arraydef printAllSubsets(arr, n, Sum): v = [] return printAllSubsetsRec(arr, n, v, Sum) # Driver codearr = [ 2, 1, 4, 3, 5, 6 ]Sum = 6n = len(arr) print(printAllSubsets(arr, n, Sum)) # This code is contributed by avanitrachhadiya2155",
"e": 4940,
"s": 3868,
"text": null
},
{
"code": "// C# implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Susing System;using System.Collections.Generic; class GFG{ // Function to find the// minimum elements required to// get the sum of given value Sstatic int printAllSubsetsRec(int[] arr, int n, List<int> v, int sum){ // Condition if the // sequence is found if (sum == 0) { return v.Count; } if (sum < 0) return Int32.MaxValue; // Condition when no // such sequence found if (n == 0) return Int32.MaxValue; // Calling for without choosing // the current index value int x = printAllSubsetsRec(arr, n - 1, v, sum); // Calling for after choosing // the current index value v.Add(arr[n - 1]); int y = printAllSubsetsRec(arr, n, v, sum - arr[n - 1]); v.RemoveAt(v.Count - 1); return Math.Min(x, y);} // Function for every arraystatic int printAllSubsets(int[] arr, int n, int sum){ List<int> v = new List<int>(); return printAllSubsetsRec(arr, n, v, sum);} // Driver code static void Main(){ int[] arr = { 2, 1, 4, 3, 5, 6 }; int sum = 6; int n = arr.Length; Console.WriteLine(printAllSubsets(arr, n, sum));}} // This code is contributed by divyeshrabadiya07",
"e": 6365,
"s": 4940,
"text": null
},
{
"code": "<script>// Javascript implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S // Function to find the// minimum elements required to// get the sum of given value Sfunction prletAllSubsetsRec(arr, n, v, sum){ // Condition if the // sequence is found if (sum == 0) { return v.length; } if (sum < 0) return Number.MAX_VALUE; // Condition when no // such sequence found if (n == 0) return Number.MAX_VALUE; // Calling for without choosing // the current index value let x = prletAllSubsetsRec( arr, n - 1, v, sum); // Calling for after choosing // the current index value v.push(arr[n - 1]); let y = prletAllSubsetsRec( arr, n, v, sum - arr[n - 1]); v.pop(v.length - 1); return Math.min(x, y);} // Function for every arrayfunction prletAllSubsets(arr, n, sum){ let v = []; return prletAllSubsetsRec(arr, n, v, sum);} // Driver Code let arr = [ 2, 1, 4, 3, 5, 6 ]; let sum = 6; let n = arr.length; document.write(prletAllSubsets(arr, n, sum)); </script>",
"e": 7657,
"s": 6365,
"text": null
},
{
"code": null,
"e": 7659,
"s": 7657,
"text": "1"
},
{
"code": null,
"e": 7685,
"s": 7661,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 7844,
"s": 7685,
"text": "Time Complexity: As in the above approach, there are two choose for every number in each step which takes O(2N) time, Hence the Time Complexity will be O(2N)."
},
{
"code": null,
"e": 7959,
"s": 7844,
"text": "Space Complexity: As in the above approach, there is no extra space used, Hence the space complexity will be O(1)."
},
{
"code": null,
"e": 8451,
"s": 7959,
"text": "Efficient Approach: As in the above approach there is overlapping subproblems, So the idea is to use Dynamic Programming paradigm to solve this problem. Create a DP table of N * S to store the pre-computed answer for the previous sequence that is the minimum length sequence required to get the sum as S – arr[i] and in this way the finally after calculating for every value of the array, the answer to the problem will be dp[N][S], where m is the length of the array and S is the given sum."
},
{
"code": null,
"e": 8504,
"s": 8451,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 8508,
"s": 8504,
"text": "C++"
},
{
"code": null,
"e": 8513,
"s": 8508,
"text": "Java"
},
{
"code": null,
"e": 8521,
"s": 8513,
"text": "Python3"
},
{
"code": null,
"e": 8524,
"s": 8521,
"text": "C#"
},
{
"code": null,
"e": 8535,
"s": 8524,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S #include <bits/stdc++.h>using namespace std; // Function to find the count of// minimum length of the sequenceint Count(int S[], int m, int n){ vector<vector<int> > table( m + 1, vector<int>( n + 1, 0)); // Loop to initialize the array // as infinite in the row 0 for (int i = 1; i <= n; i++) { table[0][i] = INT_MAX - 1; } // Loop to find the solution // by pre-computation for the // sequence for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible // for the previous // minimum value // of the sequence table[i][j] = min( table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codeint main(){ int arr[] = { 9, 6, 5, 1 }; int m = sizeof(arr) / sizeof(arr[0]); cout << Count(arr, m, 11); return 0;}",
"e": 9790,
"s": 8535,
"text": null
},
{
"code": "// Java implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Simport java.util.*; class GFG{ // Function to find the count of// minimum length of the sequencestatic int Count(int S[], int m, int n){ int [][]table = new int[m + 1][n + 1]; // Loop to initialize the array // as infinite in the row 0 for(int i = 1; i <= n; i++) { table[0][i] = Integer.MAX_VALUE - 1; } // Loop to find the solution // by pre-computation for the // sequence for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible for the // previous minimum value // of the sequence table[i][j] = Math.min(table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codepublic static void main(String[] args){ int arr[] = { 9, 6, 5, 1 }; int m = arr.length; System.out.print(Count(arr, m, 11));}} // This code is contributed by gauravrajput1",
"e": 10976,
"s": 9790,
"text": null
},
{
"code": "# Python3 implementation to find the# minimum number of sequence# required from array such that# their sum is equal to given S # Function to find the count of# minimum length of the sequencedef Count(S, m, n): table = [[0 for i in range(n + 1)] for i in range(m + 1)] # Loop to initialize the array # as infinite in the row 0 for i in range(1, n + 1): table[0][i] = 10**9 - 1 # Loop to find the solution # by pre-computation for the # sequence for i in range(1, m + 1): for j in range(1, n + 1): if (S[i - 1] > j): table[i][j] = table[i - 1][j] else: # Minimum possible # for the previous # minimum value # of the sequence table[i][j] = min(table[i - 1][j], table[i][j - S[i - 1]] + 1) return table[m][n] # Driver Codeif __name__ == '__main__': arr= [9, 6, 5, 1] m = len(arr) print(Count(arr, m, 11)) # This code is contributed by Mohit Kumar",
"e": 12032,
"s": 10976,
"text": null
},
{
"code": "// C# implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given Susing System; class GFG{ // Function to find the count of// minimum length of the sequencestatic int Count(int[] S, int m, int n){ int[,] table = new int[m + 1, n + 1]; // Loop to initialize the array // as infinite in the row 0 for(int i = 1; i <= n; i++) { table[0, i] = int.MaxValue - 1; } // Loop to find the solution // by pre-computation for the // sequence for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i, j] = table[i - 1, j]; } else { // Minimum possible for the // previous minimum value // of the sequence table[i, j] = Math.Min(table[i - 1, j], table[i, j - S[i - 1]] + 1); } } } return table[m, n];} // Driver Codepublic static void Main(String[] args){ int[] arr = { 9, 6, 5, 1 }; int m = 4; Console.WriteLine(Count(arr, m, 11));}} // This code is contributed by jrishabh99",
"e": 13189,
"s": 12032,
"text": null
},
{
"code": "<script> // JavaScript implementation to find the// minimum number of sequence// required from array such that// their sum is equal to given S // Function to find the count of// minimum length of the sequencefunction Count(S, m, n){ let table = []; for(let i = 0;i<m+1;i++){ table[i] = []; for(let j = 0;j<n+1;j++){ table[i][j] = 0; } } // Loop to initialize the array // as infinite in the row 0 for (let i = 1; i <= n; i++) { table[0][i] = Number.MAX_VALUE - 1; } // Loop to find the solution // by pre-computation for the // sequence for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { if (S[i - 1] > j) { table[i][j] = table[i - 1][j]; } else { // Minimum possible // for the previous // minimum value // of the sequence table[i][j] = Math.min( table[i - 1][j], table[i][j - S[i - 1]] + 1); } } } return table[m][n];} // Driver Codelet arr = [ 9, 6, 5, 1 ];let m = arr.length;document.write(Count(arr, m, 11)); </script>",
"e": 14438,
"s": 13189,
"text": null
},
{
"code": null,
"e": 14440,
"s": 14438,
"text": "2"
},
{
"code": null,
"e": 14465,
"s": 14442,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 14652,
"s": 14465,
"text": "Time Complexity: As in the above approach, there are two loop for the calculation of the minimum length sequence required which takes O(N2) time, Hence the Time Complexity will be O(N2)."
},
{
"code": null,
"e": 14770,
"s": 14652,
"text": "Space Complexity: As in the above approach, there is a extra dp table used, Hence the space complexity will be O(N2)."
},
{
"code": null,
"e": 14787,
"s": 14772,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 14801,
"s": 14787,
"text": "GauravRajput1"
},
{
"code": null,
"e": 14812,
"s": 14801,
"text": "jrishabh99"
},
{
"code": null,
"e": 14820,
"s": 14812,
"text": "offbeat"
},
{
"code": null,
"e": 14837,
"s": 14820,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 14855,
"s": 14837,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 14876,
"s": 14855,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14889,
"s": 14876,
"text": "simmytarika5"
},
{
"code": null,
"e": 14902,
"s": 14889,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14912,
"s": 14902,
"text": "splevel62"
},
{
"code": null,
"e": 14928,
"s": 14912,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 14935,
"s": 14928,
"text": "Arrays"
},
{
"code": null,
"e": 14948,
"s": 14935,
"text": "Backtracking"
},
{
"code": null,
"e": 14968,
"s": 14948,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14981,
"s": 14968,
"text": "Mathematical"
},
{
"code": null,
"e": 14991,
"s": 14981,
"text": "Recursion"
},
{
"code": null,
"e": 14998,
"s": 14991,
"text": "Arrays"
},
{
"code": null,
"e": 15018,
"s": 14998,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 15031,
"s": 15018,
"text": "Mathematical"
},
{
"code": null,
"e": 15041,
"s": 15031,
"text": "Recursion"
},
{
"code": null,
"e": 15054,
"s": 15041,
"text": "Backtracking"
},
{
"code": null,
"e": 15152,
"s": 15054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15184,
"s": 15152,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 15198,
"s": 15184,
"text": "Linear Search"
},
{
"code": null,
"e": 15283,
"s": 15198,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15306,
"s": 15283,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 15333,
"s": 15306,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 15393,
"s": 15333,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 15478,
"s": 15393,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15511,
"s": 15478,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 15554,
"s": 15511,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
WPF - Textblock
|
A TextBlock is a lightweight control for displaying small amounts of read-only text. The hierarchical inheritance of TextBlock class is as follows −
ContentEnd
Gets a TextPointer object for the end of text content in the TextBlock.
ContentStart
Gets a TextPointer object for the start of text content in the TextBlock.
IsTextSelectionEnabled
Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API.
IsTextSelectionEnabledProperty
Identifies the IsTextSelectionEnabled dependency property.
LineHeight
Gets or sets the height of each line of content.
MaxLines
Gets or sets the maximum lines of text shown in the TextBlock.
SelectedText
Gets a text range of selected text.
SelectionEnd
Gets the end position of the text selected in the TextBlock.
SelectionHighlightColor
Gets or sets the brush used to highlight the selected text.
SelectionStart
Gets the starting position of the text selected in the TextBlock.
Text
Gets or sets the text contents of a TextBlock.
TextAlignment
Gets or sets a value that indicates the horizontal alignment of text content.
TextTrimming
Gets or sets the text trimming behavior to employ when content overflows the content area.
TextWrapping
Gets or sets how the TextBlock wraps text.
ContextMenuOpening
Occurs when the system processes an interaction that displays a context menu.
SelectionChanged
Occurs when the text selection has changed.
Focus
Focuses the TextBlock, as if it were a conventionally focusable control.
Select
Selects a range of text in the TextBlock.
SelectAll
Selects the entire contents in the TextBlock.
Let’s create a new WPF project with WPFTextBlockControl.
Drag a text block from the toolbox.
Change the background color of the text block from the properties window.
The following example shows the usage of TextBlock in an XAML application.
Here is the XAML code in which a TextBlock is created with some properties.
<Window x:Class = "WPFTextBlockControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFTextBlockControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<TextBlock FontFamily = "Verdana"
LineStackingStrategy = "MaxHeight" LineHeight = "10" Width = "500"
TextWrapping = "Wrap" Background = "#FFE2B1B1" Margin = "48,8,48,10">
Use the <Run FontSize = "30">LineStackingStrategy</Run> property to determine how
a line box is created for each line. A value of <Run FontSize = "20">MaxHeight</Run>
specifies that the stack height is the smallest value that contains all the inline
elements on that line when those elements are properly aligned. A value of <Run
FontSize = "20"> BlockLineHeight</Run> specifies that the stack height is
determined by the block element LineHeight property value.
</TextBlock>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following output −
We recommend that you execute the above example code and try the other properties and events of TextBlock class.
|
[
{
"code": null,
"e": 2303,
"s": 2154,
"text": "A TextBlock is a lightweight control for displaying small amounts of read-only text. The hierarchical inheritance of TextBlock class is as follows −"
},
{
"code": null,
"e": 2314,
"s": 2303,
"text": "ContentEnd"
},
{
"code": null,
"e": 2386,
"s": 2314,
"text": "Gets a TextPointer object for the end of text content in the TextBlock."
},
{
"code": null,
"e": 2399,
"s": 2386,
"text": "ContentStart"
},
{
"code": null,
"e": 2473,
"s": 2399,
"text": "Gets a TextPointer object for the start of text content in the TextBlock."
},
{
"code": null,
"e": 2496,
"s": 2473,
"text": "IsTextSelectionEnabled"
},
{
"code": null,
"e": 2645,
"s": 2496,
"text": "Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API."
},
{
"code": null,
"e": 2676,
"s": 2645,
"text": "IsTextSelectionEnabledProperty"
},
{
"code": null,
"e": 2735,
"s": 2676,
"text": "Identifies the IsTextSelectionEnabled dependency property."
},
{
"code": null,
"e": 2746,
"s": 2735,
"text": "LineHeight"
},
{
"code": null,
"e": 2795,
"s": 2746,
"text": "Gets or sets the height of each line of content."
},
{
"code": null,
"e": 2804,
"s": 2795,
"text": "MaxLines"
},
{
"code": null,
"e": 2867,
"s": 2804,
"text": "Gets or sets the maximum lines of text shown in the TextBlock."
},
{
"code": null,
"e": 2880,
"s": 2867,
"text": "SelectedText"
},
{
"code": null,
"e": 2916,
"s": 2880,
"text": "Gets a text range of selected text."
},
{
"code": null,
"e": 2929,
"s": 2916,
"text": "SelectionEnd"
},
{
"code": null,
"e": 2990,
"s": 2929,
"text": "Gets the end position of the text selected in the TextBlock."
},
{
"code": null,
"e": 3014,
"s": 2990,
"text": "SelectionHighlightColor"
},
{
"code": null,
"e": 3074,
"s": 3014,
"text": "Gets or sets the brush used to highlight the selected text."
},
{
"code": null,
"e": 3089,
"s": 3074,
"text": "SelectionStart"
},
{
"code": null,
"e": 3155,
"s": 3089,
"text": "Gets the starting position of the text selected in the TextBlock."
},
{
"code": null,
"e": 3160,
"s": 3155,
"text": "Text"
},
{
"code": null,
"e": 3207,
"s": 3160,
"text": "Gets or sets the text contents of a TextBlock."
},
{
"code": null,
"e": 3221,
"s": 3207,
"text": "TextAlignment"
},
{
"code": null,
"e": 3299,
"s": 3221,
"text": "Gets or sets a value that indicates the horizontal alignment of text content."
},
{
"code": null,
"e": 3312,
"s": 3299,
"text": "TextTrimming"
},
{
"code": null,
"e": 3403,
"s": 3312,
"text": "Gets or sets the text trimming behavior to employ when content overflows the content area."
},
{
"code": null,
"e": 3416,
"s": 3403,
"text": "TextWrapping"
},
{
"code": null,
"e": 3459,
"s": 3416,
"text": "Gets or sets how the TextBlock wraps text."
},
{
"code": null,
"e": 3478,
"s": 3459,
"text": "ContextMenuOpening"
},
{
"code": null,
"e": 3557,
"s": 3478,
"text": "Occurs when the system processes an interaction that displays a context menu. "
},
{
"code": null,
"e": 3574,
"s": 3557,
"text": "SelectionChanged"
},
{
"code": null,
"e": 3618,
"s": 3574,
"text": "Occurs when the text selection has changed."
},
{
"code": null,
"e": 3624,
"s": 3618,
"text": "Focus"
},
{
"code": null,
"e": 3697,
"s": 3624,
"text": "Focuses the TextBlock, as if it were a conventionally focusable control."
},
{
"code": null,
"e": 3704,
"s": 3697,
"text": "Select"
},
{
"code": null,
"e": 3746,
"s": 3704,
"text": "Selects a range of text in the TextBlock."
},
{
"code": null,
"e": 3756,
"s": 3746,
"text": "SelectAll"
},
{
"code": null,
"e": 3802,
"s": 3756,
"text": "Selects the entire contents in the TextBlock."
},
{
"code": null,
"e": 3859,
"s": 3802,
"text": "Let’s create a new WPF project with WPFTextBlockControl."
},
{
"code": null,
"e": 3895,
"s": 3859,
"text": "Drag a text block from the toolbox."
},
{
"code": null,
"e": 3969,
"s": 3895,
"text": "Change the background color of the text block from the properties window."
},
{
"code": null,
"e": 4044,
"s": 3969,
"text": "The following example shows the usage of TextBlock in an XAML application."
},
{
"code": null,
"e": 4120,
"s": 4044,
"text": "Here is the XAML code in which a TextBlock is created with some properties."
},
{
"code": null,
"e": 5373,
"s": 4120,
"text": "<Window x:Class = \"WPFTextBlockControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFTextBlockControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <TextBlock FontFamily = \"Verdana\" \n LineStackingStrategy = \"MaxHeight\" LineHeight = \"10\" Width = \"500\" \n TextWrapping = \"Wrap\" Background = \"#FFE2B1B1\" Margin = \"48,8,48,10\">\n\t\t\t\n Use the <Run FontSize = \"30\">LineStackingStrategy</Run> property to determine how\n a line box is created for each line. A value of <Run FontSize = \"20\">MaxHeight</Run> \n specifies that the stack height is the smallest value that contains all the inline \n elements on that line when those elements are properly aligned. A value of <Run \n FontSize = \"20\"> BlockLineHeight</Run> specifies that the stack height is \n determined by the block element LineHeight property value. \n </TextBlock> \n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 5457,
"s": 5373,
"text": "When you compile and execute the above code, it will produce the following output −"
}
] |
PyQt5 – How to change size of the Label | label.resize method
|
26 Mar, 2020
While designing any GUI(Graphical User Interface) application we create labels that provide information, but sometimes there might be a case when the label size is not appropriate for the content then need of resizing of label arises.
In this tutorial, we will see how to change the size of the label in PyQt5. For this we will use resize() method.
Syntax : label.resize(width, height)
Argument : It takes two integers as the argument which are :1. Width to be set.2. Height to be set.
Code :
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel('Normal Label', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # creating a label widget self.label_2 = QLabel('====== extra width label =====', self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet("border: 1px solid black;") # resizing the widget self.label_2.resize(200, 20) # creating a label widget self.label_3 = QLabel('tiny label', self) # moving position self.label_3.move(100, 200) # setting up border self.label_3.setStyleSheet("border: 1px solid black;") # resizing the widget self.label_3.resize(60, 15) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 288,
"s": 53,
"text": "While designing any GUI(Graphical User Interface) application we create labels that provide information, but sometimes there might be a case when the label size is not appropriate for the content then need of resizing of label arises."
},
{
"code": null,
"e": 402,
"s": 288,
"text": "In this tutorial, we will see how to change the size of the label in PyQt5. For this we will use resize() method."
},
{
"code": null,
"e": 439,
"s": 402,
"text": "Syntax : label.resize(width, height)"
},
{
"code": null,
"e": 539,
"s": 439,
"text": "Argument : It takes two integers as the argument which are :1. Width to be set.2. Height to be set."
},
{
"code": null,
"e": 546,
"s": 539,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel('Normal Label', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # creating a label widget self.label_2 = QLabel('====== extra width label =====', self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet(\"border: 1px solid black;\") # resizing the widget self.label_2.resize(200, 20) # creating a label widget self.label_3 = QLabel('tiny label', self) # moving position self.label_3.move(100, 200) # setting up border self.label_3.setStyleSheet(\"border: 1px solid black;\") # resizing the widget self.label_3.resize(60, 15) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1958,
"s": 546,
"text": null
},
{
"code": null,
"e": 1967,
"s": 1958,
"text": "Output :"
},
{
"code": null,
"e": 1978,
"s": 1967,
"text": "Python-gui"
},
{
"code": null,
"e": 1990,
"s": 1978,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1997,
"s": 1990,
"text": "Python"
}
] |
SQL Server | SERVERPROPERTY()
|
05 Aug, 2020
SQL Server provides a System Defined function SERVERPROPERTY(propertyname).
SERVERPROPERTY(): SERVERPROPERTY() function is used to return the information about different properties of system or so called the instance information.
propertyname: This expression contains the information about property in question and returns the same.
Following are few property names which SERVERPROPERTY() function provides information about. Apart from mentioned properties there are other properties too.
1. MachineName: This property name is used as an argument in SERVERPROPERTY() function to find the name of the machine/computer on which SQL Server is running.
Syntax:
SELECT SERVERPROPERTY ('MachineName')
Example:
Output:
2. Edition: This property name is used an argument in SERVERPROPERTY() function to get the edition of SQL Server installed on machine/computer.
Syntax:
SELECT SERVERPROPERTY ('Edition')
Example:
3. INSTANCEDEFAULTDATAPATH: This property name is used as an argument in SERVERPROPERTY() function to find the default path of the data files.
Syntax:
SELECT SERVERPROPERTY ('INSTANCEDEFAULTDATAPATH')
Example:
4. INSTANCEDEFAULTLOGPATH: This property name is used as an argument in SERVERPROPERTY() function to find the default path of the log files.
Syntax:
SELECT SERVERPROPERTY ('INSTANCEDEFAULTLOGPATH')
Example:
5. PRODUCTVERSION: This property name is used as an argument in SERVERPROPERTY() function to get the information about the version of product being used.
Syntax:
SELECT SERVERPROPERTY (' PRODUCTVERSION')
Example:
6. BUILDCLRVERSION: This property name is used as an argument in SERVERPROPERTY() function to get the information about the version of the Microsoft .NET Framework Common Language Runtime (CLR). This framework was used for building the SQL Server instance.
Syntax:
SELECT SERVERPROPERTY ('BUILDCLRVERSION')
Example:
7. PROCESSID: This property name is used as an argument in SERVERPROPERTY() function to get the Process ID of the SQL Server service.
Syntax:
SELECT SERVERPROPERTY ('PROCESSID')
Example:
8. ResourceLastUpdateDateTime: This property name is used as an argument in SERVERPROPERTY() function to get the information about the last updates of the Resource Database i.e the Date and Time when the Resource Database was last updated on.
Syntax:
SELECT SERVERPROPERTY ('ResourceLastUpdateDateTime')
Example:
9. EditionID: This property name is used as an argument in SERVERPROPERTY() function to find the Edition ID of the SQL Server being installed on computer/machine.
Syntax:
SELECT SERVERPROPERTY ('EditionID')
Example:
10. Collation: This property name is used as an argument in SERVERPROPERTY() function to find the collation of the SQL Server being installed on computer/machine.
Syntax:
select SERVERPROPERTY ('collation')
Example:
Note: To get the information about other properties, refer Microsoft Docs.
khushboogoyal499
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "SQL Server provides a System Defined function SERVERPROPERTY(propertyname). "
},
{
"code": null,
"e": 260,
"s": 105,
"text": "SERVERPROPERTY(): SERVERPROPERTY() function is used to return the information about different properties of system or so called the instance information. "
},
{
"code": null,
"e": 365,
"s": 260,
"text": "propertyname: This expression contains the information about property in question and returns the same. "
},
{
"code": null,
"e": 523,
"s": 365,
"text": "Following are few property names which SERVERPROPERTY() function provides information about. Apart from mentioned properties there are other properties too. "
},
{
"code": null,
"e": 684,
"s": 523,
"text": "1. MachineName: This property name is used as an argument in SERVERPROPERTY() function to find the name of the machine/computer on which SQL Server is running. "
},
{
"code": null,
"e": 694,
"s": 684,
"text": "Syntax: "
},
{
"code": null,
"e": 734,
"s": 694,
"text": "SELECT SERVERPROPERTY ('MachineName')\n\n"
},
{
"code": null,
"e": 745,
"s": 734,
"text": "Example: "
},
{
"code": null,
"e": 755,
"s": 745,
"text": "Output: "
},
{
"code": null,
"e": 900,
"s": 755,
"text": "2. Edition: This property name is used an argument in SERVERPROPERTY() function to get the edition of SQL Server installed on machine/computer. "
},
{
"code": null,
"e": 910,
"s": 900,
"text": "Syntax: "
},
{
"code": null,
"e": 946,
"s": 910,
"text": "SELECT SERVERPROPERTY ('Edition')\n\n"
},
{
"code": null,
"e": 957,
"s": 946,
"text": "Example: "
},
{
"code": null,
"e": 1101,
"s": 957,
"text": "3. INSTANCEDEFAULTDATAPATH: This property name is used as an argument in SERVERPROPERTY() function to find the default path of the data files. "
},
{
"code": null,
"e": 1111,
"s": 1101,
"text": "Syntax: "
},
{
"code": null,
"e": 1163,
"s": 1111,
"text": "SELECT SERVERPROPERTY ('INSTANCEDEFAULTDATAPATH')\n\n"
},
{
"code": null,
"e": 1174,
"s": 1163,
"text": "Example: "
},
{
"code": null,
"e": 1316,
"s": 1174,
"text": "4. INSTANCEDEFAULTLOGPATH: This property name is used as an argument in SERVERPROPERTY() function to find the default path of the log files. "
},
{
"code": null,
"e": 1326,
"s": 1316,
"text": "Syntax: "
},
{
"code": null,
"e": 1377,
"s": 1326,
"text": "SELECT SERVERPROPERTY ('INSTANCEDEFAULTLOGPATH')\n\n"
},
{
"code": null,
"e": 1388,
"s": 1377,
"text": "Example: "
},
{
"code": null,
"e": 1543,
"s": 1388,
"text": "5. PRODUCTVERSION: This property name is used as an argument in SERVERPROPERTY() function to get the information about the version of product being used. "
},
{
"code": null,
"e": 1553,
"s": 1543,
"text": "Syntax: "
},
{
"code": null,
"e": 1597,
"s": 1553,
"text": "SELECT SERVERPROPERTY (' PRODUCTVERSION')\n\n"
},
{
"code": null,
"e": 1608,
"s": 1597,
"text": "Example: "
},
{
"code": null,
"e": 1866,
"s": 1608,
"text": "6. BUILDCLRVERSION: This property name is used as an argument in SERVERPROPERTY() function to get the information about the version of the Microsoft .NET Framework Common Language Runtime (CLR). This framework was used for building the SQL Server instance. "
},
{
"code": null,
"e": 1876,
"s": 1866,
"text": "Syntax: "
},
{
"code": null,
"e": 1920,
"s": 1876,
"text": "SELECT SERVERPROPERTY ('BUILDCLRVERSION')\n\n"
},
{
"code": null,
"e": 1931,
"s": 1920,
"text": "Example: "
},
{
"code": null,
"e": 2066,
"s": 1931,
"text": "7. PROCESSID: This property name is used as an argument in SERVERPROPERTY() function to get the Process ID of the SQL Server service. "
},
{
"code": null,
"e": 2076,
"s": 2066,
"text": "Syntax: "
},
{
"code": null,
"e": 2114,
"s": 2076,
"text": "SELECT SERVERPROPERTY ('PROCESSID')\n\n"
},
{
"code": null,
"e": 2125,
"s": 2114,
"text": "Example: "
},
{
"code": null,
"e": 2369,
"s": 2125,
"text": "8. ResourceLastUpdateDateTime: This property name is used as an argument in SERVERPROPERTY() function to get the information about the last updates of the Resource Database i.e the Date and Time when the Resource Database was last updated on. "
},
{
"code": null,
"e": 2379,
"s": 2369,
"text": "Syntax: "
},
{
"code": null,
"e": 2434,
"s": 2379,
"text": "SELECT SERVERPROPERTY ('ResourceLastUpdateDateTime')\n\n"
},
{
"code": null,
"e": 2445,
"s": 2434,
"text": "Example: "
},
{
"code": null,
"e": 2609,
"s": 2445,
"text": "9. EditionID: This property name is used as an argument in SERVERPROPERTY() function to find the Edition ID of the SQL Server being installed on computer/machine. "
},
{
"code": null,
"e": 2619,
"s": 2609,
"text": "Syntax: "
},
{
"code": null,
"e": 2657,
"s": 2619,
"text": "SELECT SERVERPROPERTY ('EditionID')\n\n"
},
{
"code": null,
"e": 2668,
"s": 2657,
"text": "Example: "
},
{
"code": null,
"e": 2832,
"s": 2668,
"text": "10. Collation: This property name is used as an argument in SERVERPROPERTY() function to find the collation of the SQL Server being installed on computer/machine. "
},
{
"code": null,
"e": 2840,
"s": 2832,
"text": "Syntax:"
},
{
"code": null,
"e": 2876,
"s": 2840,
"text": "select SERVERPROPERTY ('collation')"
},
{
"code": null,
"e": 2886,
"s": 2876,
"text": "Example: "
},
{
"code": null,
"e": 2962,
"s": 2886,
"text": "Note: To get the information about other properties, refer Microsoft Docs. "
},
{
"code": null,
"e": 2979,
"s": 2962,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 2990,
"s": 2979,
"text": "SQL-Server"
},
{
"code": null,
"e": 2994,
"s": 2990,
"text": "SQL"
},
{
"code": null,
"e": 2998,
"s": 2994,
"text": "SQL"
},
{
"code": null,
"e": 3096,
"s": 2998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3162,
"s": 3096,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3186,
"s": 3162,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3218,
"s": 3186,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3235,
"s": 3218,
"text": "SQL using Python"
},
{
"code": null,
"e": 3268,
"s": 3235,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 3346,
"s": 3268,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 3376,
"s": 3346,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 3412,
"s": 3376,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 3443,
"s": 3412,
"text": "SQL Query to Compare Two Dates"
}
] |
Cyclic Number
|
03 May, 2022
A cyclic number is an integer in which cyclic permutations of the digits are successive multiples of the number. The most widely known is the six-digit number 142857 (Please see below explanation given in examples).The following trivial cases are typically excluded for Cyclic Numbers.
Single digits, e.g.: 5
Repeated digits, e.g.: 555
Repeated cyclic numbers, e.g.: 142857142857
Given a number, check if it is cyclic or not.Examples:
Input : 142857
Output : Yes
Explanation
142857 × 1 = 142857
142857 × 2 = 285714
142857 × 3 = 428571
142857 × 4 = 571428
142857 × 5 = 714285
142857 × 6 = 857142
We generate all cyclic permutations of the number and check if every permutation divides number of not. We also check for three conditions. If any of the three conditions is true, we return false.
C++
Java
Python3
C#
PHP
Javascript
// Program to check if a number is cyclic.#include <bits/stdc++.h>using namespace std; #define ull unsigned long long int // Function to generate all cyclic permutations// of a numberbool isCyclic(ull N){ // Count digits and check if all // digits are same ull num = N; int count = 0; int digit = num % 10; bool allSame = true; while (num) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { ull halfPower = pow(10, count / 2); ull firstHalf = N % halfPower; ull secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (1) { // Following three lines generates a // circular permutation of a number. ull rem = num % 10; ull div = num / 10; num = (pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true;} // Driver Programint main(){ ull N = 142857; if (isCyclic(N)) cout << "Yes"; else cout << "No"; return 0;}
// Java Program to check if a number is cyclic class GFG { // Function to generate all cyclic // permutations of a number static boolean isCyclic(long N) { // Count digits and check if all // digits are same long num = N; int count = 0; int digit = (int)(num % 10); boolean allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { long halfPower = (long)Math.pow(10, count / 2); long firstHalf = N % halfPower; long secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. long rem = num % 10; long div = num / 10; num = (long)(Math.pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // Driver code public static void main(String[] args) { long N = 142857; if (isCyclic(N)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal.
# Program to check if# a number is cyclic# Function to generate# all cyclic permutations# of a numberdef isCyclic(N): # Count digits and check if all # digits are same num = N count = 0 digit =(num % 10) allSame = True while (num>0): count+= 1 if (num % 10 != digit): allSame = False num = num // 10 # If all digits are same, then # not considered cyclic. if (allSame == True): return False # If counts of digits is even and # two halves are same, then the # number is not considered cyclic. if (count % 2 == 0): halfPower = pow(10, count//2) firstHalf = N % halfPower secondHalf = N / halfPower if (firstHalf == firstHalf and isCyclic(firstHalf)): return False num = N while (True): # Following three lines # generates a # circular permutation # of a number. rem = num % 10 div = num // 10 num = pow(10, count - 1) * rem + div # If all the permutations # are checked # and we obtain original # number exit # from loop. if (num == N): break if (num % N != 0): return False return True # Driver code N = 142857if (isCyclic(N)): print("Yes")else: print("No") # This code is contributed# by Anant Agarwal.
// C# Program to check if a number is cyclicusing System; class GFG { // Function to generate all cyclic // permutations of a number static bool isCyclic(long N) { // Count digits and check if all // digits are same long num = N; int count = 0; int digit = (int)(num % 10); bool allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { long halfPower = (long)Math.Pow(10, count / 2); long firstHalf = N % halfPower; // long secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. long rem = num % 10; long div = num / 10; num = (long)(Math.Pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // Driver code public static void Main() { long N = 142857; if (isCyclic(N)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// Program to check if a number is cyclic // Function to generate all cyclic// permutations of a numberfunction isCyclic($N){ // Count digits and check if all // digits are same $num = $N; $count = 0; $digit = ($num % 10); $allSame = true; while ($num > 0) { $count += 1; if ($num % 10 != $digit) $allSame = false; $num = (int)($num / 10); } // If all digits are same, then // not considered cyclic. if ($allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if ($count % 2 == 0) { $halfPower = pow(10, (int)($count / 2)); $firstHalf = $N % $halfPower; $secondHalf = $N / $halfPower; if ($firstHalf == $firstHalf && isCyclic($firstHalf)) return false; } $num = $N; while (true) { // Following three lines generates a // circular permutation of a number. $rem = $num % 10; $div = (int)($num / 10); $num = pow(10, $count - 1) * $rem + $div; // If all the permutations are checked // and we obtain original number, exit // from loop. if ($num == $N) break; if ($num % $N != 0) return false; } return true;} // Driver code$N = 142857;if (isCyclic($N)) print("Yes");else print("No"); // This code is contributed by mits?>
<script>// Javascript Program to check if a number is cyclic // Function to generate all cyclic // permutations of a number function isCyclic(N) { // Count digits and check if all // digits are same let num = N; let count = 0; let digit = Math.floor(num % 10); let allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = Math.floor(num / 10); } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { let halfPower = Math.floor(Math.pow(10, count / 2)); let firstHalf = Math.floor(N % halfPower); let secondHalf = Math.floor(N / halfPower); if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. let rem = num % 10; let div = Math.floor(num / 10); num = Math.floor(Math.pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // driver function let N = 142857; if (isCyclic(N)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
Reference : https://en.wikipedia.org/wiki/Cyclic_numberThis article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above..
vt_m
Mithun Kumar
sanjoy_62
simmytarika5
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 342,
"s": 54,
"text": "A cyclic number is an integer in which cyclic permutations of the digits are successive multiples of the number. The most widely known is the six-digit number 142857 (Please see below explanation given in examples).The following trivial cases are typically excluded for Cyclic Numbers. "
},
{
"code": null,
"e": 365,
"s": 342,
"text": "Single digits, e.g.: 5"
},
{
"code": null,
"e": 392,
"s": 365,
"text": "Repeated digits, e.g.: 555"
},
{
"code": null,
"e": 436,
"s": 392,
"text": "Repeated cyclic numbers, e.g.: 142857142857"
},
{
"code": null,
"e": 493,
"s": 436,
"text": "Given a number, check if it is cyclic or not.Examples: "
},
{
"code": null,
"e": 678,
"s": 493,
"text": "Input : 142857\nOutput : Yes\nExplanation\n 142857 × 1 = 142857\n 142857 × 2 = 285714\n 142857 × 3 = 428571\n 142857 × 4 = 571428\n 142857 × 5 = 714285\n 142857 × 6 = 857142 "
},
{
"code": null,
"e": 878,
"s": 680,
"text": "We generate all cyclic permutations of the number and check if every permutation divides number of not. We also check for three conditions. If any of the three conditions is true, we return false. "
},
{
"code": null,
"e": 882,
"s": 878,
"text": "C++"
},
{
"code": null,
"e": 887,
"s": 882,
"text": "Java"
},
{
"code": null,
"e": 895,
"s": 887,
"text": "Python3"
},
{
"code": null,
"e": 898,
"s": 895,
"text": "C#"
},
{
"code": null,
"e": 902,
"s": 898,
"text": "PHP"
},
{
"code": null,
"e": 913,
"s": 902,
"text": "Javascript"
},
{
"code": "// Program to check if a number is cyclic.#include <bits/stdc++.h>using namespace std; #define ull unsigned long long int // Function to generate all cyclic permutations// of a numberbool isCyclic(ull N){ // Count digits and check if all // digits are same ull num = N; int count = 0; int digit = num % 10; bool allSame = true; while (num) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { ull halfPower = pow(10, count / 2); ull firstHalf = N % halfPower; ull secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (1) { // Following three lines generates a // circular permutation of a number. ull rem = num % 10; ull div = num / 10; num = (pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true;} // Driver Programint main(){ ull N = 142857; if (isCyclic(N)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 2412,
"s": 913,
"text": null
},
{
"code": "// Java Program to check if a number is cyclic class GFG { // Function to generate all cyclic // permutations of a number static boolean isCyclic(long N) { // Count digits and check if all // digits are same long num = N; int count = 0; int digit = (int)(num % 10); boolean allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { long halfPower = (long)Math.pow(10, count / 2); long firstHalf = N % halfPower; long secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. long rem = num % 10; long div = num / 10; num = (long)(Math.pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // Driver code public static void main(String[] args) { long N = 142857; if (isCyclic(N)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 4244,
"s": 2412,
"text": null
},
{
"code": "# Program to check if# a number is cyclic# Function to generate# all cyclic permutations# of a numberdef isCyclic(N): # Count digits and check if all # digits are same num = N count = 0 digit =(num % 10) allSame = True while (num>0): count+= 1 if (num % 10 != digit): allSame = False num = num // 10 # If all digits are same, then # not considered cyclic. if (allSame == True): return False # If counts of digits is even and # two halves are same, then the # number is not considered cyclic. if (count % 2 == 0): halfPower = pow(10, count//2) firstHalf = N % halfPower secondHalf = N / halfPower if (firstHalf == firstHalf and isCyclic(firstHalf)): return False num = N while (True): # Following three lines # generates a # circular permutation # of a number. rem = num % 10 div = num // 10 num = pow(10, count - 1) * rem + div # If all the permutations # are checked # and we obtain original # number exit # from loop. if (num == N): break if (num % N != 0): return False return True # Driver code N = 142857if (isCyclic(N)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Anant Agarwal.",
"e": 5647,
"s": 4244,
"text": null
},
{
"code": "// C# Program to check if a number is cyclicusing System; class GFG { // Function to generate all cyclic // permutations of a number static bool isCyclic(long N) { // Count digits and check if all // digits are same long num = N; int count = 0; int digit = (int)(num % 10); bool allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = num / 10; } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { long halfPower = (long)Math.Pow(10, count / 2); long firstHalf = N % halfPower; // long secondHalf = N / halfPower; if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. long rem = num % 10; long div = num / 10; num = (long)(Math.Pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // Driver code public static void Main() { long N = 142857; if (isCyclic(N)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 7609,
"s": 5647,
"text": null
},
{
"code": "<?php// Program to check if a number is cyclic // Function to generate all cyclic// permutations of a numberfunction isCyclic($N){ // Count digits and check if all // digits are same $num = $N; $count = 0; $digit = ($num % 10); $allSame = true; while ($num > 0) { $count += 1; if ($num % 10 != $digit) $allSame = false; $num = (int)($num / 10); } // If all digits are same, then // not considered cyclic. if ($allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if ($count % 2 == 0) { $halfPower = pow(10, (int)($count / 2)); $firstHalf = $N % $halfPower; $secondHalf = $N / $halfPower; if ($firstHalf == $firstHalf && isCyclic($firstHalf)) return false; } $num = $N; while (true) { // Following three lines generates a // circular permutation of a number. $rem = $num % 10; $div = (int)($num / 10); $num = pow(10, $count - 1) * $rem + $div; // If all the permutations are checked // and we obtain original number, exit // from loop. if ($num == $N) break; if ($num % $N != 0) return false; } return true;} // Driver code$N = 142857;if (isCyclic($N)) print(\"Yes\");else print(\"No\"); // This code is contributed by mits?>",
"e": 9076,
"s": 7609,
"text": null
},
{
"code": "<script>// Javascript Program to check if a number is cyclic // Function to generate all cyclic // permutations of a number function isCyclic(N) { // Count digits and check if all // digits are same let num = N; let count = 0; let digit = Math.floor(num % 10); let allSame = true; while (num > 0) { count++; if (num % 10 != digit) allSame = false; num = Math.floor(num / 10); } // If all digits are same, then // not considered cyclic. if (allSame == true) return false; // If counts of digits is even and // two halves are same, then the // number is not considered cyclic. if (count % 2 == 0) { let halfPower = Math.floor(Math.pow(10, count / 2)); let firstHalf = Math.floor(N % halfPower); let secondHalf = Math.floor(N / halfPower); if (firstHalf == firstHalf && isCyclic(firstHalf)) return false; } num = N; while (true) { // Following three lines generates a // circular permutation of a number. let rem = num % 10; let div = Math.floor(num / 10); num = Math.floor(Math.pow(10, count - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; if (num % N != 0) return false; } return true; } // driver function let N = 142857; if (isCyclic(N)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 10872,
"s": 9076,
"text": null
},
{
"code": null,
"e": 10882,
"s": 10872,
"text": "Output: "
},
{
"code": null,
"e": 10886,
"s": 10882,
"text": "Yes"
},
{
"code": null,
"e": 11360,
"s": 10886,
"text": "Reference : https://en.wikipedia.org/wiki/Cyclic_numberThis article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.. "
},
{
"code": null,
"e": 11365,
"s": 11360,
"text": "vt_m"
},
{
"code": null,
"e": 11378,
"s": 11365,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11388,
"s": 11378,
"text": "sanjoy_62"
},
{
"code": null,
"e": 11401,
"s": 11388,
"text": "simmytarika5"
},
{
"code": null,
"e": 11415,
"s": 11401,
"text": "Combinatorial"
},
{
"code": null,
"e": 11428,
"s": 11415,
"text": "Mathematical"
},
{
"code": null,
"e": 11441,
"s": 11428,
"text": "Mathematical"
},
{
"code": null,
"e": 11455,
"s": 11441,
"text": "Combinatorial"
}
] |
Smallest number by rearranging digits of a given number
|
25 Jan, 2022
Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number.
Examples:
Input: n = 846903
Output: 304689
Input: n = 55010
Output: 10055
Input: n = -40505
Output: -55400
Steps to find the smallest number.
Count the frequency of each digit in the number.If it is a non-negative number thenPlace the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right.Else if it is a negative number thenPlace the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left.
Count the frequency of each digit in the number.
If it is a non-negative number thenPlace the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right.
Place the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right.
Place the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.
Place all remaining digits in ascending order from left to right.
Else if it is a negative number thenPlace the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left.
Place the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left.
Place the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.
Place all remaining digits in descending order from right to left.
This solution is based on counting sort.
C++
Java
Python3
C#
PHP
Javascript
// C++ program for finding smallest number// from digits of given number#include<iostream>using namespace std; // function to find the smallest numberint smallest(int num){ // initialize frequency of each digit to Zero int freq[10] = {0}; // Checking Number is positive or Negative bool is_pos = (num>0); // Getting the absolute value of num num = abs(num); // count frequency of each digit in the number while (num) { int d = num % 10; // extract last digit freq[d]++; // increment counting num = num / 10; //remove last digit } int result = 0; // If it is positive Number then it should be smallest if(is_pos) { // Set the Leftmost digit to minimum except 0 for (int i = 1 ; i <= 9 ; i++) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]--) result = result * 10 + i; } else // If negative then number should be Largest { // Set the Leftmost digit to maximum for (int i = 9 ; i >= 1 ; i--) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in descending order for (int i = 9 ; i >=0 ; i--) while (freq[i]--) result = result * 10 + i; // Negative number should be returned here result = -result; } return result;} // Driver Programint main(){ int num = 570107; cout << smallest(num) << endl; int num2 = -691005; cout << smallest(num2); return 0;}
import java.lang.Math; // Java program for finding smallest number// from digits of given numberpublic class GFG { // function to find the smallest number static int smallest(int num) { // initialize frequency of each digit to Zero int[] freq = new int[10]; // Checking Number is positive or Negative boolean is_pos = (num>0); // Getting the absolute value of num num = Math.abs(num); // count frequency of each digit in the number while (num > 0) { int d = num % 10; // extract last digit freq[d]++; // increment counting num = num / 10; //remove last digit } int result = 0; // If it is positive Number then it should be smallest if(is_pos) { // Set the LEFTMOST digit to minimum expect 0 for (int i = 1 ; i <= 9 ; i++) { if (freq[i] != 0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]-- != 0) result = result * 10 + i; } else // If negative then number should be Largest { // Set the Rightmost digit to maximum for (int i = 9 ; i >= 1 ; i--) { if (freq[i] !=0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in descending order for (int i = 9 ; i >=0 ; i--) while (freq[i]-- != 0) result = result * 10 + i; // Negative number should be returned here result = -result; } return result; } // Driver Program public static void main(String args[]) { int num = 570107; System.out.println(smallest(num)); int num2 = -691005; System.out.println(smallest(num2)); }}// This code is contributed by Sumit Ghosh
# Function to find the smallest numberdef smallest(lst): # Here i is index and n is the number of the list for i,n in enumerate(lst): # Checking for the first non-zero digit in the sorted list if n != '0': # Remove and store the digit from the lst tmp = lst.pop(i) break # Place the first non-zero digit at the starting # and return the final number return str(tmp) + ''.join(lst) # Driver programif __name__ == '__main__': # Converting the given numbers into string to form a list lst = list(str(570107)) lst.sort() # Calling the function using the above list print (smallest(lst)) # This code is contributed by Mahendra Yadav
// C# program for finding smallest// number from digits of given// numberusing System; public class GFG { // function to find the smallest // number static int smallest(int num) { // initialize frequency of // each digit to Zero int[] freq = new int[10]; // count frequency of each // digit in the number while (num > 0) { // extract last digit int d = num % 10; // increment counting freq[d]++; //remove last digit num = num / 10; } // Set the LEFTMOST digit to // minimum expect 0 int result = 0; for (int i = 1 ; i <= 9 ; i++) { if (freq[i] != 0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]-- != 0) result = result * 10 + i; return result; } // Driver Program public static void Main() { int num = 570107; Console.WriteLine(smallest(num)); }} // This code is contributed by anuj_67.
<?php// PHP program for finding smallest// number from digits of given number // function to find the smallest numberfunction smallest($num){ // initialize frequency of // each digit to Zero $freq = array_fill(0, 10, 0); // count frequency of each // digit in the number while ($num) { $d = $num % 10; // extract last digit $freq[$d]++; // increment counting $num = (int)($num / 10); // remove last digit } // Set the LEFTMOST digit // to minimum expect 0 $result = 0; for ($i = 1 ; $i <= 9 ; $i++) { if ($freq[$i]) { $result = $i; $freq[$i]--; break; } } // arrange all remaining digits // in ascending order for ($i = 0 ; $i <= 9 ; $i++) while ($freq[$i] > 0) { $result = $result * 10 + $i; $freq[$i] -= 1; } return $result;} // Driver Code$num = 570107;echo smallest($num); // This code is contributed by mits?>
<script> // Javascript program for finding smallest number// from digits of given number // function to find the smallest numberfunction smallest(num){ // initialize frequency of each digit to Zero var freq = Array(10).fill(0); // count frequency of each digit in the number while (num) { var d = num % 10; // extract last digit freq[d]++; // increment counting num = parseInt(num / 10); //remove last digit } // Set the LEFTMOST digit to minimum expect 0 var result = 0; for (var i = 1 ; i <= 9 ; i++) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (var i = 0 ; i <= 9 ; i++) while (freq[i]--) result = result * 10 + i; return result;} // Driver Programvar num = 570107;document.write(smallest(num)); // This code is contributed by rutvik_56.</script>
100577
-965100
Another Approach:Find smallest permutation of given numberThis article is contributed by Ajay Kumar Agrahari(aJy aGr). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Mithun Kumar
rutvik_56
dangebvishal
purushottamkumar4
amartyaghoshgfg
GE
number-digits
Mathematical
GE
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Merge two sorted arrays with O(1) extra space
Program to find sum of elements in a given array
Print all possible combinations of r elements in a given array of size n
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 167,
"s": 54,
"text": "Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number. "
},
{
"code": null,
"e": 178,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 277,
"s": 178,
"text": "Input: n = 846903\nOutput: 304689\n\nInput: n = 55010\nOutput: 10055\n\nInput: n = -40505\nOutput: -55400"
},
{
"code": null,
"e": 314,
"s": 277,
"text": "Steps to find the smallest number. "
},
{
"code": null,
"e": 801,
"s": 314,
"text": "Count the frequency of each digit in the number.If it is a non-negative number thenPlace the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right.Else if it is a negative number thenPlace the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left."
},
{
"code": null,
"e": 850,
"s": 801,
"text": "Count the frequency of each digit in the number."
},
{
"code": null,
"e": 1075,
"s": 850,
"text": "If it is a non-negative number thenPlace the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right."
},
{
"code": null,
"e": 1265,
"s": 1075,
"text": "Place the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in ascending order from left to right."
},
{
"code": null,
"e": 1390,
"s": 1265,
"text": "Place the smallest digit (except 0) at the left most of the required number. and decrement the frequency of that digit by 1."
},
{
"code": null,
"e": 1456,
"s": 1390,
"text": "Place all remaining digits in ascending order from left to right."
},
{
"code": null,
"e": 1671,
"s": 1456,
"text": "Else if it is a negative number thenPlace the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left."
},
{
"code": null,
"e": 1850,
"s": 1671,
"text": "Place the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.Place all remaining digits in descending order from right to left."
},
{
"code": null,
"e": 1963,
"s": 1850,
"text": "Place the largest digit at the left most of the required number. and decrement the frequency of that digit by 1."
},
{
"code": null,
"e": 2030,
"s": 1963,
"text": "Place all remaining digits in descending order from right to left."
},
{
"code": null,
"e": 2072,
"s": 2030,
"text": "This solution is based on counting sort. "
},
{
"code": null,
"e": 2076,
"s": 2072,
"text": "C++"
},
{
"code": null,
"e": 2081,
"s": 2076,
"text": "Java"
},
{
"code": null,
"e": 2089,
"s": 2081,
"text": "Python3"
},
{
"code": null,
"e": 2092,
"s": 2089,
"text": "C#"
},
{
"code": null,
"e": 2096,
"s": 2092,
"text": "PHP"
},
{
"code": null,
"e": 2107,
"s": 2096,
"text": "Javascript"
},
{
"code": "// C++ program for finding smallest number// from digits of given number#include<iostream>using namespace std; // function to find the smallest numberint smallest(int num){ // initialize frequency of each digit to Zero int freq[10] = {0}; // Checking Number is positive or Negative bool is_pos = (num>0); // Getting the absolute value of num num = abs(num); // count frequency of each digit in the number while (num) { int d = num % 10; // extract last digit freq[d]++; // increment counting num = num / 10; //remove last digit } int result = 0; // If it is positive Number then it should be smallest if(is_pos) { // Set the Leftmost digit to minimum except 0 for (int i = 1 ; i <= 9 ; i++) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]--) result = result * 10 + i; } else // If negative then number should be Largest { // Set the Leftmost digit to maximum for (int i = 9 ; i >= 1 ; i--) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in descending order for (int i = 9 ; i >=0 ; i--) while (freq[i]--) result = result * 10 + i; // Negative number should be returned here result = -result; } return result;} // Driver Programint main(){ int num = 570107; cout << smallest(num) << endl; int num2 = -691005; cout << smallest(num2); return 0;}",
"e": 3869,
"s": 2107,
"text": null
},
{
"code": "import java.lang.Math; // Java program for finding smallest number// from digits of given numberpublic class GFG { // function to find the smallest number static int smallest(int num) { // initialize frequency of each digit to Zero int[] freq = new int[10]; // Checking Number is positive or Negative boolean is_pos = (num>0); // Getting the absolute value of num num = Math.abs(num); // count frequency of each digit in the number while (num > 0) { int d = num % 10; // extract last digit freq[d]++; // increment counting num = num / 10; //remove last digit } int result = 0; // If it is positive Number then it should be smallest if(is_pos) { // Set the LEFTMOST digit to minimum expect 0 for (int i = 1 ; i <= 9 ; i++) { if (freq[i] != 0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]-- != 0) result = result * 10 + i; } else // If negative then number should be Largest { // Set the Rightmost digit to maximum for (int i = 9 ; i >= 1 ; i--) { if (freq[i] !=0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in descending order for (int i = 9 ; i >=0 ; i--) while (freq[i]-- != 0) result = result * 10 + i; // Negative number should be returned here result = -result; } return result; } // Driver Program public static void main(String args[]) { int num = 570107; System.out.println(smallest(num)); int num2 = -691005; System.out.println(smallest(num2)); }}// This code is contributed by Sumit Ghosh",
"e": 6083,
"s": 3869,
"text": null
},
{
"code": "# Function to find the smallest numberdef smallest(lst): # Here i is index and n is the number of the list for i,n in enumerate(lst): # Checking for the first non-zero digit in the sorted list if n != '0': # Remove and store the digit from the lst tmp = lst.pop(i) break # Place the first non-zero digit at the starting # and return the final number return str(tmp) + ''.join(lst) # Driver programif __name__ == '__main__': # Converting the given numbers into string to form a list lst = list(str(570107)) lst.sort() # Calling the function using the above list print (smallest(lst)) # This code is contributed by Mahendra Yadav",
"e": 6835,
"s": 6083,
"text": null
},
{
"code": "// C# program for finding smallest// number from digits of given// numberusing System; public class GFG { // function to find the smallest // number static int smallest(int num) { // initialize frequency of // each digit to Zero int[] freq = new int[10]; // count frequency of each // digit in the number while (num > 0) { // extract last digit int d = num % 10; // increment counting freq[d]++; //remove last digit num = num / 10; } // Set the LEFTMOST digit to // minimum expect 0 int result = 0; for (int i = 1 ; i <= 9 ; i++) { if (freq[i] != 0) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (int i = 0 ; i <= 9 ; i++) while (freq[i]-- != 0) result = result * 10 + i; return result; } // Driver Program public static void Main() { int num = 570107; Console.WriteLine(smallest(num)); }} // This code is contributed by anuj_67.",
"e": 8124,
"s": 6835,
"text": null
},
{
"code": "<?php// PHP program for finding smallest// number from digits of given number // function to find the smallest numberfunction smallest($num){ // initialize frequency of // each digit to Zero $freq = array_fill(0, 10, 0); // count frequency of each // digit in the number while ($num) { $d = $num % 10; // extract last digit $freq[$d]++; // increment counting $num = (int)($num / 10); // remove last digit } // Set the LEFTMOST digit // to minimum expect 0 $result = 0; for ($i = 1 ; $i <= 9 ; $i++) { if ($freq[$i]) { $result = $i; $freq[$i]--; break; } } // arrange all remaining digits // in ascending order for ($i = 0 ; $i <= 9 ; $i++) while ($freq[$i] > 0) { $result = $result * 10 + $i; $freq[$i] -= 1; } return $result;} // Driver Code$num = 570107;echo smallest($num); // This code is contributed by mits?>",
"e": 9115,
"s": 8124,
"text": null
},
{
"code": "<script> // Javascript program for finding smallest number// from digits of given number // function to find the smallest numberfunction smallest(num){ // initialize frequency of each digit to Zero var freq = Array(10).fill(0); // count frequency of each digit in the number while (num) { var d = num % 10; // extract last digit freq[d]++; // increment counting num = parseInt(num / 10); //remove last digit } // Set the LEFTMOST digit to minimum expect 0 var result = 0; for (var i = 1 ; i <= 9 ; i++) { if (freq[i]) { result = i; freq[i]--; break; } } // arrange all remaining digits // in ascending order for (var i = 0 ; i <= 9 ; i++) while (freq[i]--) result = result * 10 + i; return result;} // Driver Programvar num = 570107;document.write(smallest(num)); // This code is contributed by rutvik_56.</script>",
"e": 10072,
"s": 9115,
"text": null
},
{
"code": null,
"e": 10087,
"s": 10072,
"text": "100577\n-965100"
},
{
"code": null,
"e": 10582,
"s": 10087,
"text": "Another Approach:Find smallest permutation of given numberThis article is contributed by Ajay Kumar Agrahari(aJy aGr). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10587,
"s": 10582,
"text": "vt_m"
},
{
"code": null,
"e": 10600,
"s": 10587,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10610,
"s": 10600,
"text": "rutvik_56"
},
{
"code": null,
"e": 10623,
"s": 10610,
"text": "dangebvishal"
},
{
"code": null,
"e": 10641,
"s": 10623,
"text": "purushottamkumar4"
},
{
"code": null,
"e": 10657,
"s": 10641,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 10660,
"s": 10657,
"text": "GE"
},
{
"code": null,
"e": 10674,
"s": 10660,
"text": "number-digits"
},
{
"code": null,
"e": 10687,
"s": 10674,
"text": "Mathematical"
},
{
"code": null,
"e": 10690,
"s": 10687,
"text": "GE"
},
{
"code": null,
"e": 10703,
"s": 10690,
"text": "Mathematical"
},
{
"code": null,
"e": 10801,
"s": 10703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10822,
"s": 10801,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10875,
"s": 10822,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 10918,
"s": 10875,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 10950,
"s": 10918,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 10977,
"s": 10950,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 11023,
"s": 10977,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 11072,
"s": 11023,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 11145,
"s": 11072,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 11189,
"s": 11145,
"text": "Program to print prime numbers from 1 to N."
}
] |
Segregate Prime and Non-Prime Numbers in an array
|
09 Jun, 2021
Given an array arr[] of size N, the task is to rearrange the array elements such that all the Prime numbers are placed before the Non-prime numbers.
Examples:
Input: arr[] = {1, 8, 2, 3, 4, 5, 7, 20}Output: 7 5 2 3 4 8 1 20Explanation:The output consists of all the prime numbers 7 5 2 3, followed by Non-Prime numbers 4 8 1 20.
Input: arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 10}Output: 2 3 7 5 6 4 8 9 10
Naive Approach: The simplest approach to solve this problem is to make two arrays to store the prime and non-prime array elements respectively and print the prime numbers followed by the non-primes numbers.
Time Complexity: O(N*sqrt(N))Auxiliary Space: O(N)
Alternate Approach: To optimize the auxiliary space of the above approach, the idea to solve this problem is using the Two-Pointer Approach. Follow the steps below to solve the problem:
Initialize two pointers left as 0 and right to the end of the array as (N – 1).
Traverse the array until left is less than right and do the following:Keep incrementing the left pointer until the element pointing to the left index is Prime Number.Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number.If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1.
Keep incrementing the left pointer until the element pointing to the left index is Prime Number.
Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number.
If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1.
After the above steps, print the update array arr[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to swap two numbers a and bvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to check if a number n// is a prime number of notbool isPrime(int n){ // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for (int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true;} // Function to segregate the primes// and non-primes present in an arrayvoid segregatePrimeNonPrime( int arr[], int N){ // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] swap(&arr[left], &arr[right]); left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = sizeof(arr) / sizeof(arr[0]); segregatePrimeNonPrime(arr, N); return 0;}
// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to check if a number n // is a prime number of not static boolean isPrime(int n) { // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for (int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true; } // Function to segregate the primes // and non-primes present in an array static void segregatePrimeNonPrime(int arr[], int N) { // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] int temp = arr[right]; arr[right] = arr[left]; arr[left] = temp; left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) System.out.print(arr[i] + " "); } // Driver Code public static void main(String[] args) { int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.length; segregatePrimeNonPrime(arr, N); }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to check if a number n# is a prime number of notdef isPrime(n): # Edges Cases if (n <= 1): return False if (n <= 3): return True # To skip middle five numbers if (n % 2 == 0 or n % 3 == 0): return False # Checks for prime or non prime i = 5 while (i * i <= n): # If n is divisible by i or i + 2, # return False if (n % i == 0 or n % (i + 2) == 0): return False i += 6 # Otherwise, the number is prime return True # Function to segregate the primes and# non-primes present in an arraydef segregatePrimeNonPrime(arr, N): # Initialize left and right pointers left, right = 0, N - 1 # Traverse the array while (left < right): # Increment left while array element # at left is prime while (isPrime(arr[left])): left += 1 # Decrement right while array element # at right is non-prime while (not isPrime(arr[right])): right -= 1 # If left < right, then swap # arr[left] and arr[right] if (left < right): # Swapp arr[left] and arr[right] arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 # Print segregated array for num in arr: print(num, end = " ") # Driver codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr) segregatePrimeNonPrime(arr, N) # This code is contributed by girishthatte
// C# program for the above approachusing System; class GFG{ // Function to check if a number n// is a prime number of notstatic bool isPrime(int n){ // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for(int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true;} // Function to segregate the primes// and non-primes present in an arraystatic void segregatePrimeNonPrime(int[] arr, int N){ // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] int temp = arr[right]; arr[right] = arr[left]; arr[left] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) Console.Write(arr[i] + " ");} // Driver Codepublic static void Main(string[] args){ int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.Length; segregatePrimeNonPrime(arr, N);}} // This code is contributed by ukasp
<script> // Javascript program implementation// of the approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction SieveOfEratosthenes(prime, n){ for(let p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primesfunction segregatePrimeNonPrime(prime, arr, N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right let left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] let temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(let i = 0; i < N; i++) document.write(arr[i] + " ");} // Driver Code let prime = Array.from({length: 10000001}, (_, i) => true); let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]; let N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N); </script>
2 3 7 6 4 8 9 10
Time Complexity: O(N*sqrt(N))Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using the Sieve of Eratosthenes to find whether the number is prime or non-prime in constant time.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std;bool prime[10000001]; // Function to swap two numbers a and bvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to generate prime numbers// using Sieve of Eratosthenesvoid SieveOfEratosthenes(int n){ memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes// and non-primesvoid segregatePrimeNonPrime( int arr[], int N){ // Generate all primes till 10^7 SieveOfEratosthenes(10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (prime[arr[left]]) left++; // Decrement right while array // element at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swap arr[left] and arr[right] swap(&arr[left], &arr[right]); left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call segregatePrimeNonPrime(arr, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to generate prime numbers// using Sieve of Eratosthenespublic static void SieveOfEratosthenes(boolean[] prime, int n){ for(int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primespublic static void segregatePrimeNonPrime(boolean[] prime, int arr[], int N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) System.out.printf(arr[i] + " ");} // Driver codepublic static void main(String[] args){ boolean[] prime = new boolean[10000001]; Arrays.fill(prime, true); int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N);}} // This code is contributed by girishthatte
# Python3 program for the above approach # Function to generate prime numbers# using Sieve of Eratosthenesdef SieveOfEratosthenes(prime, n): p = 2 while (p * p <= n): # If prime[p] is unchanged, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * p while (i <= n): prime[i] = False i += p p += 1 # Function to segregate the primes and non-primesdef segregatePrimeNonPrime(prime, arr, N): # Generate all primes till 10^7 SieveOfEratosthenes(prime, 10000000) # Initialize left and right left, right = 0, N - 1 # Traverse the array while (left < right): # Increment left while array element # at left is prime while (prime[arr[left]]): left += 1 # Decrement right while array element # at right is non-prime while (not prime[arr[right]]): right -= 1 # If left < right, then swap arr[left] # and arr[right] if (left < right): # Swap arr[left] and arr[right] arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 # Print segregated array for num in arr: print(num, end = " ") # Driver codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr)prime = [True] * 10000001 # Function CallsegregatePrimeNonPrime(prime, arr, N) # This code is contributed by girishthatte
// C# program for the above approachusing System; class GFG{ // Function to generate prime numbers// using Sieve of Eratosthenespublic static void SieveOfEratosthenes(bool[] prime, int n){ for(int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primespublic static void segregatePrimeNonPrime(bool[] prime, int []arr, int N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) Console.Write(arr[i] + " ");} // Driver codepublic static void Main(String[] args){ bool[] prime = new bool[10000001]; for(int i = 0; i < prime.Length; i++) prime[i] = true; int []arr = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.Length; // Function Call segregatePrimeNonPrime(prime, arr, N);}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction SieveOfEratosthenes(prime, n){ for(let p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primesfunction segregatePrimeNonPrime(prime, arr, N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right let left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] let temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(let i = 0; i < N; i++) document.write(arr[i] + " ");} // Driver Code let prime = Array.from({length: 10000001}, (_, i) => true); let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]; let N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N); </script>
2 3 7 6 4 8 9 10
Time Complexity: O(N*log(log(N)))Auxiliary Space: O(N)
Kingash
girishthatte
ukasp
princi singh
souravghosh0416
susmitakundugoaldanga
ankita_saini
interview-preparation
Paytm
Prime Number
sieve
two-pointer-algorithm
Arrays
Mathematical
Paytm
two-pointer-algorithm
Arrays
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 203,
"s": 54,
"text": "Given an array arr[] of size N, the task is to rearrange the array elements such that all the Prime numbers are placed before the Non-prime numbers."
},
{
"code": null,
"e": 213,
"s": 203,
"text": "Examples:"
},
{
"code": null,
"e": 383,
"s": 213,
"text": "Input: arr[] = {1, 8, 2, 3, 4, 5, 7, 20}Output: 7 5 2 3 4 8 1 20Explanation:The output consists of all the prime numbers 7 5 2 3, followed by Non-Prime numbers 4 8 1 20."
},
{
"code": null,
"e": 453,
"s": 383,
"text": "Input: arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 10}Output: 2 3 7 5 6 4 8 9 10"
},
{
"code": null,
"e": 661,
"s": 453,
"text": "Naive Approach: The simplest approach to solve this problem is to make two arrays to store the prime and non-prime array elements respectively and print the prime numbers followed by the non-primes numbers. "
},
{
"code": null,
"e": 712,
"s": 661,
"text": "Time Complexity: O(N*sqrt(N))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 898,
"s": 712,
"text": "Alternate Approach: To optimize the auxiliary space of the above approach, the idea to solve this problem is using the Two-Pointer Approach. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 978,
"s": 898,
"text": "Initialize two pointers left as 0 and right to the end of the array as (N – 1)."
},
{
"code": null,
"e": 1354,
"s": 978,
"text": "Traverse the array until left is less than right and do the following:Keep incrementing the left pointer until the element pointing to the left index is Prime Number.Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number.If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1."
},
{
"code": null,
"e": 1451,
"s": 1354,
"text": "Keep incrementing the left pointer until the element pointing to the left index is Prime Number."
},
{
"code": null,
"e": 1555,
"s": 1451,
"text": "Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number."
},
{
"code": null,
"e": 1662,
"s": 1555,
"text": "If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1."
},
{
"code": null,
"e": 1715,
"s": 1662,
"text": "After the above steps, print the update array arr[]."
},
{
"code": null,
"e": 1766,
"s": 1715,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1770,
"s": 1766,
"text": "C++"
},
{
"code": null,
"e": 1775,
"s": 1770,
"text": "Java"
},
{
"code": null,
"e": 1783,
"s": 1775,
"text": "Python3"
},
{
"code": null,
"e": 1786,
"s": 1783,
"text": "C#"
},
{
"code": null,
"e": 1797,
"s": 1786,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to swap two numbers a and bvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to check if a number n// is a prime number of notbool isPrime(int n){ // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for (int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true;} // Function to segregate the primes// and non-primes present in an arrayvoid segregatePrimeNonPrime( int arr[], int N){ // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] swap(&arr[left], &arr[right]); left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = sizeof(arr) / sizeof(arr[0]); segregatePrimeNonPrime(arr, N); return 0;}",
"e": 3551,
"s": 1797,
"text": null
},
{
"code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to check if a number n // is a prime number of not static boolean isPrime(int n) { // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for (int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true; } // Function to segregate the primes // and non-primes present in an array static void segregatePrimeNonPrime(int arr[], int N) { // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] int temp = arr[right]; arr[right] = arr[left]; arr[left] = temp; left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) System.out.print(arr[i] + \" \"); } // Driver Code public static void main(String[] args) { int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.length; segregatePrimeNonPrime(arr, N); }} // This code is contributed by Kingash.",
"e": 5572,
"s": 3551,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if a number n# is a prime number of notdef isPrime(n): # Edges Cases if (n <= 1): return False if (n <= 3): return True # To skip middle five numbers if (n % 2 == 0 or n % 3 == 0): return False # Checks for prime or non prime i = 5 while (i * i <= n): # If n is divisible by i or i + 2, # return False if (n % i == 0 or n % (i + 2) == 0): return False i += 6 # Otherwise, the number is prime return True # Function to segregate the primes and# non-primes present in an arraydef segregatePrimeNonPrime(arr, N): # Initialize left and right pointers left, right = 0, N - 1 # Traverse the array while (left < right): # Increment left while array element # at left is prime while (isPrime(arr[left])): left += 1 # Decrement right while array element # at right is non-prime while (not isPrime(arr[right])): right -= 1 # If left < right, then swap # arr[left] and arr[right] if (left < right): # Swapp arr[left] and arr[right] arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 # Print segregated array for num in arr: print(num, end = \" \") # Driver codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr) segregatePrimeNonPrime(arr, N) # This code is contributed by girishthatte",
"e": 7096,
"s": 5572,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if a number n// is a prime number of notstatic bool isPrime(int n){ // Edges Cases if (n <= 1) return false; if (n <= 3) return true; // To skip middle five numbers if (n % 2 == 0 || n % 3 == 0) return false; // Checks for prime or non prime for(int i = 5; i * i <= n; i = i + 6) { // If n is divisible by i // or i + 2, return false if (n % i == 0 || n % (i + 2) == 0) return false; } // Otherwise, the // number is prime return true;} // Function to segregate the primes// and non-primes present in an arraystatic void segregatePrimeNonPrime(int[] arr, int N){ // Initialize left and right pointers int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (isPrime(arr[left])) left++; // Decrement right while array // element at right is non-prime while (!isPrime(arr[right])) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swapp arr[left] and arr[right] int temp = arr[right]; arr[right] = arr[left]; arr[left] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) Console.Write(arr[i] + \" \");} // Driver Codepublic static void Main(string[] args){ int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.Length; segregatePrimeNonPrime(arr, N);}} // This code is contributed by ukasp",
"e": 8860,
"s": 7096,
"text": null
},
{
"code": "<script> // Javascript program implementation// of the approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction SieveOfEratosthenes(prime, n){ for(let p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primesfunction segregatePrimeNonPrime(prime, arr, N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right let left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] let temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(let i = 0; i < N; i++) document.write(arr[i] + \" \");} // Driver Code let prime = Array.from({length: 10000001}, (_, i) => true); let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]; let N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N); </script>",
"e": 10551,
"s": 8860,
"text": null
},
{
"code": null,
"e": 10568,
"s": 10551,
"text": "2 3 7 6 4 8 9 10"
},
{
"code": null,
"e": 10621,
"s": 10570,
"text": "Time Complexity: O(N*sqrt(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10779,
"s": 10621,
"text": "Efficient Approach: The above approach can be optimized by using the Sieve of Eratosthenes to find whether the number is prime or non-prime in constant time."
},
{
"code": null,
"e": 10831,
"s": 10779,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 10835,
"s": 10831,
"text": "C++"
},
{
"code": null,
"e": 10840,
"s": 10835,
"text": "Java"
},
{
"code": null,
"e": 10848,
"s": 10840,
"text": "Python3"
},
{
"code": null,
"e": 10851,
"s": 10848,
"text": "C#"
},
{
"code": null,
"e": 10862,
"s": 10851,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std;bool prime[10000001]; // Function to swap two numbers a and bvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to generate prime numbers// using Sieve of Eratosthenesvoid SieveOfEratosthenes(int n){ memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes// and non-primesvoid segregatePrimeNonPrime( int arr[], int N){ // Generate all primes till 10^7 SieveOfEratosthenes(10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array // element at left is prime while (prime[arr[left]]) left++; // Decrement right while array // element at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap // arr[left] and arr[right] if (left < right) { // Swap arr[left] and arr[right] swap(&arr[left], &arr[right]); left++; right--; } } // Print segregated array for (int i = 0; i < N; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call segregatePrimeNonPrime(arr, N); return 0;}",
"e": 12583,
"s": 10862,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to generate prime numbers// using Sieve of Eratosthenespublic static void SieveOfEratosthenes(boolean[] prime, int n){ for(int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primespublic static void segregatePrimeNonPrime(boolean[] prime, int arr[], int N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) System.out.printf(arr[i] + \" \");} // Driver codepublic static void main(String[] args){ boolean[] prime = new boolean[10000001]; Arrays.fill(prime, true); int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N);}} // This code is contributed by girishthatte",
"e": 14478,
"s": 12583,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to generate prime numbers# using Sieve of Eratosthenesdef SieveOfEratosthenes(prime, n): p = 2 while (p * p <= n): # If prime[p] is unchanged, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * p while (i <= n): prime[i] = False i += p p += 1 # Function to segregate the primes and non-primesdef segregatePrimeNonPrime(prime, arr, N): # Generate all primes till 10^7 SieveOfEratosthenes(prime, 10000000) # Initialize left and right left, right = 0, N - 1 # Traverse the array while (left < right): # Increment left while array element # at left is prime while (prime[arr[left]]): left += 1 # Decrement right while array element # at right is non-prime while (not prime[arr[right]]): right -= 1 # If left < right, then swap arr[left] # and arr[right] if (left < right): # Swap arr[left] and arr[right] arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 # Print segregated array for num in arr: print(num, end = \" \") # Driver codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr)prime = [True] * 10000001 # Function CallsegregatePrimeNonPrime(prime, arr, N) # This code is contributed by girishthatte",
"e": 16009,
"s": 14478,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to generate prime numbers// using Sieve of Eratosthenespublic static void SieveOfEratosthenes(bool[] prime, int n){ for(int p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primespublic static void segregatePrimeNonPrime(bool[] prime, int []arr, int N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right int left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(int i = 0; i < N; i++) Console.Write(arr[i] + \" \");} // Driver codepublic static void Main(String[] args){ bool[] prime = new bool[10000001]; for(int i = 0; i < prime.Length; i++) prime[i] = true; int []arr = { 2, 3, 4, 6, 7, 8, 9, 10 }; int N = arr.Length; // Function Call segregatePrimeNonPrime(prime, arr, N);}} // This code is contributed by Princi Singh",
"e": 17925,
"s": 16009,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction SieveOfEratosthenes(prime, n){ for(let p = 2; p * p <= n; p++) { // If prime[p] is unchanged, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * p; i <= n; i += p) prime[i] = false; } }} // Function to segregate the primes and non-primesfunction segregatePrimeNonPrime(prime, arr, N){ // Generate all primes till 10^ SieveOfEratosthenes(prime, 10000000); // Initialize left and right let left = 0, right = N - 1; // Traverse the array while (left < right) { // Increment left while array element // at left is prime while (prime[arr[left]]) left++; // Decrement right while array element // at right is non-prime while (!prime[arr[right]]) right--; // If left < right, then swap arr[left] // and arr[right] if (left < right) { // Swap arr[left] and arr[right] let temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Print segregated array for(let i = 0; i < N; i++) document.write(arr[i] + \" \");} // Driver Code let prime = Array.from({length: 10000001}, (_, i) => true); let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]; let N = arr.length; // Function Call segregatePrimeNonPrime(prime, arr, N); </script>",
"e": 19615,
"s": 17925,
"text": null
},
{
"code": null,
"e": 19632,
"s": 19615,
"text": "2 3 7 6 4 8 9 10"
},
{
"code": null,
"e": 19689,
"s": 19634,
"text": "Time Complexity: O(N*log(log(N)))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 19699,
"s": 19691,
"text": "Kingash"
},
{
"code": null,
"e": 19712,
"s": 19699,
"text": "girishthatte"
},
{
"code": null,
"e": 19718,
"s": 19712,
"text": "ukasp"
},
{
"code": null,
"e": 19731,
"s": 19718,
"text": "princi singh"
},
{
"code": null,
"e": 19747,
"s": 19731,
"text": "souravghosh0416"
},
{
"code": null,
"e": 19769,
"s": 19747,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 19782,
"s": 19769,
"text": "ankita_saini"
},
{
"code": null,
"e": 19804,
"s": 19782,
"text": "interview-preparation"
},
{
"code": null,
"e": 19810,
"s": 19804,
"text": "Paytm"
},
{
"code": null,
"e": 19823,
"s": 19810,
"text": "Prime Number"
},
{
"code": null,
"e": 19829,
"s": 19823,
"text": "sieve"
},
{
"code": null,
"e": 19851,
"s": 19829,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 19858,
"s": 19851,
"text": "Arrays"
},
{
"code": null,
"e": 19871,
"s": 19858,
"text": "Mathematical"
},
{
"code": null,
"e": 19877,
"s": 19871,
"text": "Paytm"
},
{
"code": null,
"e": 19899,
"s": 19877,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 19906,
"s": 19899,
"text": "Arrays"
},
{
"code": null,
"e": 19919,
"s": 19906,
"text": "Mathematical"
},
{
"code": null,
"e": 19932,
"s": 19919,
"text": "Prime Number"
},
{
"code": null,
"e": 19938,
"s": 19932,
"text": "sieve"
}
] |
How to Install Julia on Windows ?
|
06 Oct, 2021
Julia is a programming language used for statistical computations and data analysis. Julia is a combination of super-fast execution speed of C and flexible code writing of Python. Working with Julia is considered to be super fun and super easy among the Computer scientists and Software Engineers, because of its high efficiency.
Julia programs can be written in any of the widely used text editors like Notepad, Notepad++, gedit, etc. or on any of the text-editors. One can also use an online IDE for writing Julia codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Julia Codes and performing various intriguing and useful operations, one must have Julia installed on their System. This can be done by following the step by step instructions provided below:
Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the Command line(search for cmd in the Run dialog( + R)).Now run the following command:
julia
Downloading Julia:Before starting with the installation process, you need to download it. Julia for Windows is available on its official site julialang.org Download Julia and follow the further instructions for its installation.
Beginning with the Installation:
Step 1: Once the downloading is over, click on the setup to open it and follow the step-by-step instructions provided. Click on the Next button, to begin with, the installation process: Step 2: Select the destination directory to store Julia files. Click on the Next button to proceed. Step 3: Installation process might take a while to Extract and register files. Sit back and Relax! Step 4: Once the installation is over, you can proceed with creating shortcuts to open Julia and click on the Finish button to complete the installation process. After the installation process is completed, there is a need to set up the Environment for Julia to use it on the command line. Go through How to set up Environment Variable in Julia?
To check if the installation and Path setup is done correctly, type the following command on the command-line:
julia
After completing the installation process, any IDE or text editor can be used to write Julia Codes and Run them on the IDE or the Command prompt with the use of command:
julia file_name.jl
Let’s consider a simple Hello World Program.
# Julia program to print Hello World # print functionprint("Hello World!")
Julia codes can be executed in three ways:
On the command-line using ‘julia’ command: To execute the above sample code in Julia, open the command line and type the following command:julia HelloWorld.jl
julia HelloWorld.jl
On the command prompt using Julia command-line: To open Julia command-line on the Windows command prompt, type the following command:juliaNow in the Julia command-line type the filename that is to be executed and press Enter.include("HelloWorld.jl")
julia
Now in the Julia command-line type the filename that is to be executed and press Enter.
include("HelloWorld.jl")
On the Julia command-line: Search for Julia command-line in the Start Menu and open it. Now type the file name and press Enter.include("C:/Users/Abhinav Singh/HelloWorld.jl")Note: Here in the above command, there is a need to provide whole path of the directory where script file is saved unless the file is saved in the same directory where Julia compiler is stored.
include("C:/Users/Abhinav Singh/HelloWorld.jl")
Note: Here in the above command, there is a need to provide whole path of the directory where script file is saved unless the file is saved in the same directory where Julia compiler is stored.
how-to-install
Julia-Basics
Installation Guide
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
Vectors in Julia
String concatenation in Julia
Printing Output on Screen in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Julia is a programming language used for statistical computations and data analysis. Julia is a combination of super-fast execution speed of C and flexible code writing of Python. Working with Julia is considered to be super fun and super easy among the Computer scientists and Software Engineers, because of its high efficiency."
},
{
"code": null,
"e": 942,
"s": 358,
"text": "Julia programs can be written in any of the widely used text editors like Notepad, Notepad++, gedit, etc. or on any of the text-editors. One can also use an online IDE for writing Julia codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Julia Codes and performing various intriguing and useful operations, one must have Julia installed on their System. This can be done by following the step by step instructions provided below:"
},
{
"code": null,
"e": 1217,
"s": 942,
"text": "Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the Command line(search for cmd in the Run dialog( + R)).Now run the following command:"
},
{
"code": null,
"e": 1223,
"s": 1217,
"text": "julia"
},
{
"code": null,
"e": 1452,
"s": 1223,
"text": "Downloading Julia:Before starting with the installation process, you need to download it. Julia for Windows is available on its official site julialang.org Download Julia and follow the further instructions for its installation."
},
{
"code": null,
"e": 1485,
"s": 1452,
"text": "Beginning with the Installation:"
},
{
"code": null,
"e": 2216,
"s": 1485,
"text": "Step 1: Once the downloading is over, click on the setup to open it and follow the step-by-step instructions provided. Click on the Next button, to begin with, the installation process: Step 2: Select the destination directory to store Julia files. Click on the Next button to proceed. Step 3: Installation process might take a while to Extract and register files. Sit back and Relax! Step 4: Once the installation is over, you can proceed with creating shortcuts to open Julia and click on the Finish button to complete the installation process. After the installation process is completed, there is a need to set up the Environment for Julia to use it on the command line. Go through How to set up Environment Variable in Julia?"
},
{
"code": null,
"e": 2327,
"s": 2216,
"text": "To check if the installation and Path setup is done correctly, type the following command on the command-line:"
},
{
"code": null,
"e": 2333,
"s": 2327,
"text": "julia"
},
{
"code": null,
"e": 2504,
"s": 2333,
"text": " After completing the installation process, any IDE or text editor can be used to write Julia Codes and Run them on the IDE or the Command prompt with the use of command:"
},
{
"code": null,
"e": 2523,
"s": 2504,
"text": "julia file_name.jl"
},
{
"code": null,
"e": 2568,
"s": 2523,
"text": "Let’s consider a simple Hello World Program."
},
{
"code": "# Julia program to print Hello World # print functionprint(\"Hello World!\") ",
"e": 2646,
"s": 2568,
"text": null
},
{
"code": null,
"e": 2690,
"s": 2646,
"text": " Julia codes can be executed in three ways:"
},
{
"code": null,
"e": 2849,
"s": 2690,
"text": "On the command-line using ‘julia’ command: To execute the above sample code in Julia, open the command line and type the following command:julia HelloWorld.jl"
},
{
"code": null,
"e": 2869,
"s": 2849,
"text": "julia HelloWorld.jl"
},
{
"code": null,
"e": 3119,
"s": 2869,
"text": "On the command prompt using Julia command-line: To open Julia command-line on the Windows command prompt, type the following command:juliaNow in the Julia command-line type the filename that is to be executed and press Enter.include(\"HelloWorld.jl\")"
},
{
"code": null,
"e": 3125,
"s": 3119,
"text": "julia"
},
{
"code": null,
"e": 3213,
"s": 3125,
"text": "Now in the Julia command-line type the filename that is to be executed and press Enter."
},
{
"code": null,
"e": 3238,
"s": 3213,
"text": "include(\"HelloWorld.jl\")"
},
{
"code": null,
"e": 3606,
"s": 3238,
"text": "On the Julia command-line: Search for Julia command-line in the Start Menu and open it. Now type the file name and press Enter.include(\"C:/Users/Abhinav Singh/HelloWorld.jl\")Note: Here in the above command, there is a need to provide whole path of the directory where script file is saved unless the file is saved in the same directory where Julia compiler is stored."
},
{
"code": null,
"e": 3654,
"s": 3606,
"text": "include(\"C:/Users/Abhinav Singh/HelloWorld.jl\")"
},
{
"code": null,
"e": 3848,
"s": 3654,
"text": "Note: Here in the above command, there is a need to provide whole path of the directory where script file is saved unless the file is saved in the same directory where Julia compiler is stored."
},
{
"code": null,
"e": 3863,
"s": 3848,
"text": "how-to-install"
},
{
"code": null,
"e": 3876,
"s": 3863,
"text": "Julia-Basics"
},
{
"code": null,
"e": 3895,
"s": 3876,
"text": "Installation Guide"
},
{
"code": null,
"e": 3901,
"s": 3895,
"text": "Julia"
},
{
"code": null,
"e": 3999,
"s": 3901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4033,
"s": 3999,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 4068,
"s": 4033,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 4110,
"s": 4068,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 4149,
"s": 4110,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 4203,
"s": 4149,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 4220,
"s": 4203,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 4250,
"s": 4220,
"text": "String concatenation in Julia"
},
{
"code": null,
"e": 4285,
"s": 4250,
"text": "Printing Output on Screen in Julia"
},
{
"code": null,
"e": 4345,
"s": 4285,
"text": "Getting rounded value of a number in Julia - round() Method"
}
] |
Program to print the berth of given railway seat number
|
07 Jun, 2022
Given a railway seat number, the task is to check whether it is a valid seat number or not. Also print its berth type i.e lower berth, middle berth, upper berth, side lower berth, side upper berth as per the figure below.
Examples:
Input: 10 Output: middle berthInput: 7 Output: side lower berth
Approach:
Check if seat number is valid seat number or not(i.e in range of 1 to 72). if (seat_number % 8) equals 1 or 4, then berth is a lower berthif (seat_number % 8) equals 2 or 5, then berth is a middle berthif (seat_number % 8) equals 3 or 6, then berth is an upper berthif (seat_number % 8) equals 7, then berth is a side lower berthif (seat_number % 8) equals 0 then berth is a side upper berth
if (seat_number % 8) equals 1 or 4, then berth is a lower berthif (seat_number % 8) equals 2 or 5, then berth is a middle berthif (seat_number % 8) equals 3 or 6, then berth is an upper berthif (seat_number % 8) equals 7, then berth is a side lower berthif (seat_number % 8) equals 0 then berth is a side upper berth
if (seat_number % 8) equals 1 or 4, then berth is a lower berth
if (seat_number % 8) equals 2 or 5, then berth is a middle berth
if (seat_number % 8) equals 3 or 6, then berth is an upper berth
if (seat_number % 8) equals 7, then berth is a side lower berth
if (seat_number % 8) equals 0 then berth is a side upper berth
Below is the implementation of the above approach:
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to print// berth type of a provided// seat number.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // function to print berth typevoid berth_type(int s){ std::cout << std::fixed; std::cout << std::setprecision(2); if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) cout << s << " is a lower berth\n"; else if (s % 8 == 2 || s % 8 == 5) cout << s << " is a middle berth\n"; else if(s % 8 == 3 || s % 8 == 6) cout << s << " is a upper berth\n"; else if(s % 8 == 7) cout << s << " is a side lower berth\n"; else cout << s << " is a side upper berth\n"; else cout << s << " invalid seat number\n";} // Driver codeint main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s); return 0;} // This code is contributed// by Amber_Saxena.
// C program to print// berth type of a provided// seat number.#include <stdio.h> // function to print berth typevoid berth_type(int s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) printf("%d is lower berth\n", s); else if (s % 8 == 2 || s % 8 == 5) printf("%d is middle berth\n", s); else if(s % 8 == 3 || s % 8 == 6) printf("%d is upper berth\n", s); else if(s % 8 == 7) printf("%d is side lower berth\n", s); else printf("%d is side upper berth\n", s); else printf("%d invalid seat number\n", s);} // Driver codeint main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s); return 0;} // This code is contributed// by Amber_Saxena.
// Java program to print// berth type of a provided// seat number.import java .io.*; class GFG{ // Function for// printing berth typestatic void berth_type(int s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) System.out.println(s + " is lower berth"); else if (s % 8 == 2 || s % 8 == 5) System.out.println(s + " is middle berth"); else if(s % 8 == 3 || s % 8 == 6) System.out.println(s + " is upper berth"); else if(s % 8 == 7) System.out.println(s + " is side lower berth"); else System.out.println(s + " is side upper berth"); else System.out.println(s + " invalid seat number");} // Driver codepublic static void main(String[] args){int s = 10;berth_type(s); // fxn call for berth type s = 7;berth_type(s); // fxn call for berth type s = 0;berth_type(s); // fxn call for berth type}} // This code is contributed// by anuj_67.
# Python program to print berth type# of a provided seat number. # Function for printing berth typedef berth_type(s): if s>0 and s<73: if s % 8 == 1 or s % 8 == 4: print s, "is lower berth" elif s % 8 == 2 or s % 8 == 5: print s, "is middle berth" elif s % 8 == 3 or s % 8 == 6: print s, "is upper berth" elif s % 8 == 7: print s, "is side lower berth" else: print s, "is side upper berth" else: print s, "invalid seat number" # Driver codes = 10berth_type(s) # fxn call for berth type s = 7berth_type(s) # fxn call for berth type s = 0berth_type(s) # fxn call for berth type
// C# program to print// berth type of a provided// seat number.using System; class GFG{ // function to print berth typestatic void berth_type(int s){ if (s > 0 && s < 73) { if (s % 8 == 1 || s % 8 == 4) Console.WriteLine(s + " is lower berth"); else if (s % 8 == 2 || s % 8 == 5) Console.WriteLine(s + " is middle berth"); else if(s % 8 == 3 || s % 8 == 6) Console.WriteLine(s + " is upper berth"); else if(s % 8 == 7) Console.WriteLine(s + " is side lower berth"); else Console.WriteLine(s + " is side upper berth"); } else Console.WriteLine(s + " invalid seat number"); return;} // Driver codepublic static void Main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s);}} // This code is contributed// by Amber_Saxena.
<?php// PHP program to print// berth type of a provided// seat number. // function to print berth typefunction berth_type($s){ if ($s > 0 && $s < 73) { if ($s % 8 == 1 || $s % 8 == 4) { echo sprintf("%d is lower " . "berth\n", $s); } else if ($s % 8 == 2 || $s % 8 == 5) { echo sprintf("%d is middle ". "berth\n", $s); } else if($s % 8 == 3 || $s % 8 == 6) { echo sprintf("%d is upper " . "berth\n", $s); } else if($s % 8 == 7) { echo sprintf("%d is side lower ". "berth\n", $s); } else { echo sprintf("%d is side upper ". "berth\n", $s); } } else { echo sprintf("%d invalid seat ". "number\n", $s); }} // Driver Code$s = 10; // fxn call for berth typeberth_type($s); $s = 7; // fxn call for berth typeberth_type($s); $s = 0; // fxn call for berth typeberth_type($s); // This code is contributed// by Amber_Saxena.?>
<script> // Javascript program to print// berth type of a provided// seat number. // Function for// printing berth typefunction berth_type(s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) document.write(s + " is lower berth" + "<br/>"); else if (s % 8 == 2 || s % 8 == 5) document.write(s + " is middle berth" + "<br/>"); else if(s % 8 == 3 || s % 8 == 6) document.write(s + " is upper berth" + "<br/>"); else if(s % 8 == 7) document.write(s + " is side lower berth" + "<br/>"); else document.write(s + " is side upper berth" + "<br/>"); else document.write(s + " invalid seat number" + "<br/>");} // driver program let s = 10;berth_type(s); // fxn call for berth type s = 7;berth_type(s); // fxn call for berth type s = 0;berth_type(s); // fxn call for berth type // This code is contributed by susmitakundugoaldanga.</script>
10 is middle berth
7 is side lower berth
0 invalid seat number
Time Complexity: O(1)
Auxiliary Space: O(1)
vt_m
Amber_Saxena
susmitakundugoaldanga
pushpeshrajdx01
math
school-programming
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
How JVM Works - JVM Architecture?
Python program to add two numbers
Variables in Java
Data types in Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 251,
"s": 28,
"text": "Given a railway seat number, the task is to check whether it is a valid seat number or not. Also print its berth type i.e lower berth, middle berth, upper berth, side lower berth, side upper berth as per the figure below. "
},
{
"code": null,
"e": 263,
"s": 251,
"text": "Examples: "
},
{
"code": null,
"e": 329,
"s": 263,
"text": "Input: 10 Output: middle berthInput: 7 Output: side lower berth "
},
{
"code": null,
"e": 343,
"s": 331,
"text": "Approach: "
},
{
"code": null,
"e": 735,
"s": 343,
"text": "Check if seat number is valid seat number or not(i.e in range of 1 to 72). if (seat_number % 8) equals 1 or 4, then berth is a lower berthif (seat_number % 8) equals 2 or 5, then berth is a middle berthif (seat_number % 8) equals 3 or 6, then berth is an upper berthif (seat_number % 8) equals 7, then berth is a side lower berthif (seat_number % 8) equals 0 then berth is a side upper berth"
},
{
"code": null,
"e": 1052,
"s": 735,
"text": "if (seat_number % 8) equals 1 or 4, then berth is a lower berthif (seat_number % 8) equals 2 or 5, then berth is a middle berthif (seat_number % 8) equals 3 or 6, then berth is an upper berthif (seat_number % 8) equals 7, then berth is a side lower berthif (seat_number % 8) equals 0 then berth is a side upper berth"
},
{
"code": null,
"e": 1116,
"s": 1052,
"text": "if (seat_number % 8) equals 1 or 4, then berth is a lower berth"
},
{
"code": null,
"e": 1181,
"s": 1116,
"text": "if (seat_number % 8) equals 2 or 5, then berth is a middle berth"
},
{
"code": null,
"e": 1246,
"s": 1181,
"text": "if (seat_number % 8) equals 3 or 6, then berth is an upper berth"
},
{
"code": null,
"e": 1310,
"s": 1246,
"text": "if (seat_number % 8) equals 7, then berth is a side lower berth"
},
{
"code": null,
"e": 1373,
"s": 1310,
"text": "if (seat_number % 8) equals 0 then berth is a side upper berth"
},
{
"code": null,
"e": 1426,
"s": 1373,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1430,
"s": 1426,
"text": "C++"
},
{
"code": null,
"e": 1432,
"s": 1430,
"text": "C"
},
{
"code": null,
"e": 1437,
"s": 1432,
"text": "Java"
},
{
"code": null,
"e": 1444,
"s": 1437,
"text": "Python"
},
{
"code": null,
"e": 1447,
"s": 1444,
"text": "C#"
},
{
"code": null,
"e": 1451,
"s": 1447,
"text": "PHP"
},
{
"code": null,
"e": 1462,
"s": 1451,
"text": "Javascript"
},
{
"code": "// C++ program to print// berth type of a provided// seat number.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // function to print berth typevoid berth_type(int s){ std::cout << std::fixed; std::cout << std::setprecision(2); if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) cout << s << \" is a lower berth\\n\"; else if (s % 8 == 2 || s % 8 == 5) cout << s << \" is a middle berth\\n\"; else if(s % 8 == 3 || s % 8 == 6) cout << s << \" is a upper berth\\n\"; else if(s % 8 == 7) cout << s << \" is a side lower berth\\n\"; else cout << s << \" is a side upper berth\\n\"; else cout << s << \" invalid seat number\\n\";} // Driver codeint main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s); return 0;} // This code is contributed// by Amber_Saxena.",
"e": 2626,
"s": 1462,
"text": null
},
{
"code": "// C program to print// berth type of a provided// seat number.#include <stdio.h> // function to print berth typevoid berth_type(int s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) printf(\"%d is lower berth\\n\", s); else if (s % 8 == 2 || s % 8 == 5) printf(\"%d is middle berth\\n\", s); else if(s % 8 == 3 || s % 8 == 6) printf(\"%d is upper berth\\n\", s); else if(s % 8 == 7) printf(\"%d is side lower berth\\n\", s); else printf(\"%d is side upper berth\\n\", s); else printf(\"%d invalid seat number\\n\", s);} // Driver codeint main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s); return 0;} // This code is contributed// by Amber_Saxena.",
"e": 3627,
"s": 2626,
"text": null
},
{
"code": "// Java program to print// berth type of a provided// seat number.import java .io.*; class GFG{ // Function for// printing berth typestatic void berth_type(int s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) System.out.println(s + \" is lower berth\"); else if (s % 8 == 2 || s % 8 == 5) System.out.println(s + \" is middle berth\"); else if(s % 8 == 3 || s % 8 == 6) System.out.println(s + \" is upper berth\"); else if(s % 8 == 7) System.out.println(s + \" is side lower berth\"); else System.out.println(s + \" is side upper berth\"); else System.out.println(s + \" invalid seat number\");} // Driver codepublic static void main(String[] args){int s = 10;berth_type(s); // fxn call for berth type s = 7;berth_type(s); // fxn call for berth type s = 0;berth_type(s); // fxn call for berth type}} // This code is contributed// by anuj_67.",
"e": 4737,
"s": 3627,
"text": null
},
{
"code": "# Python program to print berth type# of a provided seat number. # Function for printing berth typedef berth_type(s): if s>0 and s<73: if s % 8 == 1 or s % 8 == 4: print s, \"is lower berth\" elif s % 8 == 2 or s % 8 == 5: print s, \"is middle berth\" elif s % 8 == 3 or s % 8 == 6: print s, \"is upper berth\" elif s % 8 == 7: print s, \"is side lower berth\" else: print s, \"is side upper berth\" else: print s, \"invalid seat number\" # Driver codes = 10berth_type(s) # fxn call for berth type s = 7berth_type(s) # fxn call for berth type s = 0berth_type(s) # fxn call for berth type",
"e": 5436,
"s": 4737,
"text": null
},
{
"code": "// C# program to print// berth type of a provided// seat number.using System; class GFG{ // function to print berth typestatic void berth_type(int s){ if (s > 0 && s < 73) { if (s % 8 == 1 || s % 8 == 4) Console.WriteLine(s + \" is lower berth\"); else if (s % 8 == 2 || s % 8 == 5) Console.WriteLine(s + \" is middle berth\"); else if(s % 8 == 3 || s % 8 == 6) Console.WriteLine(s + \" is upper berth\"); else if(s % 8 == 7) Console.WriteLine(s + \" is side lower berth\"); else Console.WriteLine(s + \" is side upper berth\"); } else Console.WriteLine(s + \" invalid seat number\"); return;} // Driver codepublic static void Main(){ int s = 10; // fxn call for berth type berth_type(s); s = 7; // fxn call for berth type berth_type(s); s = 0; // fxn call for berth type berth_type(s);}} // This code is contributed// by Amber_Saxena.",
"e": 6518,
"s": 5436,
"text": null
},
{
"code": "<?php// PHP program to print// berth type of a provided// seat number. // function to print berth typefunction berth_type($s){ if ($s > 0 && $s < 73) { if ($s % 8 == 1 || $s % 8 == 4) { echo sprintf(\"%d is lower \" . \"berth\\n\", $s); } else if ($s % 8 == 2 || $s % 8 == 5) { echo sprintf(\"%d is middle \". \"berth\\n\", $s); } else if($s % 8 == 3 || $s % 8 == 6) { echo sprintf(\"%d is upper \" . \"berth\\n\", $s); } else if($s % 8 == 7) { echo sprintf(\"%d is side lower \". \"berth\\n\", $s); } else { echo sprintf(\"%d is side upper \". \"berth\\n\", $s); } } else { echo sprintf(\"%d invalid seat \". \"number\\n\", $s); }} // Driver Code$s = 10; // fxn call for berth typeberth_type($s); $s = 7; // fxn call for berth typeberth_type($s); $s = 0; // fxn call for berth typeberth_type($s); // This code is contributed// by Amber_Saxena.?>",
"e": 7730,
"s": 6518,
"text": null
},
{
"code": "<script> // Javascript program to print// berth type of a provided// seat number. // Function for// printing berth typefunction berth_type(s){ if (s > 0 && s < 73) if (s % 8 == 1 || s % 8 == 4) document.write(s + \" is lower berth\" + \"<br/>\"); else if (s % 8 == 2 || s % 8 == 5) document.write(s + \" is middle berth\" + \"<br/>\"); else if(s % 8 == 3 || s % 8 == 6) document.write(s + \" is upper berth\" + \"<br/>\"); else if(s % 8 == 7) document.write(s + \" is side lower berth\" + \"<br/>\"); else document.write(s + \" is side upper berth\" + \"<br/>\"); else document.write(s + \" invalid seat number\" + \"<br/>\");} // driver program let s = 10;berth_type(s); // fxn call for berth type s = 7;berth_type(s); // fxn call for berth type s = 0;berth_type(s); // fxn call for berth type // This code is contributed by susmitakundugoaldanga.</script>",
"e": 8848,
"s": 7730,
"text": null
},
{
"code": null,
"e": 8911,
"s": 8848,
"text": "10 is middle berth\n7 is side lower berth\n0 invalid seat number"
},
{
"code": null,
"e": 8935,
"s": 8913,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 8957,
"s": 8935,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8962,
"s": 8957,
"text": "vt_m"
},
{
"code": null,
"e": 8975,
"s": 8962,
"text": "Amber_Saxena"
},
{
"code": null,
"e": 8997,
"s": 8975,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 9013,
"s": 8997,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 9018,
"s": 9013,
"text": "math"
},
{
"code": null,
"e": 9037,
"s": 9018,
"text": "school-programming"
},
{
"code": null,
"e": 9056,
"s": 9037,
"text": "School Programming"
},
{
"code": null,
"e": 9154,
"s": 9056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9175,
"s": 9154,
"text": "Constructors in Java"
},
{
"code": null,
"e": 9194,
"s": 9175,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 9220,
"s": 9194,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 9238,
"s": 9220,
"text": "Python Try Except"
},
{
"code": null,
"e": 9265,
"s": 9238,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 9299,
"s": 9265,
"text": "How JVM Works - JVM Architecture?"
},
{
"code": null,
"e": 9333,
"s": 9299,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 9351,
"s": 9333,
"text": "Variables in Java"
},
{
"code": null,
"e": 9370,
"s": 9351,
"text": "Data types in Java"
}
] |
Objective-C Program Structure
|
Before we study basic building blocks of the Objective-C programming language, let us look a bare minimum Objective-C program structure so that we can take it as a reference in upcoming chapters.
A Objective-C program basically consists of the following parts −
Preprocessor Commands
Interface
Implementation
Method
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void)sampleMethod;
@end
@implementation SampleClass
- (void)sampleMethod {
NSLog(@"Hello, World! \n");
}
@end
int main() {
/* my first program in Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
return 0;
}
Let us look various parts of the above program −
The first line of the program #import <Foundation/Foundation.h> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation.
The first line of the program #import <Foundation/Foundation.h> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation.
The next line @interface SampleClass:NSObject shows how to create an interface. It inherits NSObject, which is the base class of all objects.
The next line @interface SampleClass:NSObject shows how to create an interface. It inherits NSObject, which is the base class of all objects.
The next line - (void)sampleMethod; shows how to declare a method.
The next line - (void)sampleMethod; shows how to declare a method.
The next line @end marks the end of an interface.
The next line @end marks the end of an interface.
The next line @implementation SampleClass shows how to implement the interface SampleClass.
The next line @implementation SampleClass shows how to implement the interface SampleClass.
The next line - (void)sampleMethod{} shows the implementation of the sampleMethod.
The next line - (void)sampleMethod{} shows the implementation of the sampleMethod.
The next line @end marks the end of an implementation.
The next line @end marks the end of an implementation.
The next line int main() is the main function where program execution begins.
The next line int main() is the main function where program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.
The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.
The next line NSLog(...) is another function available in Objective-C which causes the message "Hello, World!" to be displayed on the screen.
The next line NSLog(...) is another function available in Objective-C which causes the message "Hello, World!" to be displayed on the screen.
The next line return 0; terminates main()function and returns the value 0.
The next line return 0; terminates main()function and returns the value 0.
Now when we compile and run the program, we will get the following result.
2017-10-06 07:48:32.020 demo[65832] Hello, World!
|
[
{
"code": null,
"e": 2890,
"s": 2694,
"text": "Before we study basic building blocks of the Objective-C programming language, let us look a bare minimum Objective-C program structure so that we can take it as a reference in upcoming chapters."
},
{
"code": null,
"e": 2956,
"s": 2890,
"text": "A Objective-C program basically consists of the following parts −"
},
{
"code": null,
"e": 2978,
"s": 2956,
"text": "Preprocessor Commands"
},
{
"code": null,
"e": 2988,
"s": 2978,
"text": "Interface"
},
{
"code": null,
"e": 3003,
"s": 2988,
"text": "Implementation"
},
{
"code": null,
"e": 3010,
"s": 3003,
"text": "Method"
},
{
"code": null,
"e": 3020,
"s": 3010,
"text": "Variables"
},
{
"code": null,
"e": 3045,
"s": 3020,
"text": "Statements & Expressions"
},
{
"code": null,
"e": 3054,
"s": 3045,
"text": "Comments"
},
{
"code": null,
"e": 3126,
"s": 3054,
"text": "Let us look at a simple code that would print the words \"Hello World\" −"
},
{
"code": null,
"e": 3470,
"s": 3126,
"text": "#import <Foundation/Foundation.h>\n\n@interface SampleClass:NSObject\n- (void)sampleMethod;\n@end\n\n@implementation SampleClass\n\n- (void)sampleMethod {\n NSLog(@\"Hello, World! \\n\");\n}\n\n@end\n\nint main() {\n /* my first program in Objective-C */\n SampleClass *sampleClass = [[SampleClass alloc]init];\n [sampleClass sampleMethod];\n return 0;\n}"
},
{
"code": null,
"e": 3519,
"s": 3470,
"text": "Let us look various parts of the above program −"
},
{
"code": null,
"e": 3710,
"s": 3519,
"text": "The first line of the program #import <Foundation/Foundation.h> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation."
},
{
"code": null,
"e": 3901,
"s": 3710,
"text": "The first line of the program #import <Foundation/Foundation.h> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation."
},
{
"code": null,
"e": 4043,
"s": 3901,
"text": "The next line @interface SampleClass:NSObject shows how to create an interface. It inherits NSObject, which is the base class of all objects."
},
{
"code": null,
"e": 4185,
"s": 4043,
"text": "The next line @interface SampleClass:NSObject shows how to create an interface. It inherits NSObject, which is the base class of all objects."
},
{
"code": null,
"e": 4252,
"s": 4185,
"text": "The next line - (void)sampleMethod; shows how to declare a method."
},
{
"code": null,
"e": 4319,
"s": 4252,
"text": "The next line - (void)sampleMethod; shows how to declare a method."
},
{
"code": null,
"e": 4369,
"s": 4319,
"text": "The next line @end marks the end of an interface."
},
{
"code": null,
"e": 4419,
"s": 4369,
"text": "The next line @end marks the end of an interface."
},
{
"code": null,
"e": 4511,
"s": 4419,
"text": "The next line @implementation SampleClass shows how to implement the interface SampleClass."
},
{
"code": null,
"e": 4603,
"s": 4511,
"text": "The next line @implementation SampleClass shows how to implement the interface SampleClass."
},
{
"code": null,
"e": 4686,
"s": 4603,
"text": "The next line - (void)sampleMethod{} shows the implementation of the sampleMethod."
},
{
"code": null,
"e": 4769,
"s": 4686,
"text": "The next line - (void)sampleMethod{} shows the implementation of the sampleMethod."
},
{
"code": null,
"e": 4824,
"s": 4769,
"text": "The next line @end marks the end of an implementation."
},
{
"code": null,
"e": 4879,
"s": 4824,
"text": "The next line @end marks the end of an implementation."
},
{
"code": null,
"e": 4957,
"s": 4879,
"text": "The next line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 5035,
"s": 4957,
"text": "The next line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 5202,
"s": 5035,
"text": "The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program."
},
{
"code": null,
"e": 5369,
"s": 5202,
"text": "The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program."
},
{
"code": null,
"e": 5511,
"s": 5369,
"text": "The next line NSLog(...) is another function available in Objective-C which causes the message \"Hello, World!\" to be displayed on the screen."
},
{
"code": null,
"e": 5653,
"s": 5511,
"text": "The next line NSLog(...) is another function available in Objective-C which causes the message \"Hello, World!\" to be displayed on the screen."
},
{
"code": null,
"e": 5728,
"s": 5653,
"text": "The next line return 0; terminates main()function and returns the value 0."
},
{
"code": null,
"e": 5803,
"s": 5728,
"text": "The next line return 0; terminates main()function and returns the value 0."
},
{
"code": null,
"e": 5878,
"s": 5803,
"text": "Now when we compile and run the program, we will get the following result."
}
] |
Plotting Data with Timestamps using PyQtGraph
|
31 Aug, 2021
In this article, we will see how we can plot data with timestamps using the PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and the second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).
In order to install the PyQtGraph we use the command given below.
pip install pyqtgraph
A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving date and time of day, sometimes accurate to a small fraction of a second. In this tutorial we will see how we can plot timestamps on x-axis and y-axis will have corresponding data with it.
In order to do so we have to do the following
Import the required libraries like pyqtgraph, pyqt5, time and numpyCreate a main window class using pyqt5Create a graph window having axisitem set as DateAxisItem for timestampsNow create a data to plot in this example we will plot the sin(1/x^2) with timestamps in the last 100 yearsWith this data plot the line graphAdd the graph and other widgets to the layout of central widget of main window.
Import the required libraries like pyqtgraph, pyqt5, time and numpy
Create a main window class using pyqt5
Create a graph window having axisitem set as DateAxisItem for timestamps
Now create a data to plot in this example we will plot the sin(1/x^2) with timestamps in the last 100 years
With this data plot the line graph
Add the graph and other widgets to the layout of central widget of main window.
Below is the implementation.
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # time moduleimport timefrom datetime import datetime, timedelta # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 900, 550) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = "Timestamps Plot" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # Create a plot with a date-time axis (timestamps on x-axis) w = pg.PlotWidget(axisItems={'bottom': pg.DateAxisItem()}) # show the grids on the graph w.showGrid(x=True, y=True) # Plotting sin(1/x^2) with timestamps in the last 100 years now = time.time() # x data x = np.linspace(2 * np.pi, 1000 * 2 * np.pi, 8301) # plot the data w.plot(now - (2 * np.pi / x) ** 2 * 100 * np.pi * 1e7, np.sin(x), symbol='o') # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(w, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
gabaa406
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 514,
"s": 28,
"text": "In this article, we will see how we can plot data with timestamps using the PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and the second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer)."
},
{
"code": null,
"e": 580,
"s": 514,
"text": "In order to install the PyQtGraph we use the command given below."
},
{
"code": null,
"e": 602,
"s": 580,
"text": "pip install pyqtgraph"
},
{
"code": null,
"e": 912,
"s": 602,
"text": "A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving date and time of day, sometimes accurate to a small fraction of a second. In this tutorial we will see how we can plot timestamps on x-axis and y-axis will have corresponding data with it."
},
{
"code": null,
"e": 959,
"s": 912,
"text": "In order to do so we have to do the following "
},
{
"code": null,
"e": 1357,
"s": 959,
"text": "Import the required libraries like pyqtgraph, pyqt5, time and numpyCreate a main window class using pyqt5Create a graph window having axisitem set as DateAxisItem for timestampsNow create a data to plot in this example we will plot the sin(1/x^2) with timestamps in the last 100 yearsWith this data plot the line graphAdd the graph and other widgets to the layout of central widget of main window."
},
{
"code": null,
"e": 1425,
"s": 1357,
"text": "Import the required libraries like pyqtgraph, pyqt5, time and numpy"
},
{
"code": null,
"e": 1464,
"s": 1425,
"text": "Create a main window class using pyqt5"
},
{
"code": null,
"e": 1537,
"s": 1464,
"text": "Create a graph window having axisitem set as DateAxisItem for timestamps"
},
{
"code": null,
"e": 1645,
"s": 1537,
"text": "Now create a data to plot in this example we will plot the sin(1/x^2) with timestamps in the last 100 years"
},
{
"code": null,
"e": 1680,
"s": 1645,
"text": "With this data plot the line graph"
},
{
"code": null,
"e": 1760,
"s": 1680,
"text": "Add the graph and other widgets to the layout of central widget of main window."
},
{
"code": null,
"e": 1789,
"s": 1760,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1797,
"s": 1789,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # time moduleimport timefrom datetime import datetime, timedelta # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 900, 550) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = \"Timestamps Plot\" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # Create a plot with a date-time axis (timestamps on x-axis) w = pg.PlotWidget(axisItems={'bottom': pg.DateAxisItem()}) # show the grids on the graph w.showGrid(x=True, y=True) # Plotting sin(1/x^2) with timestamps in the last 100 years now = time.time() # x data x = np.linspace(2 * np.pi, 1000 * 2 * np.pi, 8301) # plot the data w.plot(now - (2 * np.pi / x) ** 2 * 100 * np.pi * 1e7, np.sin(x), symbol='o') # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(w, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 3998,
"s": 1797,
"text": null
},
{
"code": null,
"e": 4009,
"s": 3998,
"text": "Output : "
},
{
"code": null,
"e": 4020,
"s": 4011,
"text": "gabaa406"
},
{
"code": null,
"e": 4037,
"s": 4020,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 4044,
"s": 4037,
"text": "Python"
},
{
"code": null,
"e": 4142,
"s": 4044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4174,
"s": 4142,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4201,
"s": 4174,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4222,
"s": 4201,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4245,
"s": 4222,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4301,
"s": 4245,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4332,
"s": 4301,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4374,
"s": 4332,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4416,
"s": 4374,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4455,
"s": 4416,
"text": "Python | datetime.timedelta() function"
}
] |
rm -rf Command in Linux With Examples
|
08 Mar, 2021
rm command in UNIX stands for remove and by default is used for removing files. It is simple but a powerful command especially when used with options such as -rf which allow it to delete non-empty directories forcefully.
The rm command, By default, cannot remove Directories and only works on files.
$ mkdir A
$ touch B.txt
$ rm B.txt
$ rm A
We use mkdir and touch commands to make directories and text files respectively, and ls command to list files in the current working directory.
To remove multiple files at once, we can write file names separated by spaces after the rm command or use a pattern to remove multiple files that fit the pattern.
$ rm a b
$ rm *.txt [Pattern]
removing multiple files
To remove a directory, you can use the -r or -R switch, which deletes a directory recursively including its content (subdirectories and files). If it is an empty directory you can also use rmdir command.
$ rm a/
$ rm -R a/
removing directory
To get a confirmation prompt while deleting a file, use the -i option.
$ rm -i a.txt
removing files with confirmation
To get a confirmation prompt while deleting a directory and its sub-directories, use the -R and -i option.
$ rm -Ri A/
removing Directories with confirmation
To remove a file or directory forcefully, you can use the option -f force a deletion operation without rm prompting you for confirmation. For example, if a file is unwritable, rm will prompt you whether to remove that file or not, to avoid this and simply execute the operation.
$ rm -f a.txt
When you combine the -r and -f flags, it means that you recursively and forcibly remove a directory (and its contents) without prompting for confirmation.
$ rm -rf B
Here, we created a text file and directory and made it read-only by taking its write access using chmod command.
To show more information when deleting a file or directory, use the -v option, this will enable rm command to show what is being done on the standard output.
$ rm -rv *
rm -rf as powerful as it is, can only bypass read-only access of nested files and not directories. To delete the directory ( B/C ) we need to access it through superuser privileges.
It is not recommended to use this command as a superuser if you are not 100% sure what you are doing as you can delete important files.
You should always keep in mind that “rm -rf” is one of the most dangerous commands, that you should never run on a Linux system, especially as a root. The following command will clear everything on your root(/) partition.
$ sudo rm -rf /
There are checks to prevent root deletion but the additional option of –no-preserve-root bypass that failsafe. It’s a meme on the internet that is equivalent to deletion of system32 in your windows os C:\ drive.
$ sudo rm -rf / --no-preserve-root
You should not use the above command in any case whatsoever, for curious folks I did it use the command with –no-preserve-root. And after some deletion of important files and directories, I was left with nothing but hanged up output shown below.
To permanently use -i option for safety, add an alias in your $HOME/.bashrc file.
alias rm="rm -i"
Source your .bashrc file as shown or open a new terminal for the changes to take effect.
$ source $HOME/.bashrc
Now, whenever you execute rm, it will be invoked with the -i option by default (but using the -f flag will override this setting).
Does rm actually Delete a File?
rm doesn’t actually delete files but rather unlink them (free the memory for further use). To permanently delete the data you can use the shred or dd command.
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 249,
"s": 28,
"text": "rm command in UNIX stands for remove and by default is used for removing files. It is simple but a powerful command especially when used with options such as -rf which allow it to delete non-empty directories forcefully."
},
{
"code": null,
"e": 329,
"s": 249,
"text": "The rm command, By default, cannot remove Directories and only works on files. "
},
{
"code": null,
"e": 371,
"s": 329,
"text": "$ mkdir A\n$ touch B.txt\n$ rm B.txt\n$ rm A"
},
{
"code": null,
"e": 515,
"s": 371,
"text": "We use mkdir and touch commands to make directories and text files respectively, and ls command to list files in the current working directory."
},
{
"code": null,
"e": 678,
"s": 515,
"text": "To remove multiple files at once, we can write file names separated by spaces after the rm command or use a pattern to remove multiple files that fit the pattern."
},
{
"code": null,
"e": 728,
"s": 678,
"text": "$ rm a b\n$ rm *.txt [Pattern] "
},
{
"code": null,
"e": 752,
"s": 728,
"text": "removing multiple files"
},
{
"code": null,
"e": 956,
"s": 752,
"text": "To remove a directory, you can use the -r or -R switch, which deletes a directory recursively including its content (subdirectories and files). If it is an empty directory you can also use rmdir command."
},
{
"code": null,
"e": 975,
"s": 956,
"text": "$ rm a/\n$ rm -R a/"
},
{
"code": null,
"e": 994,
"s": 975,
"text": "removing directory"
},
{
"code": null,
"e": 1065,
"s": 994,
"text": "To get a confirmation prompt while deleting a file, use the -i option."
},
{
"code": null,
"e": 1079,
"s": 1065,
"text": "$ rm -i a.txt"
},
{
"code": null,
"e": 1112,
"s": 1079,
"text": "removing files with confirmation"
},
{
"code": null,
"e": 1219,
"s": 1112,
"text": "To get a confirmation prompt while deleting a directory and its sub-directories, use the -R and -i option."
},
{
"code": null,
"e": 1231,
"s": 1219,
"text": "$ rm -Ri A/"
},
{
"code": null,
"e": 1270,
"s": 1231,
"text": "removing Directories with confirmation"
},
{
"code": null,
"e": 1549,
"s": 1270,
"text": "To remove a file or directory forcefully, you can use the option -f force a deletion operation without rm prompting you for confirmation. For example, if a file is unwritable, rm will prompt you whether to remove that file or not, to avoid this and simply execute the operation."
},
{
"code": null,
"e": 1563,
"s": 1549,
"text": "$ rm -f a.txt"
},
{
"code": null,
"e": 1718,
"s": 1563,
"text": "When you combine the -r and -f flags, it means that you recursively and forcibly remove a directory (and its contents) without prompting for confirmation."
},
{
"code": null,
"e": 1729,
"s": 1718,
"text": "$ rm -rf B"
},
{
"code": null,
"e": 1842,
"s": 1729,
"text": "Here, we created a text file and directory and made it read-only by taking its write access using chmod command."
},
{
"code": null,
"e": 2000,
"s": 1842,
"text": "To show more information when deleting a file or directory, use the -v option, this will enable rm command to show what is being done on the standard output."
},
{
"code": null,
"e": 2011,
"s": 2000,
"text": "$ rm -rv *"
},
{
"code": null,
"e": 2193,
"s": 2011,
"text": "rm -rf as powerful as it is, can only bypass read-only access of nested files and not directories. To delete the directory ( B/C ) we need to access it through superuser privileges."
},
{
"code": null,
"e": 2329,
"s": 2193,
"text": "It is not recommended to use this command as a superuser if you are not 100% sure what you are doing as you can delete important files."
},
{
"code": null,
"e": 2551,
"s": 2329,
"text": "You should always keep in mind that “rm -rf” is one of the most dangerous commands, that you should never run on a Linux system, especially as a root. The following command will clear everything on your root(/) partition."
},
{
"code": null,
"e": 2567,
"s": 2551,
"text": "$ sudo rm -rf /"
},
{
"code": null,
"e": 2779,
"s": 2567,
"text": "There are checks to prevent root deletion but the additional option of –no-preserve-root bypass that failsafe. It’s a meme on the internet that is equivalent to deletion of system32 in your windows os C:\\ drive."
},
{
"code": null,
"e": 2814,
"s": 2779,
"text": "$ sudo rm -rf / --no-preserve-root"
},
{
"code": null,
"e": 3061,
"s": 2814,
"text": "You should not use the above command in any case whatsoever, for curious folks I did it use the command with –no-preserve-root. And after some deletion of important files and directories, I was left with nothing but hanged up output shown below."
},
{
"code": null,
"e": 3143,
"s": 3061,
"text": "To permanently use -i option for safety, add an alias in your $HOME/.bashrc file."
},
{
"code": null,
"e": 3160,
"s": 3143,
"text": "alias rm=\"rm -i\""
},
{
"code": null,
"e": 3249,
"s": 3160,
"text": "Source your .bashrc file as shown or open a new terminal for the changes to take effect."
},
{
"code": null,
"e": 3272,
"s": 3249,
"text": "$ source $HOME/.bashrc"
},
{
"code": null,
"e": 3403,
"s": 3272,
"text": "Now, whenever you execute rm, it will be invoked with the -i option by default (but using the -f flag will override this setting)."
},
{
"code": null,
"e": 3435,
"s": 3403,
"text": "Does rm actually Delete a File?"
},
{
"code": null,
"e": 3595,
"s": 3435,
"text": "rm doesn’t actually delete files but rather unlink them (free the memory for further use). To permanently delete the data you can use the shred or dd command."
},
{
"code": null,
"e": 3609,
"s": 3595,
"text": "linux-command"
},
{
"code": null,
"e": 3629,
"s": 3609,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 3636,
"s": 3629,
"text": "Picked"
},
{
"code": null,
"e": 3647,
"s": 3636,
"text": "Linux-Unix"
}
] |
AIML - Quick Guide
|
AIML stands for Artificial Intelligence Markup Language. AIML was developed by the Alicebot free software community and Dr. Richard S. Wallace during 1995-2000. AIML is used to create or customize Alicebot which is a chat-box application based on A.L.I.C.E. (Artificial Linguistic Internet Computer Entity) free software.
Following are the important tags which are commonly used in AIML documents.
<aiml>
Defines the beginning and end of a AIML document.
<category>
Defines the unit of knowledge in Alicebot's knowledge base.
<pattern>
Defines the pattern to match what a user may input to an Alicebot.
<template>
Defines the response of an Alicebot to user's input.
We'll discuss each of these tags in AIML Basic tags chapter.
Following are some of the other widely used aiml tags. We'll be discussing each tag in details in coming chapters.
<star>
Used to match wild card * character(s) in the <pattern> Tag.
<srai>
Multipurpose tag, used to call/match the other categories.
<random>
Used <random> to get random responses.
<li>
Used to represent multiple responses.
<set>
Used to set value in an AIML variable.
<get>
Used to get value stored in an AIML variable.
<that>
Used in AIML to respond based on the context.
<topic>
Used in AIML to store a context so that later conversation can be done based on that context.
<think>
Used in AIML to store a variable without notifying the user.
<condition>
Similar to switch statements in programming language. It helps ALICE to respond to matching input.
AIML vocabulary uses words, space and two special characters * and _ as wild cards. AIML interpreter gives preference to pattern having _ than pattern having *. AIML tags are XML compliant and patterns are case-insensitive.
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User!
</template>
</category>
</aiml>
Following are the important points to be considered −
<aiml> tag signifies start of the AIML document.
<aiml> tag signifies start of the AIML document.
<category> tag defines the knowledge unit.
<category> tag defines the knowledge unit.
<pattern> tag defines the pattern user is going to type.
<pattern> tag defines the pattern user is going to type.
<template> tag defines the response to the user if user types Hello Alice.
<template> tag defines the response to the user if user types Hello Alice.
User: Hello Alice
Bot: Hello User
This tutorial will guide you on how to prepare a development environment to start your work with AIML to create auto chat software. Program AB is a reference implementation of AIML 2.0 developed and being maintained by ALICE A.I. Foundation. This tutorial will also teach you how to set up JDK, before you setup Program AB library −
You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.7.0_75, you would have to put the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.7.0_75\bin;%PATH%
set JAVA_HOME = C:\jdk1.7.0_75
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.7.0_75
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.
Now if everything is fine, then you can proceed to setup your Program AB. Following are the simple steps to download and install the library on your machine.
Make a choice whether you want to install AIML on Windows, or Unix and then proceed to the next step to download .zip file
Make a choice whether you want to install AIML on Windows, or Unix and then proceed to the next step to download .zip file
Download the latest version of Program AB binaries from https://code.google.com/p/program-ab/ using its program-ab-0.0.4.3.zip link.
Download the latest version of Program AB binaries from https://code.google.com/p/program-ab/ using its program-ab-0.0.4.3.zip link.
At the time of writing this tutorial, I downloaded program-ab-0.0.4.3.zip on my Windows machine and when you unzip the downloaded file it will give you directory structure inside C:\ab as follows.
At the time of writing this tutorial, I downloaded program-ab-0.0.4.3.zip on my Windows machine and when you unzip the downloaded file it will give you directory structure inside C:\ab as follows.
c:/ab/bots
Stores AIML bots
c:/ab/lib
Stores Java libraries
c:/ab/out
Java class file directory
c:/ab/run.bat
batch file for running Program AB
Once you are done with this last step, you are ready to proceed with your first AIML Example which you will see in the next chapter.
Let us start creating first bot which will simply greet a user with Hello User! when a user types Hello Alice.
As in AIML Environment Setup, we've extracted content of program-ab in C > ab with the following directory structure.
c:/ab/bots
Stores AIML bots
c:/ab/lib
Stores Java libraries
c:/ab/out
Java class file directory
c:/ab/run.bat
batch file for running Program AB
Now, create a directory test inside C > ab > bots and create the following directories in it.
c:/ab/bots/test/aiml
Stores AIML files
c:/ab/bots/test/aimlif
Stores AIMLIF files
c:/ab/bots/test/config
Stores configuration files
c:/ab/bots/test/sets
Stores AIML Sets
c:/ab/bots/test/maps
Stores AIML Maps
Create test.aiml inside C > ab > bots > test > aiml and test.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version="1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
</aiml>
0,HELLO ALICE,*,*,Hello User,test.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You'll see the following output −
Working Directory = C:\ab
Program AB 0.0.4.2 beta -- AI Foundation Reference AIML 2.0 implementation
bot = test
action = chat
trace = false
trace mode = false
Name = test Path = C:\ab/bots/test
C:\ab
C:\ab/bots
C:\ab/bots/test
C:\ab/bots/test/aiml
C:\ab/bots/test/aimlif
C:\ab/bots/test/config
C:\ab/bots/test/logs
C:\ab/bots/test/sets
C:\ab/bots/test/maps
Preprocessor: 0 norms 0 persons 0 person2
Get Properties: C:\ab/bots/test/config/properties.txt
addAIMLSets: C:\ab/bots/test/sets does not exist.
addCategories: C:\ab/bots/test/aiml does not exist.
AIML modified Tue Apr 07 22:24:29 IST 2015 AIMLIF modified Tue Apr 07 22:26:53 I
ST 2015
No deleted.aiml.csv file found
No deleted.aiml.csv file found
Loading AIML files from C:\ab/bots/test/aimlif
Reading Learnf file
Loaded 1 categories in 0.009 sec
--> Bot test 1 completed 0 deleted 0 unfinished
(1[6])--HELLO-->(1[5])--ALICE-->(1[4])--<THAT>-->(1[3])--*-->(1[2])--<TOPIC>-->(
1[1])--*-->(0[null,null]) Hello User...
7 nodes 6 singletons 1 leaves 0 shortcuts 0 n-ary 6 branches 0.85714287 average
branching
Human:
Type Hello Alice and see the result and then type anything else to see the changed result.
Human: hello alice
Robot: Hello User
Human: bye
Robot: I have no answer for that.
Human:
In this tutorial, we'll discuss the basic tags of AIML.
<aiml> − defines the beginning and end of a AIML document.
<aiml> − defines the beginning and end of a AIML document.
<category> − defines the unit of knowledge in Alicebot's knowledge base.
<category> − defines the unit of knowledge in Alicebot's knowledge base.
<pattern> − defines the pattern to match what a user may input to an Alicebot.
<pattern> − defines the pattern to match what a user may input to an Alicebot.
<template> − defines the response of an Alicebot to user's input.
<template> − defines the response of an Alicebot to user's input.
Following AIML files have been used here as reference.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
</aiml>
<aiml> tag marks the start and end of a AIML document. It contains version and encoding information under version and encoding attributes. version attribute stores the AIML version used by ALICE chatterbot Knowledge Base, KB. For example, we've used 1.0.1 version. This attribute is optional.
Encoding attributes provide the character sets to be used in the document. For example, we've used UTF-8. As a mandatory requirement, <aiml> tag must contain at least one <category> tag. We can create multiple AIML files where each AIML file contains a single <aiml> tag. The purpose of each AIML file is to add at least a single knowledge unit called category to ALICE chatterbot KB.
<aiml version = "1.0.1" encoding = "UTF-8"?>
...
</aiml>
<category> tag is the fundamental knowledge unit of an ALICE Bot. Each category contains −
User input in the form of a sentence which can be an assertion, question, and exclamation etc. User input can contain wild card characters like * and _.
User input in the form of a sentence which can be an assertion, question, and exclamation etc. User input can contain wild card characters like * and _.
Response to user input to be presented by Alicebot.
Response to user input to be presented by Alicebot.
Optional context.
Optional context.
A <category> tag must have <pattern> and <template> tag. <pattern> represents the user input and template represents the bot's response.
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
Here, if the user enters Hello Alice then bot will respond back as Hello User.
The <pattern> tag represents a user's input. It should be the first tag within the <category> tag. <pattern> tag can contain wild card to match more than one sentence as user input. For example, in our example, <pattern> contains HELLO ALICE.
AIML is case-insensitive. If a user enters Hello Alice, hello alice, HELLO ALICE etc., all inputs are valid and bot will match them against HELLO ALICE.
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
Here, the template is "Hello User" and represents a robot's response to user input.
<template> tag represents the bot's response to the user. It should be the second tag within the <category> tag. This <template> tag can save data, call another program, give conditional answers or delegate to other categories.
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
Here, the template is "Hello User" and represents a robot's response to the user input.
<star> Tag is used to match wild card * character(s) in <pattern> Tag.
<star index = "n"/>
n signifies the position of * within the user input in <pattern> Tag.
Consider the following example −
<category>
<pattern> A * is a *. </pattern>
<template>
When a <star index = "1"/> is not a <star index = "2"/>?
</template>
</category>
If the user enters "A mango is a fruit." then bot will respond as "When a mango is not a fruit?"
Create star.aiml inside C > ab > bots > test > aiml and star.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>I LIKE *</pattern>
<template>
I too like <star/>.
</template>
</category>
<category>
<pattern>A * IS A *</pattern>
<template>
How <star index = "1"/> can not be a <star index = "2"/>?
</template>
</category>
</aiml>
0,I LIKE *,*,*,I too like <star/>.,star.aiml
0,A * IS A *,*,*,How <star index = "1"/> can not be a <star index = "2"/>?,star.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: I like mango
Robot: I too like mango.
Human: A mango is a fruit
Robot: How mango can not be a fruit?
<star index = "1"/> is often used as <star />
<srai> Tag is a multipurpose tag. This tag enables AIML to define the different targets for the same template.
<srai> pattern </srai>
Following are the commonly used terms associated with srai −
Symbolic Reduction
Symbolic Reduction
Divide and Conquer
Divide and Conquer
Synonyms resolution
Synonyms resolution
Keywords detection
Keywords detection
The symbolic reduction technique is used to simplify patterns. It helps to reduce complex grammatical patterns with simple pattern(s).
For example, consider the following conversation.
Human: Who was Albert Einstein?
Robot: Albert Einstein was a German physicist.
Human: Who was Isaac Newton?
Robot: Isaac Newton was a English physicist and mathematician.
Now What if questions are raised as
Human: DO YOU KNOW WHO Albert Einstein IS?
Human: DO YOU KNOW WHO Isaac Newton IS?
Here, <srai> tag works. It can take the pattern of the user as a template.
<category>
<pattern>WHO IS ALBERT EINSTEIN?</pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON? </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS?</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
Create srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Do you know who Albert Einstein is
Robot: Albert Einstein was a German physicist.
Divide and Conquer is used to reuse sub sentences in making a complete reply. It helps to reduce defining multiple categories.
For example, consider following conversation.
Human: Bye
Robot: GoodBye!
Human: Bye Alice!
Robot: GoodBye!
Now here robot is expected to reply GoodBye! Whenever a user says Bye in the beginning of the sentence.
Let's put <srai> tag to work here.
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Bye
Robot: GoodBye!
Human: Bye Alice!
Robot: GoodBye!
Synonyms are words with similar meanings. A bot should reply in the same manner for similar words.
For example, consider the following conversation.
Human: Factory
Robot: Development Center!
Human: Industry
Robot: Development Center!
Now here robot is expected to reply Development Center! whenever a user says Factory or Industry.
Let's put <srai> tag to work here.
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
0,FACTORY,*,*,Development Center!,srai.aiml
0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Factory
Robot: Development Center!
Human: Industry
Robot: Development Center!
Using srai, we can return a simple response when the user types a specific keyword, say, School, no matter where "school" is present in the sentence.
For example, consider the following conversation.
Human: I love going to school daily.
Robot: School is an important institution in a child's life.
Human: I like my school.
Robot: School is an important institution in a child's life.
Here, the robot is expected to reply a standard message 'School is an important institution in a child's life.' whenever a user has school in the sentence.
Let's put <srai> tag to work here. We'll use wild-cards here.
<category>
<pattern>SCHOOL</pattern>
<template>School is an important institution in a child's life.</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
<category>
<pattern>SCHOOL</pattern>
<template>School is an important institution in a child's life.</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
0,FACTORY,*,*,Development Center!,srai.aiml
0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml
0,SCHOOL,*,*,School is an important institution in a child's life.,srai.aiml
0,_ SCHOOL,*,*,<srai>SCHOOL</srai>,srai.aiml
0,SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml
0,_ SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: I love going to school daily.
Robot: School is an important institution in a child's life.
Human: I like my school.
Robot: School is an important institution in a child's life.
<random> Tag is used to get random responses. This tag enables AIML to respond differently for the same input. <random> tag is used along with <li> tags. <li> tags carry different responses that are to be delivered to the user on a random basis.
<random>
<li> pattern1 </li>
<li> pattern2 </li>
...
<li> patternN </li>
</random>
For example, consider the following conversation.
Human: Hi
Robot: Hello!
Human: Hi
Robot: Hi! Nice to meet you!
Create random.aiml inside C > ab > bots > test > aiml and random.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding ="UTF-8"?>
<category>
<pattern>HI</pattern>
<template>
<random>
<li> Hello! </li>
<li> Hi! Nice to meet you! </li>
</random>
</template>
<category>
</aiml>
0,HI,*,*, <random><li> Hello! </li><li> Hi! Nice to meet you! </li></random>,random.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Hi
Robot: Hi! Nice to meet you!
Human: Hi
Robot: Hello!
Here, the response may vary considering random responses.
<set> and <get> tags are used to work with variables in AIML. Variables can be predefined variables or programmer created variables.
<set> tag is used to set value in a variable.
<set name = "variable-name"> variable-value </set>
<get> tag is used to get value from a variable.
<get name = "variable-name"></get>
For example, consider the following conversation.
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!
Create setget.aiml inside C > ab > bots > test > aiml and setget.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>I am *</pattern>
<template>
Hello <set name = "username"> <star/>! </set>
</template>
</category>
<category>
<pattern>Good Night</pattern>
<template>
Hi <get name = "username"/> Thanks for the conversation!
</template>
</category>
</aiml>
0,I am *,*,*, Hello <set name = "username"> <star/>! </set>,setget.aiml
0,Good Night,*,*, Hi <get name = "username"/> Thanks for the conversation!,setget.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!
<that> Tag is used in AIML to respond based on the context.
<that> template </that>
For example, consider the following conversation.
Human: Hi Alice! What about movies?
Robot: Do you like comedy movies?
Human: No
Robot: Ok! But I like comedy movies.
Create that.aiml inside C > ab > bots > test > aiml and that.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>WHAT ABOUT MOVIES</pattern>
<template>Do you like comedy movies</template>
</category>
<category>
<pattern>YES</pattern>
<that>Do you like comedy movies</that>
<template>Nice, I like comedy movies too.</template>
</category>
<category>
<pattern>NO</pattern>
<that>Do you like comedy movies</that>
<template>Ok! But I like comedy movies.</template>
</category>
</aiml>
0,WHAT ABOUT MOVIES,*,*,Do you like comedy movies,that.aiml
0,YES,Do you like comedy movies,*,Nice! I like comedy movies too.,that.aiml
0,NO,Do you like comedy movies,*,Ok! But I like comedy movies.,that.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: What about movies?
Robot: Do you like comedy movies?
Human: No
Robot: Ok! But I like comedy movies.
<topic> Tag is used in AIML to store a context so that later conversation can be done based on that context. Usually, <topic> tag is used in Yes/No type conversation. It helps AIML to search categories written within the context of the topic.
Define a topic using <set> tag
<template>
<set name = "topic"> topic-name </set>
</template>
Define the category using <topic> tag
<topic name = "topic-name">
<category>
...
</category>
</topic>
For example, consider the following conversation.
Human: let discuss movies
Robot: Yes movies
Human: Comedy movies are nice to watch
Robot: Watching good movie refreshes our minds.
Human: I like watching comedy
Robot: I too like watching comedy.
Here bot responds taking "movie" as the topic.
Create topic.aiml inside C > ab > bots > test > aiml and topic.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>LET DISCUSS MOVIES</pattern>
<template>Yes <set name = "topic">movies</set></template>
</category>
<topic name = "movies">
<category>
<pattern> * </pattern>
<template>Watching good movie refreshes our minds.</template>
</category>
<category>
<pattern> I LIKE WATCHING COMEDY! </pattern>
<template>I like comedy movies too.</template>
</category>
</topic>
</aiml>
0,LET DISCUSS MOVIES,*,*,Yes <set name = "topic">movies</set>,topic.aiml
0,*,*,movies,Watching good movie refreshes our minds.,topic.aiml
0,I LIKE WATCHING COMEDY!,*,movies,I like comedy movies too.,topic.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: let discuss movies
Robot: Yes movies
Human: Comedy movies are nice to watch
Robot: Watching good movie refreshes our minds.
Human: I like watching comedy
Robot: I too like watching comedy.
<think> Tag is used in AIML to store a variable without notifying the user.
Store a value using <think> tag
<think>
<set name = "variable-name"> variable-value </set>
</think>
For example, consider the following conversation.
Human: My name is Mahesh
Robot: Hello!
Human: Byeee
Robot: Hi Mahesh Thanks for the conversation!
Create think.aiml inside C > ab > bots > test > aiml and think.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>My name is *</pattern>
<template>
Hello!<think><set name = "username"> <star/></set></think>
</template>
</category>
<category>
<pattern>Byeee</pattern>
<template>
Hi <get name = "username"/> Thanks for the conversation!
</template>
</category>
</aiml>
0,My name is *,*,*, Hello! <think><set name = "username"> <star/></set></think>,think.aiml
0,Byeee,*,*, Hi <get name = "username"/> Thanks for the conversation!,think.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: My name is Mahesh
Robot: Hello!
Human: Byeee
Robot: Hi Mahesh Thanks for the conversation!
<condition> Tag is similar to switch statements in programming language. It helps ALICE to respond to the matching input.
<condition name = "variable-name" value = "variable-value"/>
For example, consider the following conversation.
Human: How are you feeling today
Robot: I am happy!
Here we've stored happy as the state of ALICE and that is how it responds as "I am happy!".
Create condition.aiml inside C > ab > bots > test > aiml and condition.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HOW ARE YOU FEELING TODAY </pattern>
<template>
<think><set name = "state"> happy</set></think>
<condition name = "state" value = "happy">
I am happy!
</condition>
<condition name = "state" value = "sad">
I am sad!
</condition>
</template>
</category>
</aiml>
0,HOW ARE YOU FEELING TODAY,*,*,
<think>
<set name = "state"> happy</set>
</think>
<condition name = "state" value = "happy">I am happy!</condition>
<condition name = "state" value = "sad">I am sad!</condition>,condition.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: How are you feeling today
Robot: I am happy!
|
[
{
"code": null,
"e": 2267,
"s": 1945,
"text": "AIML stands for Artificial Intelligence Markup Language. AIML was developed by the Alicebot free software community and Dr. Richard S. Wallace during 1995-2000. AIML is used to create or customize Alicebot which is a chat-box application based on A.L.I.C.E. (Artificial Linguistic Internet Computer Entity) free software."
},
{
"code": null,
"e": 2343,
"s": 2267,
"text": "Following are the important tags which are commonly used in AIML documents."
},
{
"code": null,
"e": 2350,
"s": 2343,
"text": "<aiml>"
},
{
"code": null,
"e": 2401,
"s": 2350,
"text": "Defines the beginning and end of a AIML document."
},
{
"code": null,
"e": 2412,
"s": 2401,
"text": "<category>"
},
{
"code": null,
"e": 2472,
"s": 2412,
"text": "Defines the unit of knowledge in Alicebot's knowledge base."
},
{
"code": null,
"e": 2482,
"s": 2472,
"text": "<pattern>"
},
{
"code": null,
"e": 2549,
"s": 2482,
"text": "Defines the pattern to match what a user may input to an Alicebot."
},
{
"code": null,
"e": 2560,
"s": 2549,
"text": "<template>"
},
{
"code": null,
"e": 2613,
"s": 2560,
"text": "Defines the response of an Alicebot to user's input."
},
{
"code": null,
"e": 2674,
"s": 2613,
"text": "We'll discuss each of these tags in AIML Basic tags chapter."
},
{
"code": null,
"e": 2789,
"s": 2674,
"text": "Following are some of the other widely used aiml tags. We'll be discussing each tag in details in coming chapters."
},
{
"code": null,
"e": 2796,
"s": 2789,
"text": "<star>"
},
{
"code": null,
"e": 2857,
"s": 2796,
"text": "Used to match wild card * character(s) in the <pattern> Tag."
},
{
"code": null,
"e": 2864,
"s": 2857,
"text": "<srai>"
},
{
"code": null,
"e": 2923,
"s": 2864,
"text": "Multipurpose tag, used to call/match the other categories."
},
{
"code": null,
"e": 2932,
"s": 2923,
"text": "<random>"
},
{
"code": null,
"e": 2971,
"s": 2932,
"text": "Used <random> to get random responses."
},
{
"code": null,
"e": 2976,
"s": 2971,
"text": "<li>"
},
{
"code": null,
"e": 3014,
"s": 2976,
"text": "Used to represent multiple responses."
},
{
"code": null,
"e": 3020,
"s": 3014,
"text": "<set>"
},
{
"code": null,
"e": 3059,
"s": 3020,
"text": "Used to set value in an AIML variable."
},
{
"code": null,
"e": 3065,
"s": 3059,
"text": "<get>"
},
{
"code": null,
"e": 3111,
"s": 3065,
"text": "Used to get value stored in an AIML variable."
},
{
"code": null,
"e": 3118,
"s": 3111,
"text": "<that>"
},
{
"code": null,
"e": 3164,
"s": 3118,
"text": "Used in AIML to respond based on the context."
},
{
"code": null,
"e": 3172,
"s": 3164,
"text": "<topic>"
},
{
"code": null,
"e": 3266,
"s": 3172,
"text": "Used in AIML to store a context so that later conversation can be done based on that context."
},
{
"code": null,
"e": 3274,
"s": 3266,
"text": "<think>"
},
{
"code": null,
"e": 3335,
"s": 3274,
"text": "Used in AIML to store a variable without notifying the user."
},
{
"code": null,
"e": 3347,
"s": 3335,
"text": "<condition>"
},
{
"code": null,
"e": 3446,
"s": 3347,
"text": "Similar to switch statements in programming language. It helps ALICE to respond to matching input."
},
{
"code": null,
"e": 3670,
"s": 3446,
"text": "AIML vocabulary uses words, space and two special characters * and _ as wild cards. AIML interpreter gives preference to pattern having _ than pattern having *. AIML tags are XML compliant and patterns are case-insensitive."
},
{
"code": null,
"e": 3861,
"s": 3670,
"text": "<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User!\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 3915,
"s": 3861,
"text": "Following are the important points to be considered −"
},
{
"code": null,
"e": 3964,
"s": 3915,
"text": "<aiml> tag signifies start of the AIML document."
},
{
"code": null,
"e": 4013,
"s": 3964,
"text": "<aiml> tag signifies start of the AIML document."
},
{
"code": null,
"e": 4056,
"s": 4013,
"text": "<category> tag defines the knowledge unit."
},
{
"code": null,
"e": 4099,
"s": 4056,
"text": "<category> tag defines the knowledge unit."
},
{
"code": null,
"e": 4156,
"s": 4099,
"text": "<pattern> tag defines the pattern user is going to type."
},
{
"code": null,
"e": 4213,
"s": 4156,
"text": "<pattern> tag defines the pattern user is going to type."
},
{
"code": null,
"e": 4288,
"s": 4213,
"text": "<template> tag defines the response to the user if user types Hello Alice."
},
{
"code": null,
"e": 4363,
"s": 4288,
"text": "<template> tag defines the response to the user if user types Hello Alice."
},
{
"code": null,
"e": 4398,
"s": 4363,
"text": "User: Hello Alice\nBot: Hello User\n"
},
{
"code": null,
"e": 4731,
"s": 4398,
"text": "This tutorial will guide you on how to prepare a development environment to start your work with AIML to create auto chat software. Program AB is a reference implementation of AIML 2.0 developed and being maintained by ALICE A.I. Foundation. This tutorial will also teach you how to set up JDK, before you setup Program AB library −"
},
{
"code": null,
"e": 5127,
"s": 4731,
"text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively."
},
{
"code": null,
"e": 5266,
"s": 5127,
"text": "If you are running Windows and installed the JDK in C:\\jdk1.7.0_75, you would have to put the following line in your C:\\autoexec.bat file."
},
{
"code": null,
"e": 5335,
"s": 5266,
"text": "set PATH = C:\\jdk1.7.0_75\\bin;%PATH%\nset JAVA_HOME = C:\\jdk1.7.0_75\n"
},
{
"code": null,
"e": 5541,
"s": 5335,
"text": "Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button."
},
{
"code": null,
"e": 5699,
"s": 5541,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C shell, you would put the following into your .cshrc file."
},
{
"code": null,
"e": 5785,
"s": 5699,
"text": "setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.7.0_75\n"
},
{
"code": null,
"e": 6066,
"s": 5785,
"text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE."
},
{
"code": null,
"e": 6224,
"s": 6066,
"text": "Now if everything is fine, then you can proceed to setup your Program AB. Following are the simple steps to download and install the library on your machine."
},
{
"code": null,
"e": 6347,
"s": 6224,
"text": "Make a choice whether you want to install AIML on Windows, or Unix and then proceed to the next step to download .zip file"
},
{
"code": null,
"e": 6470,
"s": 6347,
"text": "Make a choice whether you want to install AIML on Windows, or Unix and then proceed to the next step to download .zip file"
},
{
"code": null,
"e": 6603,
"s": 6470,
"text": "Download the latest version of Program AB binaries from https://code.google.com/p/program-ab/ using its program-ab-0.0.4.3.zip link."
},
{
"code": null,
"e": 6736,
"s": 6603,
"text": "Download the latest version of Program AB binaries from https://code.google.com/p/program-ab/ using its program-ab-0.0.4.3.zip link."
},
{
"code": null,
"e": 6933,
"s": 6736,
"text": "At the time of writing this tutorial, I downloaded program-ab-0.0.4.3.zip on my Windows machine and when you unzip the downloaded file it will give you directory structure inside C:\\ab as follows."
},
{
"code": null,
"e": 7130,
"s": 6933,
"text": "At the time of writing this tutorial, I downloaded program-ab-0.0.4.3.zip on my Windows machine and when you unzip the downloaded file it will give you directory structure inside C:\\ab as follows."
},
{
"code": null,
"e": 7141,
"s": 7130,
"text": "c:/ab/bots"
},
{
"code": null,
"e": 7158,
"s": 7141,
"text": "Stores AIML bots"
},
{
"code": null,
"e": 7168,
"s": 7158,
"text": "c:/ab/lib"
},
{
"code": null,
"e": 7190,
"s": 7168,
"text": "Stores Java libraries"
},
{
"code": null,
"e": 7200,
"s": 7190,
"text": "c:/ab/out"
},
{
"code": null,
"e": 7226,
"s": 7200,
"text": "Java class file directory"
},
{
"code": null,
"e": 7240,
"s": 7226,
"text": "c:/ab/run.bat"
},
{
"code": null,
"e": 7274,
"s": 7240,
"text": "batch file for running Program AB"
},
{
"code": null,
"e": 7407,
"s": 7274,
"text": "Once you are done with this last step, you are ready to proceed with your first AIML Example which you will see in the next chapter."
},
{
"code": null,
"e": 7518,
"s": 7407,
"text": "Let us start creating first bot which will simply greet a user with Hello User! when a user types Hello Alice."
},
{
"code": null,
"e": 7636,
"s": 7518,
"text": "As in AIML Environment Setup, we've extracted content of program-ab in C > ab with the following directory structure."
},
{
"code": null,
"e": 7647,
"s": 7636,
"text": "c:/ab/bots"
},
{
"code": null,
"e": 7664,
"s": 7647,
"text": "Stores AIML bots"
},
{
"code": null,
"e": 7674,
"s": 7664,
"text": "c:/ab/lib"
},
{
"code": null,
"e": 7696,
"s": 7674,
"text": "Stores Java libraries"
},
{
"code": null,
"e": 7706,
"s": 7696,
"text": "c:/ab/out"
},
{
"code": null,
"e": 7732,
"s": 7706,
"text": "Java class file directory"
},
{
"code": null,
"e": 7746,
"s": 7732,
"text": "c:/ab/run.bat"
},
{
"code": null,
"e": 7780,
"s": 7746,
"text": "batch file for running Program AB"
},
{
"code": null,
"e": 7874,
"s": 7780,
"text": "Now, create a directory test inside C > ab > bots and create the following directories in it."
},
{
"code": null,
"e": 7895,
"s": 7874,
"text": "c:/ab/bots/test/aiml"
},
{
"code": null,
"e": 7913,
"s": 7895,
"text": "Stores AIML files"
},
{
"code": null,
"e": 7936,
"s": 7913,
"text": "c:/ab/bots/test/aimlif"
},
{
"code": null,
"e": 7956,
"s": 7936,
"text": "Stores AIMLIF files"
},
{
"code": null,
"e": 7979,
"s": 7956,
"text": "c:/ab/bots/test/config"
},
{
"code": null,
"e": 8006,
"s": 7979,
"text": "Stores configuration files"
},
{
"code": null,
"e": 8027,
"s": 8006,
"text": "c:/ab/bots/test/sets"
},
{
"code": null,
"e": 8044,
"s": 8027,
"text": "Stores AIML Sets"
},
{
"code": null,
"e": 8065,
"s": 8044,
"text": "c:/ab/bots/test/maps"
},
{
"code": null,
"e": 8082,
"s": 8065,
"text": "Stores AIML Maps"
},
{
"code": null,
"e": 8202,
"s": 8082,
"text": "Create test.aiml inside C > ab > bots > test > aiml and test.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 8433,
"s": 8202,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version=\"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 8473,
"s": 8433,
"text": "0,HELLO ALICE,*,*,Hello User,test.aiml\n"
},
{
"code": null,
"e": 8546,
"s": 8473,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 8611,
"s": 8546,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 8645,
"s": 8611,
"text": "You'll see the following output −"
},
{
"code": null,
"e": 9722,
"s": 8645,
"text": "Working Directory = C:\\ab\n\nProgram AB 0.0.4.2 beta -- AI Foundation Reference AIML 2.0 implementation\nbot = test\naction = chat\ntrace = false\ntrace mode = false\nName = test Path = C:\\ab/bots/test\n\nC:\\ab\nC:\\ab/bots\nC:\\ab/bots/test\nC:\\ab/bots/test/aiml\nC:\\ab/bots/test/aimlif\nC:\\ab/bots/test/config\nC:\\ab/bots/test/logs\nC:\\ab/bots/test/sets\nC:\\ab/bots/test/maps\n\nPreprocessor: 0 norms 0 persons 0 person2\nGet Properties: C:\\ab/bots/test/config/properties.txt\naddAIMLSets: C:\\ab/bots/test/sets does not exist.\naddCategories: C:\\ab/bots/test/aiml does not exist.\nAIML modified Tue Apr 07 22:24:29 IST 2015 AIMLIF modified Tue Apr 07 22:26:53 I\nST 2015\nNo deleted.aiml.csv file found\nNo deleted.aiml.csv file found\nLoading AIML files from C:\\ab/bots/test/aimlif\n\nReading Learnf file\nLoaded 1 categories in 0.009 sec\n--> Bot test 1 completed 0 deleted 0 unfinished\n(1[6])--HELLO-->(1[5])--ALICE-->(1[4])--<THAT>-->(1[3])--*-->(1[2])--<TOPIC>-->(\n1[1])--*-->(0[null,null]) Hello User...\n7 nodes 6 singletons 1 leaves 0 shortcuts 0 n-ary 6 branches 0.85714287 average\nbranching\nHuman:\n"
},
{
"code": null,
"e": 9813,
"s": 9722,
"text": "Type Hello Alice and see the result and then type anything else to see the changed result."
},
{
"code": null,
"e": 9903,
"s": 9813,
"text": "Human: hello alice\nRobot: Hello User\nHuman: bye\nRobot: I have no answer for that.\nHuman:\n"
},
{
"code": null,
"e": 9959,
"s": 9903,
"text": "In this tutorial, we'll discuss the basic tags of AIML."
},
{
"code": null,
"e": 10018,
"s": 9959,
"text": "<aiml> − defines the beginning and end of a AIML document."
},
{
"code": null,
"e": 10077,
"s": 10018,
"text": "<aiml> − defines the beginning and end of a AIML document."
},
{
"code": null,
"e": 10150,
"s": 10077,
"text": "<category> − defines the unit of knowledge in Alicebot's knowledge base."
},
{
"code": null,
"e": 10223,
"s": 10150,
"text": "<category> − defines the unit of knowledge in Alicebot's knowledge base."
},
{
"code": null,
"e": 10302,
"s": 10223,
"text": "<pattern> − defines the pattern to match what a user may input to an Alicebot."
},
{
"code": null,
"e": 10381,
"s": 10302,
"text": "<pattern> − defines the pattern to match what a user may input to an Alicebot."
},
{
"code": null,
"e": 10447,
"s": 10381,
"text": "<template> − defines the response of an Alicebot to user's input."
},
{
"code": null,
"e": 10513,
"s": 10447,
"text": "<template> − defines the response of an Alicebot to user's input."
},
{
"code": null,
"e": 10568,
"s": 10513,
"text": "Following AIML files have been used here as reference."
},
{
"code": null,
"e": 10801,
"s": 10568,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 11094,
"s": 10801,
"text": "<aiml> tag marks the start and end of a AIML document. It contains version and encoding information under version and encoding attributes. version attribute stores the AIML version used by ALICE chatterbot Knowledge Base, KB. For example, we've used 1.0.1 version. This attribute is optional."
},
{
"code": null,
"e": 11479,
"s": 11094,
"text": "Encoding attributes provide the character sets to be used in the document. For example, we've used UTF-8. As a mandatory requirement, <aiml> tag must contain at least one <category> tag. We can create multiple AIML files where each AIML file contains a single <aiml> tag. The purpose of each AIML file is to add at least a single knowledge unit called category to ALICE chatterbot KB."
},
{
"code": null,
"e": 11539,
"s": 11479,
"text": "<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n ...\n</aiml>"
},
{
"code": null,
"e": 11630,
"s": 11539,
"text": "<category> tag is the fundamental knowledge unit of an ALICE Bot. Each category contains −"
},
{
"code": null,
"e": 11783,
"s": 11630,
"text": "User input in the form of a sentence which can be an assertion, question, and exclamation etc. User input can contain wild card characters like * and _."
},
{
"code": null,
"e": 11936,
"s": 11783,
"text": "User input in the form of a sentence which can be an assertion, question, and exclamation etc. User input can contain wild card characters like * and _."
},
{
"code": null,
"e": 11988,
"s": 11936,
"text": "Response to user input to be presented by Alicebot."
},
{
"code": null,
"e": 12040,
"s": 11988,
"text": "Response to user input to be presented by Alicebot."
},
{
"code": null,
"e": 12058,
"s": 12040,
"text": "Optional context."
},
{
"code": null,
"e": 12076,
"s": 12058,
"text": "Optional context."
},
{
"code": null,
"e": 12215,
"s": 12076,
"text": "A <category> tag must have <pattern> and <template> tag. <pattern> represents the user input and template represents the bot's response. "
},
{
"code": null,
"e": 12328,
"s": 12215,
"text": "<category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n</category>"
},
{
"code": null,
"e": 12407,
"s": 12328,
"text": "Here, if the user enters Hello Alice then bot will respond back as Hello User."
},
{
"code": null,
"e": 12650,
"s": 12407,
"text": "The <pattern> tag represents a user's input. It should be the first tag within the <category> tag. <pattern> tag can contain wild card to match more than one sentence as user input. For example, in our example, <pattern> contains HELLO ALICE."
},
{
"code": null,
"e": 12803,
"s": 12650,
"text": "AIML is case-insensitive. If a user enters Hello Alice, hello alice, HELLO ALICE etc., all inputs are valid and bot will match them against HELLO ALICE."
},
{
"code": null,
"e": 12916,
"s": 12803,
"text": "<category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n</category>"
},
{
"code": null,
"e": 13000,
"s": 12916,
"text": "Here, the template is \"Hello User\" and represents a robot's response to user input."
},
{
"code": null,
"e": 13229,
"s": 13000,
"text": "<template> tag represents the bot's response to the user. It should be the second tag within the <category> tag. This <template> tag can save data, call another program, give conditional answers or delegate to other categories."
},
{
"code": null,
"e": 13342,
"s": 13229,
"text": "<category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n</category>"
},
{
"code": null,
"e": 13430,
"s": 13342,
"text": "Here, the template is \"Hello User\" and represents a robot's response to the user input."
},
{
"code": null,
"e": 13501,
"s": 13430,
"text": "<star> Tag is used to match wild card * character(s) in <pattern> Tag."
},
{
"code": null,
"e": 13522,
"s": 13501,
"text": "<star index = \"n\"/>\n"
},
{
"code": null,
"e": 13593,
"s": 13522,
"text": "n signifies the position of * within the user input in <pattern> Tag."
},
{
"code": null,
"e": 13626,
"s": 13593,
"text": "Consider the following example −"
},
{
"code": null,
"e": 13785,
"s": 13626,
"text": "<category>\n <pattern> A * is a *. </pattern>\n \n <template>\n When a <star index = \"1\"/> is not a <star index = \"2\"/>?\n </template>\n \n</category>"
},
{
"code": null,
"e": 13882,
"s": 13785,
"text": "If the user enters \"A mango is a fruit.\" then bot will respond as \"When a mango is not a fruit?\""
},
{
"code": null,
"e": 14002,
"s": 13882,
"text": "Create star.aiml inside C > ab > bots > test > aiml and star.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 14404,
"s": 14002,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n \n <category>\n <pattern>I LIKE *</pattern>\n <template>\n I too like <star/>.\n </template>\n </category>\n \n <category>\n <pattern>A * IS A *</pattern>\n <template>\n How <star index = \"1\"/> can not be a <star index = \"2\"/>?\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 14534,
"s": 14404,
"text": "0,I LIKE *,*,*,I too like <star/>.,star.aiml\n0,A * IS A *,*,*,How <star index = \"1\"/> can not be a <star index = \"2\"/>?,star.aiml"
},
{
"code": null,
"e": 14607,
"s": 14534,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 14672,
"s": 14607,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 14708,
"s": 14672,
"text": "You will see the following output −"
},
{
"code": null,
"e": 14818,
"s": 14708,
"text": "Human: I like mango\nRobot: I too like mango.\nHuman: A mango is a fruit\nRobot: How mango can not be a fruit? \n"
},
{
"code": null,
"e": 14864,
"s": 14818,
"text": "<star index = \"1\"/> is often used as <star />"
},
{
"code": null,
"e": 14975,
"s": 14864,
"text": "<srai> Tag is a multipurpose tag. This tag enables AIML to define the different targets for the same template."
},
{
"code": null,
"e": 15000,
"s": 14975,
"text": "<srai> pattern </srai> \n"
},
{
"code": null,
"e": 15061,
"s": 15000,
"text": "Following are the commonly used terms associated with srai −"
},
{
"code": null,
"e": 15080,
"s": 15061,
"text": "Symbolic Reduction"
},
{
"code": null,
"e": 15099,
"s": 15080,
"text": "Symbolic Reduction"
},
{
"code": null,
"e": 15118,
"s": 15099,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 15137,
"s": 15118,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 15157,
"s": 15137,
"text": "Synonyms resolution"
},
{
"code": null,
"e": 15177,
"s": 15157,
"text": "Synonyms resolution"
},
{
"code": null,
"e": 15196,
"s": 15177,
"text": "Keywords detection"
},
{
"code": null,
"e": 15215,
"s": 15196,
"text": "Keywords detection"
},
{
"code": null,
"e": 15350,
"s": 15215,
"text": "The symbolic reduction technique is used to simplify patterns. It helps to reduce complex grammatical patterns with simple pattern(s)."
},
{
"code": null,
"e": 15400,
"s": 15350,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 15572,
"s": 15400,
"text": "Human: Who was Albert Einstein?\nRobot: Albert Einstein was a German physicist.\nHuman: Who was Isaac Newton?\nRobot: Isaac Newton was a English physicist and mathematician.\n"
},
{
"code": null,
"e": 15608,
"s": 15572,
"text": "Now What if questions are raised as"
},
{
"code": null,
"e": 15692,
"s": 15608,
"text": "Human: DO YOU KNOW WHO Albert Einstein IS?\nHuman: DO YOU KNOW WHO Isaac Newton IS?\n"
},
{
"code": null,
"e": 15768,
"s": 15692,
"text": "Here, <srai> tag works. It can take the pattern of the user as a template."
},
{
"code": null,
"e": 16050,
"s": 15768,
"text": "<category>\n <pattern>WHO IS ALBERT EINSTEIN?</pattern>\n <template>Albert Einstein was a German physicist.</template>\n</category>\n\n<category>\n <pattern> WHO IS Isaac NEWTON? </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n</category>"
},
{
"code": null,
"e": 16188,
"s": 16050,
"text": "<category>\n <pattern>DO YOU KNOW WHO * IS?</pattern>\n \n <template>\n <srai>WHO IS <star/></srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 16308,
"s": 16188,
"text": "Create srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 16864,
"s": 16308,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n</aiml>"
},
{
"code": null,
"e": 17100,
"s": 16864,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml"
},
{
"code": null,
"e": 17173,
"s": 17100,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 17238,
"s": 17173,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 17274,
"s": 17238,
"text": "You will see the following output −"
},
{
"code": null,
"e": 17364,
"s": 17274,
"text": "Human: Do you know who Albert Einstein is\nRobot: Albert Einstein was a German physicist.\n"
},
{
"code": null,
"e": 17491,
"s": 17364,
"text": "Divide and Conquer is used to reuse sub sentences in making a complete reply. It helps to reduce defining multiple categories."
},
{
"code": null,
"e": 17537,
"s": 17491,
"text": "For example, consider following conversation."
},
{
"code": null,
"e": 17598,
"s": 17537,
"text": "Human: Bye\nRobot: GoodBye!\nHuman: Bye Alice!\nRobot: GoodBye!"
},
{
"code": null,
"e": 17702,
"s": 17598,
"text": "Now here robot is expected to reply GoodBye! Whenever a user says Bye in the beginning of the sentence."
},
{
"code": null,
"e": 17737,
"s": 17702,
"text": "Let's put <srai> tag to work here."
},
{
"code": null,
"e": 17820,
"s": 17737,
"text": "<category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n</category>"
},
{
"code": null,
"e": 17931,
"s": 17820,
"text": "<category>\n <pattern>BYE *</pattern>\n \n <template>\n <srai>BYE</srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 18051,
"s": 17931,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 18833,
"s": 18051,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 19138,
"s": 18833,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml"
},
{
"code": null,
"e": 19211,
"s": 19138,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 19276,
"s": 19211,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 19312,
"s": 19276,
"text": "You will see the following output −"
},
{
"code": null,
"e": 19374,
"s": 19312,
"text": "Human: Bye\nRobot: GoodBye!\nHuman: Bye Alice!\nRobot: GoodBye!\n"
},
{
"code": null,
"e": 19473,
"s": 19374,
"text": "Synonyms are words with similar meanings. A bot should reply in the same manner for similar words."
},
{
"code": null,
"e": 19523,
"s": 19473,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 19609,
"s": 19523,
"text": "Human: Factory\nRobot: Development Center!\nHuman: Industry\nRobot: Development Center!\n"
},
{
"code": null,
"e": 19707,
"s": 19609,
"text": "Now here robot is expected to reply Development Center! whenever a user says Factory or Industry."
},
{
"code": null,
"e": 19742,
"s": 19707,
"text": "Let's put <srai> tag to work here."
},
{
"code": null,
"e": 19839,
"s": 19742,
"text": "<category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n</category>"
},
{
"code": null,
"e": 19957,
"s": 19839,
"text": "<category>\n <pattern>INDUSTRY</pattern>\n \n <template>\n <srai>FACTORY</srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 20077,
"s": 19957,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 21106,
"s": 20077,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n <category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n </category>\n \n <category>\n <pattern>INDUSTRY</pattern>\n <template>\n <srai>FACTORY</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 21501,
"s": 21106,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml\n0,FACTORY,*,*,Development Center!,srai.aiml\n0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml"
},
{
"code": null,
"e": 21574,
"s": 21501,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 21639,
"s": 21574,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 21675,
"s": 21639,
"text": "You will see the following output −"
},
{
"code": null,
"e": 21761,
"s": 21675,
"text": "Human: Factory\nRobot: Development Center!\nHuman: Industry\nRobot: Development Center!\n"
},
{
"code": null,
"e": 21911,
"s": 21761,
"text": "Using srai, we can return a simple response when the user types a specific keyword, say, School, no matter where \"school\" is present in the sentence."
},
{
"code": null,
"e": 21961,
"s": 21911,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 22146,
"s": 21961,
"text": "Human: I love going to school daily.\nRobot: School is an important institution in a child's life.\nHuman: I like my school.\nRobot: School is an important institution in a child's life.\n"
},
{
"code": null,
"e": 22302,
"s": 22146,
"text": "Here, the robot is expected to reply a standard message 'School is an important institution in a child's life.' whenever a user has school in the sentence."
},
{
"code": null,
"e": 22364,
"s": 22302,
"text": "Let's put <srai> tag to work here. We'll use wild-cards here."
},
{
"code": null,
"e": 22494,
"s": 22364,
"text": "<category>\n <pattern>SCHOOL</pattern>\n <template>School is an important institution in a child's life.</template>\n</category>"
},
{
"code": null,
"e": 22935,
"s": 22494,
"text": "<category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>_ SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>"
},
{
"code": null,
"e": 23055,
"s": 22935,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 24758,
"s": 23055,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n <category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n </category>\n \n <category>\n <pattern>INDUSTRY</pattern>\n <template>\n <srai>FACTORY</srai>\n </template>\n </category>\n \n <category>\n <pattern>SCHOOL</pattern>\n <template>School is an important institution in a child's life.</template>\n </category> \n \n <category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>_ SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 25367,
"s": 24758,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml\n0,FACTORY,*,*,Development Center!,srai.aiml\n0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml\n0,SCHOOL,*,*,School is an important institution in a child's life.,srai.aiml\n0,_ SCHOOL,*,*,<srai>SCHOOL</srai>,srai.aiml\n0,SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml\n0,_ SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml"
},
{
"code": null,
"e": 25440,
"s": 25367,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 25505,
"s": 25440,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 25541,
"s": 25505,
"text": "You will see the following output −"
},
{
"code": null,
"e": 25726,
"s": 25541,
"text": "Human: I love going to school daily.\nRobot: School is an important institution in a child's life.\nHuman: I like my school.\nRobot: School is an important institution in a child's life.\n"
},
{
"code": null,
"e": 25972,
"s": 25726,
"text": "<random> Tag is used to get random responses. This tag enables AIML to respond differently for the same input. <random> tag is used along with <li> tags. <li> tags carry different responses that are to be delivered to the user on a random basis."
},
{
"code": null,
"e": 26067,
"s": 25972,
"text": "<random>\n <li> pattern1 </li>\n <li> pattern2 </li>\n ...\n <li> patternN </li>\n</random>"
},
{
"code": null,
"e": 26117,
"s": 26067,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 26181,
"s": 26117,
"text": "Human: Hi\nRobot: Hello!\nHuman: Hi\nRobot: Hi! Nice to meet you!\n"
},
{
"code": null,
"e": 26305,
"s": 26181,
"text": "Create random.aiml inside C > ab > bots > test > aiml and random.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 26623,
"s": 26305,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding =\"UTF-8\"?>\n <category>\n <pattern>HI</pattern>\n \n <template>\n <random>\n <li> Hello! </li>\n <li> Hi! Nice to meet you! </li>\n </random>\n </template>\n \n <category> \n</aiml>"
},
{
"code": null,
"e": 26712,
"s": 26623,
"text": "0,HI,*,*, <random><li> Hello! </li><li> Hi! Nice to meet you! </li></random>,random.aiml"
},
{
"code": null,
"e": 26785,
"s": 26712,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 26850,
"s": 26785,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 26886,
"s": 26850,
"text": "You will see the following output −"
},
{
"code": null,
"e": 26950,
"s": 26886,
"text": "Human: Hi\nRobot: Hi! Nice to meet you!\nHuman: Hi\nRobot: Hello!\n"
},
{
"code": null,
"e": 27008,
"s": 26950,
"text": "Here, the response may vary considering random responses."
},
{
"code": null,
"e": 27141,
"s": 27008,
"text": "<set> and <get> tags are used to work with variables in AIML. Variables can be predefined variables or programmer created variables."
},
{
"code": null,
"e": 27187,
"s": 27141,
"text": "<set> tag is used to set value in a variable."
},
{
"code": null,
"e": 27239,
"s": 27187,
"text": "<set name = \"variable-name\"> variable-value </set>\n"
},
{
"code": null,
"e": 27287,
"s": 27239,
"text": "<get> tag is used to get value from a variable."
},
{
"code": null,
"e": 27323,
"s": 27287,
"text": "<get name = \"variable-name\"></get>\n"
},
{
"code": null,
"e": 27373,
"s": 27323,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 27487,
"s": 27373,
"text": "Human: I am Mahesh\nRobot: Hello Mahesh!\nHuman: Good Night\nRobot: Good Night Mahesh! Thanks for the conversation!\n"
},
{
"code": null,
"e": 27611,
"s": 27487,
"text": "Create setget.aiml inside C > ab > bots > test > aiml and setget.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 28040,
"s": 27611,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>I am *</pattern>\n <template>\n Hello <set name = \"username\"> <star/>! </set>\n </template> \n </category> \n \n <category>\n <pattern>Good Night</pattern>\n <template>\n Hi <get name = \"username\"/> Thanks for the conversation!\n </template> \n </category> \n \n</aiml>"
},
{
"code": null,
"e": 28199,
"s": 28040,
"text": "0,I am *,*,*, Hello <set name = \"username\"> <star/>! </set>,setget.aiml\n0,Good Night,*,*, Hi <get name = \"username\"/> Thanks for the conversation!,setget.aiml"
},
{
"code": null,
"e": 28272,
"s": 28199,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 28337,
"s": 28272,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 28373,
"s": 28337,
"text": "You will see the following output −"
},
{
"code": null,
"e": 28487,
"s": 28373,
"text": "Human: I am Mahesh\nRobot: Hello Mahesh!\nHuman: Good Night\nRobot: Good Night Mahesh! Thanks for the conversation!\n"
},
{
"code": null,
"e": 28548,
"s": 28487,
"text": "<that> Tag is used in AIML to respond based on the context. "
},
{
"code": null,
"e": 28573,
"s": 28548,
"text": "<that> template </that>\n"
},
{
"code": null,
"e": 28623,
"s": 28573,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 28741,
"s": 28623,
"text": "Human: Hi Alice! What about movies?\nRobot: Do you like comedy movies?\nHuman: No\nRobot: Ok! But I like comedy movies.\n"
},
{
"code": null,
"e": 28861,
"s": 28741,
"text": "Create that.aiml inside C > ab > bots > test > aiml and that.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 29418,
"s": 28861,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>WHAT ABOUT MOVIES</pattern>\n <template>Do you like comedy movies</template> \n </category>\n \n <category>\n <pattern>YES</pattern>\n <that>Do you like comedy movies</that>\n <template>Nice, I like comedy movies too.</template>\n </category>\n \n <category>\n <pattern>NO</pattern>\n <that>Do you like comedy movies</that>\n <template>Ok! But I like comedy movies.</template>\n </category> \n \n</aiml>"
},
{
"code": null,
"e": 29628,
"s": 29418,
"text": "0,WHAT ABOUT MOVIES,*,*,Do you like comedy movies,that.aiml\n0,YES,Do you like comedy movies,*,Nice! I like comedy movies too.,that.aiml\n0,NO,Do you like comedy movies,*,Ok! But I like comedy movies.,that.aiml\n"
},
{
"code": null,
"e": 29701,
"s": 29628,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 29766,
"s": 29701,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 29802,
"s": 29766,
"text": "You will see the following output −"
},
{
"code": null,
"e": 29910,
"s": 29802,
"text": "Human: What about movies?\nRobot: Do you like comedy movies?\nHuman: No\nRobot: Ok! But I like comedy movies.\n"
},
{
"code": null,
"e": 30154,
"s": 29910,
"text": "<topic> Tag is used in AIML to store a context so that later conversation can be done based on that context. Usually, <topic> tag is used in Yes/No type conversation. It helps AIML to search categories written within the context of the topic. "
},
{
"code": null,
"e": 30185,
"s": 30154,
"text": "Define a topic using <set> tag"
},
{
"code": null,
"e": 30252,
"s": 30185,
"text": "<template> \n <set name = \"topic\"> topic-name </set>\n</template>\n"
},
{
"code": null,
"e": 30290,
"s": 30252,
"text": "Define the category using <topic> tag"
},
{
"code": null,
"e": 30371,
"s": 30290,
"text": "<topic name = \"topic-name\">\n <category>\n ...\n </category> \n</topic>"
},
{
"code": null,
"e": 30421,
"s": 30371,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 30618,
"s": 30421,
"text": "Human: let discuss movies\nRobot: Yes movies\nHuman: Comedy movies are nice to watch\nRobot: Watching good movie refreshes our minds.\nHuman: I like watching comedy\nRobot: I too like watching comedy.\n"
},
{
"code": null,
"e": 30665,
"s": 30618,
"text": "Here bot responds taking \"movie\" as the topic."
},
{
"code": null,
"e": 30787,
"s": 30665,
"text": "Create topic.aiml inside C > ab > bots > test > aiml and topic.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 31362,
"s": 30787,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>LET DISCUSS MOVIES</pattern>\n <template>Yes <set name = \"topic\">movies</set></template> \n </category>\n \n <topic name = \"movies\">\n <category>\n <pattern> * </pattern>\n <template>Watching good movie refreshes our minds.</template>\n </category>\n \n <category>\n <pattern> I LIKE WATCHING COMEDY! </pattern>\n <template>I like comedy movies too.</template>\n </category>\n \n </topic>\n</aiml>"
},
{
"code": null,
"e": 31572,
"s": 31362,
"text": "0,LET DISCUSS MOVIES,*,*,Yes <set name = \"topic\">movies</set>,topic.aiml\n0,*,*,movies,Watching good movie refreshes our minds.,topic.aiml\n0,I LIKE WATCHING COMEDY!,*,movies,I like comedy movies too.,topic.aiml"
},
{
"code": null,
"e": 31645,
"s": 31572,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 31710,
"s": 31645,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 31746,
"s": 31710,
"text": "You will see the following output −"
},
{
"code": null,
"e": 31943,
"s": 31746,
"text": "Human: let discuss movies\nRobot: Yes movies\nHuman: Comedy movies are nice to watch\nRobot: Watching good movie refreshes our minds.\nHuman: I like watching comedy\nRobot: I too like watching comedy.\n"
},
{
"code": null,
"e": 32019,
"s": 31943,
"text": "<think> Tag is used in AIML to store a variable without notifying the user."
},
{
"code": null,
"e": 32051,
"s": 32019,
"text": "Store a value using <think> tag"
},
{
"code": null,
"e": 32124,
"s": 32051,
"text": "<think> \n <set name = \"variable-name\"> variable-value </set>\n</think>\n"
},
{
"code": null,
"e": 32174,
"s": 32124,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 32273,
"s": 32174,
"text": "Human: My name is Mahesh\nRobot: Hello!\nHuman: Byeee\nRobot: Hi Mahesh Thanks for the conversation!\n"
},
{
"code": null,
"e": 32395,
"s": 32273,
"text": "Create think.aiml inside C > ab > bots > test > aiml and think.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 32838,
"s": 32395,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>My name is *</pattern>\n <template>\n Hello!<think><set name = \"username\"> <star/></set></think>\n </template> \n </category> \n \n <category>\n <pattern>Byeee</pattern>\n <template>\n Hi <get name = \"username\"/> Thanks for the conversation!\n </template> \n </category> \n \n</aiml>"
},
{
"code": null,
"e": 33010,
"s": 32838,
"text": "0,My name is *,*,*, Hello! <think><set name = \"username\"> <star/></set></think>,think.aiml\n0,Byeee,*,*, Hi <get name = \"username\"/> Thanks for the conversation!,think.aiml"
},
{
"code": null,
"e": 33083,
"s": 33010,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 33148,
"s": 33083,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 33184,
"s": 33148,
"text": "You will see the following output −"
},
{
"code": null,
"e": 33283,
"s": 33184,
"text": "Human: My name is Mahesh\nRobot: Hello!\nHuman: Byeee\nRobot: Hi Mahesh Thanks for the conversation!\n"
},
{
"code": null,
"e": 33406,
"s": 33283,
"text": "<condition> Tag is similar to switch statements in programming language. It helps ALICE to respond to the matching input. "
},
{
"code": null,
"e": 33468,
"s": 33406,
"text": "<condition name = \"variable-name\" value = \"variable-value\"/>\n"
},
{
"code": null,
"e": 33518,
"s": 33468,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 33571,
"s": 33518,
"text": "Human: How are you feeling today\nRobot: I am happy!\n"
},
{
"code": null,
"e": 33663,
"s": 33571,
"text": "Here we've stored happy as the state of ALICE and that is how it responds as \"I am happy!\"."
},
{
"code": null,
"e": 33793,
"s": 33663,
"text": "Create condition.aiml inside C > ab > bots > test > aiml and condition.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 34279,
"s": 33793,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HOW ARE YOU FEELING TODAY </pattern>\n \n <template>\n <think><set name = \"state\"> happy</set></think>\n <condition name = \"state\" value = \"happy\">\n I am happy!\n </condition>\n \n <condition name = \"state\" value = \"sad\">\n I am sad!\n </condition>\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 34527,
"s": 34279,
"text": "0,HOW ARE YOU FEELING TODAY,*,*,\n <think>\n <set name = \"state\"> happy</set>\n </think>\n \n <condition name = \"state\" value = \"happy\">I am happy!</condition>\n <condition name = \"state\" value = \"sad\">I am sad!</condition>,condition.aiml"
},
{
"code": null,
"e": 34600,
"s": 34527,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 34665,
"s": 34600,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 34701,
"s": 34665,
"text": "You will see the following output −"
}
] |
Non-blocking I/O with pipes in C
|
01 Oct, 2021
Prerequisite: pipe() System callWhen I/O block in pipe() happens? Consider two processes, one process that’s gathering data(read data) in real time and another process that’s plotting it(write data). The two processes are connected by a pipe, with the data acquisition process feeding the data plotting process. Speed of the data acquisition of two process is different. The default behavior in a pipe is for the writing and reading ends of a pipe is to exhibit blocking behavior, if the partner process is slower. This is bad because the data acquisition process can wait on the plotting process(write data). So, during the data acquisition process, block read call in pipe and program hangs. If we want this not to happen, we must close the write end in process before read end call. In simple language,
A read call gets as much data as it requests or as much data as the pipe has, whichever is less
If the pipe is empty Reads on the pipe will return EOF (return value 0) if no process has the write end openIf some process has the pipe open for writing, read will block in anticipation of new data
Reads on the pipe will return EOF (return value 0) if no process has the write end open
If some process has the pipe open for writing, read will block in anticipation of new data
Non-blocking I/O with pipes
Sometimes it’s convenient to have I/O that doesn’t block i.e we don’t want a read call to block on one in case of input from the other. Solution for this is the given function:
To specify non-blocking option:
#include<fcntl.h>
int fd;
fcntl(fd, F_SETFL, O_NONBLOCK);
fd: file descriptor
F_SETFL: Set the file status flags to the value specified by arg. File access mode here in our purpose use only for O_NONBLOCK flag.
O_NONBLOCK: use for non-blocking option.
0: return on successful
-1: return on error, set errorno
After this function runs successfully, a call to read/write returns -1 if pipe is empty/full and sets errno to EAGAINExample: Child writes “hello” to parent every 3 seconds and Parent does a non-blocking read each second.
C
// C program to illustrate// non I/O blocking calls#include <stdio.h>#include <unistd.h>#include <fcntl.h> // library for fcntl function#define MSGSIZE 6char* msg1 =“hello”;char* msg2 =“bye !!”; int main(){ int p[2], i; // error checking for pipe if (pipe(p) < 0) exit(1); // error checking for fcntl if (fcntl(p[0], F_SETFL, O_NONBLOCK) < 0) exit(2); // continued switch (fork()) { // error case -1: exit(3); // 0 for child process case 0: child_write(p); break; default: parent_read(p); break; } return 0;}void parent_read(int p[]){ int nread; char buf[MSGSIZE]; // write link close(p[1]); while (1) { // read call if return -1 then pipe is // empty because of fcntl nread = read(p[0], buf, MSGSIZE); switch (nread) { case -1: // case -1 means pipe is empty and errono // set EAGAIN if (errno == EAGAIN) { printf(“(pipe empty)\n”); sleep(1); break; } else { perror(“read”); exit(4); } // case 0 means all bytes are read and EOF(end of conv.) case 0: printf(“End of conversation\n”); // read link close(p[0]); exit(0); default: // text read // by default return no. of bytes // which read call read at that time printf(“MSG = % s\n”, buf); } }}void child_write(int p[]){ int i; // read link close(p[0]); // write 3 times "hello" in 3 second interval for (i = 0; i < 3; i++) { write(p[1], msg1, MSGSIZE); sleep(3); } // write "bye" one times write(p[1], msg2, MSGSIZE); // here after write all bytes then write end // doesn't close so read end block but // because of fcntl block doesn't happen.. exit(0);}
Output:
(pipe empty)
MSG=hello
(pipe empty)
(pipe empty)
(pipe empty)
MSG=hello
(pipe empty)
(pipe empty)
(pipe empty)
MSG=hello
(pipe empty)
(pipe empty)
(pipe empty)
MSG=bye!!
End of conversation
Atomic writes in pipe
Atomic means no other process ever observes that its partially done. Reading or writing pipe data is atomic if the size of data written is not greater than PIPE_BUF(4096 bytes). This means that the data transfer seems to be an instantaneous unit means nothing else in the system can observe a state in which it is partially complete. Atomic I/O may not begin right away (it may need to wait for buffer space or for data), but once it does begin it finishes immediately.Data Writes of up to PIPE_BUF (4096 Bytes) are atomic. Reading or writing a larger amount of data may not be atomic; For example, output data from other processes sharing the descriptor may be interspersed. Also, once PIPE_BUF characters have been written, further writes will block until some characters are readExample: Process 1 sends a 100-byte message at the same time, process 2 sends a 100-byte message No guarantee about the order, but pipe will receive all of one message followed by all of the other.In non atomic writes for larger writes there is no such guarantee, data could get confusingly intermingled like, this:
Pipe Capacity
A pipe can hold a limited number of bytes.
Writes fill the pipe and block when the pipe is full They block until another process reads enough data at the other end of the pipe and return when all the data given to write have been transmitted
They block until another process reads enough data at the other end of the pipe and return when all the data given to write have been transmitted
Capacity of a pipe is at least 512 bytes, usually more (system dependent)
C
// C program to illustrate// finding capacity of pipe#include <stdio.h>#include <unistd.h>#include <signal.h>int count = 0; // SIGALRM signal handlervoid alrm_action(int signo){ printf("Write blocked after %d characters\n", count); exit(0);}int main(){ int p[2]; char c = 'x'; // SIGALRM signal signal(SIGALRM, alrm_action); // pipe error check if (pipe(p) == -1) exit(1); while (1) { alarm(5); // write 'x' at one time when capacity full // write() block and after 5 second alarm write(p[1], &c, 1); // send signal and alrm_action handler execute. ++count; alarm(0); }}
Output:
Write blocked after 65536 characters
//output depend on the system so output may change in different system
Here, in while loop first 5 second alarm is set after write() call writes one character ‘x’ in the pipe. And count variable is used for count character write in the pipe. strong>alarm(0) means cancel the set alarm of 5 second. After some time when pipe capacity is full then write() call is block and program does not execute next instruction, after 5 second set alarm ringing and send signal SIGALRM. After that alram_action handler executes and prints how many maximum character can be written by pipe. This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surindertarika1234
system-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
What is the purpose of a function prototype?
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
Ways to copy a vector in C++
'this' pointer in C++
Storage Classes in C
Arrow operator -> in C/C++ with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 862,
"s": 54,
"text": "Prerequisite: pipe() System callWhen I/O block in pipe() happens? Consider two processes, one process that’s gathering data(read data) in real time and another process that’s plotting it(write data). The two processes are connected by a pipe, with the data acquisition process feeding the data plotting process. Speed of the data acquisition of two process is different. The default behavior in a pipe is for the writing and reading ends of a pipe is to exhibit blocking behavior, if the partner process is slower. This is bad because the data acquisition process can wait on the plotting process(write data). So, during the data acquisition process, block read call in pipe and program hangs. If we want this not to happen, we must close the write end in process before read end call. In simple language, "
},
{
"code": null,
"e": 958,
"s": 862,
"text": "A read call gets as much data as it requests or as much data as the pipe has, whichever is less"
},
{
"code": null,
"e": 1157,
"s": 958,
"text": "If the pipe is empty Reads on the pipe will return EOF (return value 0) if no process has the write end openIf some process has the pipe open for writing, read will block in anticipation of new data"
},
{
"code": null,
"e": 1245,
"s": 1157,
"text": "Reads on the pipe will return EOF (return value 0) if no process has the write end open"
},
{
"code": null,
"e": 1336,
"s": 1245,
"text": "If some process has the pipe open for writing, read will block in anticipation of new data"
},
{
"code": null,
"e": 1364,
"s": 1336,
"text": "Non-blocking I/O with pipes"
},
{
"code": null,
"e": 1542,
"s": 1364,
"text": "Sometimes it’s convenient to have I/O that doesn’t block i.e we don’t want a read call to block on one in case of input from the other. Solution for this is the given function: "
},
{
"code": null,
"e": 1658,
"s": 1542,
"text": " To specify non-blocking option:\n #include<fcntl.h> \n int fd; \n fcntl(fd, F_SETFL, O_NONBLOCK); "
},
{
"code": null,
"e": 1678,
"s": 1658,
"text": "fd: file descriptor"
},
{
"code": null,
"e": 1811,
"s": 1678,
"text": "F_SETFL: Set the file status flags to the value specified by arg. File access mode here in our purpose use only for O_NONBLOCK flag."
},
{
"code": null,
"e": 1852,
"s": 1811,
"text": "O_NONBLOCK: use for non-blocking option."
},
{
"code": null,
"e": 1876,
"s": 1852,
"text": "0: return on successful"
},
{
"code": null,
"e": 1909,
"s": 1876,
"text": "-1: return on error, set errorno"
},
{
"code": null,
"e": 2132,
"s": 1909,
"text": "After this function runs successfully, a call to read/write returns -1 if pipe is empty/full and sets errno to EAGAINExample: Child writes “hello” to parent every 3 seconds and Parent does a non-blocking read each second. "
},
{
"code": null,
"e": 2136,
"s": 2134,
"text": "C"
},
{
"code": "// C program to illustrate// non I/O blocking calls#include <stdio.h>#include <unistd.h>#include <fcntl.h> // library for fcntl function#define MSGSIZE 6char* msg1 =“hello”;char* msg2 =“bye !!”; int main(){ int p[2], i; // error checking for pipe if (pipe(p) < 0) exit(1); // error checking for fcntl if (fcntl(p[0], F_SETFL, O_NONBLOCK) < 0) exit(2); // continued switch (fork()) { // error case -1: exit(3); // 0 for child process case 0: child_write(p); break; default: parent_read(p); break; } return 0;}void parent_read(int p[]){ int nread; char buf[MSGSIZE]; // write link close(p[1]); while (1) { // read call if return -1 then pipe is // empty because of fcntl nread = read(p[0], buf, MSGSIZE); switch (nread) { case -1: // case -1 means pipe is empty and errono // set EAGAIN if (errno == EAGAIN) { printf(“(pipe empty)\\n”); sleep(1); break; } else { perror(“read”); exit(4); } // case 0 means all bytes are read and EOF(end of conv.) case 0: printf(“End of conversation\\n”); // read link close(p[0]); exit(0); default: // text read // by default return no. of bytes // which read call read at that time printf(“MSG = % s\\n”, buf); } }}void child_write(int p[]){ int i; // read link close(p[0]); // write 3 times \"hello\" in 3 second interval for (i = 0; i < 3; i++) { write(p[1], msg1, MSGSIZE); sleep(3); } // write \"bye\" one times write(p[1], msg2, MSGSIZE); // here after write all bytes then write end // doesn't close so read end block but // because of fcntl block doesn't happen.. exit(0);}",
"e": 4113,
"s": 2136,
"text": null
},
{
"code": null,
"e": 4122,
"s": 4113,
"text": "Output: "
},
{
"code": null,
"e": 4312,
"s": 4122,
"text": "(pipe empty)\nMSG=hello\n(pipe empty)\n(pipe empty)\n(pipe empty)\nMSG=hello\n(pipe empty)\n(pipe empty)\n(pipe empty)\nMSG=hello\n(pipe empty)\n(pipe empty)\n(pipe empty)\nMSG=bye!!\nEnd of conversation"
},
{
"code": null,
"e": 4336,
"s": 4314,
"text": "Atomic writes in pipe"
},
{
"code": null,
"e": 5436,
"s": 4336,
"text": "Atomic means no other process ever observes that its partially done. Reading or writing pipe data is atomic if the size of data written is not greater than PIPE_BUF(4096 bytes). This means that the data transfer seems to be an instantaneous unit means nothing else in the system can observe a state in which it is partially complete. Atomic I/O may not begin right away (it may need to wait for buffer space or for data), but once it does begin it finishes immediately.Data Writes of up to PIPE_BUF (4096 Bytes) are atomic. Reading or writing a larger amount of data may not be atomic; For example, output data from other processes sharing the descriptor may be interspersed. Also, once PIPE_BUF characters have been written, further writes will block until some characters are readExample: Process 1 sends a 100-byte message at the same time, process 2 sends a 100-byte message No guarantee about the order, but pipe will receive all of one message followed by all of the other.In non atomic writes for larger writes there is no such guarantee, data could get confusingly intermingled like, this: "
},
{
"code": null,
"e": 5450,
"s": 5436,
"text": "Pipe Capacity"
},
{
"code": null,
"e": 5493,
"s": 5450,
"text": "A pipe can hold a limited number of bytes."
},
{
"code": null,
"e": 5692,
"s": 5493,
"text": "Writes fill the pipe and block when the pipe is full They block until another process reads enough data at the other end of the pipe and return when all the data given to write have been transmitted"
},
{
"code": null,
"e": 5838,
"s": 5692,
"text": "They block until another process reads enough data at the other end of the pipe and return when all the data given to write have been transmitted"
},
{
"code": null,
"e": 5912,
"s": 5838,
"text": "Capacity of a pipe is at least 512 bytes, usually more (system dependent)"
},
{
"code": null,
"e": 5914,
"s": 5912,
"text": "C"
},
{
"code": "// C program to illustrate// finding capacity of pipe#include <stdio.h>#include <unistd.h>#include <signal.h>int count = 0; // SIGALRM signal handlervoid alrm_action(int signo){ printf(\"Write blocked after %d characters\\n\", count); exit(0);}int main(){ int p[2]; char c = 'x'; // SIGALRM signal signal(SIGALRM, alrm_action); // pipe error check if (pipe(p) == -1) exit(1); while (1) { alarm(5); // write 'x' at one time when capacity full // write() block and after 5 second alarm write(p[1], &c, 1); // send signal and alrm_action handler execute. ++count; alarm(0); }}",
"e": 6576,
"s": 5914,
"text": null
},
{
"code": null,
"e": 6585,
"s": 6576,
"text": "Output: "
},
{
"code": null,
"e": 6694,
"s": 6585,
"text": "Write blocked after 65536 characters \n//output depend on the system so output may change in different system"
},
{
"code": null,
"e": 7619,
"s": 6694,
"text": "Here, in while loop first 5 second alarm is set after write() call writes one character ‘x’ in the pipe. And count variable is used for count character write in the pipe. strong>alarm(0) means cancel the set alarm of 5 second. After some time when pipe capacity is full then write() call is block and program does not execute next instruction, after 5 second set alarm ringing and send signal SIGALRM. After that alram_action handler executes and prints how many maximum character can be written by pipe. This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7638,
"s": 7619,
"text": "surindertarika1234"
},
{
"code": null,
"e": 7657,
"s": 7638,
"text": "system-programming"
},
{
"code": null,
"e": 7668,
"s": 7657,
"text": "C Language"
},
{
"code": null,
"e": 7766,
"s": 7668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7814,
"s": 7766,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 7835,
"s": 7814,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7880,
"s": 7835,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 7906,
"s": 7880,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 7944,
"s": 7906,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 7986,
"s": 7944,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 8015,
"s": 7986,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 8037,
"s": 8015,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 8058,
"s": 8037,
"text": "Storage Classes in C"
}
] |
Minimum increment/decrement operations required to make Median as X
|
23 Apr, 2021
Given an array A[] of n odd integers and an integer X. Calculate the minimum number of operations required to make the median of the array equal to X, where, in one operation we can either increase or decrease any single element by one.
Examples:
Input: A[] = {6, 5, 8}, X = 8 Output: 2 Explanation: Here 6 can be increased twice. The array will become 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8.
Input: A[] = {1, 4, 7, 12, 3, 5, 9}, X = 5 Output: 0 Explanation: After sorting 5 is in middle position hence 0 steps are required.
Approach: The idea for changing the median of the array will be to sort the given array. Then after sorting, the best possible candidate for making the median is the middle element because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to determine the// Minimum numbers of steps to make// median of an array equal X #include <bits/stdc++.h>using namespace std; // Function to count minimum// required operations to// make median Xint count(vector<int> a, int X){ // Sorting the array a[] sort(a.begin(), a.end()); int ans = 0; // Calculate the size of array int n = a.size(); // Iterate over the array for (int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += abs(X - a[i]); // For all elements // greater than median else ans += max(0, X - a[i]); } // Return the answer return ans;} // Driver codeint main(){ vector<int> a = { 6, 5, 8 }; int X = 8; cout << count(a, X) << "\n"; return 0;}
// Java implementation to determine the// Minimum numbers of steps to make// median of an array equal Ximport java.util.*; class GFG{ // Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){ // Sorting the array a[] Arrays.sort(a); int ans = 0; // Calculate the size of array int n = a.length; // Iterate over the array for(int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += Math.max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += Math.abs(X - a[i]); // For all elements // greater than median else ans += Math.max(0, X - a[i]); } // Return the answer return ans;} // Driver codepublic static void main(String[] args){ int []a = { 6, 5, 8 }; int X = 8; System.out.print(count(a, X) + "\n");}} // This code is contributed by Amit Katiyar
# Python3 implementation to determine the# Minimum numbers of steps to make# median of an array equal X # Function to count minimum# required operations to# make median Xdef count(a, X): # Sorting the array a[] a.sort() ans = 0 # Calculate the size of array n = len(a) # Iterate over the array for i in range(n): # For all elements # less than median if (i < n // 2): ans += max(0, a[i] - X) # For element equal # to median elif (i == n // 2): ans += abs(X - a[i]) # For all elements # greater than median else: ans += max(0, X - a[i]); # Return the answer return ans # Driver codea = [ 6, 5, 8 ]X = 8 print(count(a, X)) # This code is contributed by divyeshrabadiya07
// C# implementation to determine the// Minimum numbers of steps to make// median of an array equal Xusing System; class GFG{ // Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){ // Sorting the array []a Array.Sort(a); int ans = 0; // Calculate the size of array int n = a.Length; // Iterate over the array for(int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += Math.Max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += Math.Abs(X - a[i]); // For all elements // greater than median else ans += Math.Max(0, X - a[i]); } // Return the answer return ans;} // Driver codepublic static void Main(String[] args){ int []a = { 6, 5, 8 }; int X = 8; Console.Write(count(a, X) + "\n");}} // This code is contributed by Amit Katiyar
<script> // Javascript implementation to determine the// Minimum numbers of steps to make// median of an array equal X // Creating the bblSort functionfunction bblSort(arr){ for(var i = 0; i < arr.length; i++) { // Last i elements are already in place for(var j = 0; j < (arr.length - i - 1); j++) { // Checking if the item at present // iteration is greater than the // next iteration if (arr[j] > arr[j+1]) { // If the condition is true // then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } // Return the sorted array return (arr);} // Function to count minimum// required operations to// make median Xfunction count(a, X){ // Sorting the array a a = bblSort(a); var ans = 0; // Calculate the size of array var n = a.length; // Iterate over the array for(i = 0; i < n; i++) { // For all elements // less than median if (i < parseInt(n / 2)) ans += Math.max(0, a[i] - X); // For element equal // to median else if (i == parseInt(n / 2)) ans += Math.abs(X - a[i]); // For all elements // greater than median else ans += Math.max(0, X - a[i]); } // Return the answer return ans;} // Driver codevar a = [ 6, 5, 8 ];var X = 8; document.write(count(a, X)); // This code is contributed by aashish1995 </script>
2
Time Complexity: O(N * log N)Auxiliary Space Complexity: O(1)
amit143katiyar
divyeshrabadiya07
aashish1995
median-finding
Algorithms
Arrays
Greedy
Sorting
Arrays
Greedy
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 291,
"s": 54,
"text": "Given an array A[] of n odd integers and an integer X. Calculate the minimum number of operations required to make the median of the array equal to X, where, in one operation we can either increase or decrease any single element by one."
},
{
"code": null,
"e": 302,
"s": 291,
"text": "Examples: "
},
{
"code": null,
"e": 486,
"s": 302,
"text": "Input: A[] = {6, 5, 8}, X = 8 Output: 2 Explanation: Here 6 can be increased twice. The array will become 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8."
},
{
"code": null,
"e": 620,
"s": 486,
"text": "Input: A[] = {1, 4, 7, 12, 3, 5, 9}, X = 5 Output: 0 Explanation: After sorting 5 is in middle position hence 0 steps are required. "
},
{
"code": null,
"e": 965,
"s": 620,
"text": "Approach: The idea for changing the median of the array will be to sort the given array. Then after sorting, the best possible candidate for making the median is the middle element because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger."
},
{
"code": null,
"e": 1018,
"s": 965,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1022,
"s": 1018,
"text": "C++"
},
{
"code": null,
"e": 1027,
"s": 1022,
"text": "Java"
},
{
"code": null,
"e": 1035,
"s": 1027,
"text": "Python3"
},
{
"code": null,
"e": 1038,
"s": 1035,
"text": "C#"
},
{
"code": null,
"e": 1049,
"s": 1038,
"text": "Javascript"
},
{
"code": "// C++ implementation to determine the// Minimum numbers of steps to make// median of an array equal X #include <bits/stdc++.h>using namespace std; // Function to count minimum// required operations to// make median Xint count(vector<int> a, int X){ // Sorting the array a[] sort(a.begin(), a.end()); int ans = 0; // Calculate the size of array int n = a.size(); // Iterate over the array for (int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += abs(X - a[i]); // For all elements // greater than median else ans += max(0, X - a[i]); } // Return the answer return ans;} // Driver codeint main(){ vector<int> a = { 6, 5, 8 }; int X = 8; cout << count(a, X) << \"\\n\"; return 0;}",
"e": 1983,
"s": 1049,
"text": null
},
{
"code": "// Java implementation to determine the// Minimum numbers of steps to make// median of an array equal Ximport java.util.*; class GFG{ // Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){ // Sorting the array a[] Arrays.sort(a); int ans = 0; // Calculate the size of array int n = a.length; // Iterate over the array for(int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += Math.max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += Math.abs(X - a[i]); // For all elements // greater than median else ans += Math.max(0, X - a[i]); } // Return the answer return ans;} // Driver codepublic static void main(String[] args){ int []a = { 6, 5, 8 }; int X = 8; System.out.print(count(a, X) + \"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 2997,
"s": 1983,
"text": null
},
{
"code": "# Python3 implementation to determine the# Minimum numbers of steps to make# median of an array equal X # Function to count minimum# required operations to# make median Xdef count(a, X): # Sorting the array a[] a.sort() ans = 0 # Calculate the size of array n = len(a) # Iterate over the array for i in range(n): # For all elements # less than median if (i < n // 2): ans += max(0, a[i] - X) # For element equal # to median elif (i == n // 2): ans += abs(X - a[i]) # For all elements # greater than median else: ans += max(0, X - a[i]); # Return the answer return ans # Driver codea = [ 6, 5, 8 ]X = 8 print(count(a, X)) # This code is contributed by divyeshrabadiya07",
"e": 3804,
"s": 2997,
"text": null
},
{
"code": "// C# implementation to determine the// Minimum numbers of steps to make// median of an array equal Xusing System; class GFG{ // Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){ // Sorting the array []a Array.Sort(a); int ans = 0; // Calculate the size of array int n = a.Length; // Iterate over the array for(int i = 0; i < n; i++) { // For all elements // less than median if (i < n / 2) ans += Math.Max(0, a[i] - X); // For element equal // to median else if (i == n / 2) ans += Math.Abs(X - a[i]); // For all elements // greater than median else ans += Math.Max(0, X - a[i]); } // Return the answer return ans;} // Driver codepublic static void Main(String[] args){ int []a = { 6, 5, 8 }; int X = 8; Console.Write(count(a, X) + \"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 4811,
"s": 3804,
"text": null
},
{
"code": "<script> // Javascript implementation to determine the// Minimum numbers of steps to make// median of an array equal X // Creating the bblSort functionfunction bblSort(arr){ for(var i = 0; i < arr.length; i++) { // Last i elements are already in place for(var j = 0; j < (arr.length - i - 1); j++) { // Checking if the item at present // iteration is greater than the // next iteration if (arr[j] > arr[j+1]) { // If the condition is true // then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } // Return the sorted array return (arr);} // Function to count minimum// required operations to// make median Xfunction count(a, X){ // Sorting the array a a = bblSort(a); var ans = 0; // Calculate the size of array var n = a.length; // Iterate over the array for(i = 0; i < n; i++) { // For all elements // less than median if (i < parseInt(n / 2)) ans += Math.max(0, a[i] - X); // For element equal // to median else if (i == parseInt(n / 2)) ans += Math.abs(X - a[i]); // For all elements // greater than median else ans += Math.max(0, X - a[i]); } // Return the answer return ans;} // Driver codevar a = [ 6, 5, 8 ];var X = 8; document.write(count(a, X)); // This code is contributed by aashish1995 </script>",
"e": 6413,
"s": 4811,
"text": null
},
{
"code": null,
"e": 6415,
"s": 6413,
"text": "2"
},
{
"code": null,
"e": 6480,
"s": 6417,
"text": "Time Complexity: O(N * log N)Auxiliary Space Complexity: O(1) "
},
{
"code": null,
"e": 6495,
"s": 6480,
"text": "amit143katiyar"
},
{
"code": null,
"e": 6513,
"s": 6495,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6525,
"s": 6513,
"text": "aashish1995"
},
{
"code": null,
"e": 6540,
"s": 6525,
"text": "median-finding"
},
{
"code": null,
"e": 6551,
"s": 6540,
"text": "Algorithms"
},
{
"code": null,
"e": 6558,
"s": 6551,
"text": "Arrays"
},
{
"code": null,
"e": 6565,
"s": 6558,
"text": "Greedy"
},
{
"code": null,
"e": 6573,
"s": 6565,
"text": "Sorting"
},
{
"code": null,
"e": 6580,
"s": 6573,
"text": "Arrays"
},
{
"code": null,
"e": 6587,
"s": 6580,
"text": "Greedy"
},
{
"code": null,
"e": 6595,
"s": 6587,
"text": "Sorting"
},
{
"code": null,
"e": 6606,
"s": 6595,
"text": "Algorithms"
},
{
"code": null,
"e": 6704,
"s": 6606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6729,
"s": 6704,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 6778,
"s": 6729,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6816,
"s": 6778,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6867,
"s": 6816,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 6903,
"s": 6867,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 6918,
"s": 6903,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6964,
"s": 6918,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 7032,
"s": 6964,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7064,
"s": 7032,
"text": "Largest Sum Contiguous Subarray"
}
] |
Matplotlib – How to show the coordinates of a point upon mouse click?
|
To create a custom mouse cursor in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Bind the function *mouse_event* to the event *button_press_event*.
Bind the function *mouse_event* to the event *button_press_event*.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot the x and y data points using plot() method.
Plot the x and y data points using plot() method.
To display the figure, use Show() method.
To display the figure, use Show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def mouse_event(event):
print('x: {} and y: {}'.format(event.xdata, event.ydata))
fig = plt.figure()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)
x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
It will produce the following output −
Now, click different points on the plot and it will show their coordinates on the console.
x: -3.099305446290094 and y: -0.013811108549791173
x: -0.2865652183685867 and y: -0.2067543563498595
x: -3.0280968329249927 and y: -0.1844916739113902
x: -5.7696284474814 and y: 0.4240216460734405
x: -3.9182044999887626 and y: 0.6837529411889172
|
[
{
"code": null,
"e": 1266,
"s": 1187,
"text": "To create a custom mouse cursor in matplotlib, we can take the following steps"
},
{
"code": null,
"e": 1342,
"s": 1266,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1418,
"s": 1342,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1470,
"s": 1418,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1522,
"s": 1470,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1589,
"s": 1522,
"text": "Bind the function *mouse_event* to the event *button_press_event*."
},
{
"code": null,
"e": 1656,
"s": 1589,
"text": "Bind the function *mouse_event* to the event *button_press_event*."
},
{
"code": null,
"e": 1696,
"s": 1656,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1736,
"s": 1696,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1786,
"s": 1736,
"text": "Plot the x and y data points using plot() method."
},
{
"code": null,
"e": 1836,
"s": 1786,
"text": "Plot the x and y data points using plot() method."
},
{
"code": null,
"e": 1878,
"s": 1836,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 1920,
"s": 1878,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 2309,
"s": 1920,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef mouse_event(event):\n print('x: {} and y: {}'.format(event.xdata, event.ydata))\n\nfig = plt.figure()\ncid = fig.canvas.mpl_connect('button_press_event', mouse_event)\n\nx = np.linspace(-10, 10, 100)\ny = np.sin(x)\n\nplt.plot(x, y)\n\nplt.show()\n"
},
{
"code": null,
"e": 2348,
"s": 2309,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2439,
"s": 2348,
"text": "Now, click different points on the plot and it will show their coordinates on the console."
},
{
"code": null,
"e": 2685,
"s": 2439,
"text": "x: -3.099305446290094 and y: -0.013811108549791173\nx: -0.2865652183685867 and y: -0.2067543563498595\nx: -3.0280968329249927 and y: -0.1844916739113902\nx: -5.7696284474814 and y: 0.4240216460734405\nx: -3.9182044999887626 and y: 0.6837529411889172"
}
] |
Python | Find missing elements in List
|
19 Jun, 2019
Sometimes, we can get elements in range as input but some values are missing in otherwise consecutive range. We might have a use case in which we need to get all the missing elements. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehensionWe can perform the task of finding missing elements using the range function to get the maximum element fill and then insert the elements if there is a miss.
# Python3 code to demonstrate# Finding missing elements in List# using list comprehension # initializing listtest_list = [3, 5, 6, 8, 10] # printing original listprint("The original list : " + str(test_list)) # using list comprehension# Finding missing elements in Listres = [ele for ele in range(max(test_list)+1) if ele not in test_list] # print resultprint("The list of missing elements : " + str(res))
The original list : [3, 5, 6, 8, 10]
The list of missing elements : [0, 1, 2, 4, 7, 9]
Method #2 : Using set()This problem can also be performed using the properties of difference of set and then getting the elements that are missing in a range.
# Python3 code to demonstrate# Finding missing elements in List# Using set() # initializing listtest_list = [3, 5, 6, 8, 10] # printing original listprint("The original list : " + str(test_list)) # Using set()# Finding missing elements in Listres = list(set(range(max(test_list) + 1)) - set(test_list)) # print resultprint("The list of missing elements : " + str(res))
The original list : [3, 5, 6, 8, 10]
The list of missing elements : [0, 1, 2, 4, 7, 9]
Akanksha_Rai
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 292,
"s": 54,
"text": "Sometimes, we can get elements in range as input but some values are missing in otherwise consecutive range. We might have a use case in which we need to get all the missing elements. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 486,
"s": 292,
"text": "Method #1 : Using list comprehensionWe can perform the task of finding missing elements using the range function to get the maximum element fill and then insert the elements if there is a miss."
},
{
"code": "# Python3 code to demonstrate# Finding missing elements in List# using list comprehension # initializing listtest_list = [3, 5, 6, 8, 10] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension# Finding missing elements in Listres = [ele for ele in range(max(test_list)+1) if ele not in test_list] # print resultprint(\"The list of missing elements : \" + str(res))",
"e": 896,
"s": 486,
"text": null
},
{
"code": null,
"e": 984,
"s": 896,
"text": "The original list : [3, 5, 6, 8, 10]\nThe list of missing elements : [0, 1, 2, 4, 7, 9]\n"
},
{
"code": null,
"e": 1145,
"s": 986,
"text": "Method #2 : Using set()This problem can also be performed using the properties of difference of set and then getting the elements that are missing in a range."
},
{
"code": "# Python3 code to demonstrate# Finding missing elements in List# Using set() # initializing listtest_list = [3, 5, 6, 8, 10] # printing original listprint(\"The original list : \" + str(test_list)) # Using set()# Finding missing elements in Listres = list(set(range(max(test_list) + 1)) - set(test_list)) # print resultprint(\"The list of missing elements : \" + str(res))",
"e": 1518,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1518,
"text": "The original list : [3, 5, 6, 8, 10]\nThe list of missing elements : [0, 1, 2, 4, 7, 9]\n"
},
{
"code": null,
"e": 1619,
"s": 1606,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1640,
"s": 1619,
"text": "Python list-programs"
},
{
"code": null,
"e": 1647,
"s": 1640,
"text": "Python"
},
{
"code": null,
"e": 1663,
"s": 1647,
"text": "Python Programs"
},
{
"code": null,
"e": 1761,
"s": 1663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1779,
"s": 1761,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1821,
"s": 1779,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1843,
"s": 1821,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1878,
"s": 1843,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1904,
"s": 1878,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1947,
"s": 1904,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1986,
"s": 1947,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2024,
"s": 1986,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2073,
"s": 2024,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Pure Function In Scala
|
09 Mar, 2022
In any programming language, there are two types of functions:
1. PURE FUNCTIONS
2. IMPURE FUNCTIONSThere is a basic difference between the two, that is pure function doesn’t change the variable it’s passed and an impure function does. For example, there exists a function which increases the input by 10. So, there are two possibilities, the first one is it could directly return x + 10 and so x does not change whereas in another case it could go with the statement like x = x + 10 and then return x, thus changing the value of x. So, the first function is pure whereas the other is impure.
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. They are those functions which don’t read any other values except those given as input and follows its internal algorithm to produce the output. A pure function is side-effect free i.e it doesn’t change the value of the variable implicitly and thus doesn’t end up altering the values of the input. These Scala String methods are also pure functions:
isEmpty
length
substring
A pure function can be made as shown in the following program code: Example 1:
Scala
// Pure function In Scalaobject GFG{ // Driver code def main(args: Array[String]) { def square(a:Int) = { var b:Int = a * a; println("Square of the number is " + b); println("Number is " + a); } square(4); }}
Output:
Square of the number is 16
Number is 4
Now, we know that this function don’t change the variable implicitly so we add the result of two different functions in different ways, as shown: Example 2:
Scala
// Scala Pure Functionobject GFG{ // Driver code def main(args: Array[String]) { // Function 1 def add(a:Int, b:Int):Int = { var c:Int = a + b; return c; } // Function 2 def multiply(a:Int, b:Int):Int = { var c:Int = a * b; return c; } // Calculating same value but changing // the position of the functions println("Output in case 1 :" + add(1, 2) * multiply(3, 4)); println("Output in case 2 :" + multiply(4, 3) * add(2, 1)); }}
Output:
Output in case 1 :36
Output in case 2 :36
Now, as output of both the cases are same then it is proved that input in the pure function in scala is not changed implicitly.Below are befits Of using Pure Functions:
They don’t cause any implicitly changes in input.They are easier to test.They can be debug easily.
They don’t cause any implicitly changes in input.
They are easier to test.
They can be debug easily.
gabaa406
kothavvsaakash
Picked
Ruby-Basics
Ruby-Methods
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala String substring() method with example
Scala | Arrays
Scala Constructors
Enumeration in Scala
Inheritance in Scala
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 92,
"s": 28,
"text": "In any programming language, there are two types of functions: "
},
{
"code": null,
"e": 110,
"s": 92,
"text": "1. PURE FUNCTIONS"
},
{
"code": null,
"e": 623,
"s": 110,
"text": "2. IMPURE FUNCTIONSThere is a basic difference between the two, that is pure function doesn’t change the variable it’s passed and an impure function does. For example, there exists a function which increases the input by 10. So, there are two possibilities, the first one is it could directly return x + 10 and so x does not change whereas in another case it could go with the statement like x = x + 10 and then return x, thus changing the value of x. So, the first function is pure whereas the other is impure. "
},
{
"code": null,
"e": 1172,
"s": 623,
"text": "A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. They are those functions which don’t read any other values except those given as input and follows its internal algorithm to produce the output. A pure function is side-effect free i.e it doesn’t change the value of the variable implicitly and thus doesn’t end up altering the values of the input. These Scala String methods are also pure functions: "
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "isEmpty"
},
{
"code": null,
"e": 1187,
"s": 1180,
"text": "length"
},
{
"code": null,
"e": 1197,
"s": 1187,
"text": "substring"
},
{
"code": null,
"e": 1278,
"s": 1197,
"text": "A pure function can be made as shown in the following program code: Example 1: "
},
{
"code": null,
"e": 1284,
"s": 1278,
"text": "Scala"
},
{
"code": "// Pure function In Scalaobject GFG{ // Driver code def main(args: Array[String]) { def square(a:Int) = { var b:Int = a * a; println(\"Square of the number is \" + b); println(\"Number is \" + a); } square(4); }}",
"e": 1559,
"s": 1284,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1559,
"text": "Output: "
},
{
"code": null,
"e": 1608,
"s": 1569,
"text": "Square of the number is 16\nNumber is 4"
},
{
"code": null,
"e": 1767,
"s": 1608,
"text": "Now, we know that this function don’t change the variable implicitly so we add the result of two different functions in different ways, as shown: Example 2: "
},
{
"code": null,
"e": 1773,
"s": 1767,
"text": "Scala"
},
{
"code": "// Scala Pure Functionobject GFG{ // Driver code def main(args: Array[String]) { // Function 1 def add(a:Int, b:Int):Int = { var c:Int = a + b; return c; } // Function 2 def multiply(a:Int, b:Int):Int = { var c:Int = a * b; return c; } // Calculating same value but changing // the position of the functions println(\"Output in case 1 :\" + add(1, 2) * multiply(3, 4)); println(\"Output in case 2 :\" + multiply(4, 3) * add(2, 1)); }}",
"e": 2378,
"s": 1773,
"text": null
},
{
"code": null,
"e": 2388,
"s": 2378,
"text": "Output: "
},
{
"code": null,
"e": 2430,
"s": 2388,
"text": "Output in case 1 :36\nOutput in case 2 :36"
},
{
"code": null,
"e": 2601,
"s": 2430,
"text": "Now, as output of both the cases are same then it is proved that input in the pure function in scala is not changed implicitly.Below are befits Of using Pure Functions: "
},
{
"code": null,
"e": 2700,
"s": 2601,
"text": "They don’t cause any implicitly changes in input.They are easier to test.They can be debug easily."
},
{
"code": null,
"e": 2750,
"s": 2700,
"text": "They don’t cause any implicitly changes in input."
},
{
"code": null,
"e": 2775,
"s": 2750,
"text": "They are easier to test."
},
{
"code": null,
"e": 2801,
"s": 2775,
"text": "They can be debug easily."
},
{
"code": null,
"e": 2812,
"s": 2803,
"text": "gabaa406"
},
{
"code": null,
"e": 2827,
"s": 2812,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 2834,
"s": 2827,
"text": "Picked"
},
{
"code": null,
"e": 2846,
"s": 2834,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 2859,
"s": 2846,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 2865,
"s": 2859,
"text": "Scala"
},
{
"code": null,
"e": 2963,
"s": 2865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2989,
"s": 2963,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 3011,
"s": 2989,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 3064,
"s": 3011,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 3076,
"s": 3064,
"text": "Scala Lists"
},
{
"code": null,
"e": 3095,
"s": 3076,
"text": "Operators in Scala"
},
{
"code": null,
"e": 3140,
"s": 3095,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 3155,
"s": 3140,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 3174,
"s": 3155,
"text": "Scala Constructors"
},
{
"code": null,
"e": 3195,
"s": 3174,
"text": "Enumeration in Scala"
}
] |
How to merge multiple folders into one folder using Python ?
|
28 Apr, 2021
In this article, we will discuss how to move multiple folders into one folder. This can be done using Python’s OS and Shutil module.
Get the current directory and the list of the folders you want to merge.Loop through the list of folders and store their content in a list. Here, we have stored them in the dictionary so that we can have the name of the folder as a key and its content as a value list.Specify the folder in which you want to merge all the other folders. If the folder exists then we are good to go but if the folder does not exist then create a new folder.Loop through the dictionary and move all the content of all the listed folders inside the merge folder.
Get the current directory and the list of the folders you want to merge.
Loop through the list of folders and store their content in a list. Here, we have stored them in the dictionary so that we can have the name of the folder as a key and its content as a value list.
Specify the folder in which you want to merge all the other folders. If the folder exists then we are good to go but if the folder does not exist then create a new folder.
Loop through the dictionary and move all the content of all the listed folders inside the merge folder.
Let’s implement this approach step by step:
Step 1: Below code does the following:
Get the current directory.
List all the folders that you want to merge.
Stores content of all the listed folders in the dictionary with folder name as key and its content as a value list.
Python3
# current folder pathcurrent_folder = os.getcwd() # list of folders to be mergedlist_dir = ['Folder 1', 'Folder 2', 'Folder 3'] # enumerate on list_dir to get the # content of all the folders ans store it in a dictionarycontent_list = {}for index, val in enumerate(list_dir): path = os.path.join(current_folder, val) content_list[ list_dir[index] ] = os.listdir(path)
Step 2: Creates the merge folder if it does not already exist.
Python3
# Function to create new folder if not existsdef make_new_folder(folder_name, parent_folder_path): # Path path = os.path.join(parent_folder_path, folder_name) # Create the folder # 'new_folder' in # parent_folder try: # mode of the folder mode = 0o777 # Create folder os.mkdir(path, mode) except OSError as error: print(error) # folder in which all the content # will be mergedmerge_folder = "merge_folder" # merge_folder path - current_folder # + merge_foldermerge_folder_path = os.path.join(current_folder, merge_folder) # create merge_folder if not existsmake_new_folder(merge_folder, current_folder)
Step 3: Below code does the following:
Loop through the dictionary with all the folders.
Now loop through the content of each folder and one by one move them to the merge folder.
Python3
# loop through the list of foldersfor sub_dir in content_list: # loop through the contents of the # list of folders for contents in content_list[sub_dir]: # make the path of the content to move path_to_content = sub_dir + "/" + contents # make the path with the current folder dir_to_move = os.path.join(current_folder, path_to_content ) # move the file shutil.move(dir_to_move, merge_folder_path)
Complete Code:
Python3
import shutilimport os # Function to create new folder if not existsdef make_new_folder(folder_name, parent_folder): # Path path = os.path.join(parent_folder, folder_name) # Create the folder # 'new_folder' in # parent_folder try: # mode of the folder mode = 0o777 # Create folder os.mkdir(path, mode) except OSError as error: print(error) # current folder pathcurrent_folder = os.getcwd() # list of folders to be mergedlist_dir = ['Folder 1', 'Folder 2', 'Folder 3'] # enumerate on list_dir to get the # content of all the folders ans store # it in a dictionarycontent_list = {}for index, val in enumerate(list_dir): path = os.path.join(current_folder, val) content_list[ list_dir[index] ] = os.listdir(path) # folder in which all the content will# be mergedmerge_folder = "merge_folder" # merge_folder path - current_folder # + merge_foldermerge_folder_path = os.path.join(current_folder, merge_folder) # create merge_folder if not existsmake_new_folder(merge_folder, current_folder) # loop through the list of foldersfor sub_dir in content_list: # loop through the contents of the # list of folders for contents in content_list[sub_dir]: # make the path of the content to move path_to_content = sub_dir + "/" + contents # make the path with the current folder dir_to_move = os.path.join(current_folder, path_to_content ) # move the file shutil.move(dir_to_move, merge_folder_path)
Folder structure before running the above program.
Folder 1
File 1
File 2
Folder 2
File 3
File 4
Folder 3
File 5
File 6
Folder 4
File 7
File 8
merge_folder (Empty)
move_script.py
Folder structure after running the above program.
Folder 1 (Empty)
Folder 2 (Empty)
Folder 3 (Empty)
Folder 4 (Untouched)
File 7
File 8
merge_folder
File 1
File 2
File 3
File 4
File 5
File 6
move_script.py
Program in Working :
Picked
python-os-module
Python-shutil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 186,
"s": 53,
"text": "In this article, we will discuss how to move multiple folders into one folder. This can be done using Python’s OS and Shutil module."
},
{
"code": null,
"e": 729,
"s": 186,
"text": "Get the current directory and the list of the folders you want to merge.Loop through the list of folders and store their content in a list. Here, we have stored them in the dictionary so that we can have the name of the folder as a key and its content as a value list.Specify the folder in which you want to merge all the other folders. If the folder exists then we are good to go but if the folder does not exist then create a new folder.Loop through the dictionary and move all the content of all the listed folders inside the merge folder."
},
{
"code": null,
"e": 802,
"s": 729,
"text": "Get the current directory and the list of the folders you want to merge."
},
{
"code": null,
"e": 999,
"s": 802,
"text": "Loop through the list of folders and store their content in a list. Here, we have stored them in the dictionary so that we can have the name of the folder as a key and its content as a value list."
},
{
"code": null,
"e": 1171,
"s": 999,
"text": "Specify the folder in which you want to merge all the other folders. If the folder exists then we are good to go but if the folder does not exist then create a new folder."
},
{
"code": null,
"e": 1275,
"s": 1171,
"text": "Loop through the dictionary and move all the content of all the listed folders inside the merge folder."
},
{
"code": null,
"e": 1319,
"s": 1275,
"text": "Let’s implement this approach step by step:"
},
{
"code": null,
"e": 1358,
"s": 1319,
"text": "Step 1: Below code does the following:"
},
{
"code": null,
"e": 1385,
"s": 1358,
"text": "Get the current directory."
},
{
"code": null,
"e": 1430,
"s": 1385,
"text": "List all the folders that you want to merge."
},
{
"code": null,
"e": 1546,
"s": 1430,
"text": "Stores content of all the listed folders in the dictionary with folder name as key and its content as a value list."
},
{
"code": null,
"e": 1554,
"s": 1546,
"text": "Python3"
},
{
"code": "# current folder pathcurrent_folder = os.getcwd() # list of folders to be mergedlist_dir = ['Folder 1', 'Folder 2', 'Folder 3'] # enumerate on list_dir to get the # content of all the folders ans store it in a dictionarycontent_list = {}for index, val in enumerate(list_dir): path = os.path.join(current_folder, val) content_list[ list_dir[index] ] = os.listdir(path)",
"e": 1931,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1931,
"text": "Step 2: Creates the merge folder if it does not already exist."
},
{
"code": null,
"e": 2002,
"s": 1994,
"text": "Python3"
},
{
"code": "# Function to create new folder if not existsdef make_new_folder(folder_name, parent_folder_path): # Path path = os.path.join(parent_folder_path, folder_name) # Create the folder # 'new_folder' in # parent_folder try: # mode of the folder mode = 0o777 # Create folder os.mkdir(path, mode) except OSError as error: print(error) # folder in which all the content # will be mergedmerge_folder = \"merge_folder\" # merge_folder path - current_folder # + merge_foldermerge_folder_path = os.path.join(current_folder, merge_folder) # create merge_folder if not existsmake_new_folder(merge_folder, current_folder)",
"e": 2701,
"s": 2002,
"text": null
},
{
"code": null,
"e": 2740,
"s": 2701,
"text": "Step 3: Below code does the following:"
},
{
"code": null,
"e": 2790,
"s": 2740,
"text": "Loop through the dictionary with all the folders."
},
{
"code": null,
"e": 2880,
"s": 2790,
"text": "Now loop through the content of each folder and one by one move them to the merge folder."
},
{
"code": null,
"e": 2888,
"s": 2880,
"text": "Python3"
},
{
"code": "# loop through the list of foldersfor sub_dir in content_list: # loop through the contents of the # list of folders for contents in content_list[sub_dir]: # make the path of the content to move path_to_content = sub_dir + \"/\" + contents # make the path with the current folder dir_to_move = os.path.join(current_folder, path_to_content ) # move the file shutil.move(dir_to_move, merge_folder_path)",
"e": 3348,
"s": 2888,
"text": null
},
{
"code": null,
"e": 3363,
"s": 3348,
"text": "Complete Code:"
},
{
"code": null,
"e": 3371,
"s": 3363,
"text": "Python3"
},
{
"code": "import shutilimport os # Function to create new folder if not existsdef make_new_folder(folder_name, parent_folder): # Path path = os.path.join(parent_folder, folder_name) # Create the folder # 'new_folder' in # parent_folder try: # mode of the folder mode = 0o777 # Create folder os.mkdir(path, mode) except OSError as error: print(error) # current folder pathcurrent_folder = os.getcwd() # list of folders to be mergedlist_dir = ['Folder 1', 'Folder 2', 'Folder 3'] # enumerate on list_dir to get the # content of all the folders ans store # it in a dictionarycontent_list = {}for index, val in enumerate(list_dir): path = os.path.join(current_folder, val) content_list[ list_dir[index] ] = os.listdir(path) # folder in which all the content will# be mergedmerge_folder = \"merge_folder\" # merge_folder path - current_folder # + merge_foldermerge_folder_path = os.path.join(current_folder, merge_folder) # create merge_folder if not existsmake_new_folder(merge_folder, current_folder) # loop through the list of foldersfor sub_dir in content_list: # loop through the contents of the # list of folders for contents in content_list[sub_dir]: # make the path of the content to move path_to_content = sub_dir + \"/\" + contents # make the path with the current folder dir_to_move = os.path.join(current_folder, path_to_content ) # move the file shutil.move(dir_to_move, merge_folder_path)",
"e": 4909,
"s": 3371,
"text": null
},
{
"code": null,
"e": 4960,
"s": 4909,
"text": "Folder structure before running the above program."
},
{
"code": null,
"e": 5120,
"s": 4960,
"text": "Folder 1\n File 1\n File 2\nFolder 2\n File 3\n File 4\nFolder 3\n File 5\n File 6\nFolder 4\n File 7\n File 8\nmerge_folder (Empty)\nmove_script.py"
},
{
"code": null,
"e": 5170,
"s": 5120,
"text": "Folder structure after running the above program."
},
{
"code": null,
"e": 5358,
"s": 5170,
"text": "Folder 1 (Empty)\nFolder 2 (Empty)\nFolder 3 (Empty)\nFolder 4 (Untouched)\n File 7\n File 8\nmerge_folder\n File 1\n File 2\n File 3\n File 4\n File 5\n File 6\nmove_script.py"
},
{
"code": null,
"e": 5379,
"s": 5358,
"text": "Program in Working :"
},
{
"code": null,
"e": 5386,
"s": 5379,
"text": "Picked"
},
{
"code": null,
"e": 5403,
"s": 5386,
"text": "python-os-module"
},
{
"code": null,
"e": 5417,
"s": 5403,
"text": "Python-shutil"
},
{
"code": null,
"e": 5424,
"s": 5417,
"text": "Python"
},
{
"code": null,
"e": 5522,
"s": 5424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5554,
"s": 5522,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5581,
"s": 5554,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5602,
"s": 5581,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5625,
"s": 5602,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5656,
"s": 5625,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5712,
"s": 5656,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5754,
"s": 5712,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5796,
"s": 5754,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5835,
"s": 5796,
"text": "Python | Get unique values from a list"
}
] |
Null Pointer Exception in Java Programming
|
NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value.
For example, using a method on a null reference.
Live Demo
public class Tester {
public static void main(String[] args) {
Object ref = null;
ref.toString(); // this will throw a NullPointerException
}
}
Exception in thread "main" java.lang.NullPointerException
at Tester.main(Tester.java:4)
|
[
{
"code": null,
"e": 1324,
"s": 1187,
"text": "NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value."
},
{
"code": null,
"e": 1373,
"s": 1324,
"text": "For example, using a method on a null reference."
},
{
"code": null,
"e": 1384,
"s": 1373,
"text": " Live Demo"
},
{
"code": null,
"e": 1546,
"s": 1384,
"text": "public class Tester {\n public static void main(String[] args) {\n Object ref = null;\n ref.toString(); // this will throw a NullPointerException\n }\n}"
},
{
"code": null,
"e": 1636,
"s": 1546,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n\tat Tester.main(Tester.java:4)\n"
}
] |
How to Un-Delete Your Jupyter Notebooks | by Ray Johns | Towards Data Science
|
Who doesn’t love Jupyter notebooks? They’re interactive, giving you the instant gratification of immediate feedback. They’re extensible — you can even deploy them as websites. Most importantly for data scientists and machine learning engineers, they’re expressive — they span the space between the scientists and engineers who manipulate data and the lay audience that consumes and wants to understand the information that data represents.
But Jupyter notebooks have their drawbacks. They’re big JSON files that store the code, markdown, input, output, and metadata of every cell that you run. To understand what I mean, here’s a short notebook I wrote to define and test the sigmoid function.
And here’s what (part of) it looks like when IPython isn’t rendering it (I’ve abridged all but the first actual input cell, because even for a short notebook it’s long and ugly):
{ "nbformat": 4, "nbformat_minor": 2, "metadata": { "language_info": { "name": "python", "codemirror_mode": { "name": "ipython", "version": 3 }, "version": "3.6.8-final" }, "orig_nbformat": 2, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "npconvert_exporter": "python", "pygments_lexer": "ipython3", "version": 3, "kernelspec": { "name": "python36864bitvenvscivenv55fc700d3ea9447888c06400e9b2b088", "display_name": "Python 3.6.8 64-bit ('venv-sci': venv)" } }, "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import random" ] }, ...}
It’s kind of hard to version control them as a result. It also means there’s a lot of junk data in there you usually don’t care very much about saving, like the cell execution count and outputs.
The next time you wonder why your Jupyter notebook is running so slowly, open it in a plain-text editor and see how many massive dataframes are just hanging out in your notebook’s metadata.
Under the right circumstances, though, all that junk can look like precious gems. Those circumstances usually involve:
Accidentally closing a notebook without saving it
Hitting the wrong keyboard shortcut and deleting important cells
Opening the same notebook in multiple browser windows and overwriting your own work
Anyone who’s ever strayed into the dangerous territory of doing their development in an IPython notebook has done these things at least once, probably at the same time.
If this is you, and you’re here because you Googled recover deleted jupyter notebook refreshed browser window, don’t panic. First I’m going to tell you how to fix it.* Then I’m going to tell you how to prevent it from happening again.
*Yes, you can fix it. (Probably.)
A Python virtual environment with Jupyter, IPython (with nbformat and nbconvert) and jupytext installed (preferably a fresh venv, so you can test things out)
Working installation of sqlite3 (optional but recommended: a database browser like SQLiteStudio)
Hope and determination
(Unscientific) estimated probability of recovery: 90%
Relative difficulty: Easier
In the least-worst case, you’ve hit x on a cell you didn’t actually want to delete, and now you want to get back its code or data.
When you use a notebook, the IPython kernel runs your code. The IPython kernel is a process that is separate from your Python interpreter. (That’s also why you need to link a new kernel to a new virtual environment. The two are not automatically connected.) It sends and receives messages, like your code cells, using JSON.
When you run a cell or hit “save”, the notebook server sends your code as JSON to a notebook on your computer that stores your input and output. So the little words In and Out next to your cell aren’t just words, they’re containers — specifically lists of your session history. You can print out and index into them.
Use the %history line magic to print your input history (last in, first out). This powerful command grants you access to your current and past sessions by absolute or relative number.
If the current IPython process is still connected, and you’ve installed nbformat in your virtual environment, execute this code in a cell to recover your notebook:
>>> %notebook your_notebook_filename_backup.ipynb
This magic renders the entire current session history as a new Jupyter notebook.
Well, that wasn’t so bad.
This won’t always work, and you might need to expend a bit of effort weeding extraneous cells from the output.
There are lots more things you can do with the history magic. Here are a few recipes I find useful:
%history -l [LIMIT] get the last n inputs
%history -g -f FILENAME: writes your entire saved history to a file
%history -n -g [PATTERN]: search your history with a glob pattern and print the session and line numbers
%history -u: get only the unique history from the current session.
%history [RANGE] -t: get the native history, a.k.a. the IPython-generated source code (good for debugging)
%history [SESSION]/[RANGE] -p -o: print input and output with the >>> prompt (nice for readmes and documentation)
If you’ve been working in a really big data science notebook for a long time, the %notebook magic strategy might produce a lot of noise that you don’t want. Use the other parameters to whittle down the output of %history -g, then use jupytext (explained below) to convert the results.
(Unscientific) estimated probability of recovery: 70–85%
Relative difficulty: Harder
Remember how we said version control is hard with notebooks? A kernel can connect to more than one frontend at the same time. Which means those two browser tabs with the same notebook open can access the same variables. Which is how you overwrote your code in the first place.
IPython stores your session history in a database. By default, you can find it under your home directory in a folder called .ipython/profile_default.
$ ls ~/.ipython/profile_defaultdb history.sqlite log pid security startup
Back up history.sqlite to a copy.
$ cp history.sqlite history-bak.sqlite
Open the backup, either in a database browser or via the sqlite3 command line interface. It has three tables: history, output_history, and sessions. Depending on what you want to recover, you may need to join all three, so brush off your SQL.
If you can tell from the database browser GUI which session number in the history table has your code, then your life is a bit simpler.
Either execute the SQL command in the browser or on the command line:
sqlite3 ~/.ipython/profile_default/history-bak.sqlite \ "select source || char(10) from history where session = 1;" > recovered.py
All this does is specify the session number and the filename to write to (in the example given, 1 and recovered.py) and selects your source code from the database, separating each block with a newline character (which in ASCII is 10).
If you wanted to select the line number as a Python comment, you could do so with a query like:
"select '# Line:' || line || char(10) || source || char(10) from history where session = 1;"
Once you have a Python executable, you can pretty much breathe easy. But you could turn it back into a notebook with jupytext, a miraculous tool that can convert plaintext formats to Jupyter notebooks.
jupytext --to notebook recovered.py
Not too terrible!
(Unscientific) estimated probability of recovery: 50–75%
Relative difficulty: Hardest
None of the above worked, but you’re not ready to give up yet.
Go back to whatever tool you’re using to navigate your history-bak.sqlite database. The queries you write will require creative search techniques that make the most of the information you have:
Timestamps for session starts (always non-null)
Timestamps for session ends (sometimes null in useful ways)
Output history
Number of commands executed per session
Your input (code and markdown)
IPython’s rendered source code
For example, you could find everything you wrote involving pytest this year with a query like:
select line, sourcefrom historyjoin sessionson sessions.session = history.sessionwhere sessions.start > '2020-01-01 00:00:00.000000'and history.source like '%pytest%';
Once you’ve shaped your view to the rows you want, you can export it to an executable .py file as before, and convert it back to .ipynb with jupytext.
As you savor your relief at not having to rewrite your notebook from scratch, take a moment to ponder a few measures to guard against future expeditions into history.sqlite:
Don’t connect identical frontends to the same kernel. In other words, don’t keep the same notebook open in multiple browser tabs. Using Visual Studio Code as your Jupyter IDE largely eliminates this risk.
Back up your IPython history database file regularly just in case.
Convert your notebooks to plaintext whenever possible — at least for backup. Jupytext makes this almost trivial.
Use IPython’s %store magic to store variables, macros, and aliases in the IPython database. All you need to do is find your ipython_config.py file in profile_default (or run ipython profile create if you don’t have one), and add this line: c.StoreMagics.autorestore = True. You can store, alias, and access anything from environment variables to small machine learning models if you want to. Here’s the full documentation.
What are some of your biggest challenges with Jupyter notebooks? Drop a comment on topics you’d like to tackle in future posts.
Power up your Python Projects with Visual Studio Code
Advanced Google Skills for Data Science
Jupytext
IPython storemagic
IPython history magic
|
[
{
"code": null,
"e": 612,
"s": 172,
"text": "Who doesn’t love Jupyter notebooks? They’re interactive, giving you the instant gratification of immediate feedback. They’re extensible — you can even deploy them as websites. Most importantly for data scientists and machine learning engineers, they’re expressive — they span the space between the scientists and engineers who manipulate data and the lay audience that consumes and wants to understand the information that data represents."
},
{
"code": null,
"e": 866,
"s": 612,
"text": "But Jupyter notebooks have their drawbacks. They’re big JSON files that store the code, markdown, input, output, and metadata of every cell that you run. To understand what I mean, here’s a short notebook I wrote to define and test the sigmoid function."
},
{
"code": null,
"e": 1045,
"s": 866,
"text": "And here’s what (part of) it looks like when IPython isn’t rendering it (I’ve abridged all but the first actual input cell, because even for a short notebook it’s long and ugly):"
},
{
"code": null,
"e": 1735,
"s": 1045,
"text": "{ \"nbformat\": 4, \"nbformat_minor\": 2, \"metadata\": { \"language_info\": { \"name\": \"python\", \"codemirror_mode\": { \"name\": \"ipython\", \"version\": 3 }, \"version\": \"3.6.8-final\" }, \"orig_nbformat\": 2, \"file_extension\": \".py\", \"mimetype\": \"text/x-python\", \"name\": \"python\", \"npconvert_exporter\": \"python\", \"pygments_lexer\": \"ipython3\", \"version\": 3, \"kernelspec\": { \"name\": \"python36864bitvenvscivenv55fc700d3ea9447888c06400e9b2b088\", \"display_name\": \"Python 3.6.8 64-bit ('venv-sci': venv)\" } }, \"cells\": [ { \"cell_type\": \"code\", \"execution_count\": 2, \"metadata\": {}, \"outputs\": [], \"source\": [ \"import numpy as np\\n\", \"import random\" ] }, ...}"
},
{
"code": null,
"e": 1930,
"s": 1735,
"text": "It’s kind of hard to version control them as a result. It also means there’s a lot of junk data in there you usually don’t care very much about saving, like the cell execution count and outputs."
},
{
"code": null,
"e": 2120,
"s": 1930,
"text": "The next time you wonder why your Jupyter notebook is running so slowly, open it in a plain-text editor and see how many massive dataframes are just hanging out in your notebook’s metadata."
},
{
"code": null,
"e": 2239,
"s": 2120,
"text": "Under the right circumstances, though, all that junk can look like precious gems. Those circumstances usually involve:"
},
{
"code": null,
"e": 2289,
"s": 2239,
"text": "Accidentally closing a notebook without saving it"
},
{
"code": null,
"e": 2354,
"s": 2289,
"text": "Hitting the wrong keyboard shortcut and deleting important cells"
},
{
"code": null,
"e": 2438,
"s": 2354,
"text": "Opening the same notebook in multiple browser windows and overwriting your own work"
},
{
"code": null,
"e": 2607,
"s": 2438,
"text": "Anyone who’s ever strayed into the dangerous territory of doing their development in an IPython notebook has done these things at least once, probably at the same time."
},
{
"code": null,
"e": 2842,
"s": 2607,
"text": "If this is you, and you’re here because you Googled recover deleted jupyter notebook refreshed browser window, don’t panic. First I’m going to tell you how to fix it.* Then I’m going to tell you how to prevent it from happening again."
},
{
"code": null,
"e": 2876,
"s": 2842,
"text": "*Yes, you can fix it. (Probably.)"
},
{
"code": null,
"e": 3034,
"s": 2876,
"text": "A Python virtual environment with Jupyter, IPython (with nbformat and nbconvert) and jupytext installed (preferably a fresh venv, so you can test things out)"
},
{
"code": null,
"e": 3131,
"s": 3034,
"text": "Working installation of sqlite3 (optional but recommended: a database browser like SQLiteStudio)"
},
{
"code": null,
"e": 3154,
"s": 3131,
"text": "Hope and determination"
},
{
"code": null,
"e": 3208,
"s": 3154,
"text": "(Unscientific) estimated probability of recovery: 90%"
},
{
"code": null,
"e": 3236,
"s": 3208,
"text": "Relative difficulty: Easier"
},
{
"code": null,
"e": 3367,
"s": 3236,
"text": "In the least-worst case, you’ve hit x on a cell you didn’t actually want to delete, and now you want to get back its code or data."
},
{
"code": null,
"e": 3691,
"s": 3367,
"text": "When you use a notebook, the IPython kernel runs your code. The IPython kernel is a process that is separate from your Python interpreter. (That’s also why you need to link a new kernel to a new virtual environment. The two are not automatically connected.) It sends and receives messages, like your code cells, using JSON."
},
{
"code": null,
"e": 4008,
"s": 3691,
"text": "When you run a cell or hit “save”, the notebook server sends your code as JSON to a notebook on your computer that stores your input and output. So the little words In and Out next to your cell aren’t just words, they’re containers — specifically lists of your session history. You can print out and index into them."
},
{
"code": null,
"e": 4192,
"s": 4008,
"text": "Use the %history line magic to print your input history (last in, first out). This powerful command grants you access to your current and past sessions by absolute or relative number."
},
{
"code": null,
"e": 4356,
"s": 4192,
"text": "If the current IPython process is still connected, and you’ve installed nbformat in your virtual environment, execute this code in a cell to recover your notebook:"
},
{
"code": null,
"e": 4406,
"s": 4356,
"text": ">>> %notebook your_notebook_filename_backup.ipynb"
},
{
"code": null,
"e": 4487,
"s": 4406,
"text": "This magic renders the entire current session history as a new Jupyter notebook."
},
{
"code": null,
"e": 4513,
"s": 4487,
"text": "Well, that wasn’t so bad."
},
{
"code": null,
"e": 4624,
"s": 4513,
"text": "This won’t always work, and you might need to expend a bit of effort weeding extraneous cells from the output."
},
{
"code": null,
"e": 4724,
"s": 4624,
"text": "There are lots more things you can do with the history magic. Here are a few recipes I find useful:"
},
{
"code": null,
"e": 4766,
"s": 4724,
"text": "%history -l [LIMIT] get the last n inputs"
},
{
"code": null,
"e": 4834,
"s": 4766,
"text": "%history -g -f FILENAME: writes your entire saved history to a file"
},
{
"code": null,
"e": 4939,
"s": 4834,
"text": "%history -n -g [PATTERN]: search your history with a glob pattern and print the session and line numbers"
},
{
"code": null,
"e": 5006,
"s": 4939,
"text": "%history -u: get only the unique history from the current session."
},
{
"code": null,
"e": 5113,
"s": 5006,
"text": "%history [RANGE] -t: get the native history, a.k.a. the IPython-generated source code (good for debugging)"
},
{
"code": null,
"e": 5227,
"s": 5113,
"text": "%history [SESSION]/[RANGE] -p -o: print input and output with the >>> prompt (nice for readmes and documentation)"
},
{
"code": null,
"e": 5512,
"s": 5227,
"text": "If you’ve been working in a really big data science notebook for a long time, the %notebook magic strategy might produce a lot of noise that you don’t want. Use the other parameters to whittle down the output of %history -g, then use jupytext (explained below) to convert the results."
},
{
"code": null,
"e": 5569,
"s": 5512,
"text": "(Unscientific) estimated probability of recovery: 70–85%"
},
{
"code": null,
"e": 5597,
"s": 5569,
"text": "Relative difficulty: Harder"
},
{
"code": null,
"e": 5874,
"s": 5597,
"text": "Remember how we said version control is hard with notebooks? A kernel can connect to more than one frontend at the same time. Which means those two browser tabs with the same notebook open can access the same variables. Which is how you overwrote your code in the first place."
},
{
"code": null,
"e": 6024,
"s": 5874,
"text": "IPython stores your session history in a database. By default, you can find it under your home directory in a folder called .ipython/profile_default."
},
{
"code": null,
"e": 6103,
"s": 6024,
"text": "$ ls ~/.ipython/profile_defaultdb history.sqlite log pid security startup"
},
{
"code": null,
"e": 6137,
"s": 6103,
"text": "Back up history.sqlite to a copy."
},
{
"code": null,
"e": 6176,
"s": 6137,
"text": "$ cp history.sqlite history-bak.sqlite"
},
{
"code": null,
"e": 6419,
"s": 6176,
"text": "Open the backup, either in a database browser or via the sqlite3 command line interface. It has three tables: history, output_history, and sessions. Depending on what you want to recover, you may need to join all three, so brush off your SQL."
},
{
"code": null,
"e": 6555,
"s": 6419,
"text": "If you can tell from the database browser GUI which session number in the history table has your code, then your life is a bit simpler."
},
{
"code": null,
"e": 6625,
"s": 6555,
"text": "Either execute the SQL command in the browser or on the command line:"
},
{
"code": null,
"e": 6757,
"s": 6625,
"text": "sqlite3 ~/.ipython/profile_default/history-bak.sqlite \\ \"select source || char(10) from history where session = 1;\" > recovered.py"
},
{
"code": null,
"e": 6992,
"s": 6757,
"text": "All this does is specify the session number and the filename to write to (in the example given, 1 and recovered.py) and selects your source code from the database, separating each block with a newline character (which in ASCII is 10)."
},
{
"code": null,
"e": 7088,
"s": 6992,
"text": "If you wanted to select the line number as a Python comment, you could do so with a query like:"
},
{
"code": null,
"e": 7181,
"s": 7088,
"text": "\"select '# Line:' || line || char(10) || source || char(10) from history where session = 1;\""
},
{
"code": null,
"e": 7383,
"s": 7181,
"text": "Once you have a Python executable, you can pretty much breathe easy. But you could turn it back into a notebook with jupytext, a miraculous tool that can convert plaintext formats to Jupyter notebooks."
},
{
"code": null,
"e": 7419,
"s": 7383,
"text": "jupytext --to notebook recovered.py"
},
{
"code": null,
"e": 7437,
"s": 7419,
"text": "Not too terrible!"
},
{
"code": null,
"e": 7494,
"s": 7437,
"text": "(Unscientific) estimated probability of recovery: 50–75%"
},
{
"code": null,
"e": 7523,
"s": 7494,
"text": "Relative difficulty: Hardest"
},
{
"code": null,
"e": 7586,
"s": 7523,
"text": "None of the above worked, but you’re not ready to give up yet."
},
{
"code": null,
"e": 7780,
"s": 7586,
"text": "Go back to whatever tool you’re using to navigate your history-bak.sqlite database. The queries you write will require creative search techniques that make the most of the information you have:"
},
{
"code": null,
"e": 7828,
"s": 7780,
"text": "Timestamps for session starts (always non-null)"
},
{
"code": null,
"e": 7888,
"s": 7828,
"text": "Timestamps for session ends (sometimes null in useful ways)"
},
{
"code": null,
"e": 7903,
"s": 7888,
"text": "Output history"
},
{
"code": null,
"e": 7943,
"s": 7903,
"text": "Number of commands executed per session"
},
{
"code": null,
"e": 7974,
"s": 7943,
"text": "Your input (code and markdown)"
},
{
"code": null,
"e": 8005,
"s": 7974,
"text": "IPython’s rendered source code"
},
{
"code": null,
"e": 8100,
"s": 8005,
"text": "For example, you could find everything you wrote involving pytest this year with a query like:"
},
{
"code": null,
"e": 8268,
"s": 8100,
"text": "select line, sourcefrom historyjoin sessionson sessions.session = history.sessionwhere sessions.start > '2020-01-01 00:00:00.000000'and history.source like '%pytest%';"
},
{
"code": null,
"e": 8419,
"s": 8268,
"text": "Once you’ve shaped your view to the rows you want, you can export it to an executable .py file as before, and convert it back to .ipynb with jupytext."
},
{
"code": null,
"e": 8593,
"s": 8419,
"text": "As you savor your relief at not having to rewrite your notebook from scratch, take a moment to ponder a few measures to guard against future expeditions into history.sqlite:"
},
{
"code": null,
"e": 8798,
"s": 8593,
"text": "Don’t connect identical frontends to the same kernel. In other words, don’t keep the same notebook open in multiple browser tabs. Using Visual Studio Code as your Jupyter IDE largely eliminates this risk."
},
{
"code": null,
"e": 8865,
"s": 8798,
"text": "Back up your IPython history database file regularly just in case."
},
{
"code": null,
"e": 8978,
"s": 8865,
"text": "Convert your notebooks to plaintext whenever possible — at least for backup. Jupytext makes this almost trivial."
},
{
"code": null,
"e": 9401,
"s": 8978,
"text": "Use IPython’s %store magic to store variables, macros, and aliases in the IPython database. All you need to do is find your ipython_config.py file in profile_default (or run ipython profile create if you don’t have one), and add this line: c.StoreMagics.autorestore = True. You can store, alias, and access anything from environment variables to small machine learning models if you want to. Here’s the full documentation."
},
{
"code": null,
"e": 9529,
"s": 9401,
"text": "What are some of your biggest challenges with Jupyter notebooks? Drop a comment on topics you’d like to tackle in future posts."
},
{
"code": null,
"e": 9583,
"s": 9529,
"text": "Power up your Python Projects with Visual Studio Code"
},
{
"code": null,
"e": 9623,
"s": 9583,
"text": "Advanced Google Skills for Data Science"
},
{
"code": null,
"e": 9632,
"s": 9623,
"text": "Jupytext"
},
{
"code": null,
"e": 9651,
"s": 9632,
"text": "IPython storemagic"
}
] |
How to draw a circular gradient in HTML5?
|
This method returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2.
createRadialGradient(x0, y0, r0, x1, y1, r1)
Here are the parameter values of the createRadialGradient() method −
You can try to run the following code to learn how to draw a radial/circular gradient in HTML5 −
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Radial Gradient</title>
</head>
<body>
<canvas id="newCanvas" width="450" height="250" style="border:1px solid
#d3d3d3;"></canvas>
<script>
var c = document.getElementById("newCanvas");
var ctxt = c.getContext("2d");
var linegrd = ctxt.createRadialGradient(75, 50, 5, 90, 60, 100);
linegrd.addColorStop(0, "#FFFFFF");
linegrd.addColorStop(1, "#66CC00");
ctxt.fillStyle = linegrd;
ctxt.fillRect(20, 10, 200, 150);
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "This method returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2."
},
{
"code": null,
"e": 1408,
"s": 1363,
"text": "createRadialGradient(x0, y0, r0, x1, y1, r1)"
},
{
"code": null,
"e": 1477,
"s": 1408,
"text": "Here are the parameter values of the createRadialGradient() method −"
},
{
"code": null,
"e": 1574,
"s": 1477,
"text": "You can try to run the following code to learn how to draw a radial/circular gradient in HTML5 −"
},
{
"code": null,
"e": 2165,
"s": 1574,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML5 Radial Gradient</title>\n </head>\n\n <body>\n <canvas id=\"newCanvas\" width=\"450\" height=\"250\" style=\"border:1px solid\n #d3d3d3;\"></canvas>\n <script>\n var c = document.getElementById(\"newCanvas\");\n var ctxt = c.getContext(\"2d\");\n var linegrd = ctxt.createRadialGradient(75, 50, 5, 90, 60, 100);\n linegrd.addColorStop(0, \"#FFFFFF\");\n linegrd.addColorStop(1, \"#66CC00\");\n ctxt.fillStyle = linegrd;\n ctxt.fillRect(20, 10, 200, 150);\n </script>\n </body>\n</html>"
}
] |
How to zoom a portion of an image and insert in the same plot in Matplotlib?
|
To zoom a portion of an image and insert in the same plot, we can take the following steps −
Create x and y points, using numpy.
Create x and y points, using numpy.
To zoom a part of an image, we can make data for x and y points, in that range.
To zoom a part of an image, we can make data for x and y points, in that range.
Plot x and y points (Step 1), using the plot() method with lw=2, color red and label.
Plot x and y points (Step 1), using the plot() method with lw=2, color red and label.
Use the legend() method to place text for the plot, Main curve.
Use the legend() method to place text for the plot, Main curve.
Create the axes using the axes() method by putting the rectangle’s coordinate.
Create the axes using the axes() method by putting the rectangle’s coordinate.
Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot.
Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot.
Use the legend() method to place text for the plot, zoomed curve.
Use the legend() method to place text for the plot, zoomed curve.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 1000)
y = np.sin(x)
x_zoom = np.linspace(-1, 1, 50)
y_zoom = np.sin(x_zoom)
plt.plot(x, y, c='red', lw=2, label="Main curve")
plt.legend()
axes = plt.axes([.30, .6, .20, .15])
axes.plot(x_zoom, y_zoom, c='green', lw=1, label="Zoomed curve")
axes.legend()
plt.show()
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To zoom a portion of an image and insert in the same plot, we can take the following steps −"
},
{
"code": null,
"e": 1191,
"s": 1155,
"text": "Create x and y points, using numpy."
},
{
"code": null,
"e": 1227,
"s": 1191,
"text": "Create x and y points, using numpy."
},
{
"code": null,
"e": 1307,
"s": 1227,
"text": "To zoom a part of an image, we can make data for x and y points, in that range."
},
{
"code": null,
"e": 1387,
"s": 1307,
"text": "To zoom a part of an image, we can make data for x and y points, in that range."
},
{
"code": null,
"e": 1473,
"s": 1387,
"text": "Plot x and y points (Step 1), using the plot() method with lw=2, color red and label."
},
{
"code": null,
"e": 1559,
"s": 1473,
"text": "Plot x and y points (Step 1), using the plot() method with lw=2, color red and label."
},
{
"code": null,
"e": 1623,
"s": 1559,
"text": "Use the legend() method to place text for the plot, Main curve."
},
{
"code": null,
"e": 1687,
"s": 1623,
"text": "Use the legend() method to place text for the plot, Main curve."
},
{
"code": null,
"e": 1766,
"s": 1687,
"text": "Create the axes using the axes() method by putting the rectangle’s coordinate."
},
{
"code": null,
"e": 1845,
"s": 1766,
"text": "Create the axes using the axes() method by putting the rectangle’s coordinate."
},
{
"code": null,
"e": 1962,
"s": 1845,
"text": "Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot."
},
{
"code": null,
"e": 2079,
"s": 1962,
"text": "Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot."
},
{
"code": null,
"e": 2145,
"s": 2079,
"text": "Use the legend() method to place text for the plot, zoomed curve."
},
{
"code": null,
"e": 2211,
"s": 2145,
"text": "Use the legend() method to place text for the plot, zoomed curve."
},
{
"code": null,
"e": 2257,
"s": 2211,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 2303,
"s": 2257,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 2735,
"s": 2303,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-5, 5, 1000)\ny = np.sin(x)\nx_zoom = np.linspace(-1, 1, 50)\ny_zoom = np.sin(x_zoom)\nplt.plot(x, y, c='red', lw=2, label=\"Main curve\")\nplt.legend()\naxes = plt.axes([.30, .6, .20, .15])\naxes.plot(x_zoom, y_zoom, c='green', lw=1, label=\"Zoomed curve\")\naxes.legend()\nplt.show()"
}
] |
Android RecyclerView Load More on Scroll with Example - GeeksforGeeks
|
30 Apr, 2021
Many apps display so many amounts of data in the form of a list. This data is so much so that it cannot be loaded at a time. If we load this data at a time then it may take so much loading time and degrades the performance of our RecyclerView. So to solve this we generally load the data in chunks and display it at a time. In this article, we will take a look at loading this data by showing a ProgressBar and load data in the infinite list.
We will be building a simple application in which we will be displaying the infinite list and we will load the data with the help of the ProgressBar below. We will be calling the same method to add data to our ArrayList. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file and allow internet permission in the manifests file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below line is used for volley library
implementation ‘com.android.volley:volley:1.1.1’
// below line is used for image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
Add internet permission in the manifests file.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/idNestedSV" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--linear layout for displaying our recycler view--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--recycler view for displaying our list of data and we are making nested scroll for our recycler view as false--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourses" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:nestedScrollingEnabled="false" /> <!--we are adding progress bar for the purpose of loading--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </androidx.core.widget.NestedScrollView>
Step 4: Working with Modal Class
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it.
Java
public class CourseModal { // variables for our course name, // description and duration. private String courseName; private String courseModes; private String courseTracks; private String courseImg; // constructor class. public CourseModal(String courseName, String courseModes, String courseTracks, String courseImg) { this.courseName = courseName; this.courseModes = courseModes; this.courseTracks = courseTracks; this.courseImg = courseImg; } // getter and setter methods. public String getCourseImg() { return courseImg; } public void setCourseImg(String courseImg) { this.courseImg = courseImg; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getcourseModes() { return courseModes; } public void setcourseModes(String courseModes) { this.courseModes = courseModes; } public String getcourseTracks() { return courseTracks; } public void setcourseTracks(String courseTracks) { this.courseTracks = courseTracks; }}
Step 5: Creating a layout file for our item of RecyclerView
Navigate to the app > res > layout > Right-click on it > New > Layout Resource File and name it as course_rv_item and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/idCVCOurseItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" app:cardCornerRadius="6dp" app:cardElevation="4dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!--image view for displaying course image--> <ImageView android:id="@+id/idIVCourse" android:layout_width="100dp" android:layout_height="100dp" android:layout_margin="10dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="2dp" android:layout_marginTop="10dp" android:layout_marginEnd="2dp" android:layout_toEndOf="@id/idIVCourse" android:gravity="center" android:orientation="vertical" android:padding="4dp"> <!--Textview for displaying our Course Name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="CourseName" android:textColor="@color/purple_500" android:textSize="18sp" android:textStyle="bold" /> <!--Textview for displaying our Course Duration--> <TextView android:id="@+id/idTVCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="Duration" android:textColor="@color/black" /> <!--Textview for displaying our Course Description--> <TextView android:id="@+id/idTVCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="Description" android:textColor="@color/black" /> </LinearLayout> </RelativeLayout> </androidx.cardview.widget.CardView>
Step 6: Creating an adapter class for setting our data
Similarly, create another Java class and name it as CourseRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { private Context context; private ArrayList<CourseModal> courseModalArrayList; // creating a constructor class. public CourseRVAdapter(Context context, ArrayList<CourseModal> courseModalArrayList) { this.context = context; this.courseModalArrayList = courseModalArrayList; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // passing our layout file for displaying our card item return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false)); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our text views from our modal class. CourseModal courses = courseModalArrayList.get(position); holder.courseNameTV.setText(courses.getCourseName()); holder.courseTracksTV.setText(courses.getcourseTracks()); holder.courseModesTV.setText(courses.getcourseModes()); Picasso.get().load(courses.getCourseImg()).into(holder.courseIV); } @Override public int getItemCount() { return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private final TextView courseNameTV; private final TextView courseTracksTV; private final TextView courseModesTV; private final ImageView courseIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseIV = itemView.findViewById(R.id.idIVCourse); courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseTracksTV = itemView.findViewById(R.id.idTVCourseDuration); courseModesTV = itemView.findViewById(R.id.idTVCourseDescription); } }}
Step 7: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonArrayRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our UI components. int count = 0; String url = "https://jsonkeeper.com/b/WO6S"; private ArrayList<CourseModal> courseArrayList; private RecyclerView courseRV; private CourseRVAdapter courseRVAdapter; private ProgressBar loadingPB; private NestedScrollView nestedSV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourses); loadingPB = findViewById(R.id.idPBLoading); nestedSV = findViewById(R.id.idNestedSV); // initializing our array list. courseArrayList = new ArrayList<>(); // calling a method to add data to our array list. getData(); // on below line we are setting layout manger to our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); courseRV.setLayoutManager(manager); // adding on scroll change listener method for our nested scroll view. nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // on scroll change we are checking when users scroll as bottom. if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) { // in this method we are incrementing page number, // making progress bar visible and calling get data method. count++; // on below line we are making our progress bar visible. loadingPB.setVisibility(View.VISIBLE); if (count < 20) { // on below line we are again calling // a method to load data in our array list. getData(); } } } }); } private void getData() { // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in this case the data we are getting is in the form // of array so we are making a json array request. // below is the line where we are making an json array // request and then extracting data from each json object. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { courseRV.setVisibility(View.VISIBLE); for (int i = 0; i < response.length(); i++) { // creating a new json object and // getting each object from our json array. try { // we are getting each json object. JSONObject responseObj = response.getJSONObject(i); // now we get our response from API in json object format. // in below line we are extracting a string with // its key value from our json object. // similarly we are extracting all the strings from our json object. String courseName = responseObj.getString("courseName"); String courseTracks = responseObj.getString("courseTracks"); String courseMode = responseObj.getString("courseMode"); String courseImageURL = responseObj.getString("courseimg"); courseArrayList.add(new CourseModal(courseName, courseMode, courseTracks, courseImageURL)); // on below line we are adding our array list to our adapter class. courseRVAdapter = new CourseRVAdapter(MainActivity.this, courseArrayList); // on below line we are setting // adapter to our recycler view. courseRV.setAdapter(courseRVAdapter); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonArrayRequest); }}
Now run your app and see the output of the app.
Output:
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25169,
"s": 24725,
"text": "Many apps display so many amounts of data in the form of a list. This data is so much so that it cannot be loaded at a time. If we load this data at a time then it may take so much loading time and degrades the performance of our RecyclerView. So to solve this we generally load the data in chunks and display it at a time. In this article, we will take a look at loading this data by showing a ProgressBar and load data in the infinite list. "
},
{
"code": null,
"e": 25555,
"s": 25169,
"text": "We will be building a simple application in which we will be displaying the infinite list and we will load the data with the help of the ProgressBar below. We will be calling the same method to add data to our ArrayList. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25584,
"s": 25555,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25746,
"s": 25584,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25857,
"s": 25746,
"text": "Step 2: Add the below dependency in your build.gradle file and allow internet permission in the manifests file"
},
{
"code": null,
"e": 26153,
"s": 25857,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. "
},
{
"code": null,
"e": 26346,
"s": 26153,
"text": "// below line is used for volley library\nimplementation ‘com.android.volley:volley:1.1.1’\n\n// below line is used for image loading library\nimplementation ‘com.squareup.picasso:picasso:2.71828’"
},
{
"code": null,
"e": 26393,
"s": 26346,
"text": "Add internet permission in the manifests file."
},
{
"code": null,
"e": 26455,
"s": 26393,
"text": "<uses-permission android:name=\"android.permission.INTERNET\"/>"
},
{
"code": null,
"e": 26503,
"s": 26455,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26646,
"s": 26503,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26650,
"s": 26646,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.core.widget.NestedScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/idNestedSV\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--linear layout for displaying our recycler view--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--recycler view for displaying our list of data and we are making nested scroll for our recycler view as false--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourses\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_weight=\"1\" android:nestedScrollingEnabled=\"false\" /> <!--we are adding progress bar for the purpose of loading--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </LinearLayout> </androidx.core.widget.NestedScrollView>",
"e": 27908,
"s": 26650,
"text": null
},
{
"code": null,
"e": 27942,
"s": 27908,
"text": "Step 4: Working with Modal Class "
},
{
"code": null,
"e": 28092,
"s": 27942,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it. "
},
{
"code": null,
"e": 28097,
"s": 28092,
"text": "Java"
},
{
"code": "public class CourseModal { // variables for our course name, // description and duration. private String courseName; private String courseModes; private String courseTracks; private String courseImg; // constructor class. public CourseModal(String courseName, String courseModes, String courseTracks, String courseImg) { this.courseName = courseName; this.courseModes = courseModes; this.courseTracks = courseTracks; this.courseImg = courseImg; } // getter and setter methods. public String getCourseImg() { return courseImg; } public void setCourseImg(String courseImg) { this.courseImg = courseImg; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getcourseModes() { return courseModes; } public void setcourseModes(String courseModes) { this.courseModes = courseModes; } public String getcourseTracks() { return courseTracks; } public void setcourseTracks(String courseTracks) { this.courseTracks = courseTracks; }}",
"e": 29297,
"s": 28097,
"text": null
},
{
"code": null,
"e": 29357,
"s": 29297,
"text": "Step 5: Creating a layout file for our item of RecyclerView"
},
{
"code": null,
"e": 29502,
"s": 29357,
"text": "Navigate to the app > res > layout > Right-click on it > New > Layout Resource File and name it as course_rv_item and add the below code to it. "
},
{
"code": null,
"e": 29506,
"s": 29502,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/idCVCOurseItem\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"6dp\" app:cardElevation=\"4dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!--image view for displaying course image--> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"2dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"2dp\" android:layout_toEndOf=\"@id/idIVCourse\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"4dp\"> <!--Textview for displaying our Course Name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"2dp\" android:text=\"CourseName\" android:textColor=\"@color/purple_500\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <!--Textview for displaying our Course Duration--> <TextView android:id=\"@+id/idTVCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"2dp\" android:text=\"Duration\" android:textColor=\"@color/black\" /> <!--Textview for displaying our Course Description--> <TextView android:id=\"@+id/idTVCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"2dp\" android:text=\"Description\" android:textColor=\"@color/black\" /> </LinearLayout> </RelativeLayout> </androidx.cardview.widget.CardView>",
"e": 31965,
"s": 29506,
"text": null
},
{
"code": null,
"e": 32021,
"s": 31965,
"text": "Step 6: Creating an adapter class for setting our data "
},
{
"code": null,
"e": 32182,
"s": 32021,
"text": "Similarly, create another Java class and name it as CourseRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 32187,
"s": 32182,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { private Context context; private ArrayList<CourseModal> courseModalArrayList; // creating a constructor class. public CourseRVAdapter(Context context, ArrayList<CourseModal> courseModalArrayList) { this.context = context; this.courseModalArrayList = courseModalArrayList; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // passing our layout file for displaying our card item return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false)); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our text views from our modal class. CourseModal courses = courseModalArrayList.get(position); holder.courseNameTV.setText(courses.getCourseName()); holder.courseTracksTV.setText(courses.getcourseTracks()); holder.courseModesTV.setText(courses.getcourseModes()); Picasso.get().load(courses.getCourseImg()).into(holder.courseIV); } @Override public int getItemCount() { return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private final TextView courseNameTV; private final TextView courseTracksTV; private final TextView courseModesTV; private final ImageView courseIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseIV = itemView.findViewById(R.id.idIVCourse); courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseTracksTV = itemView.findViewById(R.id.idTVCourseDuration); courseModesTV = itemView.findViewById(R.id.idTVCourseDescription); } }}",
"e": 34538,
"s": 32187,
"text": null
},
{
"code": null,
"e": 34586,
"s": 34538,
"text": "Step 7: Working with the MainActivity.java file"
},
{
"code": null,
"e": 34776,
"s": 34586,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 34781,
"s": 34776,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonArrayRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our UI components. int count = 0; String url = \"https://jsonkeeper.com/b/WO6S\"; private ArrayList<CourseModal> courseArrayList; private RecyclerView courseRV; private CourseRVAdapter courseRVAdapter; private ProgressBar loadingPB; private NestedScrollView nestedSV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourses); loadingPB = findViewById(R.id.idPBLoading); nestedSV = findViewById(R.id.idNestedSV); // initializing our array list. courseArrayList = new ArrayList<>(); // calling a method to add data to our array list. getData(); // on below line we are setting layout manger to our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); courseRV.setLayoutManager(manager); // adding on scroll change listener method for our nested scroll view. nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // on scroll change we are checking when users scroll as bottom. if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) { // in this method we are incrementing page number, // making progress bar visible and calling get data method. count++; // on below line we are making our progress bar visible. loadingPB.setVisibility(View.VISIBLE); if (count < 20) { // on below line we are again calling // a method to load data in our array list. getData(); } } } }); } private void getData() { // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in this case the data we are getting is in the form // of array so we are making a json array request. // below is the line where we are making an json array // request and then extracting data from each json object. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { courseRV.setVisibility(View.VISIBLE); for (int i = 0; i < response.length(); i++) { // creating a new json object and // getting each object from our json array. try { // we are getting each json object. JSONObject responseObj = response.getJSONObject(i); // now we get our response from API in json object format. // in below line we are extracting a string with // its key value from our json object. // similarly we are extracting all the strings from our json object. String courseName = responseObj.getString(\"courseName\"); String courseTracks = responseObj.getString(\"courseTracks\"); String courseMode = responseObj.getString(\"courseMode\"); String courseImageURL = responseObj.getString(\"courseimg\"); courseArrayList.add(new CourseModal(courseName, courseMode, courseTracks, courseImageURL)); // on below line we are adding our array list to our adapter class. courseRVAdapter = new CourseRVAdapter(MainActivity.this, courseArrayList); // on below line we are setting // adapter to our recycler view. courseRV.setAdapter(courseRVAdapter); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, \"Fail to get the data..\", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonArrayRequest); }}",
"e": 40220,
"s": 34781,
"text": null
},
{
"code": null,
"e": 40269,
"s": 40220,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 40277,
"s": 40269,
"text": "Output:"
},
{
"code": null,
"e": 40284,
"s": 40277,
"text": "Picked"
},
{
"code": null,
"e": 40292,
"s": 40284,
"text": "Android"
},
{
"code": null,
"e": 40297,
"s": 40292,
"text": "Java"
},
{
"code": null,
"e": 40302,
"s": 40297,
"text": "Java"
},
{
"code": null,
"e": 40310,
"s": 40302,
"text": "Android"
},
{
"code": null,
"e": 40408,
"s": 40310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40417,
"s": 40408,
"text": "Comments"
},
{
"code": null,
"e": 40430,
"s": 40417,
"text": "Old Comments"
},
{
"code": null,
"e": 40469,
"s": 40430,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 40519,
"s": 40469,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 40570,
"s": 40519,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 40612,
"s": 40570,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 40650,
"s": 40612,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 40665,
"s": 40650,
"text": "Arrays in Java"
},
{
"code": null,
"e": 40709,
"s": 40665,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 40731,
"s": 40709,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 40756,
"s": 40731,
"text": "Reverse a string in Java"
}
] |
How to use __dir__ in PHP?
|
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
Consider the following directory structure −
A directory called "master", that has two files named 'worker_1', and 'worker_2'. The master directory itself is a subfolder of the main project directory.
The project directory also contains an index.php file.
Consider having two files in a directory called inc, which is a subfolder of our project's directory, where the index.php file lies −
project_directory
├── master
│ ├── worker_1.php
│ └── worker_2.php
└── index.php
If we execute the code −
include "master/worker_1.php";
from the index.php, it runs successfully.
But to run worker_1.php by including worker_2.php, a relative include to the index.php file has to be done, as shown below −
include "master/worker_2.php";
Using __DIR__ will get this running. From worker_1.php the below code can be executed −
<?php
include __DIR__ . "/worker_2.php";
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file."
},
{
"code": null,
"e": 1357,
"s": 1312,
"text": "Consider the following directory structure −"
},
{
"code": null,
"e": 1513,
"s": 1357,
"text": "A directory called \"master\", that has two files named 'worker_1', and 'worker_2'. The master directory itself is a subfolder of the main project directory."
},
{
"code": null,
"e": 1568,
"s": 1513,
"text": "The project directory also contains an index.php file."
},
{
"code": null,
"e": 1702,
"s": 1568,
"text": "Consider having two files in a directory called inc, which is a subfolder of our project's directory, where the index.php file lies −"
},
{
"code": null,
"e": 1783,
"s": 1702,
"text": "project_directory\n├── master\n│ ├── worker_1.php\n│ └── worker_2.php\n└── index.php"
},
{
"code": null,
"e": 1808,
"s": 1783,
"text": "If we execute the code −"
},
{
"code": null,
"e": 1839,
"s": 1808,
"text": "include \"master/worker_1.php\";"
},
{
"code": null,
"e": 1881,
"s": 1839,
"text": "from the index.php, it runs successfully."
},
{
"code": null,
"e": 2006,
"s": 1881,
"text": "But to run worker_1.php by including worker_2.php, a relative include to the index.php file has to be done, as shown below −"
},
{
"code": null,
"e": 2037,
"s": 2006,
"text": "include \"master/worker_2.php\";"
},
{
"code": null,
"e": 2125,
"s": 2037,
"text": "Using __DIR__ will get this running. From worker_1.php the below code can be executed −"
},
{
"code": null,
"e": 2166,
"s": 2125,
"text": "<?php\ninclude __DIR__ . \"/worker_2.php\";"
}
] |
How to set viewport height and width in CSS
|
To set viewport height in CSS:
h1 {
font-size: 4.0vh;
}
To set viewport width in CSS:
h1 {
font-size: 5.5vw;
}
|
[
{
"code": null,
"e": 1093,
"s": 1062,
"text": "To set viewport height in CSS:"
},
{
"code": null,
"e": 1121,
"s": 1093,
"text": "h1 {\n font-size: 4.0vh;\n}"
},
{
"code": null,
"e": 1151,
"s": 1121,
"text": "To set viewport width in CSS:"
},
{
"code": null,
"e": 1179,
"s": 1151,
"text": "h1 {\n font-size: 5.5vw;\n}"
}
] |
Nested Classes in C++ - GeeksforGeeks
|
04 Jan, 2019
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.
For example, program 1 compiles without any error and program 2 fails in compilation.
Program 1
#include<iostream> using namespace std; /* start of Enclosing class declaration */ class Enclosing { private: int x; /* start of Nested class declaration */ class Nested { int y; void NestedFun(Enclosing *e) { cout<<e->x; // works fine: nested class can access // private members of Enclosing class } }; // declaration Nested class ends here}; // declaration Enclosing class ends here int main(){ }
Program 2
#include<iostream> using namespace std; /* start of Enclosing class declaration */ class Enclosing { int x; /* start of Nested class declaration */ class Nested { int y; }; // declaration Nested class ends here void EnclosingFun(Nested *n) { cout<<n->y; // Compiler Error: y is private in Nested } }; // declaration Enclosing class ends here int main(){ }
References:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akshit Agarwal 3
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Substring in C++
Multidimensional Arrays in C / C++
C++ Data Types
Sorting a vector in C++
Set in C++ Standard Template Library (STL)
2D Vector In C++ With User Defined Size
|
[
{
"code": null,
"e": 25393,
"s": 25365,
"text": "\n04 Jan, 2019"
},
{
"code": null,
"e": 25679,
"s": 25393,
"text": "A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed."
},
{
"code": null,
"e": 25765,
"s": 25679,
"text": "For example, program 1 compiles without any error and program 2 fails in compilation."
},
{
"code": null,
"e": 25775,
"s": 25765,
"text": "Program 1"
},
{
"code": "#include<iostream> using namespace std; /* start of Enclosing class declaration */ class Enclosing { private: int x; /* start of Nested class declaration */ class Nested { int y; void NestedFun(Enclosing *e) { cout<<e->x; // works fine: nested class can access // private members of Enclosing class } }; // declaration Nested class ends here}; // declaration Enclosing class ends here int main(){ }",
"e": 26269,
"s": 25775,
"text": null
},
{
"code": null,
"e": 26279,
"s": 26269,
"text": "Program 2"
},
{
"code": "#include<iostream> using namespace std; /* start of Enclosing class declaration */ class Enclosing { int x; /* start of Nested class declaration */ class Nested { int y; }; // declaration Nested class ends here void EnclosingFun(Nested *n) { cout<<n->y; // Compiler Error: y is private in Nested } }; // declaration Enclosing class ends here int main(){ }",
"e": 26701,
"s": 26279,
"text": null
},
{
"code": null,
"e": 26778,
"s": 26701,
"text": "References:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf"
},
{
"code": null,
"e": 26903,
"s": 26778,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26920,
"s": 26903,
"text": "Akshit Agarwal 3"
},
{
"code": null,
"e": 26924,
"s": 26920,
"text": "C++"
},
{
"code": null,
"e": 26928,
"s": 26924,
"text": "CPP"
},
{
"code": null,
"e": 27026,
"s": 26928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27057,
"s": 27026,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27085,
"s": 27057,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27113,
"s": 27085,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27147,
"s": 27113,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 27164,
"s": 27147,
"text": "Substring in C++"
},
{
"code": null,
"e": 27199,
"s": 27164,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27214,
"s": 27199,
"text": "C++ Data Types"
},
{
"code": null,
"e": 27238,
"s": 27214,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27281,
"s": 27238,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python program to find difference between current time and given time
|
30 Jan, 2020
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format.
Examples:
Input : h1=7, m1=20, h2=9, m2=45Output : 2 : 25The current time is 7 : 20 and given time is 9 : 45.The difference between them is 145 minutes.The result is 2 : 25 after converting to h : m format.
Input : h1=15, m1=23, h2=18, m2=54Output : 3 : 31The current time is 15 : 23 and given time is 18 : 54.The difference between them is 211 minutes.The result is 3 : 31 after converting to h : m format.
Input : h1=16, m1=20, h2=16, m2=20Output : Both times are sameThe current time is 16 : 20 and given time is also 16 : 20.The difference between them is 0 minutes.As the difference is 0, we are printing “Both are same times”.
Approach:
convert both the times into minutes
find the difference in minutes
if difference is 0, print “Both are same times”
else convert difference into h : m format and print
Below is the implementation.
# Python program to find the# difference between two times # function to obtain the time# in minutes formdef difference(h1, m1, h2, m2): # convert h1 : m1 into # minutes t1 = h1 * 60 + m1 # convert h2 : m2 into # minutes t2 = h2 * 60 + m2 if (t1 == t2): print("Both are same times") return else: # calculating the difference diff = t2-t1 # calculating hours from # difference h = (int(diff / 60)) % 24 # calculating minutes from # difference m = diff % 60 print(h, ":", m) # Driver's codeif __name__ == "__main__": difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) # This code is contributed by SrujayReddy
Output:
2 : 25
3 : 31
Both are same times
Python datetime-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 306,
"s": 52,
"text": "Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format."
},
{
"code": null,
"e": 316,
"s": 306,
"text": "Examples:"
},
{
"code": null,
"e": 513,
"s": 316,
"text": "Input : h1=7, m1=20, h2=9, m2=45Output : 2 : 25The current time is 7 : 20 and given time is 9 : 45.The difference between them is 145 minutes.The result is 2 : 25 after converting to h : m format."
},
{
"code": null,
"e": 714,
"s": 513,
"text": "Input : h1=15, m1=23, h2=18, m2=54Output : 3 : 31The current time is 15 : 23 and given time is 18 : 54.The difference between them is 211 minutes.The result is 3 : 31 after converting to h : m format."
},
{
"code": null,
"e": 939,
"s": 714,
"text": "Input : h1=16, m1=20, h2=16, m2=20Output : Both times are sameThe current time is 16 : 20 and given time is also 16 : 20.The difference between them is 0 minutes.As the difference is 0, we are printing “Both are same times”."
},
{
"code": null,
"e": 949,
"s": 939,
"text": "Approach:"
},
{
"code": null,
"e": 985,
"s": 949,
"text": "convert both the times into minutes"
},
{
"code": null,
"e": 1016,
"s": 985,
"text": "find the difference in minutes"
},
{
"code": null,
"e": 1064,
"s": 1016,
"text": "if difference is 0, print “Both are same times”"
},
{
"code": null,
"e": 1116,
"s": 1064,
"text": "else convert difference into h : m format and print"
},
{
"code": null,
"e": 1145,
"s": 1116,
"text": "Below is the implementation."
},
{
"code": "# Python program to find the# difference between two times # function to obtain the time# in minutes formdef difference(h1, m1, h2, m2): # convert h1 : m1 into # minutes t1 = h1 * 60 + m1 # convert h2 : m2 into # minutes t2 = h2 * 60 + m2 if (t1 == t2): print(\"Both are same times\") return else: # calculating the difference diff = t2-t1 # calculating hours from # difference h = (int(diff / 60)) % 24 # calculating minutes from # difference m = diff % 60 print(h, \":\", m) # Driver's codeif __name__ == \"__main__\": difference(7, 20, 9, 45) difference(15, 23, 18, 54) difference(16, 20, 16, 20) # This code is contributed by SrujayReddy",
"e": 1924,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1932,
"s": 1924,
"text": "Output:"
},
{
"code": null,
"e": 1967,
"s": 1932,
"text": "2 : 25\n3 : 31\nBoth are same times\n"
},
{
"code": null,
"e": 1991,
"s": 1967,
"text": "Python datetime-program"
},
{
"code": null,
"e": 1998,
"s": 1991,
"text": "Python"
},
{
"code": null,
"e": 2096,
"s": 1998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2138,
"s": 2096,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2160,
"s": 2138,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2192,
"s": 2160,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2221,
"s": 2192,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2248,
"s": 2221,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2269,
"s": 2248,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2292,
"s": 2269,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2328,
"s": 2292,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2384,
"s": 2328,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Splitting Strings in R programming – strsplit() method
|
11 Nov, 2021
strsplit() method in R Programming Language is used to split the string by using a delimiter.
Syntax: strsplit(string, split, fixed)
Parameters:
string: Input vector or string.
split: It is a character of string to being split.
fixed: Match the split or use the regular expression.
Return: Returns the list of words or sentences after split.
Here, we are using strsplit() along with delimiter, delimiter is a character of an existing string to being removed from the string and display out.
R
# R program to split a string # Given Stringgfg < - "Geeks For Geeks" # Using strsplit() methodanswer < - strsplit(gfg, " ") print(answer)
Output:
[1] "Geeks" "For" "Geeks"
Here, we are using regular expressions in delimiter to split the string.
R
# R program to split a string # Given Stringgfg <- "Geeks9For2Geeks" # Using strsplit() methodanswer <- strsplit(gfg, split = "[0-9]+") print(answer)
Output:
[1] "Geeks" "For" "Geeks"
We can also manipulate with date using strsplit(), only we need to understand the date formatting, for example in this date( 2-07-2020) following the same pattern (-), so we can remove them using delimiter along with “-“.
R
string_date<-c("2-07-2020","5-07-2020","6-07-2020", "7-07-2020","8-07-2020")result<-strsplit(string_date,split = "-")print(result)
Output:
[[1]]
[1] "2" "07" "2020"
[[2]]
[1] "5" "07" "2020"
[[3]]
[1] "6" "07" "2020"
[[4]]
[1] "7" "07" "2020"
[[5]]
[1] "8" "07" "2020"
kumar_satyam
surinderdawra388
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 122,
"s": 28,
"text": "strsplit() method in R Programming Language is used to split the string by using a delimiter."
},
{
"code": null,
"e": 161,
"s": 122,
"text": "Syntax: strsplit(string, split, fixed)"
},
{
"code": null,
"e": 173,
"s": 161,
"text": "Parameters:"
},
{
"code": null,
"e": 205,
"s": 173,
"text": "string: Input vector or string."
},
{
"code": null,
"e": 256,
"s": 205,
"text": "split: It is a character of string to being split."
},
{
"code": null,
"e": 310,
"s": 256,
"text": "fixed: Match the split or use the regular expression."
},
{
"code": null,
"e": 371,
"s": 310,
"text": "Return: Returns the list of words or sentences after split. "
},
{
"code": null,
"e": 520,
"s": 371,
"text": "Here, we are using strsplit() along with delimiter, delimiter is a character of an existing string to being removed from the string and display out."
},
{
"code": null,
"e": 522,
"s": 520,
"text": "R"
},
{
"code": "# R program to split a string # Given Stringgfg < - \"Geeks For Geeks\" # Using strsplit() methodanswer < - strsplit(gfg, \" \") print(answer)",
"e": 661,
"s": 522,
"text": null
},
{
"code": null,
"e": 669,
"s": 661,
"text": "Output:"
},
{
"code": null,
"e": 697,
"s": 669,
"text": "[1] \"Geeks\" \"For\" \"Geeks\""
},
{
"code": null,
"e": 770,
"s": 697,
"text": "Here, we are using regular expressions in delimiter to split the string."
},
{
"code": null,
"e": 772,
"s": 770,
"text": "R"
},
{
"code": "# R program to split a string # Given Stringgfg <- \"Geeks9For2Geeks\" # Using strsplit() methodanswer <- strsplit(gfg, split = \"[0-9]+\") print(answer)",
"e": 922,
"s": 772,
"text": null
},
{
"code": null,
"e": 930,
"s": 922,
"text": "Output:"
},
{
"code": null,
"e": 958,
"s": 930,
"text": "[1] \"Geeks\" \"For\" \"Geeks\""
},
{
"code": null,
"e": 1181,
"s": 958,
"text": "We can also manipulate with date using strsplit(), only we need to understand the date formatting, for example in this date( 2-07-2020) following the same pattern (-), so we can remove them using delimiter along with “-“. "
},
{
"code": null,
"e": 1183,
"s": 1181,
"text": "R"
},
{
"code": "string_date<-c(\"2-07-2020\",\"5-07-2020\",\"6-07-2020\", \"7-07-2020\",\"8-07-2020\")result<-strsplit(string_date,split = \"-\")print(result)",
"e": 1328,
"s": 1183,
"text": null
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Output:"
},
{
"code": null,
"e": 1495,
"s": 1336,
"text": "[[1]]\n[1] \"2\" \"07\" \"2020\"\n\n[[2]]\n[1] \"5\" \"07\" \"2020\"\n\n[[3]]\n[1] \"6\" \"07\" \"2020\"\n\n[[4]]\n[1] \"7\" \"07\" \"2020\"\n\n[[5]]\n[1] \"8\" \"07\" \"2020\""
},
{
"code": null,
"e": 1508,
"s": 1495,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1525,
"s": 1508,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1536,
"s": 1525,
"text": "R Language"
},
{
"code": null,
"e": 1634,
"s": 1536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1686,
"s": 1634,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 1738,
"s": 1686,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1796,
"s": 1738,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1831,
"s": 1796,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1875,
"s": 1831,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 1913,
"s": 1875,
"text": "R Programming Language - Introduction"
},
{
"code": null,
"e": 1951,
"s": 1913,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2000,
"s": 1951,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2017,
"s": 2000,
"text": "R - if statement"
}
] |
Maximum 0’s between two immediate 1’s in binary representation
|
31 May, 2022
Given a number n, the task is to find the maximum 0’s between two immediate 1’s in binary representation of given n. Return -1 if binary representation contains less than two 1’s.
Examples :
Input : n = 47
Output: 1
// binary of n = 47 is 101111
Input : n = 549
Output: 3
// binary of n = 549 is 1000100101
Input : n = 1030
Output: 7
// binary of n = 1030 is 10000000110
Input : n = 8
Output: -1
// There is only one 1 in binary representation
// of 8.
The idea to solve this problem is to use shift operator. We just need to find the position of two immediate 1’s in binary representation of n and maximize the difference of these position.
Return -1 if number is 0 or is a power of 2. In these cases there are less than two 1’s in binary representation.
Initialize variable prev with position of first right most 1, it basically stores the position of previously seen 1.
Now take another variable cur which stores the position of immediate 1 just after prev.
Now take difference of cur – prev – 1, it will be the number of 0’s between to immediate 1’s and compare it with previous max value of 0’s and update prev i.e; prev=cur for next iteration.
Use auxiliary variable setBit, which scans all bits of n and helps to detect if current bits is 0 or 1.
Initially check if N is 0 or power of 2.
Below is the implementation of the above idea :
C++
Java
Python3
C#
Javascript
// C++ program to find maximum number of 0's// in binary representation of a number#include <bits/stdc++.h>using namespace std; // Returns maximum 0's between two immediate// 1's in binary representation of numberint maxZeros(int n){ // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) return -1; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= sizeof(int) * 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = INT_MIN, cur = prev; for (int j = i + 1; j <= sizeof(int) * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) max0 = cur - prev - 1; // update prev prev = cur; } setBit = setBit << 1; } return max0;} // Driver program to run the caseint main(){ int n = 549; // Initially check that number must not // be 0 and power of 2 cout << maxZeros(n); return 0;}
// Java program to find maximum number of 0's// in binary representation of a numberclass GFG { // Returns maximum 0's between two immediate // 1's in binary representation of number static int maxZeros(int n) { // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) { return -1; } //int size in java is 4 byte byte b = 4; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= b* 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = Integer.MIN_VALUE, cur = prev; for (int j = i + 1; j <= b * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) { max0 = cur - prev - 1; } // update prev prev = cur; } setBit = setBit << 1; } return max0; } // Driver program to run the case static public void main(String[] args) { int n = 549; // Initially check that number must not // be 0 and power of 2 System.out.println(maxZeros(n)); }} // This code is contributed by 29AjayKumar
# Python3 program to find maximum number of# 0's in binary representation of a number # Returns maximum 0's between two immediate# 1's in binary representation of numberdef maxZeros(n): # If there are no 1's or there is # only 1, then return -1 if (n == 0 or (n & (n - 1)) == 0): return -1 # loop to find position of right most 1 # here sizeof is 4 that means total 32 bits setBit = 1 prev = 0 i = 1 while(i < 33): prev += 1 # we have found right most 1 if ((n & setBit) == setBit): setBit = setBit << 1 break # left shift setBit by 1 to check next bit setBit = setBit << 1 # now loop through for remaining bits and find # position of immediate 1 after prev max0 = -10**9 cur = prev for j in range(i + 1, 33): cur += 1 # if current bit is set, then compare # difference of cur - prev -1 with # previous maximum number of zeros if ((n & setBit) == setBit): if (max0 < (cur - prev - 1)): max0 = cur - prev - 1 # update prev prev = cur setBit = setBit << 1 return max0 # Driver Coden = 549 # Initially check that number must not# be 0 and power of 2print(maxZeros(n)) # This code is contributed by Mohit Kumar
// C# program to find maximum number of 0's// in binary representation of a numberusing System; class GFG { // Returns maximum 0's between two immediate // 1's in binary representation of number static int maxZeros(int n) { // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) return -1; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= sizeof(int) * 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = int.MinValue, cur = prev; for (int j = i + 1; j <= sizeof(int) * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) max0 = cur - prev - 1; // update prev prev = cur; } setBit = setBit << 1; } return max0; } // Driver program to run the case static public void Main() { int n = 549; // Initially check that number must not // be 0 and power of 2 Console.WriteLine(maxZeros(n)); }} // This code is contributed by vt_m.
<script> // JavaScript program to find maximum number of 0's// in binary representation of a number // Returns maximum 0's between two immediate// 1's in binary representation of numberfunction maxZeros(n){ // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) { return -1; } // int size in java is 4 byte let b = 4; // Loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits let setBit = 1, prev = 0, i; for(i = 1; i <= b* 8; i++) { prev++; // We have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // Left shift setBit by 1 // to check next bit setBit = setBit << 1; } // Now loop through for remaining bits // and find position of immediate 1 after prev let max0 = Number.MIN_VALUE, cur = prev; for(let j = i + 1; j <= b * 8; j++) { cur++; // If current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) { max0 = cur - prev - 1; } // Update prev prev = cur; } setBit = setBit << 1; } return max0;} // Driver Codelet n = 549; // Initially check that number must not// be 0 and power of 2document.write(maxZeros(n)); // This code is contributed by code_hunt </script>
Output:
3
Time Complexity: O(1), because it is taking constant time irrespective of the input n.
Auxiliary Space: O(1)This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
29AjayKumar
mohit kumar 29
code_hunt
arorakashish0911
shivamanandrj9
binary-representation
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Binary representation of a given number
Bits manipulation (Important tactics)
Find most significant set bit of a number
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
C++ bitset and its application
Rotate bits of a number
Bit Fields in C
Find the element that appears once
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Given a number n, the task is to find the maximum 0’s between two immediate 1’s in binary representation of given n. Return -1 if binary representation contains less than two 1’s."
},
{
"code": null,
"e": 244,
"s": 232,
"text": "Examples : "
},
{
"code": null,
"e": 509,
"s": 244,
"text": "Input : n = 47\nOutput: 1\n// binary of n = 47 is 101111\n\nInput : n = 549\nOutput: 3\n// binary of n = 549 is 1000100101\n\nInput : n = 1030\nOutput: 7\n// binary of n = 1030 is 10000000110\n\nInput : n = 8\nOutput: -1\n// There is only one 1 in binary representation\n// of 8."
},
{
"code": null,
"e": 699,
"s": 509,
"text": "The idea to solve this problem is to use shift operator. We just need to find the position of two immediate 1’s in binary representation of n and maximize the difference of these position. "
},
{
"code": null,
"e": 813,
"s": 699,
"text": "Return -1 if number is 0 or is a power of 2. In these cases there are less than two 1’s in binary representation."
},
{
"code": null,
"e": 930,
"s": 813,
"text": "Initialize variable prev with position of first right most 1, it basically stores the position of previously seen 1."
},
{
"code": null,
"e": 1018,
"s": 930,
"text": "Now take another variable cur which stores the position of immediate 1 just after prev."
},
{
"code": null,
"e": 1207,
"s": 1018,
"text": "Now take difference of cur – prev – 1, it will be the number of 0’s between to immediate 1’s and compare it with previous max value of 0’s and update prev i.e; prev=cur for next iteration."
},
{
"code": null,
"e": 1311,
"s": 1207,
"text": "Use auxiliary variable setBit, which scans all bits of n and helps to detect if current bits is 0 or 1."
},
{
"code": null,
"e": 1352,
"s": 1311,
"text": "Initially check if N is 0 or power of 2."
},
{
"code": null,
"e": 1400,
"s": 1352,
"text": "Below is the implementation of the above idea :"
},
{
"code": null,
"e": 1404,
"s": 1400,
"text": "C++"
},
{
"code": null,
"e": 1409,
"s": 1404,
"text": "Java"
},
{
"code": null,
"e": 1417,
"s": 1409,
"text": "Python3"
},
{
"code": null,
"e": 1420,
"s": 1417,
"text": "C#"
},
{
"code": null,
"e": 1431,
"s": 1420,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum number of 0's// in binary representation of a number#include <bits/stdc++.h>using namespace std; // Returns maximum 0's between two immediate// 1's in binary representation of numberint maxZeros(int n){ // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) return -1; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= sizeof(int) * 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = INT_MIN, cur = prev; for (int j = i + 1; j <= sizeof(int) * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) max0 = cur - prev - 1; // update prev prev = cur; } setBit = setBit << 1; } return max0;} // Driver program to run the caseint main(){ int n = 549; // Initially check that number must not // be 0 and power of 2 cout << maxZeros(n); return 0;}",
"e": 2917,
"s": 1431,
"text": null
},
{
"code": "// Java program to find maximum number of 0's// in binary representation of a numberclass GFG { // Returns maximum 0's between two immediate // 1's in binary representation of number static int maxZeros(int n) { // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) { return -1; } //int size in java is 4 byte byte b = 4; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= b* 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = Integer.MIN_VALUE, cur = prev; for (int j = i + 1; j <= b * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) { max0 = cur - prev - 1; } // update prev prev = cur; } setBit = setBit << 1; } return max0; } // Driver program to run the case static public void main(String[] args) { int n = 549; // Initially check that number must not // be 0 and power of 2 System.out.println(maxZeros(n)); }} // This code is contributed by 29AjayKumar",
"e": 4704,
"s": 2917,
"text": null
},
{
"code": "# Python3 program to find maximum number of# 0's in binary representation of a number # Returns maximum 0's between two immediate# 1's in binary representation of numberdef maxZeros(n): # If there are no 1's or there is # only 1, then return -1 if (n == 0 or (n & (n - 1)) == 0): return -1 # loop to find position of right most 1 # here sizeof is 4 that means total 32 bits setBit = 1 prev = 0 i = 1 while(i < 33): prev += 1 # we have found right most 1 if ((n & setBit) == setBit): setBit = setBit << 1 break # left shift setBit by 1 to check next bit setBit = setBit << 1 # now loop through for remaining bits and find # position of immediate 1 after prev max0 = -10**9 cur = prev for j in range(i + 1, 33): cur += 1 # if current bit is set, then compare # difference of cur - prev -1 with # previous maximum number of zeros if ((n & setBit) == setBit): if (max0 < (cur - prev - 1)): max0 = cur - prev - 1 # update prev prev = cur setBit = setBit << 1 return max0 # Driver Coden = 549 # Initially check that number must not# be 0 and power of 2print(maxZeros(n)) # This code is contributed by Mohit Kumar",
"e": 6017,
"s": 4704,
"text": null
},
{
"code": "// C# program to find maximum number of 0's// in binary representation of a numberusing System; class GFG { // Returns maximum 0's between two immediate // 1's in binary representation of number static int maxZeros(int n) { // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) return -1; // loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits int setBit = 1, prev = 0, i; for (i = 1; i <= sizeof(int) * 8; i++) { prev++; // we have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // left shift setBit by 1 to check next bit setBit = setBit << 1; } // now loop through for remaining bits and find // position of immediate 1 after prev int max0 = int.MinValue, cur = prev; for (int j = i + 1; j <= sizeof(int) * 8; j++) { cur++; // if current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) max0 = cur - prev - 1; // update prev prev = cur; } setBit = setBit << 1; } return max0; } // Driver program to run the case static public void Main() { int n = 549; // Initially check that number must not // be 0 and power of 2 Console.WriteLine(maxZeros(n)); }} // This code is contributed by vt_m.",
"e": 7734,
"s": 6017,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum number of 0's// in binary representation of a number // Returns maximum 0's between two immediate// 1's in binary representation of numberfunction maxZeros(n){ // If there are no 1's or there is only // 1, then return -1 if (n == 0 || (n & (n - 1)) == 0) { return -1; } // int size in java is 4 byte let b = 4; // Loop to find position of right most 1 // here sizeof int is 4 that means total 32 bits let setBit = 1, prev = 0, i; for(i = 1; i <= b* 8; i++) { prev++; // We have found right most 1 if ((n & setBit) == setBit) { setBit = setBit << 1; break; } // Left shift setBit by 1 // to check next bit setBit = setBit << 1; } // Now loop through for remaining bits // and find position of immediate 1 after prev let max0 = Number.MIN_VALUE, cur = prev; for(let j = i + 1; j <= b * 8; j++) { cur++; // If current bit is set, then compare // difference of cur - prev -1 with // previous maximum number of zeros if ((n & setBit) == setBit) { if (max0 < (cur - prev - 1)) { max0 = cur - prev - 1; } // Update prev prev = cur; } setBit = setBit << 1; } return max0;} // Driver Codelet n = 549; // Initially check that number must not// be 0 and power of 2document.write(maxZeros(n)); // This code is contributed by code_hunt </script>",
"e": 9310,
"s": 7734,
"text": null
},
{
"code": null,
"e": 9319,
"s": 9310,
"text": "Output: "
},
{
"code": null,
"e": 9321,
"s": 9319,
"text": "3"
},
{
"code": null,
"e": 9408,
"s": 9321,
"text": "Time Complexity: O(1), because it is taking constant time irrespective of the input n."
},
{
"code": null,
"e": 9863,
"s": 9408,
"text": "Auxiliary Space: O(1)This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9868,
"s": 9863,
"text": "vt_m"
},
{
"code": null,
"e": 9880,
"s": 9868,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9895,
"s": 9880,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9905,
"s": 9895,
"text": "code_hunt"
},
{
"code": null,
"e": 9922,
"s": 9905,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9937,
"s": 9922,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 9959,
"s": 9937,
"text": "binary-representation"
},
{
"code": null,
"e": 9969,
"s": 9959,
"text": "Bit Magic"
},
{
"code": null,
"e": 9979,
"s": 9969,
"text": "Bit Magic"
},
{
"code": null,
"e": 10077,
"s": 9979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10107,
"s": 10077,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 10147,
"s": 10107,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 10185,
"s": 10147,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 10227,
"s": 10185,
"text": "Find most significant set bit of a number"
},
{
"code": null,
"e": 10278,
"s": 10227,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 10321,
"s": 10278,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 10352,
"s": 10321,
"text": "C++ bitset and its application"
},
{
"code": null,
"e": 10376,
"s": 10352,
"text": "Rotate bits of a number"
},
{
"code": null,
"e": 10392,
"s": 10376,
"text": "Bit Fields in C"
}
] |
Different ways to iterate over rows in Pandas Dataframe
|
24 Jun, 2022
In this article, we will cover how to iterate over rows in a DataFrame in Pandas.
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Different Ways to Iterate Over Rows in Pandas DataFrame | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersDifferent Ways to Iterate Over Rows in Pandas DataFrame | 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:002:59 / 9:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mT-2AxZLtvw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Let’s see the Different ways to iterate over rows in Pandas Dataframe :
Method 1: Using the index attribute of the Dataframe.
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using index attribute :\n") # iterate through each row and select# 'Name' and 'Stream' column respectively.for ind in df.index: print(df['Name'][ind], df['Stream'][ind])
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using index attribute :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using loc function :\n") # iterate through each row and select# 'Name' and 'Age' column respectively.for i in range(len(df)): print(df.loc[i, "Name"], df.loc[i, "Age"])
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using loc function :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using iloc function :\n") # iterate through each row and select# 0th and 2nd index column respectively.for i in range(len(df)): print(df.iloc[i, 0], df.iloc[i, 2])
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using iloc function :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using iterrows() method :\n") # iterate through each row and select# 'Name' and 'Age' column respectively.for index, row in df.iterrows(): print(row["Name"], row["Age"])
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using iterrows() method :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using itertuples() method :\n") # iterate through each row and select# 'Name' and 'Percentage' column respectively.for row in df.itertuples(index=True, name='Pandas'): print(getattr(row, "Name"), getattr(row, "Percentage"))
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using itertuples() method :
Ankit 88
Amit 92
Aishwarya 95
Priyanka 70
Python3
# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print("Given Dataframe :\n", df) print("\nIterating over rows using apply function :\n") # iterate through each row and concatenate# 'Name' and 'Percentage' column respectively.print(df.apply(lambda row: row["Name"] + " " + str(row["Percentage"]), axis=1))
Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70
Iterating over rows using apply function :
0 Ankit 88
1 Amit 92
2 Aishwarya 95
3 Priyanka 70
dtype: object
surajkumarguptaintern
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 136,
"s": 54,
"text": "In this article, we will cover how to iterate over rows in a DataFrame in Pandas."
},
{
"code": null,
"e": 351,
"s": 136,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. "
},
{
"code": null,
"e": 1279,
"s": 351,
"text": "Different Ways to Iterate Over Rows in Pandas DataFrame | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersDifferent Ways to Iterate Over Rows in Pandas DataFrame | 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:002:59 / 9:26•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mT-2AxZLtvw\" 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": 1351,
"s": 1279,
"text": "Let’s see the Different ways to iterate over rows in Pandas Dataframe :"
},
{
"code": null,
"e": 1406,
"s": 1351,
"text": "Method 1: Using the index attribute of the Dataframe. "
},
{
"code": null,
"e": 1414,
"s": 1406,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using index attribute :\\n\") # iterate through each row and select# 'Name' and 'Stream' column respectively.for ind in df.index: print(df['Name'][ind], df['Stream'][ind])",
"e": 2117,
"s": 1414,
"text": null
},
{
"code": null,
"e": 2125,
"s": 2117,
"text": "Output:"
},
{
"code": null,
"e": 2447,
"s": 2125,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using index attribute :\n\nAnkit Math\nAmit Commerce\nAishwarya Arts\nPriyanka Biology"
},
{
"code": null,
"e": 2455,
"s": 2447,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using loc function :\\n\") # iterate through each row and select# 'Name' and 'Age' column respectively.for i in range(len(df)): print(df.loc[i, \"Name\"], df.loc[i, \"Age\"])",
"e": 3189,
"s": 2455,
"text": null
},
{
"code": null,
"e": 3197,
"s": 3189,
"text": "Output:"
},
{
"code": null,
"e": 3501,
"s": 3197,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using loc function :\n\nAnkit 21\nAmit 19\nAishwarya 20\nPriyanka 18"
},
{
"code": null,
"e": 3509,
"s": 3501,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using iloc function :\\n\") # iterate through each row and select# 0th and 2nd index column respectively.for i in range(len(df)): print(df.iloc[i, 0], df.iloc[i, 2])",
"e": 4207,
"s": 3509,
"text": null
},
{
"code": null,
"e": 4215,
"s": 4207,
"text": "Output:"
},
{
"code": null,
"e": 4537,
"s": 4215,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using iloc function :\n\nAnkit Math\nAmit Commerce\nAishwarya Arts\nPriyanka Biology\n"
},
{
"code": null,
"e": 4545,
"s": 4537,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using iterrows() method :\\n\") # iterate through each row and select# 'Name' and 'Age' column respectively.for index, row in df.iterrows(): print(row[\"Name\"], row[\"Age\"])",
"e": 5249,
"s": 4545,
"text": null
},
{
"code": null,
"e": 5257,
"s": 5249,
"text": "Output:"
},
{
"code": null,
"e": 5566,
"s": 5257,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using iterrows() method :\n\nAnkit 21\nAmit 19\nAishwarya 20\nPriyanka 18"
},
{
"code": null,
"e": 5574,
"s": 5566,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using itertuples() method :\\n\") # iterate through each row and select# 'Name' and 'Percentage' column respectively.for row in df.itertuples(index=True, name='Pandas'): print(getattr(row, \"Name\"), getattr(row, \"Percentage\"))",
"e": 6364,
"s": 5574,
"text": null
},
{
"code": null,
"e": 6372,
"s": 6364,
"text": "Output:"
},
{
"code": null,
"e": 6685,
"s": 6372,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using itertuples() method :\n\nAnkit 88\nAmit 92\nAishwarya 95\nPriyanka 70\n"
},
{
"code": null,
"e": 6693,
"s": 6685,
"text": "Python3"
},
{
"code": "# import pandas package as pdimport pandas as pd # Define a dictionary containing students datadata = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 'Age': [21, 19, 20, 18], 'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 'Percentage': [88, 92, 95, 70]} # Convert the dictionary into DataFramedf = pd.DataFrame(data, columns=['Name', 'Age', 'Stream', 'Percentage']) print(\"Given Dataframe :\\n\", df) print(\"\\nIterating over rows using apply function :\\n\") # iterate through each row and concatenate# 'Name' and 'Percentage' column respectively.print(df.apply(lambda row: row[\"Name\"] + \" \" + str(row[\"Percentage\"]), axis=1))",
"e": 7432,
"s": 6693,
"text": null
},
{
"code": null,
"e": 7440,
"s": 7432,
"text": "Output:"
},
{
"code": null,
"e": 7790,
"s": 7440,
"text": "Given Dataframe :\n Name Age Stream Percentage\n0 Ankit 21 Math 88\n1 Amit 19 Commerce 92\n2 Aishwarya 20 Arts 95\n3 Priyanka 18 Biology 70\n\nIterating over rows using apply function :\n\n0 Ankit 88\n1 Amit 92\n2 Aishwarya 95\n3 Priyanka 70\ndtype: object"
},
{
"code": null,
"e": 7812,
"s": 7790,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 7837,
"s": 7812,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 7844,
"s": 7837,
"text": "Picked"
},
{
"code": null,
"e": 7868,
"s": 7844,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 7882,
"s": 7868,
"text": "Python-pandas"
},
{
"code": null,
"e": 7906,
"s": 7882,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 7913,
"s": 7906,
"text": "Python"
},
{
"code": null,
"e": 7932,
"s": 7913,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8030,
"s": 7932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8048,
"s": 8030,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8090,
"s": 8048,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8112,
"s": 8090,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8144,
"s": 8112,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8173,
"s": 8144,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 8200,
"s": 8173,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8230,
"s": 8200,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 8251,
"s": 8230,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8287,
"s": 8251,
"text": "Convert integer to string in Python"
}
] |
response.content – Python requests
|
26 Jul, 2021
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.content out of a response object. response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content.
To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Prerequisites –
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
Example code –
Python3
import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request contentprint(response.content)
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
Check that b’ at the start of output, it means the reference to a bytes object.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2 , treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
sumitgumber28
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 509,
"s": 28,
"text": "Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.content out of a response object. response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content. "
},
{
"code": null,
"e": 654,
"s": 509,
"text": "To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 670,
"s": 654,
"text": "Prerequisites –"
},
{
"code": null,
"e": 715,
"s": 670,
"text": "Download and Install Python 3 Latest Version"
},
{
"code": null,
"e": 775,
"s": 715,
"text": "How to install requests in Python – For windows, linux, mac"
},
{
"code": null,
"e": 791,
"s": 775,
"text": "Example code – "
},
{
"code": null,
"e": 799,
"s": 791,
"text": "Python3"
},
{
"code": "import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request contentprint(response.content)",
"e": 937,
"s": 799,
"text": null
},
{
"code": null,
"e": 962,
"s": 937,
"text": "Example Implementation –"
},
{
"code": null,
"e": 1008,
"s": 962,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 1026,
"s": 1008,
"text": "Python request.py"
},
{
"code": null,
"e": 1035,
"s": 1026,
"text": "Output –"
},
{
"code": null,
"e": 1116,
"s": 1035,
"text": "Check that b’ at the start of output, it means the reference to a bytes object. "
},
{
"code": null,
"e": 1370,
"s": 1116,
"text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2 , treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. "
},
{
"code": null,
"e": 1391,
"s": 1370,
"text": "requests.status_code"
},
{
"code": null,
"e": 1549,
"s": 1391,
"text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. "
},
{
"code": null,
"e": 1563,
"s": 1549,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1579,
"s": 1563,
"text": "Python-requests"
},
{
"code": null,
"e": 1586,
"s": 1579,
"text": "Python"
}
] |
Program for power of a complex number in O(log n)
|
30 Nov, 2021
Given a complex number of the form x + yi and an integer n, the task is to calculate the value of this complex number raised to the power n.Examples:
Input: num = 17 - 12i, n = 3
Output: -2431 + i ( -8676 )
Input: num = 18 - 13i, n = 8
Output: 16976403601 + i ( 56580909840 )
Approach: This algorithm works in O(log n) time complexity. Let c = a + bi and n is the exponent then,
power(x, n) {
if(n == 1)
return x
sq = power(x, n/2);
if(n % 2 == 0)
return cmul(sq, sq);
if(n % 2 != 0)
return cmul(x, cmul(sq, sq));
}
As complex number has 2 fields one is real and other is complex hence we store it in an array. We use cmul() function to multiply two arrays where cmul() implements the below multiplication.
If x1 = a + bi and x2 = c + di
then x1 * x2 = a * c - b * d + (b * c + d * a )i
As we can see in power() function the same function is called for input decreased by 1/2 times. T(n) = T(n / 2) + c therefore, T(n) = log nBelow is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
PHP
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the product// of two complex numberslong long* cmul(long long* sq1, long long* sq2){ long long* ans = new long long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans;} // Function to return the complex number// raised to the power nlong long* power(long long* x, long long n){ long long* ans = new long long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long long* sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq));} // Driver codeint main(){ int n; long long* x = new long long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long long* a = power(x, n); cout << a[0] << " + i ( " << a[1] << " )" << endl; return 0;}
// Java implementation of the approachpublic class Main{ // Function to return the product // of two complex numbers static long[] cmul(long[] sq1, long[] sq2) { long[] ans = new long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n static long[] power(long[] x, long n) { long[] ans = new long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long[] sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } public static void main(String[] args) { long n; long[] x = new long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long[] a = power(x, n); System.out.print(a[0] + " + i ( " + a[1] + " )"); }} // This code is contributed by divyesh072019.
# Python3 implementation of the approach # Function to return the product# of two complex numbersdef cmul(sq1, sq2): ans = [0] * 2 # For real part ans[0] = ((sq1[0] * sq2[0]) - (sq1[1] * sq2[1])) # For imaginary part ans[1] = ((sq1[1] * sq2[0]) + sq1[0] * sq2[1]) return ans # Function to return the complex# number raised to the power ndef power(x, n): ans = [0] * 2 if (n == 0): ans[0] = 0 ans[1] = 0 return ans if (n == 1): return x # Recursive call for n/2 sq = power(x, n // 2) if (n % 2 == 0): return cmul(sq, sq) return cmul(x, cmul(sq, sq)) # Driver codeif __name__ == "__main__": x = [0] * 2 # Real part of the complex number x[0] = 18 # Imaginary part of the # complex number x[1] = -13 n = 8 # Calculate and print the result a = power(x, n) print(a[0], " + i ( ", a[1], " )") # This code is contributed by ita_c
// C# implementation of the approachusing System;class GFG { // Function to return the product // of two complex numbers static long[] cmul(long[] sq1, long[] sq2) { long[] ans = new long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n static long[] power(long[] x, long n) { long[] ans = new long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long[] sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } static void Main() { long n; long[] x = new long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long[] a = power(x, n); Console.Write(a[0] + " + i ( " + a[1] + " )"); }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript implementation of the approach // Function to return the product // of two complex numbers function cmul(sq1, sq2) { let ans = new Array(2); // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n function power(x, n) { let ans = new Array(2); if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 let sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } let n; let x = new Array(2); // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result let a = power(x, n); document.write(a[0] + " + i ( " + a[1] + " )"); // This code is contributed by decode2207.</script>
<?php// PHP implementation of the approach // Function to return the product// of two complex numbersfunction cmul($sq1, $sq2){ $ans = array(); // For real part $ans[0] = ($sq1[0] * $sq2[0]) - ($sq1[1] * $sq2[1]); // For imaginary part $ans[1] = ($sq1[1] * $sq2[0]) + $sq1[0] * $sq2[1]; return $ans;} // Function to return the complex// number raised to the power nfunction power($x, $n){ $ans = array(); if ($n == 0) { $ans[0] = 0; $ans[1] = 0; return $ans; } if ($n == 1) return $x; // Recursive call for n/2 $sq = power($x, $n / 2); if ($n % 2 == 0) return cmul($sq, $sq); return cmul($x, cmul($sq, $sq));} // Driver code$x = array(); // Real part of the complex number$x[0] = 18; // Imaginary part of the complex number$x[1] = -13;$n = 8; // Calculate and print the result$a = power($x, $n);echo $a[0], " + i ( ", $a[1], " )"; // This code is contributed by Ryuga?>
16976403601 + i ( 56580909840 )
ankthon
ukasp
decode2207
divyeshrabadiya07
divyesh072019
Algorithms
Recursion
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Backtracking | Introduction
Print all subsequences of a string
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "Given a complex number of the form x + yi and an integer n, the task is to calculate the value of this complex number raised to the power n.Examples: "
},
{
"code": null,
"e": 307,
"s": 180,
"text": "Input: num = 17 - 12i, n = 3\nOutput: -2431 + i ( -8676 )\n\nInput: num = 18 - 13i, n = 8\nOutput: 16976403601 + i ( 56580909840 )"
},
{
"code": null,
"e": 414,
"s": 309,
"text": "Approach: This algorithm works in O(log n) time complexity. Let c = a + bi and n is the exponent then, "
},
{
"code": null,
"e": 591,
"s": 414,
"text": "power(x, n) {\n if(n == 1)\n return x\n sq = power(x, n/2);\n if(n % 2 == 0)\n return cmul(sq, sq);\n if(n % 2 != 0)\n return cmul(x, cmul(sq, sq));\n}"
},
{
"code": null,
"e": 784,
"s": 591,
"text": "As complex number has 2 fields one is real and other is complex hence we store it in an array. We use cmul() function to multiply two arrays where cmul() implements the below multiplication. "
},
{
"code": null,
"e": 865,
"s": 784,
"text": "If x1 = a + bi and x2 = c + di\nthen x1 * x2 = a * c - b * d + (b * c + d * a )i "
},
{
"code": null,
"e": 1057,
"s": 865,
"text": "As we can see in power() function the same function is called for input decreased by 1/2 times. T(n) = T(n / 2) + c therefore, T(n) = log nBelow is the implementation of the above approach: "
},
{
"code": null,
"e": 1061,
"s": 1057,
"text": "C++"
},
{
"code": null,
"e": 1066,
"s": 1061,
"text": "Java"
},
{
"code": null,
"e": 1075,
"s": 1066,
"text": "Python 3"
},
{
"code": null,
"e": 1078,
"s": 1075,
"text": "C#"
},
{
"code": null,
"e": 1089,
"s": 1078,
"text": "Javascript"
},
{
"code": null,
"e": 1093,
"s": 1089,
"text": "PHP"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the product// of two complex numberslong long* cmul(long long* sq1, long long* sq2){ long long* ans = new long long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans;} // Function to return the complex number// raised to the power nlong long* power(long long* x, long long n){ long long* ans = new long long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long long* sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq));} // Driver codeint main(){ int n; long long* x = new long long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long long* a = power(x, n); cout << a[0] << \" + i ( \" << a[1] << \" )\" << endl; return 0;}",
"e": 2221,
"s": 1093,
"text": null
},
{
"code": "// Java implementation of the approachpublic class Main{ // Function to return the product // of two complex numbers static long[] cmul(long[] sq1, long[] sq2) { long[] ans = new long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n static long[] power(long[] x, long n) { long[] ans = new long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long[] sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } public static void main(String[] args) { long n; long[] x = new long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long[] a = power(x, n); System.out.print(a[0] + \" + i ( \" + a[1] + \" )\"); }} // This code is contributed by divyesh072019.",
"e": 3541,
"s": 2221,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the product# of two complex numbersdef cmul(sq1, sq2): ans = [0] * 2 # For real part ans[0] = ((sq1[0] * sq2[0]) - (sq1[1] * sq2[1])) # For imaginary part ans[1] = ((sq1[1] * sq2[0]) + sq1[0] * sq2[1]) return ans # Function to return the complex# number raised to the power ndef power(x, n): ans = [0] * 2 if (n == 0): ans[0] = 0 ans[1] = 0 return ans if (n == 1): return x # Recursive call for n/2 sq = power(x, n // 2) if (n % 2 == 0): return cmul(sq, sq) return cmul(x, cmul(sq, sq)) # Driver codeif __name__ == \"__main__\": x = [0] * 2 # Real part of the complex number x[0] = 18 # Imaginary part of the # complex number x[1] = -13 n = 8 # Calculate and print the result a = power(x, n) print(a[0], \" + i ( \", a[1], \" )\") # This code is contributed by ita_c",
"e": 4510,
"s": 3541,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { // Function to return the product // of two complex numbers static long[] cmul(long[] sq1, long[] sq2) { long[] ans = new long[2]; // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n static long[] power(long[] x, long n) { long[] ans = new long[2]; if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 long[] sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } static void Main() { long n; long[] x = new long[2]; // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result long[] a = power(x, n); Console.Write(a[0] + \" + i ( \" + a[1] + \" )\"); }} // This code is contributed by divyeshrabadiya07.",
"e": 5752,
"s": 4510,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the product // of two complex numbers function cmul(sq1, sq2) { let ans = new Array(2); // For real part ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]); // For imaginary part ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1]; return ans; } // Function to return the complex number // raised to the power n function power(x, n) { let ans = new Array(2); if (n == 0) { ans[0] = 0; ans[1] = 0; return ans; } if (n == 1) return x; // Recursive call for n/2 let sq = power(x, n / 2); if (n % 2 == 0) return cmul(sq, sq); return cmul(x, cmul(sq, sq)); } let n; let x = new Array(2); // Real part of the complex number x[0] = 18; // Imaginary part of the complex number x[1] = -13; n = 8; // Calculate and print the result let a = power(x, n); document.write(a[0] + \" + i ( \" + a[1] + \" )\"); // This code is contributed by decode2207.</script>",
"e": 6904,
"s": 5752,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the product// of two complex numbersfunction cmul($sq1, $sq2){ $ans = array(); // For real part $ans[0] = ($sq1[0] * $sq2[0]) - ($sq1[1] * $sq2[1]); // For imaginary part $ans[1] = ($sq1[1] * $sq2[0]) + $sq1[0] * $sq2[1]; return $ans;} // Function to return the complex// number raised to the power nfunction power($x, $n){ $ans = array(); if ($n == 0) { $ans[0] = 0; $ans[1] = 0; return $ans; } if ($n == 1) return $x; // Recursive call for n/2 $sq = power($x, $n / 2); if ($n % 2 == 0) return cmul($sq, $sq); return cmul($x, cmul($sq, $sq));} // Driver code$x = array(); // Real part of the complex number$x[0] = 18; // Imaginary part of the complex number$x[1] = -13;$n = 8; // Calculate and print the result$a = power($x, $n);echo $a[0], \" + i ( \", $a[1], \" )\"; // This code is contributed by Ryuga?>",
"e": 7885,
"s": 6904,
"text": null
},
{
"code": null,
"e": 7917,
"s": 7885,
"text": "16976403601 + i ( 56580909840 )"
},
{
"code": null,
"e": 7927,
"s": 7919,
"text": "ankthon"
},
{
"code": null,
"e": 7933,
"s": 7927,
"text": "ukasp"
},
{
"code": null,
"e": 7944,
"s": 7933,
"text": "decode2207"
},
{
"code": null,
"e": 7962,
"s": 7944,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 7976,
"s": 7962,
"text": "divyesh072019"
},
{
"code": null,
"e": 7987,
"s": 7976,
"text": "Algorithms"
},
{
"code": null,
"e": 7997,
"s": 7987,
"text": "Recursion"
},
{
"code": null,
"e": 8007,
"s": 7997,
"text": "Recursion"
},
{
"code": null,
"e": 8018,
"s": 8007,
"text": "Algorithms"
},
{
"code": null,
"e": 8116,
"s": 8018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8154,
"s": 8116,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 8222,
"s": 8154,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 8249,
"s": 8222,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 8292,
"s": 8249,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 8359,
"s": 8292,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 8419,
"s": 8359,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8504,
"s": 8419,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 8531,
"s": 8504,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 8559,
"s": 8531,
"text": "Backtracking | Introduction"
}
] |
Powershell - Write-Host Cmdlet
|
Write-Host cmdlet is used to write customized messages.
In these example, we're see the Write-Host cmdlet in action.
In this example, we'll show a customized message.
Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -BackgroundColor White
You can see the even numbers with separator, in green color and on white background.
2, -> 4, -> 6, -> 8, -> 10, -> 12
|
[
{
"code": null,
"e": 2224,
"s": 2168,
"text": "Write-Host cmdlet is used to write customized messages."
},
{
"code": null,
"e": 2285,
"s": 2224,
"text": "In these example, we're see the Write-Host cmdlet in action."
},
{
"code": null,
"e": 2335,
"s": 2285,
"text": "In this example, we'll show a customized message."
},
{
"code": null,
"e": 2431,
"s": 2335,
"text": "Write-Host (2,4,6,8,10,12) -Separator \", -> \" -ForegroundColor DarkGreen -BackgroundColor White"
},
{
"code": null,
"e": 2516,
"s": 2431,
"text": "You can see the even numbers with separator, in green color and on white background."
}
] |
How to use dynamic variable names in JavaScript ?
|
21 Jul, 2021
In programming, dynamic variable names don’t have a specific name hard-coded in the script. They are named dynamically with string values from other sources. Dynamic variables are rarely used in JavaScript. But in some cases they are useful. Unlike PHP, there is no special implementation of dynamic variable names in JavaScript. But similar results can be achieved by using some other methods. In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below.
eval(): The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression. Inside eval(), we pass a string in which variable valuei is declared and assigned a value of i for each iteration. The eval() function executes this and creates the variable with the assigned values. The code is given below implements the creation of dynamic variable names using eval().Example:<script> var k = 'value'; var i = 0; for(i = 1; i < 5; i++) { eval('var ' + k + i + '= ' + i + ';'); } console.log("value1=" + value1); console.log("value2=" + value2); console.log("value3=" + value3); console.log("value4=" + value4);</script>Output:value1=1
value2=2
value3=3
value4=4
Example:
<script> var k = 'value'; var i = 0; for(i = 1; i < 5; i++) { eval('var ' + k + i + '= ' + i + ';'); } console.log("value1=" + value1); console.log("value2=" + value2); console.log("value3=" + value3); console.log("value4=" + value4);</script>
Output:
value1=1
value2=2
value3=3
value4=4
Window object: JavaScript always has a global object defined. When the program creates global variables they’re created as members of the global object. The window object is the global object in the browser. Any global variables or functions can be accessed with the window object. After defining a global variable we can access its value from the window object. The code given below implements dynamic variable names using the window object. So, the code basically creates a global variable with dynamic name “valuei” for each iteration of i and assigns a value of i to it. Later these variables can be accessed in the script anywhere as they become global variables.Example:<script> var i; for(i = 1; i < 5; i++) { window['value'+i] = + i; } console.log("value1=" + value1); console.log("value2=" + value2); console.log("value3=" + value3); console.log("value4=" + value4);</script>Output:value1=1
value2=2
value3=3
value4=4JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.My Personal Notes
arrow_drop_upSave
Example:
<script> var i; for(i = 1; i < 5; i++) { window['value'+i] = + i; } console.log("value1=" + value1); console.log("value2=" + value2); console.log("value3=" + value3); console.log("value4=" + value4);</script>
Output:
value1=1
value2=2
value3=3
value4=4
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 538,
"s": 52,
"text": "In programming, dynamic variable names don’t have a specific name hard-coded in the script. They are named dynamically with string values from other sources. Dynamic variables are rarely used in JavaScript. But in some cases they are useful. Unlike PHP, there is no special implementation of dynamic variable names in JavaScript. But similar results can be achieved by using some other methods. In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below."
},
{
"code": null,
"e": 1364,
"s": 538,
"text": "eval(): The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression. Inside eval(), we pass a string in which variable valuei is declared and assigned a value of i for each iteration. The eval() function executes this and creates the variable with the assigned values. The code is given below implements the creation of dynamic variable names using eval().Example:<script> var k = 'value'; var i = 0; for(i = 1; i < 5; i++) { eval('var ' + k + i + '= ' + i + ';'); } console.log(\"value1=\" + value1); console.log(\"value2=\" + value2); console.log(\"value3=\" + value3); console.log(\"value4=\" + value4);</script>Output:value1=1\nvalue2=2\nvalue3=3\nvalue4=4"
},
{
"code": null,
"e": 1373,
"s": 1364,
"text": "Example:"
},
{
"code": "<script> var k = 'value'; var i = 0; for(i = 1; i < 5; i++) { eval('var ' + k + i + '= ' + i + ';'); } console.log(\"value1=\" + value1); console.log(\"value2=\" + value2); console.log(\"value3=\" + value3); console.log(\"value4=\" + value4);</script>",
"e": 1648,
"s": 1373,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1648,
"text": "Output:"
},
{
"code": null,
"e": 1692,
"s": 1656,
"text": "value1=1\nvalue2=2\nvalue3=3\nvalue4=4"
},
{
"code": null,
"e": 2904,
"s": 1692,
"text": "Window object: JavaScript always has a global object defined. When the program creates global variables they’re created as members of the global object. The window object is the global object in the browser. Any global variables or functions can be accessed with the window object. After defining a global variable we can access its value from the window object. The code given below implements dynamic variable names using the window object. So, the code basically creates a global variable with dynamic name “valuei” for each iteration of i and assigns a value of i to it. Later these variables can be accessed in the script anywhere as they become global variables.Example:<script> var i; for(i = 1; i < 5; i++) { window['value'+i] = + i; } console.log(\"value1=\" + value1); console.log(\"value2=\" + value2); console.log(\"value3=\" + value3); console.log(\"value4=\" + value4);</script>Output:value1=1\nvalue2=2\nvalue3=3\nvalue4=4JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2913,
"s": 2904,
"text": "Example:"
},
{
"code": "<script> var i; for(i = 1; i < 5; i++) { window['value'+i] = + i; } console.log(\"value1=\" + value1); console.log(\"value2=\" + value2); console.log(\"value3=\" + value3); console.log(\"value4=\" + value4);</script>",
"e": 3154,
"s": 2913,
"text": null
},
{
"code": null,
"e": 3162,
"s": 3154,
"text": "Output:"
},
{
"code": null,
"e": 3198,
"s": 3162,
"text": "value1=1\nvalue2=2\nvalue3=3\nvalue4=4"
},
{
"code": null,
"e": 3417,
"s": 3198,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3433,
"s": 3417,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3440,
"s": 3433,
"text": "Picked"
},
{
"code": null,
"e": 3451,
"s": 3440,
"text": "JavaScript"
},
{
"code": null,
"e": 3468,
"s": 3451,
"text": "Web Technologies"
},
{
"code": null,
"e": 3495,
"s": 3468,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3593,
"s": 3495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3654,
"s": 3593,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3726,
"s": 3654,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3766,
"s": 3726,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3807,
"s": 3766,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3849,
"s": 3807,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3882,
"s": 3849,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3944,
"s": 3882,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4005,
"s": 3944,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4055,
"s": 4005,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python object serialization
|
Serialization is a process in which an object is transformed into a format that can be stored/save (in a file or memory buffer), so we are able to deserialize it later and recover the original content/object from the serialized format. We are going to use a python pickle module to do all these operations.
Python pickle module is used for serializing and de-serializing python object structures. The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshaling. We can convert the byte stream (generated through pickling) back into python objects by a process called as unpickling.
To pickle an object we just need to −
Import the pickle
Call the dumps() function
import pickle
class Vehicle:
def __init__(self, number_of_doors, color):
self.number_of_doors = number_of_doors
self.color = color
class Car(Vehicle):
def __init__(self, color):
Vehicle.__init__(self, 5, color)
Maruti = Car('Red')
print(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)
print('Here is my pickled Vehicle: ')
print(pickle_Maruti)
My Vehicle Maruti is Red and has 5 doors
Here is my pickled Vehicle:
b'\x80\x03c__main__\nCar\nq\x00)\x81q\x01}q\x02(X\x0f\x00\x00\x00number_of_doorsq\x03K\x05X\x05\x00\x00\x00colorq\x04X\x03\x00\x00\x00Redq\x05ub.'
In the above example, we have created an instance of a Car class and then we’ve pickled it, transforming our car instance into a simple array of bytes. After our car instance is pickled, we can easily store it on a binary file or in a db field and restore it later to transform back this bunch of bytes in an object hierarchy.
Note: In case we want to create a file with a pickled object, we need to use the dump() method instead of the dumps() method.
It is the inverse (or pickling) operation, where we take the binary stream and convert it into an object hierarchy.
The unpickling is done using the load() function of the pickle module and returns back a complete object hierarchy from the byte stream.
Below is the load
import pickle
class Vehicle:
def __init__(self, number_of_doors, color):
self.number_of_doors = number_of_doors
self.color = color
class Car(Vehicle):
def __init__(self, color):
Vehicle.__init__(self, 5, color)
Maruti = Car('Red')
print(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)
#Now, let's unpickle our car Maruti creating another instance, another car ... unpickle_Maruti
Hyundai = pickle.loads(pickle_Maruti)
#Set another color of our new instance
Hyundai.color = 'Black'
print(str.format("Hyundai is {0} ", Hyundai.color))
print(str.format("Maruti is {0} ", Maruti.color))
In above example, you can see that we have pickled our first car object (Maruti) and then we have unpickled it to another variable (Hyundai) and so we have in a sense – cloned Maruti to create Hyundai.
My Vehicle Maruti is Red and has 5 doors
Hyundai is Black
Maruti is Red
JSON stands for Javascript Object Notation, is a lightweight format for data-interchange and is humans readable. One of the big advantages of JSON over pickle is that it’s standardized and language-independent. It is much more secure and faster than pickle.
One more alternative to pickle is cPickle, which is very much like a pickle but is written in C language and is 1000 times faster. You can use the same files for pickle and cPickle.
import json
mylist = [2, 4, 5, "ab", "cd", "ef"]
print("Here is my list: ", mylist)
json_string = json.dumps(mylist )
print("Here is my json encoded object: ", json_string)
print ("Here is JSON back to a data structure: ",json.loads(json_string))
Here is my list: [2, 4, 5, 'ab', 'cd', 'ef']
Here is my json encoded object: [2, 4, 5, "ab", "cd", "ef"]
Here is JSON back to a data structure: [2, 4, 5, 'ab', 'cd', 'ef']
In the above code, we first take the object (my list) and use the “dumps” method to returns a string and then to load JSON back to a data structure we use the “loads” method that turns a string and turns it into the JSON object data structure.
|
[
{
"code": null,
"e": 1494,
"s": 1187,
"text": "Serialization is a process in which an object is transformed into a format that can be stored/save (in a file or memory buffer), so we are able to deserialize it later and recover the original content/object from the serialized format. We are going to use a python pickle module to do all these operations."
},
{
"code": null,
"e": 1869,
"s": 1494,
"text": "Python pickle module is used for serializing and de-serializing python object structures. The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshaling. We can convert the byte stream (generated through pickling) back into python objects by a process called as unpickling."
},
{
"code": null,
"e": 1907,
"s": 1869,
"text": "To pickle an object we just need to −"
},
{
"code": null,
"e": 1925,
"s": 1907,
"text": "Import the pickle"
},
{
"code": null,
"e": 1951,
"s": 1925,
"text": "Call the dumps() function"
},
{
"code": null,
"e": 2404,
"s": 1951,
"text": "import pickle\nclass Vehicle:\n def __init__(self, number_of_doors, color):\n self.number_of_doors = number_of_doors\n self.color = color\nclass Car(Vehicle):\n def __init__(self, color):\n Vehicle.__init__(self, 5, color)\nMaruti = Car('Red')\nprint(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))\npickle_Maruti = pickle.dumps(Maruti)\nprint('Here is my pickled Vehicle: ')\nprint(pickle_Maruti)"
},
{
"code": null,
"e": 2620,
"s": 2404,
"text": "My Vehicle Maruti is Red and has 5 doors\nHere is my pickled Vehicle:\nb'\\x80\\x03c__main__\\nCar\\nq\\x00)\\x81q\\x01}q\\x02(X\\x0f\\x00\\x00\\x00number_of_doorsq\\x03K\\x05X\\x05\\x00\\x00\\x00colorq\\x04X\\x03\\x00\\x00\\x00Redq\\x05ub.'"
},
{
"code": null,
"e": 2947,
"s": 2620,
"text": "In the above example, we have created an instance of a Car class and then we’ve pickled it, transforming our car instance into a simple array of bytes. After our car instance is pickled, we can easily store it on a binary file or in a db field and restore it later to transform back this bunch of bytes in an object hierarchy."
},
{
"code": null,
"e": 3073,
"s": 2947,
"text": "Note: In case we want to create a file with a pickled object, we need to use the dump() method instead of the dumps() method."
},
{
"code": null,
"e": 3189,
"s": 3073,
"text": "It is the inverse (or pickling) operation, where we take the binary stream and convert it into an object hierarchy."
},
{
"code": null,
"e": 3326,
"s": 3189,
"text": "The unpickling is done using the load() function of the pickle module and returns back a complete object hierarchy from the byte stream."
},
{
"code": null,
"e": 3344,
"s": 3326,
"text": "Below is the load"
},
{
"code": null,
"e": 4036,
"s": 3344,
"text": "import pickle\nclass Vehicle:\n def __init__(self, number_of_doors, color):\n self.number_of_doors = number_of_doors\n self.color = color\nclass Car(Vehicle):\n def __init__(self, color):\n Vehicle.__init__(self, 5, color)\nMaruti = Car('Red')\nprint(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))\npickle_Maruti = pickle.dumps(Maruti)\n#Now, let's unpickle our car Maruti creating another instance, another car ... unpickle_Maruti\nHyundai = pickle.loads(pickle_Maruti)\n#Set another color of our new instance\nHyundai.color = 'Black'\nprint(str.format(\"Hyundai is {0} \", Hyundai.color))\nprint(str.format(\"Maruti is {0} \", Maruti.color))"
},
{
"code": null,
"e": 4238,
"s": 4036,
"text": "In above example, you can see that we have pickled our first car object (Maruti) and then we have unpickled it to another variable (Hyundai) and so we have in a sense – cloned Maruti to create Hyundai."
},
{
"code": null,
"e": 4310,
"s": 4238,
"text": "My Vehicle Maruti is Red and has 5 doors\nHyundai is Black\nMaruti is Red"
},
{
"code": null,
"e": 4568,
"s": 4310,
"text": "JSON stands for Javascript Object Notation, is a lightweight format for data-interchange and is humans readable. One of the big advantages of JSON over pickle is that it’s standardized and language-independent. It is much more secure and faster than pickle."
},
{
"code": null,
"e": 4750,
"s": 4568,
"text": "One more alternative to pickle is cPickle, which is very much like a pickle but is written in C language and is 1000 times faster. You can use the same files for pickle and cPickle."
},
{
"code": null,
"e": 4997,
"s": 4750,
"text": "import json\nmylist = [2, 4, 5, \"ab\", \"cd\", \"ef\"]\nprint(\"Here is my list: \", mylist)\njson_string = json.dumps(mylist )\nprint(\"Here is my json encoded object: \", json_string)\nprint (\"Here is JSON back to a data structure: \",json.loads(json_string))"
},
{
"code": null,
"e": 5169,
"s": 4997,
"text": "Here is my list: [2, 4, 5, 'ab', 'cd', 'ef']\nHere is my json encoded object: [2, 4, 5, \"ab\", \"cd\", \"ef\"]\nHere is JSON back to a data structure: [2, 4, 5, 'ab', 'cd', 'ef']"
},
{
"code": null,
"e": 5413,
"s": 5169,
"text": "In the above code, we first take the object (my list) and use the “dumps” method to returns a string and then to load JSON back to a data structure we use the “loads” method that turns a string and turns it into the JSON object data structure."
}
] |
Readability Index in Python(NLP)
|
03 Sep, 2021
Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend.
Our main objective in writing is to pass along information that both the writer and the reader think is worthwhile. If we fail to convey that information, our efforts are wasted. In order to engage the reader, it’s critical to present information to them that they’ll gladly keep reading and be able to understand clearly. So, it is required that the content be easy enough to read and understand this is as readable as possible. There are various available Difficulty Scales with their own difficulty determining formulae.
This article illustrates various traditional readability formulae available for readability score evaluation. In Natural Language Processing, sometimes it is required to analyze words and sentences to determine the difficulty of the text. Readability Scores are generally grade levels on particular scales, which rates the text as to whats the difficulty of that particular text. It assists the writer in improving the text to make it understandable for a larger audience, thus making content engaging.
Various available Readability Score Determination Methods/Formulae:
The Dale–Chall formulaThe Gunning fog formulaFry readability graphMcLaughlin’s SMOG formulaThe FORECAST formulaReadability and newspaper readershipFlesch Scores
The Dale–Chall formula
The Gunning fog formula
Fry readability graph
McLaughlin’s SMOG formula
The FORECAST formula
Readability and newspaper readership
Flesch Scores
Read about more available Readability Formulae from here.
The implementation of the readability formulae is shown below.
The Dale Chall Formula:
To apply the formula:Select several 100-word samples throughout the text. Compute the average sentence length in words (divide the number of words by the number of sentences). Compute the percentage of words NOT on the Dale–Chall word list of 3, 000 easy words. Compute this equation
Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365
Here,
PDW = Percentage of difficult words not on the Dale–Chall word list.
ASL = Average sentence length
The Gunning fog Formula
Grade level= 0.4 * ( (average sentence length) + (percentage of Hard Words) )
Here, Hard Words = words with more than two syllables.
Smog Formula
SMOG grading = 3 + √(polysyllable count).
Here, polysyllable count = number of words of more than two syllables in a
sample of 30 sentences.
Flesch Formula
Reading Ease score = 206.835 - (1.015 × ASL) - (84.6 × ASW)
Here,
ASL = average sentence length (number of words divided by number of sentences)
ASW = average word length in syllables (number of syllables divided by number of words)
Advantages of Readability Formulae:1. Readability formulas measure the grade-level readers must have to be to read a given text. Thus provides the writer of the text with much-needed information to reach his target audience. 2. Know beforehand if the target audience can understand your content.3. Easy-to-use. 4. A readable text attracts more audience.
Disadvantages of Readability Formulae:1. Due to many readability formulas, there is an increasing chance of getting wide variations in results of a same text. 2. Applies Mathematics to Literature which isn’t always a good idea.3. Cannot measure the complexity of a word or phrase to pinpoint where you need to correct it.
Python
import spacyfrom textstat.textstat import textstatistics,legacy_round # Splits the text into sentences, using# Spacy's sentence segmentation which can# be found at https://spacy.io/usage/spacy-101def break_sentences(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) return list(doc.sents) # Returns Number of Words in the textdef word_count(text): sentences = break_sentences(text) words = 0 for sentence in sentences: words += len([token for token in sentence]) return words # Returns the number of sentences in the textdef sentence_count(text): sentences = break_sentences(text) return len(sentences) # Returns average sentence lengthdef avg_sentence_length(text): words = word_count(text) sentences = sentence_count(text) average_sentence_length = float(words / sentences) return average_sentence_length # Textstat is a python package, to calculate statistics from# text to determine readability,# complexity and grade level of a particular corpus.# Package can be found at https://pypi.python.org/pypi/textstatdef syllables_count(word): return textstatistics().syllable_count(word) # Returns the average number of syllables per# word in the textdef avg_syllables_per_word(text): syllable = syllables_count(text) words = word_count(text) ASPW = float(syllable) / float(words) return legacy_round(ASPW, 1) # Return total Difficult Words in a textdef difficult_words(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) # Find all words in the text words = [] sentences = break_sentences(text) for sentence in sentences: words += [str(token) for token in sentence] # difficult words are those with syllables >= 2 # easy_word_set is provide by Textstat as # a list of common words diff_words_set = set() for word in words: syllable_count = syllables_count(word) if word not in nlp.Defaults.stop_words and syllable_count >= 2: diff_words_set.add(word) return len(diff_words_set) # A word is polysyllablic if it has more than 3 syllables# this functions returns the number of all such words# present in the textdef poly_syllable_count(text): count = 0 words = [] sentences = break_sentences(text) for sentence in sentences: words += [token for token in sentence] for word in words: syllable_count = syllables_count(word) if syllable_count >= 3: count += 1 return count def flesch_reading_ease(text): """ Implements Flesch Formula: Reading Ease score = 206.835 - (1.015 × ASL) - (84.6 × ASW) Here, ASL = average sentence length (number of words divided by number of sentences) ASW = average word length in syllables (number of syllables divided by number of words) """ FRE = 206.835 - float(1.015 * avg_sentence_length(text)) -\ float(84.6 * avg_syllables_per_word(text)) return legacy_round(FRE, 2) def gunning_fog(text): per_diff_words = (difficult_words(text) / word_count(text) * 100) + 5 grade = 0.4 * (avg_sentence_length(text) + per_diff_words) return grade def smog_index(text): """ Implements SMOG Formula / Grading SMOG grading = 3 + ?polysyllable count. Here, polysyllable count = number of words of more than two syllables in a sample of 30 sentences. """ if sentence_count(text) >= 3: poly_syllab = poly_syllable_count(text) SMOG = (1.043 * (30*(poly_syllab / sentence_count(text)))**0.5) \ + 3.1291 return legacy_round(SMOG, 1) else: return 0 def dale_chall_readability_score(text): """ Implements Dale Challe Formula: Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365 Here, PDW = Percentage of difficult words. ASL = Average sentence length """ words = word_count(text) # Number of words not termed as difficult words count = word_count - difficult_words(text) if words > 0: # Percentage of words not on difficult word list per = float(count) / float(words) * 100 # diff_words stores percentage of difficult words diff_words = 100 - per raw_score = (0.1579 * diff_words) + \ (0.0496 * avg_sentence_length(text)) # If Percentage of Difficult Words is greater than 5 %, then; # Adjusted Score = Raw Score + 3.6365, # otherwise Adjusted Score = Raw Score if diff_words > 5: raw_score += 3.6365 return legacy_round(score, 2)
Source : https://en.wikipedia.org/wiki/Readability
Satheesh Kumar Mohan
apra8001
surindertarika1234
gabaa406
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 361,
"s": 54,
"text": "Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend. "
},
{
"code": null,
"e": 885,
"s": 361,
"text": "Our main objective in writing is to pass along information that both the writer and the reader think is worthwhile. If we fail to convey that information, our efforts are wasted. In order to engage the reader, it’s critical to present information to them that they’ll gladly keep reading and be able to understand clearly. So, it is required that the content be easy enough to read and understand this is as readable as possible. There are various available Difficulty Scales with their own difficulty determining formulae."
},
{
"code": null,
"e": 1389,
"s": 885,
"text": "This article illustrates various traditional readability formulae available for readability score evaluation. In Natural Language Processing, sometimes it is required to analyze words and sentences to determine the difficulty of the text. Readability Scores are generally grade levels on particular scales, which rates the text as to whats the difficulty of that particular text. It assists the writer in improving the text to make it understandable for a larger audience, thus making content engaging. "
},
{
"code": null,
"e": 1457,
"s": 1389,
"text": "Various available Readability Score Determination Methods/Formulae:"
},
{
"code": null,
"e": 1618,
"s": 1457,
"text": "The Dale–Chall formulaThe Gunning fog formulaFry readability graphMcLaughlin’s SMOG formulaThe FORECAST formulaReadability and newspaper readershipFlesch Scores"
},
{
"code": null,
"e": 1641,
"s": 1618,
"text": "The Dale–Chall formula"
},
{
"code": null,
"e": 1665,
"s": 1641,
"text": "The Gunning fog formula"
},
{
"code": null,
"e": 1687,
"s": 1665,
"text": "Fry readability graph"
},
{
"code": null,
"e": 1713,
"s": 1687,
"text": "McLaughlin’s SMOG formula"
},
{
"code": null,
"e": 1734,
"s": 1713,
"text": "The FORECAST formula"
},
{
"code": null,
"e": 1771,
"s": 1734,
"text": "Readability and newspaper readership"
},
{
"code": null,
"e": 1785,
"s": 1771,
"text": "Flesch Scores"
},
{
"code": null,
"e": 1843,
"s": 1785,
"text": "Read about more available Readability Formulae from here."
},
{
"code": null,
"e": 1907,
"s": 1843,
"text": "The implementation of the readability formulae is shown below. "
},
{
"code": null,
"e": 1931,
"s": 1907,
"text": "The Dale Chall Formula:"
},
{
"code": null,
"e": 2216,
"s": 1931,
"text": "To apply the formula:Select several 100-word samples throughout the text. Compute the average sentence length in words (divide the number of words by the number of sentences). Compute the percentage of words NOT on the Dale–Chall word list of 3, 000 easy words. Compute this equation "
},
{
"code": null,
"e": 2371,
"s": 2216,
"text": " Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365\nHere,\nPDW = Percentage of difficult words not on the Dale–Chall word list.\nASL = Average sentence length"
},
{
"code": null,
"e": 2395,
"s": 2371,
"text": "The Gunning fog Formula"
},
{
"code": null,
"e": 2528,
"s": 2395,
"text": "Grade level= 0.4 * ( (average sentence length) + (percentage of Hard Words) )\nHere, Hard Words = words with more than two syllables."
},
{
"code": null,
"e": 2541,
"s": 2528,
"text": "Smog Formula"
},
{
"code": null,
"e": 2683,
"s": 2541,
"text": "SMOG grading = 3 + √(polysyllable count).\nHere, polysyllable count = number of words of more than two syllables in a \nsample of 30 sentences."
},
{
"code": null,
"e": 2698,
"s": 2683,
"text": "Flesch Formula"
},
{
"code": null,
"e": 2931,
"s": 2698,
"text": "Reading Ease score = 206.835 - (1.015 × ASL) - (84.6 × ASW)\nHere,\nASL = average sentence length (number of words divided by number of sentences)\nASW = average word length in syllables (number of syllables divided by number of words)"
},
{
"code": null,
"e": 3286,
"s": 2931,
"text": "Advantages of Readability Formulae:1. Readability formulas measure the grade-level readers must have to be to read a given text. Thus provides the writer of the text with much-needed information to reach his target audience. 2. Know beforehand if the target audience can understand your content.3. Easy-to-use. 4. A readable text attracts more audience. "
},
{
"code": null,
"e": 3609,
"s": 3286,
"text": "Disadvantages of Readability Formulae:1. Due to many readability formulas, there is an increasing chance of getting wide variations in results of a same text. 2. Applies Mathematics to Literature which isn’t always a good idea.3. Cannot measure the complexity of a word or phrase to pinpoint where you need to correct it. "
},
{
"code": null,
"e": 3616,
"s": 3609,
"text": "Python"
},
{
"code": "import spacyfrom textstat.textstat import textstatistics,legacy_round # Splits the text into sentences, using# Spacy's sentence segmentation which can# be found at https://spacy.io/usage/spacy-101def break_sentences(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) return list(doc.sents) # Returns Number of Words in the textdef word_count(text): sentences = break_sentences(text) words = 0 for sentence in sentences: words += len([token for token in sentence]) return words # Returns the number of sentences in the textdef sentence_count(text): sentences = break_sentences(text) return len(sentences) # Returns average sentence lengthdef avg_sentence_length(text): words = word_count(text) sentences = sentence_count(text) average_sentence_length = float(words / sentences) return average_sentence_length # Textstat is a python package, to calculate statistics from# text to determine readability,# complexity and grade level of a particular corpus.# Package can be found at https://pypi.python.org/pypi/textstatdef syllables_count(word): return textstatistics().syllable_count(word) # Returns the average number of syllables per# word in the textdef avg_syllables_per_word(text): syllable = syllables_count(text) words = word_count(text) ASPW = float(syllable) / float(words) return legacy_round(ASPW, 1) # Return total Difficult Words in a textdef difficult_words(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) # Find all words in the text words = [] sentences = break_sentences(text) for sentence in sentences: words += [str(token) for token in sentence] # difficult words are those with syllables >= 2 # easy_word_set is provide by Textstat as # a list of common words diff_words_set = set() for word in words: syllable_count = syllables_count(word) if word not in nlp.Defaults.stop_words and syllable_count >= 2: diff_words_set.add(word) return len(diff_words_set) # A word is polysyllablic if it has more than 3 syllables# this functions returns the number of all such words# present in the textdef poly_syllable_count(text): count = 0 words = [] sentences = break_sentences(text) for sentence in sentences: words += [token for token in sentence] for word in words: syllable_count = syllables_count(word) if syllable_count >= 3: count += 1 return count def flesch_reading_ease(text): \"\"\" Implements Flesch Formula: Reading Ease score = 206.835 - (1.015 × ASL) - (84.6 × ASW) Here, ASL = average sentence length (number of words divided by number of sentences) ASW = average word length in syllables (number of syllables divided by number of words) \"\"\" FRE = 206.835 - float(1.015 * avg_sentence_length(text)) -\\ float(84.6 * avg_syllables_per_word(text)) return legacy_round(FRE, 2) def gunning_fog(text): per_diff_words = (difficult_words(text) / word_count(text) * 100) + 5 grade = 0.4 * (avg_sentence_length(text) + per_diff_words) return grade def smog_index(text): \"\"\" Implements SMOG Formula / Grading SMOG grading = 3 + ?polysyllable count. Here, polysyllable count = number of words of more than two syllables in a sample of 30 sentences. \"\"\" if sentence_count(text) >= 3: poly_syllab = poly_syllable_count(text) SMOG = (1.043 * (30*(poly_syllab / sentence_count(text)))**0.5) \\ + 3.1291 return legacy_round(SMOG, 1) else: return 0 def dale_chall_readability_score(text): \"\"\" Implements Dale Challe Formula: Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365 Here, PDW = Percentage of difficult words. ASL = Average sentence length \"\"\" words = word_count(text) # Number of words not termed as difficult words count = word_count - difficult_words(text) if words > 0: # Percentage of words not on difficult word list per = float(count) / float(words) * 100 # diff_words stores percentage of difficult words diff_words = 100 - per raw_score = (0.1579 * diff_words) + \\ (0.0496 * avg_sentence_length(text)) # If Percentage of Difficult Words is greater than 5 %, then; # Adjusted Score = Raw Score + 3.6365, # otherwise Adjusted Score = Raw Score if diff_words > 5: raw_score += 3.6365 return legacy_round(score, 2)",
"e": 8208,
"s": 3616,
"text": null
},
{
"code": null,
"e": 8260,
"s": 8208,
"text": "Source : https://en.wikipedia.org/wiki/Readability "
},
{
"code": null,
"e": 8281,
"s": 8260,
"text": "Satheesh Kumar Mohan"
},
{
"code": null,
"e": 8290,
"s": 8281,
"text": "apra8001"
},
{
"code": null,
"e": 8309,
"s": 8290,
"text": "surindertarika1234"
},
{
"code": null,
"e": 8318,
"s": 8309,
"text": "gabaa406"
},
{
"code": null,
"e": 8333,
"s": 8318,
"text": "python-utility"
},
{
"code": null,
"e": 8340,
"s": 8333,
"text": "Python"
},
{
"code": null,
"e": 8359,
"s": 8340,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8457,
"s": 8359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8489,
"s": 8457,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8516,
"s": 8489,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8537,
"s": 8516,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8568,
"s": 8537,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8624,
"s": 8568,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8647,
"s": 8624,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8689,
"s": 8647,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8731,
"s": 8689,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8770,
"s": 8731,
"text": "Python | datetime.timedelta() function"
}
] |
Decoding Strategies that You Need to Know for Response Generation | by Vitou Phy | Towards Data Science
|
Deep learning has been deployed in many tasks in NLP, such as translation, image captioning, and dialogue systems. In machine translation, it is used to read source language (input) and generate the desired language (output). Similarly in a dialogue system, it is used to generate a response given a context. This is also known as Natural Language Generation (NLG).
The model splits into 2 parts: encoder and decoder. Encoder reads the input text and returns a vector representing that input. Then, the decoder takes that vector and generates a corresponding text.
To generate a text, commonly it is done by generating one token at a time. Without proper techniques, the generated response may be very generic and boring. In this article, we will explore the following strategies:
Greedy
Beam Search
Random Sampling
Temperature
Top-K Sampling
Nucleus Sampling
At each timestep during decoding, we take the vector (that holds the information from one step to another) and apply it with softmax function to convert it into an array of probability for each word.
This approach is the simplest. At each time-step, it just chooses whichever token that is the most probable.
Context: Try this cake. I baked it myself.Optimal Response : This cake tastes great.Generated Response: This is okay.
However, this approach may generate a suboptimal response, as shown in the example above. The generated response may not be the best possible response. This is due to the training data that commonly have examples like “That is [...]”. Therefore, if we generate the most probable token at a time, it might output “is” instead of “cake”.
Exhaustive search can solve the previous problem since it will search for the whole space. However, it would be computationally expensive. Suppose there are 10,000 vocabularies, to generate a sentence with the length of 10 tokens, it would be (10,000)10.
Beam search can cope with this problem. At each timestep, it generates all possible tokens in the vocabulary list; then, it will choose top B candidates that have the most probability. Those B candidates will move to the next time step, and the process repeats. In the end, there will only be B candidates. The search space is only (10,000)*B.
Context: Try this cake. I baked it myself.Response A: That cake tastes great.Response B: Thank you.
But sometimes, it chooses an even more optimal (Response B). In this case, it makes perfect sense. But imagine that the model likes to play safe and keeps on generating “I don’t know” or “Thank you” to most of the context, that is a pretty bad bot.
Alternatively, we can look into stochastic approaches to avoid the response being generic. We can utilize the probability of each token from the softmax function to generate the next token.
Suppose we are generating the first token of a context “I love watching movies”, Figure below shows the probability of what the first word should be.
If we use a greedy approach, a token “i” will be chosen. With random sampling, however, token i has a probability of around 0.2 to occur. At the same time, any token that has a probability of 0.0001 can also occur. It’s just very unlikely.
Random sampling, by itself, could potentially generate a very random word by chance. Temperature is used to increase the probability of probable tokens while reducing the one that is not. Usually, the range is 0 < temp ≤ 1. Note that when temp=1, there is no effect.
In Figure 4, with temp=0.5, the most probable words like i, yeah, me, have more chance of being generated. At the same time, this also lowers the probability of the less probable ones, although this does not stop them from occurring.
Top-K sampling is used to ensure that the less probable words should not have any chance at all. Only top K probable tokens should be considered for a generation.
The token index between 50 to 80 has some small probabilities if we use random sampling with temperature=0.5 or 1.0. With top-k sampling (K=10), those tokens have no chance of being generated. Note that we can also combine Top-K sampling with temperature, but you kinda get the idea already, so we choose not to discuss it here.
This sampling technique has been adopted in many recent generation tasks. Its performance is quite good. One limitation with this approach is the number of top K words need to be defined in the beginning. Suppose we choose K=300; however, at a decoding timestep, the model is sure that there should be 10 highly probable words. If we use Top-K, that means we will also consider the other 290 less probable words.
Nucleus sampling is similar to Top-K sampling. Instead of focusing on Top-K words, nucleus sampling focuses on the smallest possible sets of Top-V words such that the sum of their probability is ≥ p. Then, the tokens that are not in V^(p) are set to 0; the rest are re-scaled to ensure that they sum to 1.
The intuition is that when the model is very certain on some tokens, the set of potential candidate tokens is small otherwise, there will be more potential candidate tokens.
Certain → those few tokens have high probability = sum of few tokens is enough to exceed p.Uncertain → Many tokens have small probability = sum of many tokens is needed to exceed p.
Comparing nucleus sampling (p=0.5) with top-K sampling (K = 10), we can see the nucleus does not consider token “you” to be a candidate. This shows that it can adapt to different cases and select different numbers of tokens, unlike Top-K sampling.
Greedy: Select the best probable token at a time
Beam Search: Select the best probable response
Random Sampling: Random based on probability
Temperature: Shrink or enlarge probabilities
Top-K Sampling: Select top probable K tokens
Nucleus Sampling: Dynamically choose the number of K (sort of)
Commonly, top choices by researchers are beam search, top-K sampling (with temperature), and nucleus sampling.
We have gone through a list of different ways to decode a response. These techniques can be applied to different generation tasks, i.e., image captioning, translation, and story generation. Using a good model with bad decoding strategies or a bad model with good decoding strategies is not enough. A good balance between the two can make the generation a lot more interesting.
Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2020). The Curious Case of Neural Text Degeneration. In International Conference on Learning Representations.
|
[
{
"code": null,
"e": 537,
"s": 171,
"text": "Deep learning has been deployed in many tasks in NLP, such as translation, image captioning, and dialogue systems. In machine translation, it is used to read source language (input) and generate the desired language (output). Similarly in a dialogue system, it is used to generate a response given a context. This is also known as Natural Language Generation (NLG)."
},
{
"code": null,
"e": 736,
"s": 537,
"text": "The model splits into 2 parts: encoder and decoder. Encoder reads the input text and returns a vector representing that input. Then, the decoder takes that vector and generates a corresponding text."
},
{
"code": null,
"e": 952,
"s": 736,
"text": "To generate a text, commonly it is done by generating one token at a time. Without proper techniques, the generated response may be very generic and boring. In this article, we will explore the following strategies:"
},
{
"code": null,
"e": 959,
"s": 952,
"text": "Greedy"
},
{
"code": null,
"e": 971,
"s": 959,
"text": "Beam Search"
},
{
"code": null,
"e": 987,
"s": 971,
"text": "Random Sampling"
},
{
"code": null,
"e": 999,
"s": 987,
"text": "Temperature"
},
{
"code": null,
"e": 1014,
"s": 999,
"text": "Top-K Sampling"
},
{
"code": null,
"e": 1031,
"s": 1014,
"text": "Nucleus Sampling"
},
{
"code": null,
"e": 1231,
"s": 1031,
"text": "At each timestep during decoding, we take the vector (that holds the information from one step to another) and apply it with softmax function to convert it into an array of probability for each word."
},
{
"code": null,
"e": 1340,
"s": 1231,
"text": "This approach is the simplest. At each time-step, it just chooses whichever token that is the most probable."
},
{
"code": null,
"e": 1470,
"s": 1340,
"text": "Context: Try this cake. I baked it myself.Optimal Response : This cake tastes great.Generated Response: This is okay."
},
{
"code": null,
"e": 1806,
"s": 1470,
"text": "However, this approach may generate a suboptimal response, as shown in the example above. The generated response may not be the best possible response. This is due to the training data that commonly have examples like “That is [...]”. Therefore, if we generate the most probable token at a time, it might output “is” instead of “cake”."
},
{
"code": null,
"e": 2061,
"s": 1806,
"text": "Exhaustive search can solve the previous problem since it will search for the whole space. However, it would be computationally expensive. Suppose there are 10,000 vocabularies, to generate a sentence with the length of 10 tokens, it would be (10,000)10."
},
{
"code": null,
"e": 2405,
"s": 2061,
"text": "Beam search can cope with this problem. At each timestep, it generates all possible tokens in the vocabulary list; then, it will choose top B candidates that have the most probability. Those B candidates will move to the next time step, and the process repeats. In the end, there will only be B candidates. The search space is only (10,000)*B."
},
{
"code": null,
"e": 2508,
"s": 2405,
"text": "Context: Try this cake. I baked it myself.Response A: That cake tastes great.Response B: Thank you."
},
{
"code": null,
"e": 2757,
"s": 2508,
"text": "But sometimes, it chooses an even more optimal (Response B). In this case, it makes perfect sense. But imagine that the model likes to play safe and keeps on generating “I don’t know” or “Thank you” to most of the context, that is a pretty bad bot."
},
{
"code": null,
"e": 2947,
"s": 2757,
"text": "Alternatively, we can look into stochastic approaches to avoid the response being generic. We can utilize the probability of each token from the softmax function to generate the next token."
},
{
"code": null,
"e": 3097,
"s": 2947,
"text": "Suppose we are generating the first token of a context “I love watching movies”, Figure below shows the probability of what the first word should be."
},
{
"code": null,
"e": 3337,
"s": 3097,
"text": "If we use a greedy approach, a token “i” will be chosen. With random sampling, however, token i has a probability of around 0.2 to occur. At the same time, any token that has a probability of 0.0001 can also occur. It’s just very unlikely."
},
{
"code": null,
"e": 3604,
"s": 3337,
"text": "Random sampling, by itself, could potentially generate a very random word by chance. Temperature is used to increase the probability of probable tokens while reducing the one that is not. Usually, the range is 0 < temp ≤ 1. Note that when temp=1, there is no effect."
},
{
"code": null,
"e": 3838,
"s": 3604,
"text": "In Figure 4, with temp=0.5, the most probable words like i, yeah, me, have more chance of being generated. At the same time, this also lowers the probability of the less probable ones, although this does not stop them from occurring."
},
{
"code": null,
"e": 4001,
"s": 3838,
"text": "Top-K sampling is used to ensure that the less probable words should not have any chance at all. Only top K probable tokens should be considered for a generation."
},
{
"code": null,
"e": 4330,
"s": 4001,
"text": "The token index between 50 to 80 has some small probabilities if we use random sampling with temperature=0.5 or 1.0. With top-k sampling (K=10), those tokens have no chance of being generated. Note that we can also combine Top-K sampling with temperature, but you kinda get the idea already, so we choose not to discuss it here."
},
{
"code": null,
"e": 4743,
"s": 4330,
"text": "This sampling technique has been adopted in many recent generation tasks. Its performance is quite good. One limitation with this approach is the number of top K words need to be defined in the beginning. Suppose we choose K=300; however, at a decoding timestep, the model is sure that there should be 10 highly probable words. If we use Top-K, that means we will also consider the other 290 less probable words."
},
{
"code": null,
"e": 5049,
"s": 4743,
"text": "Nucleus sampling is similar to Top-K sampling. Instead of focusing on Top-K words, nucleus sampling focuses on the smallest possible sets of Top-V words such that the sum of their probability is ≥ p. Then, the tokens that are not in V^(p) are set to 0; the rest are re-scaled to ensure that they sum to 1."
},
{
"code": null,
"e": 5223,
"s": 5049,
"text": "The intuition is that when the model is very certain on some tokens, the set of potential candidate tokens is small otherwise, there will be more potential candidate tokens."
},
{
"code": null,
"e": 5405,
"s": 5223,
"text": "Certain → those few tokens have high probability = sum of few tokens is enough to exceed p.Uncertain → Many tokens have small probability = sum of many tokens is needed to exceed p."
},
{
"code": null,
"e": 5653,
"s": 5405,
"text": "Comparing nucleus sampling (p=0.5) with top-K sampling (K = 10), we can see the nucleus does not consider token “you” to be a candidate. This shows that it can adapt to different cases and select different numbers of tokens, unlike Top-K sampling."
},
{
"code": null,
"e": 5702,
"s": 5653,
"text": "Greedy: Select the best probable token at a time"
},
{
"code": null,
"e": 5749,
"s": 5702,
"text": "Beam Search: Select the best probable response"
},
{
"code": null,
"e": 5794,
"s": 5749,
"text": "Random Sampling: Random based on probability"
},
{
"code": null,
"e": 5839,
"s": 5794,
"text": "Temperature: Shrink or enlarge probabilities"
},
{
"code": null,
"e": 5884,
"s": 5839,
"text": "Top-K Sampling: Select top probable K tokens"
},
{
"code": null,
"e": 5947,
"s": 5884,
"text": "Nucleus Sampling: Dynamically choose the number of K (sort of)"
},
{
"code": null,
"e": 6058,
"s": 5947,
"text": "Commonly, top choices by researchers are beam search, top-K sampling (with temperature), and nucleus sampling."
},
{
"code": null,
"e": 6435,
"s": 6058,
"text": "We have gone through a list of different ways to decode a response. These techniques can be applied to different generation tasks, i.e., image captioning, translation, and story generation. Using a good model with bad decoding strategies or a bad model with good decoding strategies is not enough. A good balance between the two can make the generation a lot more interesting."
}
] |
Explain some string functions of PHP - GeeksforGeeks
|
20 Oct, 2021
In the programming world, a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols as well. For example, “Hello World!”, “ID-34#90” etc. PHP also allows single quotes(‘ ‘) for defining a string. Every programming language provides some in-built functions for the manipulation of strings. Some of the basic string functions provided by PHP are as follows:
strlen() Function: It returns the length of the string i.e. the count of all the characters in the string including whitespaces characters.
Syntax:
strlen(string or variable name)
Example:
PHP
<?php $str = "Hello World!"; // Prints 12 as outputecho strlen($str); // Prints 13 in a new lineecho "<br>" . strlen("GeeksForGeeks"); ?>
Output:
12
13
strrev() Function: It returns the reversed string of the given string.
Syntax:
strrev(string or variable name)
Example:
PHP
<?php $str = "Hello World!";echo strrev($str); ?>
!dlroW olleH
trim(), ltrim(), rtrim(), and chop() Functions: It remove white spaces or other characters from the string. They have two parameters: one string and another charList, which is a list of characters that need to be omitted.
trim() – Removes characters or whitespaces from both sides.
rtrim() & chop() – Removes characters or whitespaces from right side.
ltrim() – Removes characters or whitespaces from the left side.
Note: The browser output of the code given in the examples below may vary from HTML output for these functions.
Syntax:
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)
Parameter Values:
$string: This mandatory parameter specifies the string to be checked.
$charlist: This optional parameter specifies which characters are to be removed from the string. In case, this parameter is not provided, the following characters are removed :“\0” – NULL“\t” – tab“\n” – new line“\x0B” – vertical tab“\r” – carriage return” “ – ordinary white space
“\0” – NULL
“\t” – tab
“\n” – new line
“\x0B” – vertical tab
“\r” – carriage return
” “ – ordinary white space
Note – The parameter charList is available only in PHP version 4.1 or higher.
Example:
PHP
<?php $str = "\nThis is an example for string functions.\n"; // Prints original stringecho $str; // Removes whitespaces from right endecho chop($str) . "<br>"; // Removes whitespaces from both endsecho trim($str) . "<br>"; // Removes whitespaces from right endecho rtrim($str) . "<br>"; // Removes whitespaces from left endecho ltrim($str); ?>
This is an example for string functions.
This is an example for string functions.<br>This is an example for string functions.<br>
This is an example for string functions.<br>This is an example for string functions.
strtoupper() and strtolower() Function: It returns the string after changing cases of its letters.
strtoupper() – It returns the string after converting all the letters to uppercase.
strtolower() – It returns the string after converting all the letters to lowercase.
Syntax:
strtoupper(string)
strtolower(string)
Example:
PHP
<?php $str = "GeeksForGeeks";echo strtoupper($str)."<br>";echo strtolower($str); ?>
Output:
GEEKSFORGEEKS
geeksforgeeks
str_split() Function: It returns an array containing parts of the string.
Syntax:
str_split(string, length)
Parameters:
string: It specifies the string to be checked, it can also be a variable name of type string.
length: It specifies the length of each part of the string to be stored in the string, by default, it is 1. If the length is larger than the size of the string, then the complete string is returned.
Example:
PHP
<?php $str = "GeeksForGeeks";print_r(str_split($str));echo "<br>";print_r(str_split($str, 3)); ?>
Output:
Array (
[0] => G
[1] => e
[2] => e
[3] => k
[4] => s
[5] => F
[6] => o
[7] => r
[8] => G
[9] => e
[10] => e
[11] => k
[12] => s
)
Array (
[0] => Gee
[1] => ksF
[2] => orG
[3] => eek
[4] => s
)
PHP-Questions
PHP-string
Picked
TrueGeek-2021
PHP
Strings
TrueGeek
Web Technologies
Strings
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24555,
"s": 24527,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25014,
"s": 24555,
"text": "In the programming world, a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols as well. For example, “Hello World!”, “ID-34#90” etc. PHP also allows single quotes(‘ ‘) for defining a string. Every programming language provides some in-built functions for the manipulation of strings. Some of the basic string functions provided by PHP are as follows:"
},
{
"code": null,
"e": 25154,
"s": 25014,
"text": "strlen() Function: It returns the length of the string i.e. the count of all the characters in the string including whitespaces characters."
},
{
"code": null,
"e": 25162,
"s": 25154,
"text": "Syntax:"
},
{
"code": null,
"e": 25194,
"s": 25162,
"text": "strlen(string or variable name)"
},
{
"code": null,
"e": 25203,
"s": 25194,
"text": "Example:"
},
{
"code": null,
"e": 25207,
"s": 25203,
"text": "PHP"
},
{
"code": "<?php $str = \"Hello World!\"; // Prints 12 as outputecho strlen($str); // Prints 13 in a new lineecho \"<br>\" . strlen(\"GeeksForGeeks\"); ?>",
"e": 25351,
"s": 25207,
"text": null
},
{
"code": null,
"e": 25361,
"s": 25353,
"text": "Output:"
},
{
"code": null,
"e": 25367,
"s": 25361,
"text": "12\n13"
},
{
"code": null,
"e": 25438,
"s": 25367,
"text": "strrev() Function: It returns the reversed string of the given string."
},
{
"code": null,
"e": 25446,
"s": 25438,
"text": "Syntax:"
},
{
"code": null,
"e": 25478,
"s": 25446,
"text": "strrev(string or variable name)"
},
{
"code": null,
"e": 25487,
"s": 25478,
"text": "Example:"
},
{
"code": null,
"e": 25491,
"s": 25487,
"text": "PHP"
},
{
"code": "<?php $str = \"Hello World!\";echo strrev($str); ?>",
"e": 25543,
"s": 25491,
"text": null
},
{
"code": null,
"e": 25556,
"s": 25543,
"text": "!dlroW olleH"
},
{
"code": null,
"e": 25779,
"s": 25556,
"text": "trim(), ltrim(), rtrim(), and chop() Functions: It remove white spaces or other characters from the string. They have two parameters: one string and another charList, which is a list of characters that need to be omitted."
},
{
"code": null,
"e": 25839,
"s": 25779,
"text": "trim() – Removes characters or whitespaces from both sides."
},
{
"code": null,
"e": 25910,
"s": 25839,
"text": "rtrim() & chop() – Removes characters or whitespaces from right side."
},
{
"code": null,
"e": 25974,
"s": 25910,
"text": "ltrim() – Removes characters or whitespaces from the left side."
},
{
"code": null,
"e": 26086,
"s": 25974,
"text": "Note: The browser output of the code given in the examples below may vary from HTML output for these functions."
},
{
"code": null,
"e": 26094,
"s": 26086,
"text": "Syntax:"
},
{
"code": null,
"e": 26188,
"s": 26094,
"text": "rtrim(string, charList)\nltrim(string, charList)\ntrim(string, charList)\nchop(string, charList)"
},
{
"code": null,
"e": 26206,
"s": 26188,
"text": "Parameter Values:"
},
{
"code": null,
"e": 26276,
"s": 26206,
"text": "$string: This mandatory parameter specifies the string to be checked."
},
{
"code": null,
"e": 26558,
"s": 26276,
"text": "$charlist: This optional parameter specifies which characters are to be removed from the string. In case, this parameter is not provided, the following characters are removed :“\\0” – NULL“\\t” – tab“\\n” – new line“\\x0B” – vertical tab“\\r” – carriage return” “ – ordinary white space"
},
{
"code": null,
"e": 26570,
"s": 26558,
"text": "“\\0” – NULL"
},
{
"code": null,
"e": 26581,
"s": 26570,
"text": "“\\t” – tab"
},
{
"code": null,
"e": 26597,
"s": 26581,
"text": "“\\n” – new line"
},
{
"code": null,
"e": 26619,
"s": 26597,
"text": "“\\x0B” – vertical tab"
},
{
"code": null,
"e": 26642,
"s": 26619,
"text": "“\\r” – carriage return"
},
{
"code": null,
"e": 26669,
"s": 26642,
"text": "” “ – ordinary white space"
},
{
"code": null,
"e": 26747,
"s": 26669,
"text": "Note – The parameter charList is available only in PHP version 4.1 or higher."
},
{
"code": null,
"e": 26756,
"s": 26747,
"text": "Example:"
},
{
"code": null,
"e": 26760,
"s": 26756,
"text": "PHP"
},
{
"code": "<?php $str = \"\\nThis is an example for string functions.\\n\"; // Prints original stringecho $str; // Removes whitespaces from right endecho chop($str) . \"<br>\"; // Removes whitespaces from both endsecho trim($str) . \"<br>\"; // Removes whitespaces from right endecho rtrim($str) . \"<br>\"; // Removes whitespaces from left endecho ltrim($str); ?>",
"e": 27111,
"s": 26760,
"text": null
},
{
"code": null,
"e": 27328,
"s": 27111,
"text": "This is an example for string functions.\n\nThis is an example for string functions.<br>This is an example for string functions.<br>\nThis is an example for string functions.<br>This is an example for string functions.\n"
},
{
"code": null,
"e": 27427,
"s": 27328,
"text": "strtoupper() and strtolower() Function: It returns the string after changing cases of its letters."
},
{
"code": null,
"e": 27511,
"s": 27427,
"text": "strtoupper() – It returns the string after converting all the letters to uppercase."
},
{
"code": null,
"e": 27595,
"s": 27511,
"text": "strtolower() – It returns the string after converting all the letters to lowercase."
},
{
"code": null,
"e": 27603,
"s": 27595,
"text": "Syntax:"
},
{
"code": null,
"e": 27641,
"s": 27603,
"text": "strtoupper(string)\nstrtolower(string)"
},
{
"code": null,
"e": 27650,
"s": 27641,
"text": "Example:"
},
{
"code": null,
"e": 27654,
"s": 27650,
"text": "PHP"
},
{
"code": "<?php $str = \"GeeksForGeeks\";echo strtoupper($str).\"<br>\";echo strtolower($str); ?>",
"e": 27740,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27748,
"s": 27740,
"text": "Output:"
},
{
"code": null,
"e": 27776,
"s": 27748,
"text": "GEEKSFORGEEKS\ngeeksforgeeks"
},
{
"code": null,
"e": 27850,
"s": 27776,
"text": "str_split() Function: It returns an array containing parts of the string."
},
{
"code": null,
"e": 27858,
"s": 27850,
"text": "Syntax:"
},
{
"code": null,
"e": 27884,
"s": 27858,
"text": "str_split(string, length)"
},
{
"code": null,
"e": 27896,
"s": 27884,
"text": "Parameters:"
},
{
"code": null,
"e": 27990,
"s": 27896,
"text": "string: It specifies the string to be checked, it can also be a variable name of type string."
},
{
"code": null,
"e": 28189,
"s": 27990,
"text": "length: It specifies the length of each part of the string to be stored in the string, by default, it is 1. If the length is larger than the size of the string, then the complete string is returned."
},
{
"code": null,
"e": 28198,
"s": 28189,
"text": "Example:"
},
{
"code": null,
"e": 28202,
"s": 28198,
"text": "PHP"
},
{
"code": "<?php $str = \"GeeksForGeeks\";print_r(str_split($str));echo \"<br>\";print_r(str_split($str, 3)); ?>",
"e": 28302,
"s": 28202,
"text": null
},
{
"code": null,
"e": 28310,
"s": 28302,
"text": "Output:"
},
{
"code": null,
"e": 28596,
"s": 28310,
"text": "Array ( \n [0] => G \n [1] => e \n [2] => e \n [3] => k \n [4] => s \n [5] => F \n [6] => o \n [7] => r \n [8] => G \n [9] => e \n [10] => e \n [11] => k \n [12] => s \n)\nArray ( \n [0] => Gee \n [1] => ksF \n [2] => orG \n [3] => eek \n [4] => s \n) "
},
{
"code": null,
"e": 28610,
"s": 28596,
"text": "PHP-Questions"
},
{
"code": null,
"e": 28621,
"s": 28610,
"text": "PHP-string"
},
{
"code": null,
"e": 28628,
"s": 28621,
"text": "Picked"
},
{
"code": null,
"e": 28642,
"s": 28628,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 28646,
"s": 28642,
"text": "PHP"
},
{
"code": null,
"e": 28654,
"s": 28646,
"text": "Strings"
},
{
"code": null,
"e": 28663,
"s": 28654,
"text": "TrueGeek"
},
{
"code": null,
"e": 28680,
"s": 28663,
"text": "Web Technologies"
},
{
"code": null,
"e": 28688,
"s": 28680,
"text": "Strings"
},
{
"code": null,
"e": 28692,
"s": 28688,
"text": "PHP"
},
{
"code": null,
"e": 28790,
"s": 28692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28840,
"s": 28790,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28880,
"s": 28840,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28941,
"s": 28880,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28991,
"s": 28941,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29018,
"s": 28991,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29043,
"s": 29018,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29089,
"s": 29043,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29123,
"s": 29089,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29183,
"s": 29123,
"text": "Write a program to print all permutations of a given string"
}
] |
Object Oriented Programming in Python?
|
Python has been an object oriented programming language since its existence. Classes and objects are the two main building blocks of object oriented programming.
A class creates a new type of objects where objects are instances of the class.
Let’s create one of the simplest class,
Let just define an empty class.
#Define a class
class Vehicle():
pass # An empty block
# Instantiating objects
v = Vehicle()
print(v)
<__main__.Vehicle object at 0x055DB9F0>
So first, we use class statement to create new class Vehicle, which is followed by an indented block of statements which form the body of the class. In our case, we have an empty block which is indicted using the pass statement.
Next, to use Vehicle class, we have created an object/instance of this class using the name of the class followed by a pair of parentheses. Then to confirm the object is created, we simply print it and get the information that we have an instance of the Vehicle class in the __main__ module.
Object(v) is an instance of a class. Each specific object is an instance of a particular class. We can create as many instances of a class and contain classes methods and properties.
All the methods and variables defined inside the class are accessible to its objects.
class Vehicle():
def car(self):
color = 'Red'
return color
v = Vehicle()
print(v.car())
print(v)
Red
<__main__.Vehicle object at 0x05A59690>
In python, when we define any method in a class, we need to provide one default argument to any instances method, which is self. It means when we create an object from that class, that object itself will pass in that method.
Generally we don’t provide any argument(self) while calling the function, but the argument(self) is a must, whenever we define that function inside that class.
Let’s understand above concept using example.
class myClass():
def myMethod(self):
return 'Hello'
myInstance = myClass()
print(myInstance.myMethod())
Hello
So in above program, we define a class myClass and inside it we defined a method myMethod() and pass only one argument called self.
However, when we call the method through the instance of a class, we have not provided any argument to it. This is because whenever we call the method on an instance, the first argument itself is an instance of a class.
Let’s modify one line from above program-
def myMethod():
I just remove the argument (self) from my method (myMethod()). Now let’s run the program again and see what happened.
================ RESTART: C:\Python\Python361\oops_python.py ================
Traceback (most recent call last):
File "C:\Python\Python361\oops_python.py", line 18, in <module>
print(myInstance.myMethod())
TypeError: myMethod() takes 0 positional arguments but 1 was given
So its mandatory that your first argument to the method is a self.
These are object-specific attributes defined as parameters to the __init__ method. Each object can have different values for themselves.
Consider below example,
import random
class myClass():
def myMethod(self):
self.attrib1 = random.randint(1, 11)
self.attrib2 = random.randint(1,21)
myInst = myClass()
myInst.myMethod()
print(myInst.attrib1)
print(myInst.attrib2)
2
18
In above program, the “attrib1” and “attrib2” are the instance attributes.
A constructor is a particular type of method which is used to initialize the instance members of the class.
Constructors can be of two types−
Parameterized Constructor
Non-parameterized constructor
In python, “__init__” is a unique method associated with every python class.
Python calls it automatically for every object created from the class. Its purpose is to initialize the class attributes with user-supplied values.
It is called constructor in object-oriented programming.
class Employee:
def __init__(self, name):
self.name = name
def display(self):
print("The name of the employee is: ", self.name)
obj1 = Employee('Zack')
obj2 = Employee('Rajesh')
obj3 = Employee('Tashleem')
obj3.display()
obj1.display()
The name of the employee is: Tashleem
The name of the employee is: Zack
In above program, when we create an instance (obj1 & obj2), we pass the name argument and constructor will assign that argument to the instance attribute.
So when we call the display method on a particular instance, we will get the particular name.
Being python is oop in nature, it provides a way to restrict the access to methods and variables.
With data encapsulation in place, we can not directly modify the instance attribute by calling an attribute on the object. It will make our application vulnerable to hackers. However, we only change the instance attribute values by calling the specific method.
class Product:
def __init__(self):
self.__maxprice = 1000
self.__minprice = 1
def sellingPrice(self):
print('Our product maximum price is: {}'.format(self.__maxprice))
print('Our product minimum price is: {}'.format(self.__minprice))
def productMaxPrice(self, price):
self.__maxprice = price
def productMinPrice(self, price):
self.__minprice = price
prod1= Product()
prod1.sellingPrice()
prod1.__maxprice = 1500
prod1.sellingPrice()
prod1.__minprice = 10
prod1.sellingPrice()
prod1.productMaxPrice(1500)
prod1.sellingPrice()
prod1.productMinPrice(10)
prod1.sellingPrice()
Our product maximum price is: 1000
Our product minimum price is: 1
Our product maximum price is: 1000
Our product minimum price is: 1
Our product maximum price is: 1000
Our product minimum price is: 1
Our product maximum price is: 1500
Our product minimum price is: 1
Our product maximum price is: 1500
Our product minimum price is: 10
In above program, we have created an instance of Product class and try to modify the instance variable’s value, but it still gives the value which set inside the constructor.
Only way to modify the instance attribute’s value is by calling the productMaxPrice() or productMinPrice() method.
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "Python has been an object oriented programming language since its existence. Classes and objects are the two main building blocks of object oriented programming."
},
{
"code": null,
"e": 1304,
"s": 1224,
"text": "A class creates a new type of objects where objects are instances of the class."
},
{
"code": null,
"e": 1344,
"s": 1304,
"text": "Let’s create one of the simplest class,"
},
{
"code": null,
"e": 1376,
"s": 1344,
"text": "Let just define an empty class."
},
{
"code": null,
"e": 1482,
"s": 1376,
"text": "#Define a class\nclass Vehicle():\n pass # An empty block\n\n# Instantiating objects\nv = Vehicle()\nprint(v)"
},
{
"code": null,
"e": 1522,
"s": 1482,
"text": "<__main__.Vehicle object at 0x055DB9F0>"
},
{
"code": null,
"e": 1751,
"s": 1522,
"text": "So first, we use class statement to create new class Vehicle, which is followed by an indented block of statements which form the body of the class. In our case, we have an empty block which is indicted using the pass statement."
},
{
"code": null,
"e": 2043,
"s": 1751,
"text": "Next, to use Vehicle class, we have created an object/instance of this class using the name of the class followed by a pair of parentheses. Then to confirm the object is created, we simply print it and get the information that we have an instance of the Vehicle class in the __main__ module."
},
{
"code": null,
"e": 2226,
"s": 2043,
"text": "Object(v) is an instance of a class. Each specific object is an instance of a particular class. We can create as many instances of a class and contain classes methods and properties."
},
{
"code": null,
"e": 2312,
"s": 2226,
"text": "All the methods and variables defined inside the class are accessible to its objects."
},
{
"code": null,
"e": 2425,
"s": 2312,
"text": "class Vehicle():\n def car(self):\n color = 'Red'\n return color\n\nv = Vehicle()\nprint(v.car())\nprint(v)"
},
{
"code": null,
"e": 2469,
"s": 2425,
"text": "Red\n<__main__.Vehicle object at 0x05A59690>"
},
{
"code": null,
"e": 2694,
"s": 2469,
"text": "In python, when we define any method in a class, we need to provide one default argument to any instances method, which is self. It means when we create an object from that class, that object itself will pass in that method."
},
{
"code": null,
"e": 2854,
"s": 2694,
"text": "Generally we don’t provide any argument(self) while calling the function, but the argument(self) is a must, whenever we define that function inside that class."
},
{
"code": null,
"e": 2900,
"s": 2854,
"text": "Let’s understand above concept using example."
},
{
"code": null,
"e": 3014,
"s": 2900,
"text": "class myClass():\n def myMethod(self):\n return 'Hello'\n\nmyInstance = myClass()\nprint(myInstance.myMethod())"
},
{
"code": null,
"e": 3020,
"s": 3014,
"text": "Hello"
},
{
"code": null,
"e": 3152,
"s": 3020,
"text": "So in above program, we define a class myClass and inside it we defined a method myMethod() and pass only one argument called self."
},
{
"code": null,
"e": 3372,
"s": 3152,
"text": "However, when we call the method through the instance of a class, we have not provided any argument to it. This is because whenever we call the method on an instance, the first argument itself is an instance of a class."
},
{
"code": null,
"e": 3414,
"s": 3372,
"text": "Let’s modify one line from above program-"
},
{
"code": null,
"e": 3430,
"s": 3414,
"text": "def myMethod():"
},
{
"code": null,
"e": 3548,
"s": 3430,
"text": "I just remove the argument (self) from my method (myMethod()). Now let’s run the program again and see what happened."
},
{
"code": null,
"e": 3821,
"s": 3548,
"text": "================ RESTART: C:\\Python\\Python361\\oops_python.py ================\nTraceback (most recent call last):\nFile \"C:\\Python\\Python361\\oops_python.py\", line 18, in <module>\nprint(myInstance.myMethod())\nTypeError: myMethod() takes 0 positional arguments but 1 was given"
},
{
"code": null,
"e": 3888,
"s": 3821,
"text": "So its mandatory that your first argument to the method is a self."
},
{
"code": null,
"e": 4025,
"s": 3888,
"text": "These are object-specific attributes defined as parameters to the __init__ method. Each object can have different values for themselves."
},
{
"code": null,
"e": 4049,
"s": 4025,
"text": "Consider below example,"
},
{
"code": null,
"e": 4257,
"s": 4049,
"text": "import random\n\nclass myClass():\ndef myMethod(self):\nself.attrib1 = random.randint(1, 11)\nself.attrib2 = random.randint(1,21)\n\nmyInst = myClass()\nmyInst.myMethod()\n\nprint(myInst.attrib1)\nprint(myInst.attrib2)"
},
{
"code": null,
"e": 4262,
"s": 4257,
"text": "2\n18"
},
{
"code": null,
"e": 4337,
"s": 4262,
"text": "In above program, the “attrib1” and “attrib2” are the instance attributes."
},
{
"code": null,
"e": 4445,
"s": 4337,
"text": "A constructor is a particular type of method which is used to initialize the instance members of the class."
},
{
"code": null,
"e": 4479,
"s": 4445,
"text": "Constructors can be of two types−"
},
{
"code": null,
"e": 4505,
"s": 4479,
"text": "Parameterized Constructor"
},
{
"code": null,
"e": 4535,
"s": 4505,
"text": "Non-parameterized constructor"
},
{
"code": null,
"e": 4612,
"s": 4535,
"text": "In python, “__init__” is a unique method associated with every python class."
},
{
"code": null,
"e": 4760,
"s": 4612,
"text": "Python calls it automatically for every object created from the class. Its purpose is to initialize the class attributes with user-supplied values."
},
{
"code": null,
"e": 4817,
"s": 4760,
"text": "It is called constructor in object-oriented programming."
},
{
"code": null,
"e": 5076,
"s": 4817,
"text": "class Employee:\n def __init__(self, name):\n self.name = name\n \n def display(self):\n print(\"The name of the employee is: \", self.name)\nobj1 = Employee('Zack')\nobj2 = Employee('Rajesh')\nobj3 = Employee('Tashleem')\n\nobj3.display()\nobj1.display()"
},
{
"code": null,
"e": 5148,
"s": 5076,
"text": "The name of the employee is: Tashleem\nThe name of the employee is: Zack"
},
{
"code": null,
"e": 5303,
"s": 5148,
"text": "In above program, when we create an instance (obj1 & obj2), we pass the name argument and constructor will assign that argument to the instance attribute."
},
{
"code": null,
"e": 5397,
"s": 5303,
"text": "So when we call the display method on a particular instance, we will get the particular name."
},
{
"code": null,
"e": 5495,
"s": 5397,
"text": "Being python is oop in nature, it provides a way to restrict the access to methods and variables."
},
{
"code": null,
"e": 5756,
"s": 5495,
"text": "With data encapsulation in place, we can not directly modify the instance attribute by calling an attribute on the object. It will make our application vulnerable to hackers. However, we only change the instance attribute values by calling the specific method."
},
{
"code": null,
"e": 6375,
"s": 5756,
"text": "class Product:\n def __init__(self):\n self.__maxprice = 1000\n self.__minprice = 1\n\n def sellingPrice(self):\n print('Our product maximum price is: {}'.format(self.__maxprice))\n print('Our product minimum price is: {}'.format(self.__minprice))\n\n def productMaxPrice(self, price):\n self.__maxprice = price\n\ndef productMinPrice(self, price):\nself.__minprice = price\n\nprod1= Product()\nprod1.sellingPrice()\n\nprod1.__maxprice = 1500\nprod1.sellingPrice()\n\nprod1.__minprice = 10\nprod1.sellingPrice()\n\nprod1.productMaxPrice(1500)\nprod1.sellingPrice()\n\nprod1.productMinPrice(10)\nprod1.sellingPrice()"
},
{
"code": null,
"e": 6711,
"s": 6375,
"text": "Our product maximum price is: 1000\nOur product minimum price is: 1\nOur product maximum price is: 1000\nOur product minimum price is: 1\nOur product maximum price is: 1000\nOur product minimum price is: 1\nOur product maximum price is: 1500\nOur product minimum price is: 1\nOur product maximum price is: 1500\nOur product minimum price is: 10"
},
{
"code": null,
"e": 6886,
"s": 6711,
"text": "In above program, we have created an instance of Product class and try to modify the instance variable’s value, but it still gives the value which set inside the constructor."
},
{
"code": null,
"e": 7001,
"s": 6886,
"text": "Only way to modify the instance attribute’s value is by calling the productMaxPrice() or productMinPrice() method."
}
] |
Node.js - Console
|
Node.js console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning, and error messages.
It is used in synchronous way when the destination is a file or a terminal and in asynchronous way when the destination is a pipe.
Following is a list of methods available with the console global object.
console.log([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-like way.
console.info([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-like way.
console.error([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-like way.
console.warn([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-like way
console.dir(obj[, options])
Uses util.inspect on obj and prints resulting string to stdout.
console.time(label)
Mark a time.
console.timeEnd(label)
Finish timer, record output.
console.trace(message[, ...])
Print to stderr 'Trace :', followed by the formatted message and stack trace to the current position.
console.assert(value[, message][, ...])
Similar to assert.ok(), but the error message is formatted as util.format(message...).
Let us create a js file named main.js with the following code −
console.info("Program Started");
var counter = 10;
console.log("Counter: %d", counter);
console.time("Getting data");
//
// Do some processing here...
//
console.timeEnd('Getting data');
console.info("Program Ended")
Now run the main.js to see the result −
node main.js
Verify the Output.
Program Started
Counter: 10
Getting data: 0ms
Program Ended
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2220,
"s": 2018,
"text": "Node.js console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning, and error messages."
},
{
"code": null,
"e": 2352,
"s": 2220,
"text": "It is used in synchronous way when the destination is a file or a terminal and in asynchronous way when the destination is a pipe. "
},
{
"code": null,
"e": 2425,
"s": 2352,
"text": "Following is a list of methods available with the console global object."
},
{
"code": null,
"e": 2452,
"s": 2425,
"text": "console.log([data][, ...])"
},
{
"code": null,
"e": 2549,
"s": 2452,
"text": "Prints to stdout with newline. This function can take multiple arguments in a printf()-like way."
},
{
"code": null,
"e": 2577,
"s": 2549,
"text": "console.info([data][, ...])"
},
{
"code": null,
"e": 2674,
"s": 2577,
"text": "Prints to stdout with newline. This function can take multiple arguments in a printf()-like way."
},
{
"code": null,
"e": 2703,
"s": 2674,
"text": "console.error([data][, ...])"
},
{
"code": null,
"e": 2800,
"s": 2703,
"text": "Prints to stderr with newline. This function can take multiple arguments in a printf()-like way."
},
{
"code": null,
"e": 2828,
"s": 2800,
"text": "console.warn([data][, ...])"
},
{
"code": null,
"e": 2924,
"s": 2828,
"text": "Prints to stderr with newline. This function can take multiple arguments in a printf()-like way"
},
{
"code": null,
"e": 2952,
"s": 2924,
"text": "console.dir(obj[, options])"
},
{
"code": null,
"e": 3016,
"s": 2952,
"text": "Uses util.inspect on obj and prints resulting string to stdout."
},
{
"code": null,
"e": 3036,
"s": 3016,
"text": "console.time(label)"
},
{
"code": null,
"e": 3049,
"s": 3036,
"text": "Mark a time."
},
{
"code": null,
"e": 3072,
"s": 3049,
"text": "console.timeEnd(label)"
},
{
"code": null,
"e": 3101,
"s": 3072,
"text": "Finish timer, record output."
},
{
"code": null,
"e": 3131,
"s": 3101,
"text": "console.trace(message[, ...])"
},
{
"code": null,
"e": 3233,
"s": 3131,
"text": "Print to stderr 'Trace :', followed by the formatted message and stack trace to the current position."
},
{
"code": null,
"e": 3273,
"s": 3233,
"text": "console.assert(value[, message][, ...])"
},
{
"code": null,
"e": 3360,
"s": 3273,
"text": "Similar to assert.ok(), but the error message is formatted as util.format(message...)."
},
{
"code": null,
"e": 3424,
"s": 3360,
"text": "Let us create a js file named main.js with the following code −"
},
{
"code": null,
"e": 3645,
"s": 3424,
"text": "console.info(\"Program Started\");\n\nvar counter = 10;\nconsole.log(\"Counter: %d\", counter);\n\nconsole.time(\"Getting data\");\n//\n// Do some processing here...\n// \nconsole.timeEnd('Getting data');\n\nconsole.info(\"Program Ended\")"
},
{
"code": null,
"e": 3685,
"s": 3645,
"text": "Now run the main.js to see the result −"
},
{
"code": null,
"e": 3699,
"s": 3685,
"text": "node main.js\n"
},
{
"code": null,
"e": 3718,
"s": 3699,
"text": "Verify the Output."
},
{
"code": null,
"e": 3779,
"s": 3718,
"text": "Program Started\nCounter: 10\nGetting data: 0ms\nProgram Ended\n"
},
{
"code": null,
"e": 3814,
"s": 3779,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3842,
"s": 3814,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3876,
"s": 3842,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3904,
"s": 3876,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3939,
"s": 3904,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3954,
"s": 3939,
"text": " Richard Wells"
},
{
"code": null,
"e": 3985,
"s": 3954,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 3999,
"s": 3985,
"text": " Anant Rungta"
},
{
"code": null,
"e": 4033,
"s": 3999,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4053,
"s": 4033,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4086,
"s": 4053,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4106,
"s": 4086,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4113,
"s": 4106,
"text": " Print"
},
{
"code": null,
"e": 4124,
"s": 4113,
"text": " Add Notes"
}
] |
Install Pyspark and use GraphFrames on macOS and Linux | by Andrewngai | Towards Data Science
|
All the following operations should be done under Terminal.
Download Spark
Download Spark
wget http://d3kbcqa49mib13.cloudfront.net/spark-2.2.0-bin-hadoop2.7.tgz
2. Unpack the file
tar xf spark-2.2.0-bin-hadoop2.7.tgz
3. Install Java8 if necessary
sudo add-apt-repository ppa:openjdk-r/ppasudo apt-get updatesudo apt-get install openjdk-8-jdk
You can check your installation by “java -version”. If it is not “1.8.xxx”, you need to follow step5–6 to choose the right java version for spark to use.
sudo update-java-alternatives — set java-1.8.0-openjdk-amd64
Restart your terminal.
4. (Optional) If you want to use Spark more skillfully, it’s better for you to get familiar with Basic Linux Commands and Basic Bash Operations. You can refer to the following book http://linux-training.be/linuxfun.pdf
Install Homebrew:
Install Homebrew:
/usr/bin/ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2. Install Scala:
brew install scala
3. Install Spark:
brew install apache-spark
4. Start spark python shell (in the spark directory):
pyspark
Install Anaconda.
Install Anaconda.
Linux:
wget https://repo.continuum.io/archive/Anaconda2-4.3.0-Linux-x86_64.sh
Mac OS:
wget https://repo.anaconda.com/archive/Anaconda2-2019.07-MacOSX-x86_64.sh
Install:
bash Anaconda2–4.3.0-Linux-x86_64.sh (Use corresponding file)
Update $PATH variable
Linux: source ~/.bashrc
Mac OS: source ~/.bash_profile
Modify pyspark driver
export PYSPARK_DRIVER_PYTHON=”jupyter”
export PYSPARK_DRIVER_PYTHON_OPTS=”notebook”
Start spark python shell (in the spark directory):
./bin/pyspark
Notes:
you can execute “unset PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS” to run normal pyspark shellIf you find this error “I couldn’t find a kernel matching PySpark. Please select a kernel:” after you upload notebooks from lecture notes, you just choose Python2 kernel which already supports pyspark kernel.After you finish the steps, create a new notebook, type “sc” and run it. If you see “pyspark.context.SparkContext” in the output, the installation should be successful.
you can execute “unset PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS” to run normal pyspark shell
If you find this error “I couldn’t find a kernel matching PySpark. Please select a kernel:” after you upload notebooks from lecture notes, you just choose Python2 kernel which already supports pyspark kernel.
After you finish the steps, create a new notebook, type “sc” and run it. If you see “pyspark.context.SparkContext” in the output, the installation should be successful.
For pre-installed Spark version ubuntu, to use GraphFrames:
get the jar file:
wget http://dl.bintray.com/spark-packages/maven/graphframes/graphframes/0.7.0-spark2.4-s_2.11/graphframes-0.7.0-spark2.4-s_2.11.jar
Load the jar file in the Jupyter notebooksc.addPyFile(‘path_to_the_jar_file’)
Using the pyspark shell directly with GraphFrames:
./bin/pyspark — packages graphframes:graphframes:0.7.0-spark2.4-s_2.11
Using Jupyter locally:
Set the environment variable:export SPARK_OPTS=” — packages graphframes:graphframes:0.7.0-spark2.4-s_2.11"
get the jar file:wget http://dl.bintray.com/spark-packages/maven/graphframes/graphframes/0.7.0-spark2.4-s_2.11/graphframes-0.7.0-spark2.4-s_2.11.jar
Load the jar file in the Jupyter notebooksc.addPyFile(‘path_to_the_jar_file’)
In Azure Databricks Service:
Start the cluster
Search for “graphframes’ and install the library
Thanks for reading and I am looking forward to hearing your questions and thoughts. If you want to learn more about Data Science and Cloud Computing, you can find me on Linkedin.
|
[
{
"code": null,
"e": 232,
"s": 172,
"text": "All the following operations should be done under Terminal."
},
{
"code": null,
"e": 247,
"s": 232,
"text": "Download Spark"
},
{
"code": null,
"e": 262,
"s": 247,
"text": "Download Spark"
},
{
"code": null,
"e": 334,
"s": 262,
"text": "wget http://d3kbcqa49mib13.cloudfront.net/spark-2.2.0-bin-hadoop2.7.tgz"
},
{
"code": null,
"e": 353,
"s": 334,
"text": "2. Unpack the file"
},
{
"code": null,
"e": 390,
"s": 353,
"text": "tar xf spark-2.2.0-bin-hadoop2.7.tgz"
},
{
"code": null,
"e": 420,
"s": 390,
"text": "3. Install Java8 if necessary"
},
{
"code": null,
"e": 515,
"s": 420,
"text": "sudo add-apt-repository ppa:openjdk-r/ppasudo apt-get updatesudo apt-get install openjdk-8-jdk"
},
{
"code": null,
"e": 669,
"s": 515,
"text": "You can check your installation by “java -version”. If it is not “1.8.xxx”, you need to follow step5–6 to choose the right java version for spark to use."
},
{
"code": null,
"e": 730,
"s": 669,
"text": "sudo update-java-alternatives — set java-1.8.0-openjdk-amd64"
},
{
"code": null,
"e": 753,
"s": 730,
"text": "Restart your terminal."
},
{
"code": null,
"e": 972,
"s": 753,
"text": "4. (Optional) If you want to use Spark more skillfully, it’s better for you to get familiar with Basic Linux Commands and Basic Bash Operations. You can refer to the following book http://linux-training.be/linuxfun.pdf"
},
{
"code": null,
"e": 990,
"s": 972,
"text": "Install Homebrew:"
},
{
"code": null,
"e": 1008,
"s": 990,
"text": "Install Homebrew:"
},
{
"code": null,
"e": 1107,
"s": 1008,
"text": "/usr/bin/ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\""
},
{
"code": null,
"e": 1125,
"s": 1107,
"text": "2. Install Scala:"
},
{
"code": null,
"e": 1144,
"s": 1125,
"text": "brew install scala"
},
{
"code": null,
"e": 1162,
"s": 1144,
"text": "3. Install Spark:"
},
{
"code": null,
"e": 1188,
"s": 1162,
"text": "brew install apache-spark"
},
{
"code": null,
"e": 1242,
"s": 1188,
"text": "4. Start spark python shell (in the spark directory):"
},
{
"code": null,
"e": 1250,
"s": 1242,
"text": "pyspark"
},
{
"code": null,
"e": 1268,
"s": 1250,
"text": "Install Anaconda."
},
{
"code": null,
"e": 1286,
"s": 1268,
"text": "Install Anaconda."
},
{
"code": null,
"e": 1293,
"s": 1286,
"text": "Linux:"
},
{
"code": null,
"e": 1364,
"s": 1293,
"text": "wget https://repo.continuum.io/archive/Anaconda2-4.3.0-Linux-x86_64.sh"
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Mac OS:"
},
{
"code": null,
"e": 1446,
"s": 1372,
"text": "wget https://repo.anaconda.com/archive/Anaconda2-2019.07-MacOSX-x86_64.sh"
},
{
"code": null,
"e": 1455,
"s": 1446,
"text": "Install:"
},
{
"code": null,
"e": 1517,
"s": 1455,
"text": "bash Anaconda2–4.3.0-Linux-x86_64.sh (Use corresponding file)"
},
{
"code": null,
"e": 1539,
"s": 1517,
"text": "Update $PATH variable"
},
{
"code": null,
"e": 1563,
"s": 1539,
"text": "Linux: source ~/.bashrc"
},
{
"code": null,
"e": 1594,
"s": 1563,
"text": "Mac OS: source ~/.bash_profile"
},
{
"code": null,
"e": 1616,
"s": 1594,
"text": "Modify pyspark driver"
},
{
"code": null,
"e": 1655,
"s": 1616,
"text": "export PYSPARK_DRIVER_PYTHON=”jupyter”"
},
{
"code": null,
"e": 1700,
"s": 1655,
"text": "export PYSPARK_DRIVER_PYTHON_OPTS=”notebook”"
},
{
"code": null,
"e": 1751,
"s": 1700,
"text": "Start spark python shell (in the spark directory):"
},
{
"code": null,
"e": 1765,
"s": 1751,
"text": "./bin/pyspark"
},
{
"code": null,
"e": 1772,
"s": 1765,
"text": "Notes:"
},
{
"code": null,
"e": 2249,
"s": 1772,
"text": "you can execute “unset PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS” to run normal pyspark shellIf you find this error “I couldn’t find a kernel matching PySpark. Please select a kernel:” after you upload notebooks from lecture notes, you just choose Python2 kernel which already supports pyspark kernel.After you finish the steps, create a new notebook, type “sc” and run it. If you see “pyspark.context.SparkContext” in the output, the installation should be successful."
},
{
"code": null,
"e": 2350,
"s": 2249,
"text": "you can execute “unset PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS” to run normal pyspark shell"
},
{
"code": null,
"e": 2559,
"s": 2350,
"text": "If you find this error “I couldn’t find a kernel matching PySpark. Please select a kernel:” after you upload notebooks from lecture notes, you just choose Python2 kernel which already supports pyspark kernel."
},
{
"code": null,
"e": 2728,
"s": 2559,
"text": "After you finish the steps, create a new notebook, type “sc” and run it. If you see “pyspark.context.SparkContext” in the output, the installation should be successful."
},
{
"code": null,
"e": 2788,
"s": 2728,
"text": "For pre-installed Spark version ubuntu, to use GraphFrames:"
},
{
"code": null,
"e": 2806,
"s": 2788,
"text": "get the jar file:"
},
{
"code": null,
"e": 2938,
"s": 2806,
"text": "wget http://dl.bintray.com/spark-packages/maven/graphframes/graphframes/0.7.0-spark2.4-s_2.11/graphframes-0.7.0-spark2.4-s_2.11.jar"
},
{
"code": null,
"e": 3016,
"s": 2938,
"text": "Load the jar file in the Jupyter notebooksc.addPyFile(‘path_to_the_jar_file’)"
},
{
"code": null,
"e": 3067,
"s": 3016,
"text": "Using the pyspark shell directly with GraphFrames:"
},
{
"code": null,
"e": 3138,
"s": 3067,
"text": "./bin/pyspark — packages graphframes:graphframes:0.7.0-spark2.4-s_2.11"
},
{
"code": null,
"e": 3161,
"s": 3138,
"text": "Using Jupyter locally:"
},
{
"code": null,
"e": 3268,
"s": 3161,
"text": "Set the environment variable:export SPARK_OPTS=” — packages graphframes:graphframes:0.7.0-spark2.4-s_2.11\""
},
{
"code": null,
"e": 3417,
"s": 3268,
"text": "get the jar file:wget http://dl.bintray.com/spark-packages/maven/graphframes/graphframes/0.7.0-spark2.4-s_2.11/graphframes-0.7.0-spark2.4-s_2.11.jar"
},
{
"code": null,
"e": 3495,
"s": 3417,
"text": "Load the jar file in the Jupyter notebooksc.addPyFile(‘path_to_the_jar_file’)"
},
{
"code": null,
"e": 3524,
"s": 3495,
"text": "In Azure Databricks Service:"
},
{
"code": null,
"e": 3542,
"s": 3524,
"text": "Start the cluster"
},
{
"code": null,
"e": 3591,
"s": 3542,
"text": "Search for “graphframes’ and install the library"
}
] |
GATE CS 2013 - GeeksforGeeks
|
11 Oct, 2021
Which one of the following does NOT equal to
C
D
B
A
First of all, you should know the basic properties of determinants before approaching For these kind of problems. 1) Applying any row or column transformation does not change the determinant 2) If you interchange any two rows, sign of the determinant will change
A = | 1 x x^2 | | 1 y y^2 | | 1 z z^2 |
To prove option (b)
=> Apply column transformation C2 -> C2+C1
C3 -> C3+C1
=> det(A) = | 1 x+1 x^2+1 | | 1 y+1 y^2+1 | | 1 z+1 z^2+1 |
To prove option (c),
=> Apply row transformations R1 -> R1-R2
R2 -> R2-R3
=> det(A) = | 0 x-y x^2-y^2 | | 0 y-z y^2-z^2 | | 1 z z^2 |
To prove option (d),
=> Apply row transformations R1 -> R1+R2
R2 -> R2+R3
=> det(A) = | 2 x+y x^2+y^2 | | 2 y+z y^2+z^2 | | 1 z z^2 |
To insert 50, we will have to traverse all nodes.
10
\
20
\
30
\
40
S->aB
B->bC
C->cd
S -> aB ( Reduction 3 )
-> abC ( Reduction 2 )
-> abcd ( Reduction 1 )
S->abA
A-> cd
S -> abA ( Reduction 2 )
-> abcd ( Reduction 1 )
GROUP I GROUP II
(P) Service oriented computing (1) Interoperability
(Q) Heterogeneous communicating systems (2) BPMN
(R) Information representation (3) Publish-find-bind
(S) Process description (4) XML
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
HackWithInfy - A Coding Competition by Infosys
|
[
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 27265,
"s": 27219,
"text": "Which one of the following does NOT equal to "
},
{
"code": null,
"e": 27272,
"s": 27269,
"text": "C "
},
{
"code": null,
"e": 27275,
"s": 27272,
"text": "D "
},
{
"code": null,
"e": 27278,
"s": 27275,
"text": "B "
},
{
"code": null,
"e": 27281,
"s": 27278,
"text": "A "
},
{
"code": null,
"e": 27548,
"s": 27285,
"text": "First of all, you should know the basic properties of determinants before approaching For these kind of problems. 1) Applying any row or column transformation does not change the determinant 2) If you interchange any two rows, sign of the determinant will change"
},
{
"code": null,
"e": 27592,
"s": 27552,
"text": "A = | 1 x x^2 | | 1 y y^2 | | 1 z z^2 |"
},
{
"code": null,
"e": 27614,
"s": 27594,
"text": "To prove option (b)"
},
{
"code": null,
"e": 27659,
"s": 27616,
"text": "=> Apply column transformation C2 -> C2+C1"
},
{
"code": null,
"e": 27673,
"s": 27661,
"text": "C3 -> C3+C1"
},
{
"code": null,
"e": 27735,
"s": 27675,
"text": "=> det(A) = | 1 x+1 x^2+1 | | 1 y+1 y^2+1 | | 1 z+1 z^2+1 |"
},
{
"code": null,
"e": 27758,
"s": 27737,
"text": "To prove option (c),"
},
{
"code": null,
"e": 27801,
"s": 27760,
"text": "=> Apply row transformations R1 -> R1-R2"
},
{
"code": null,
"e": 27815,
"s": 27803,
"text": "R2 -> R2-R3"
},
{
"code": null,
"e": 27877,
"s": 27817,
"text": "=> det(A) = | 0 x-y x^2-y^2 | | 0 y-z y^2-z^2 | | 1 z z^2 |"
},
{
"code": null,
"e": 27900,
"s": 27879,
"text": "To prove option (d),"
},
{
"code": null,
"e": 27943,
"s": 27902,
"text": "=> Apply row transformations R1 -> R1+R2"
},
{
"code": null,
"e": 27957,
"s": 27945,
"text": "R2 -> R2+R3"
},
{
"code": null,
"e": 28019,
"s": 27959,
"text": "=> det(A) = | 2 x+y x^2+y^2 | | 2 y+z y^2+z^2 | | 1 z z^2 |"
},
{
"code": null,
"e": 28173,
"s": 28021,
"text": "To insert 50, we will have to traverse all nodes.\n 10\n \\\n 20\n \\\n 30\n \\\n 40\n"
},
{
"code": null,
"e": 28192,
"s": 28173,
"text": "S->aB\nB->bC\nC->cd "
},
{
"code": null,
"e": 28263,
"s": 28192,
"text": "S -> aB ( Reduction 3 )\n-> abC ( Reduction 2 )\n-> abcd ( Reduction 1 )"
},
{
"code": null,
"e": 28277,
"s": 28263,
"text": "S->abA\nA-> cd"
},
{
"code": null,
"e": 28326,
"s": 28277,
"text": "S -> abA ( Reduction 2 )\n-> abcd ( Reduction 1 )"
},
{
"code": null,
"e": 28632,
"s": 28326,
"text": "GROUP I GROUP II\n(P) Service oriented computing (1) Interoperability\n(Q) Heterogeneous communicating systems (2) BPMN\n(R) Information representation (3) Publish-find-bind\n(S) Process description (4) XML "
},
{
"code": null,
"e": 28730,
"s": 28632,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28739,
"s": 28730,
"text": "Comments"
},
{
"code": null,
"e": 28752,
"s": 28739,
"text": "Old Comments"
},
{
"code": null,
"e": 28805,
"s": 28752,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 28864,
"s": 28805,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28925,
"s": 28864,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29002,
"s": 28925,
"text": "Find number of rectangles that can be formed from a given set of coordinates"
},
{
"code": null,
"e": 29064,
"s": 29002,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29105,
"s": 29064,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29148,
"s": 29105,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29184,
"s": 29148,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29234,
"s": 29184,
"text": "Infosys DSE Interview Experience | On-Campus 2021"
}
] |
Design 101 sequence detector (Mealy machine) - GeeksforGeeks
|
01 Apr, 2021
Prerequisite – Mealy and Moore machines A sequence detector is a sequential state machine that takes an input string of bits and generates an output 1 whenever the target sequence has been detected. In a Mealy machine, output depends on the present state and the external input (x). Hence, in the diagram, the output is written outside the states, along with inputs. Sequence detector is of two types:
OverlappingNon-Overlapping
Overlapping
Non-Overlapping
In an overlapping sequence detector, the last bit of one sequence becomes the first bit of the next sequence. However, in a non-overlapping sequence detector, the last bit of one sequence does not become the first bit of the next sequence. In this post, we’ll discuss the design procedure for non-overlapping 101 Mealy sequence detectors.
Examples:
For non overlapping case
Input :0110101011001
Output:0000100010000
For overlapping case
Input :0110101011001
Output:0000101010000
The steps to design a non-overlapping 101 Mealy sequence detectors are:
Step 1: Develop the state diagram – The state diagram of a Mealy machine for a 101 sequence detector is:
Step 2: Code Assignment –
Rule 1 : States having the same next states for a given input condition should have adjacent assignments. Rule 2: States that are the next states to a single state must be given adjacent assignments. Rule 1 given preference over Rule 2.
The state diagram after the code assignment is:
Step 3: Make Present State/Next State table – We’ll use D-Flip Flops for design purposes.
Step 4: Draw K-maps for Dx, Dy and output (Z) –
Step 5: Finally implement the circuit –
This is the final circuit for a Mealy 101 non-overlapping sequence detector.
pavanpal25878543
Digital Electronics & Logic Design
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between RAM and ROM
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Difference between Half adder and full adder
Difference between DFA and NFA
Introduction of Finite Automata
Regular Expressions, Regular Grammar and Regular Languages
Conversion from NFA to DFA
Pumping Lemma in Theory of Computation
|
[
{
"code": null,
"e": 26445,
"s": 26417,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 26849,
"s": 26445,
"text": "Prerequisite – Mealy and Moore machines A sequence detector is a sequential state machine that takes an input string of bits and generates an output 1 whenever the target sequence has been detected. In a Mealy machine, output depends on the present state and the external input (x). Hence, in the diagram, the output is written outside the states, along with inputs. Sequence detector is of two types: "
},
{
"code": null,
"e": 26876,
"s": 26849,
"text": "OverlappingNon-Overlapping"
},
{
"code": null,
"e": 26888,
"s": 26876,
"text": "Overlapping"
},
{
"code": null,
"e": 26904,
"s": 26888,
"text": "Non-Overlapping"
},
{
"code": null,
"e": 27245,
"s": 26904,
"text": "In an overlapping sequence detector, the last bit of one sequence becomes the first bit of the next sequence. However, in a non-overlapping sequence detector, the last bit of one sequence does not become the first bit of the next sequence. In this post, we’ll discuss the design procedure for non-overlapping 101 Mealy sequence detectors. "
},
{
"code": null,
"e": 27256,
"s": 27245,
"text": "Examples: "
},
{
"code": null,
"e": 27387,
"s": 27256,
"text": "For non overlapping case\nInput :0110101011001\nOutput:0000100010000\n\nFor overlapping case\nInput :0110101011001\nOutput:0000101010000"
},
{
"code": null,
"e": 27461,
"s": 27387,
"text": "The steps to design a non-overlapping 101 Mealy sequence detectors are: "
},
{
"code": null,
"e": 27567,
"s": 27461,
"text": "Step 1: Develop the state diagram – The state diagram of a Mealy machine for a 101 sequence detector is: "
},
{
"code": null,
"e": 27596,
"s": 27569,
"text": "Step 2: Code Assignment – "
},
{
"code": null,
"e": 27834,
"s": 27596,
"text": "Rule 1 : States having the same next states for a given input condition should have adjacent assignments. Rule 2: States that are the next states to a single state must be given adjacent assignments. Rule 1 given preference over Rule 2. "
},
{
"code": null,
"e": 27885,
"s": 27836,
"text": "The state diagram after the code assignment is: "
},
{
"code": null,
"e": 27978,
"s": 27887,
"text": "Step 3: Make Present State/Next State table – We’ll use D-Flip Flops for design purposes. "
},
{
"code": null,
"e": 28029,
"s": 27980,
"text": "Step 4: Draw K-maps for Dx, Dy and output (Z) – "
},
{
"code": null,
"e": 28072,
"s": 28031,
"text": "Step 5: Finally implement the circuit – "
},
{
"code": null,
"e": 28152,
"s": 28074,
"text": "This is the final circuit for a Mealy 101 non-overlapping sequence detector. "
},
{
"code": null,
"e": 28169,
"s": 28152,
"text": "pavanpal25878543"
},
{
"code": null,
"e": 28204,
"s": 28169,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 28237,
"s": 28204,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 28335,
"s": 28237,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28344,
"s": 28335,
"text": "Comments"
},
{
"code": null,
"e": 28357,
"s": 28344,
"text": "Old Comments"
},
{
"code": null,
"e": 28398,
"s": 28357,
"text": "IEEE Standard 754 Floating Point Numbers"
},
{
"code": null,
"e": 28428,
"s": 28398,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 28459,
"s": 28428,
"text": "Difference between RAM and ROM"
},
{
"code": null,
"e": 28526,
"s": 28459,
"text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes"
},
{
"code": null,
"e": 28571,
"s": 28526,
"text": "Difference between Half adder and full adder"
},
{
"code": null,
"e": 28602,
"s": 28571,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 28634,
"s": 28602,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 28693,
"s": 28634,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 28720,
"s": 28693,
"text": "Conversion from NFA to DFA"
}
] |
Find the next fibonacci number - GeeksforGeeks
|
10 Mar, 2022
Given a fibonacci number N, the task is to find the next fibonacci number.Examples:
Input: N = 5 Output: 8 8 is the next fibonacci number after 5Input: N = 3 Output: 5
Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is multiplied by ((1 + sqrt(5)) / 2) and round it, the resultant number will be the next fibonacci number.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the next// fibonacci numberint nextFibonacci(int n){ double a = n * (1 + sqrt(5)) / 2.0; return round(a);} // Driver codeint main(){ int n = 5; cout << nextFibonacci(n);} // This code is contributed by mohit kumar 29
// Java implementation of the approachclass GFG{ // Function to return the next // fibonacci number static long nextFibonacci(int n) { double a = n * (1 + Math.sqrt(5)) / 2.0; return Math.round(a); } // Driver code public static void main (String[] args) { int n = 5; System.out.println(nextFibonacci(n)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachfrom math import * # Function to return the next# fibonacci numberdef nextFibonacci(n): a = n*(1 + sqrt(5))/2.0 return round(a) # Driver coden = 5print(nextFibonacci(n))
// C# implementation of the approachusing System; class GFG{ // Function to return the next // fibonacci number static long nextFibonacci(int n) { double a = n * (1 + Math.Sqrt(5)) / 2.0; return (long)Math.Round(a); } // Driver code public static void Main(String[] args) { int n = 5; Console.WriteLine(nextFibonacci(n)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Function to return the next// fibonacci numberfunction nextFibonacci(n){ let a = n * (1 + Math.sqrt(5)) / 2.0; return Math.round(a);} // Driver code let n = 5; document.write(nextFibonacci(n)); // This code is contributed by Mayank Tyagi </script>
8
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
29AjayKumar
mayanktyagi1709
subham348
Fibonacci
Mathematical
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Program to multiply two matrices
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 24327,
"s": 24299,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 24413,
"s": 24327,
"text": "Given a fibonacci number N, the task is to find the next fibonacci number.Examples: "
},
{
"code": null,
"e": 24499,
"s": 24413,
"text": "Input: N = 5 Output: 8 8 is the next fibonacci number after 5Input: N = 3 Output: 5 "
},
{
"code": null,
"e": 24776,
"s": 24501,
"text": "Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is multiplied by ((1 + sqrt(5)) / 2) and round it, the resultant number will be the next fibonacci number.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24780,
"s": 24776,
"text": "C++"
},
{
"code": null,
"e": 24785,
"s": 24780,
"text": "Java"
},
{
"code": null,
"e": 24793,
"s": 24785,
"text": "Python3"
},
{
"code": null,
"e": 24796,
"s": 24793,
"text": "C#"
},
{
"code": null,
"e": 24807,
"s": 24796,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the next// fibonacci numberint nextFibonacci(int n){ double a = n * (1 + sqrt(5)) / 2.0; return round(a);} // Driver codeint main(){ int n = 5; cout << nextFibonacci(n);} // This code is contributed by mohit kumar 29",
"e": 25139,
"s": 24807,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the next // fibonacci number static long nextFibonacci(int n) { double a = n * (1 + Math.sqrt(5)) / 2.0; return Math.round(a); } // Driver code public static void main (String[] args) { int n = 5; System.out.println(nextFibonacci(n)); }} // This code is contributed by AnkitRai01",
"e": 25555,
"s": 25139,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom math import * # Function to return the next# fibonacci numberdef nextFibonacci(n): a = n*(1 + sqrt(5))/2.0 return round(a) # Driver coden = 5print(nextFibonacci(n))",
"e": 25771,
"s": 25555,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the next // fibonacci number static long nextFibonacci(int n) { double a = n * (1 + Math.Sqrt(5)) / 2.0; return (long)Math.Round(a); } // Driver code public static void Main(String[] args) { int n = 5; Console.WriteLine(nextFibonacci(n)); }} // This code is contributed by 29AjayKumar",
"e": 26204,
"s": 25771,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the next// fibonacci numberfunction nextFibonacci(n){ let a = n * (1 + Math.sqrt(5)) / 2.0; return Math.round(a);} // Driver code let n = 5; document.write(nextFibonacci(n)); // This code is contributed by Mayank Tyagi </script>",
"e": 26523,
"s": 26204,
"text": null
},
{
"code": null,
"e": 26525,
"s": 26523,
"text": "8"
},
{
"code": null,
"e": 26549,
"s": 26527,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 26571,
"s": 26549,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26586,
"s": 26571,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "ankthon"
},
{
"code": null,
"e": 26606,
"s": 26594,
"text": "29AjayKumar"
},
{
"code": null,
"e": 26622,
"s": 26606,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 26632,
"s": 26622,
"text": "subham348"
},
{
"code": null,
"e": 26642,
"s": 26632,
"text": "Fibonacci"
},
{
"code": null,
"e": 26655,
"s": 26642,
"text": "Mathematical"
},
{
"code": null,
"e": 26668,
"s": 26655,
"text": "Mathematical"
},
{
"code": null,
"e": 26678,
"s": 26668,
"text": "Fibonacci"
},
{
"code": null,
"e": 26776,
"s": 26678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26785,
"s": 26776,
"text": "Comments"
},
{
"code": null,
"e": 26798,
"s": 26785,
"text": "Old Comments"
},
{
"code": null,
"e": 26843,
"s": 26798,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 26875,
"s": 26843,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 26919,
"s": 26875,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 26953,
"s": 26919,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 26978,
"s": 26953,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 27011,
"s": 26978,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 27050,
"s": 27011,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 27101,
"s": 27050,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 27172,
"s": 27101,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Building A Simple Voice Assistant for Your Mac in Python | by Kyle Gallatin | Towards Data Science
|
Voice assistants like Siri or Cortana can do cool and useful things for you: open applications, search for information, send messages and more. While it’s cool to use the ones you’ve been given...it’s way more fun to make your own. In this post I’ll show you how to start building a voice assistant framework that can do like 1% of things fully developed ones can do on a Mac — sorry but I won’t be covering too much for any other OS.
Like my last blog post on creating a chatbot using your own text messages, this isn’t going to be a fully developed idea and won’t get you too far in a production. Honestly, it took me longer to find/make the gifs for this post than it did to code it out.
This blog post should, however, give you a great place to start if you’ve ever wondered how to create your own voice assistant in python and love to screw around. There’s some other posts out there with pretty much the same general concept — but didn’t see anything much like this on TDS and figured what the hell 🤷🏻 I can write better than that and mine will be more fun.
I’ll show two different voice activated capabilities in this blog post:
Opening applicationsSearching the internet
Opening applications
Searching the internet
We’ll first need 2 special packages. The first one is to get access to the microphone — credit to this post for a great intro to speech recognition in python. The second is the same as my past post, and uses elasticsearch to do query-query matching and return a response.
On Mac, install portaudio and elasticsearch with homebrew. Homebrew is a great package manager for macOS and can be downloaded here. Then in a terminal run:
brew install portaudiobrew install elasticsearch
I’ll be using pip for python package management. The speech_recognition package we’ll use to translate speech to text, and pyaudio is necessary for connecting to your computer’s microphone. We’ll also use the elasticsearch Python client to make things easier for us, I’m working in Python 3.
pip install SpeechRecognitionpip install pyaudiopip install elasticsearch
The speech_recognition package is great because as stated in this aforementioned post — “The SpeechRecognition library acts as a wrapper for several popular speech APIs and is thus extremely flexible. One of these — the Google Web Speech API — supports a default API key that is hard-coded into the SpeechRecognition library.”
Super convenient if you don’t feel like setting up an account for any of the other providers. In less than 10 lines of code, this package should let us connect to our built in computer mic and transcribe our voice!
import speech_recognition as srr = sr.Recognizer()mic = sr.Microphone()with mic as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) print(transcript)
This code should run until it hears something, then print it out what you said (or what it thinks you said). Super easy. For more on these classes and how that stuff works, refer to aforementioned post.
There’s multiple ways to do this in Python, but the easiest is just to use the one that comes with macOS. Using the subprocess package, we can easily make our computer speak:
import subprocessdef say(text): subprocess.call(['say', text])say("yo whatup dog")
So now you can transcribe voice to text, make your computer speak and the world is your oyster, sick. Now we can decide how we wanna use the input. For an offhand easy idea my first instinct was to use it to open applications. Obviously it’s not really that cool at all, but it works well as an example, and the general structure I’ll use can be applied to a much wider range of functionality. So let’s first get a list of all our applications.
On Mac, all the apps that I’d want to open are in the /Applications directory and for the most part all have a .app extension, so we can get their names using something like this:
d = '/Applications'apps = list(map(lambda x: x.split('.app')[0], os.listdir(d)))
List the directory and remove the extension. Cool.
Opening the applications is pretty easy too. Here a quick example using the os package and Spotify.
import osapp = 'Spotify'os.system('open ' +d+'/%s.app' %app.replace(' ','\ '))
The .replace is just for properly escaping spaces in longer app names, but if you have Spotify installed and in your applications it should open up.
The obvious solution to tie the voice transcript together with functionality is some kind of exact match, if transcript == 'open spotify' then do this...I probably don’t have to explain how unscalable that is. Besides, it’s way better to get experience with a cool framework like elastic. Also...it wouldn’t be a data science blog post without any actual data or algorithms.
From my last blog post on chatbots — “Elasticsearch is a scalable search platform that uses an algorithm similar to TF-IDF or term frequency inverse document frequency. Essentially, it’s a simple function often used within the search/similarity space that targets documents based on keywords... For a basic overview of it just check wikipedia.”
Basically we’re gonna upload all our voice commands (something like “open spotify”) to elasticsearch and map them to the system commands (the actual programming command) we want to run. To do this, we can quickly create a list of dictionaries.
import osd = '/Applications'records = []apps = os.listdir(d)for app in apps: record = {} record['voice_command'] = 'open ' + app.split('.app')[0] record['sys_command'] = 'open ' + d +'/%s' %app.replace(' ','\ ') records.append(record)
Now we have all our voice commands and our system commands mapped to one another. Next, open a terminal and start elasticsearch. If you installed it via Homebrew it’ll be in your path so just type elasticsearch and it’ll start on the default port 9200.
Next, we can index our data to make it searchable. We start up the python client and throw our data in a new index named voice_assistant.
from elasticsearch import Elasticsearchfrom elasticsearch.helpers import bulkes = Elasticsearch(['localhost:9200'])bulk(es, records, index='voice_assistant', doc_type='text', raise_on_error=True)
Now your data is all searchable in the index voice_assistant. The response variable we get back from the search function below is generated by the language elastic uses referred to as Query DSL. We’re basically doing a simple TF-IDF search on the voice command with some fuzziness — to account for misspellings/bad transcriptions.
def search_es(query): res = es.search(index="voice_assistant", doc_type="text", body={ "query" :{ "match": { "voice_command": { "query": query, "fuzziness": 2 } } }, }) return res['hits']['hits'][0]['_source']['sys_command']
Now try it out! search_es('open spotify') should return the command we will pass to os.system which is open /Applications/Spotify.app. Because we have the fuzziness parameter set to 2, search_es('open spofity') will also return the same thing even though there is a misspelling.
Even though this is a small functionality, the key here is that this principle can be applied to a lot of different functionalities — Q&A, other commands, etc...
Now we can transcribe speech to text, and have all our commands properly indexed which we can access with our search_es function. All that’s left it to tie it all together! Let’s create a script that looks for user input, and when it gets it, it searches our index for that command and then tries to run it. The only thing missing is a phrase to trigger our chatbot, so let’s define one more helper function so we have a keyword phrase to activate it, I chose mine to be just “hey dude”.
def activate(phrase='hey dude'): try: with mic as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) if transcript.lower() == phrase: return True else: return False
Using this trigger, we can now more selectively activate our actual search function. Putting it all together with the help of our previously defined functions, we can wrap our code in an infinite loop so it’ll just keep running and waiting for us to activate it. I have my assistant ask me how it can help before running anything, obviously feel free to replace “Kyle” with your name.
import speech_recognition as srimport os from elasticsearch import Elasticsearch##start python client es = Elasticsearch(['localhost:9200'])##initialize speech recognizer and micr = sr.Recognizer()mic = sr.Microphone()while True: if activate() == True: try: say("Hey Kyle, how can I help you today?") with mic as source: print("Say Something!") r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) sys_command = search_es(transcript) os.system(sys_command) say("I opened that application for you") except: pass else: pass
One thing to note — because of all the except statements we’ve got here, you won’t be able to keyboard interrupt out of this once you’ve got it going, you’ll legit have to stop the whole process or if you’re in jupyter restart the kernel — feel free to build in more proper error handling.
Run it and start indiscriminately open applications because you can! It’s cool. Just make sure you’ve started elasticsearch, and defined all your helper functions.
Opening apps is cool but tbh I’m definitely not actually going to use that...having my computer automatically search the internet for whatever I say is a much better use of this assistant. You could probably customize this part more using therequests and BeautifulSoup libraries, but there’s really no point if you can just have selenium open a Chrome/Firefox/whatever window and search for you.
Just use pip to install the necessary python package and make sure you have the webdriver you want to use installed. I’ll use the one for chrome.
pip install selenium
Searching from google is super easy with selenium. I use Chrome as my preferred browser so I start selenium with webdriver.Chrome() below. If you use something else, feel free to replace it.
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysdef search_google(query): browser = webdriver.Chrome() browser.get('http://www.google.com') search = browser.find_element_by_name('q') search.send_keys(query) search.send_keys(Keys.RETURN)
That’s it. Selenium opens google in a window, finds the search bar, types for us and then clicks the search button. You can test it real quick to make sure it works:
search_google('how to build a voice assistant in python')
Unlike before we don’t have an elasticsearch index to look into for our information — our searches are more dynamic we have to do some shoddier text preprocessing. Assuming our query will contain the phrase “search google for”, we can just split the string there and pass the rest of the string to our function.
while True: if activate() == True: try: say("Hey Kyle, how can I help you today?") with mic as source: print('Say Something!') r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) phrase = 'search google for ' if phrase in transcript.lower(): search = transcript.lower().split(phrase)[-1] search_google(search) say("I got these results for you") else: say('I only search google, sorry fam') except: pass else: pass
Cool, now you also have a voice assistant constantly listening for you to search the internet or open applications. There’s tons more you can do: actually tie them together in the same assistant (didn’t feel like it) incorporate news/weather APIs, maybe automate email stuff, put your own custom phrases in elasticsearch, build a more complex model for the activation, etc...but this is a decent place to start just for kicks. Hope you enjoyed it!
|
[
{
"code": null,
"e": 607,
"s": 172,
"text": "Voice assistants like Siri or Cortana can do cool and useful things for you: open applications, search for information, send messages and more. While it’s cool to use the ones you’ve been given...it’s way more fun to make your own. In this post I’ll show you how to start building a voice assistant framework that can do like 1% of things fully developed ones can do on a Mac — sorry but I won’t be covering too much for any other OS."
},
{
"code": null,
"e": 863,
"s": 607,
"text": "Like my last blog post on creating a chatbot using your own text messages, this isn’t going to be a fully developed idea and won’t get you too far in a production. Honestly, it took me longer to find/make the gifs for this post than it did to code it out."
},
{
"code": null,
"e": 1236,
"s": 863,
"text": "This blog post should, however, give you a great place to start if you’ve ever wondered how to create your own voice assistant in python and love to screw around. There’s some other posts out there with pretty much the same general concept — but didn’t see anything much like this on TDS and figured what the hell 🤷🏻 I can write better than that and mine will be more fun."
},
{
"code": null,
"e": 1308,
"s": 1236,
"text": "I’ll show two different voice activated capabilities in this blog post:"
},
{
"code": null,
"e": 1351,
"s": 1308,
"text": "Opening applicationsSearching the internet"
},
{
"code": null,
"e": 1372,
"s": 1351,
"text": "Opening applications"
},
{
"code": null,
"e": 1395,
"s": 1372,
"text": "Searching the internet"
},
{
"code": null,
"e": 1667,
"s": 1395,
"text": "We’ll first need 2 special packages. The first one is to get access to the microphone — credit to this post for a great intro to speech recognition in python. The second is the same as my past post, and uses elasticsearch to do query-query matching and return a response."
},
{
"code": null,
"e": 1824,
"s": 1667,
"text": "On Mac, install portaudio and elasticsearch with homebrew. Homebrew is a great package manager for macOS and can be downloaded here. Then in a terminal run:"
},
{
"code": null,
"e": 1873,
"s": 1824,
"text": "brew install portaudiobrew install elasticsearch"
},
{
"code": null,
"e": 2165,
"s": 1873,
"text": "I’ll be using pip for python package management. The speech_recognition package we’ll use to translate speech to text, and pyaudio is necessary for connecting to your computer’s microphone. We’ll also use the elasticsearch Python client to make things easier for us, I’m working in Python 3."
},
{
"code": null,
"e": 2239,
"s": 2165,
"text": "pip install SpeechRecognitionpip install pyaudiopip install elasticsearch"
},
{
"code": null,
"e": 2566,
"s": 2239,
"text": "The speech_recognition package is great because as stated in this aforementioned post — “The SpeechRecognition library acts as a wrapper for several popular speech APIs and is thus extremely flexible. One of these — the Google Web Speech API — supports a default API key that is hard-coded into the SpeechRecognition library.”"
},
{
"code": null,
"e": 2781,
"s": 2566,
"text": "Super convenient if you don’t feel like setting up an account for any of the other providers. In less than 10 lines of code, this package should let us connect to our built in computer mic and transcribe our voice!"
},
{
"code": null,
"e": 3001,
"s": 2781,
"text": "import speech_recognition as srr = sr.Recognizer()mic = sr.Microphone()with mic as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) print(transcript)"
},
{
"code": null,
"e": 3204,
"s": 3001,
"text": "This code should run until it hears something, then print it out what you said (or what it thinks you said). Super easy. For more on these classes and how that stuff works, refer to aforementioned post."
},
{
"code": null,
"e": 3379,
"s": 3204,
"text": "There’s multiple ways to do this in Python, but the easiest is just to use the one that comes with macOS. Using the subprocess package, we can easily make our computer speak:"
},
{
"code": null,
"e": 3465,
"s": 3379,
"text": "import subprocessdef say(text): subprocess.call(['say', text])say(\"yo whatup dog\")"
},
{
"code": null,
"e": 3910,
"s": 3465,
"text": "So now you can transcribe voice to text, make your computer speak and the world is your oyster, sick. Now we can decide how we wanna use the input. For an offhand easy idea my first instinct was to use it to open applications. Obviously it’s not really that cool at all, but it works well as an example, and the general structure I’ll use can be applied to a much wider range of functionality. So let’s first get a list of all our applications."
},
{
"code": null,
"e": 4090,
"s": 3910,
"text": "On Mac, all the apps that I’d want to open are in the /Applications directory and for the most part all have a .app extension, so we can get their names using something like this:"
},
{
"code": null,
"e": 4171,
"s": 4090,
"text": "d = '/Applications'apps = list(map(lambda x: x.split('.app')[0], os.listdir(d)))"
},
{
"code": null,
"e": 4222,
"s": 4171,
"text": "List the directory and remove the extension. Cool."
},
{
"code": null,
"e": 4322,
"s": 4222,
"text": "Opening the applications is pretty easy too. Here a quick example using the os package and Spotify."
},
{
"code": null,
"e": 4401,
"s": 4322,
"text": "import osapp = 'Spotify'os.system('open ' +d+'/%s.app' %app.replace(' ','\\ '))"
},
{
"code": null,
"e": 4550,
"s": 4401,
"text": "The .replace is just for properly escaping spaces in longer app names, but if you have Spotify installed and in your applications it should open up."
},
{
"code": null,
"e": 4925,
"s": 4550,
"text": "The obvious solution to tie the voice transcript together with functionality is some kind of exact match, if transcript == 'open spotify' then do this...I probably don’t have to explain how unscalable that is. Besides, it’s way better to get experience with a cool framework like elastic. Also...it wouldn’t be a data science blog post without any actual data or algorithms."
},
{
"code": null,
"e": 5270,
"s": 4925,
"text": "From my last blog post on chatbots — “Elasticsearch is a scalable search platform that uses an algorithm similar to TF-IDF or term frequency inverse document frequency. Essentially, it’s a simple function often used within the search/similarity space that targets documents based on keywords... For a basic overview of it just check wikipedia.”"
},
{
"code": null,
"e": 5514,
"s": 5270,
"text": "Basically we’re gonna upload all our voice commands (something like “open spotify”) to elasticsearch and map them to the system commands (the actual programming command) we want to run. To do this, we can quickly create a list of dictionaries."
},
{
"code": null,
"e": 5761,
"s": 5514,
"text": "import osd = '/Applications'records = []apps = os.listdir(d)for app in apps: record = {} record['voice_command'] = 'open ' + app.split('.app')[0] record['sys_command'] = 'open ' + d +'/%s' %app.replace(' ','\\ ') records.append(record)"
},
{
"code": null,
"e": 6014,
"s": 5761,
"text": "Now we have all our voice commands and our system commands mapped to one another. Next, open a terminal and start elasticsearch. If you installed it via Homebrew it’ll be in your path so just type elasticsearch and it’ll start on the default port 9200."
},
{
"code": null,
"e": 6152,
"s": 6014,
"text": "Next, we can index our data to make it searchable. We start up the python client and throw our data in a new index named voice_assistant."
},
{
"code": null,
"e": 6348,
"s": 6152,
"text": "from elasticsearch import Elasticsearchfrom elasticsearch.helpers import bulkes = Elasticsearch(['localhost:9200'])bulk(es, records, index='voice_assistant', doc_type='text', raise_on_error=True)"
},
{
"code": null,
"e": 6679,
"s": 6348,
"text": "Now your data is all searchable in the index voice_assistant. The response variable we get back from the search function below is generated by the language elastic uses referred to as Query DSL. We’re basically doing a simple TF-IDF search on the voice command with some fuzziness — to account for misspellings/bad transcriptions."
},
{
"code": null,
"e": 7014,
"s": 6679,
"text": "def search_es(query): res = es.search(index=\"voice_assistant\", doc_type=\"text\", body={ \"query\" :{ \"match\": { \"voice_command\": { \"query\": query, \"fuzziness\": 2 } } }, }) return res['hits']['hits'][0]['_source']['sys_command']"
},
{
"code": null,
"e": 7293,
"s": 7014,
"text": "Now try it out! search_es('open spotify') should return the command we will pass to os.system which is open /Applications/Spotify.app. Because we have the fuzziness parameter set to 2, search_es('open spofity') will also return the same thing even though there is a misspelling."
},
{
"code": null,
"e": 7455,
"s": 7293,
"text": "Even though this is a small functionality, the key here is that this principle can be applied to a lot of different functionalities — Q&A, other commands, etc..."
},
{
"code": null,
"e": 7943,
"s": 7455,
"text": "Now we can transcribe speech to text, and have all our commands properly indexed which we can access with our search_es function. All that’s left it to tie it all together! Let’s create a script that looks for user input, and when it gets it, it searches our index for that command and then tries to run it. The only thing missing is a phrase to trigger our chatbot, so let’s define one more helper function so we have a keyword phrase to activate it, I chose mine to be just “hey dude”."
},
{
"code": null,
"e": 8259,
"s": 7943,
"text": "def activate(phrase='hey dude'): try: with mic as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) if transcript.lower() == phrase: return True else: return False"
},
{
"code": null,
"e": 8644,
"s": 8259,
"text": "Using this trigger, we can now more selectively activate our actual search function. Putting it all together with the help of our previously defined functions, we can wrap our code in an infinite loop so it’ll just keep running and waiting for us to activate it. I have my assistant ask me how it can help before running anything, obviously feel free to replace “Kyle” with your name."
},
{
"code": null,
"e": 9380,
"s": 8644,
"text": "import speech_recognition as srimport os from elasticsearch import Elasticsearch##start python client es = Elasticsearch(['localhost:9200'])##initialize speech recognizer and micr = sr.Recognizer()mic = sr.Microphone()while True: if activate() == True: try: say(\"Hey Kyle, how can I help you today?\") with mic as source: print(\"Say Something!\") r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) sys_command = search_es(transcript) os.system(sys_command) say(\"I opened that application for you\") except: pass else: pass"
},
{
"code": null,
"e": 9670,
"s": 9380,
"text": "One thing to note — because of all the except statements we’ve got here, you won’t be able to keyboard interrupt out of this once you’ve got it going, you’ll legit have to stop the whole process or if you’re in jupyter restart the kernel — feel free to build in more proper error handling."
},
{
"code": null,
"e": 9834,
"s": 9670,
"text": "Run it and start indiscriminately open applications because you can! It’s cool. Just make sure you’ve started elasticsearch, and defined all your helper functions."
},
{
"code": null,
"e": 10230,
"s": 9834,
"text": "Opening apps is cool but tbh I’m definitely not actually going to use that...having my computer automatically search the internet for whatever I say is a much better use of this assistant. You could probably customize this part more using therequests and BeautifulSoup libraries, but there’s really no point if you can just have selenium open a Chrome/Firefox/whatever window and search for you."
},
{
"code": null,
"e": 10376,
"s": 10230,
"text": "Just use pip to install the necessary python package and make sure you have the webdriver you want to use installed. I’ll use the one for chrome."
},
{
"code": null,
"e": 10397,
"s": 10376,
"text": "pip install selenium"
},
{
"code": null,
"e": 10588,
"s": 10397,
"text": "Searching from google is super easy with selenium. I use Chrome as my preferred browser so I start selenium with webdriver.Chrome() below. If you use something else, feel free to replace it."
},
{
"code": null,
"e": 10869,
"s": 10588,
"text": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysdef search_google(query): browser = webdriver.Chrome() browser.get('http://www.google.com') search = browser.find_element_by_name('q') search.send_keys(query) search.send_keys(Keys.RETURN)"
},
{
"code": null,
"e": 11035,
"s": 10869,
"text": "That’s it. Selenium opens google in a window, finds the search bar, types for us and then clicks the search button. You can test it real quick to make sure it works:"
},
{
"code": null,
"e": 11093,
"s": 11035,
"text": "search_google('how to build a voice assistant in python')"
},
{
"code": null,
"e": 11405,
"s": 11093,
"text": "Unlike before we don’t have an elasticsearch index to look into for our information — our searches are more dynamic we have to do some shoddier text preprocessing. Assuming our query will contain the phrase “search google for”, we can just split the string there and pass the rest of the string to our function."
},
{
"code": null,
"e": 12107,
"s": 11405,
"text": "while True: if activate() == True: try: say(\"Hey Kyle, how can I help you today?\") with mic as source: print('Say Something!') r.adjust_for_ambient_noise(source) audio = r.listen(source) transcript = r.recognize_google(audio) phrase = 'search google for ' if phrase in transcript.lower(): search = transcript.lower().split(phrase)[-1] search_google(search) say(\"I got these results for you\") else: say('I only search google, sorry fam') except: pass else: pass"
}
] |
How do I pass a variable to a MySQL script?
|
You can pass a variable to a MySQL script using session variable. First you need to set a session variable using SET command. After that you need to pass that variable to a MySQL script.
The syntax is as follows −
First Step: Use of Set command.
SET @anyVariableName − = ’yourValue’;
Second Step: Pass a variable to a MySQL script.
UPDATE yourTableName SET yourColumnName1 = yourColumnName1+integerValue WHERE yourColumnName2 = @anyVariableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Employee_Information
-> (
-> EmployeeId int NOT NULL AUTO_INCREMENT,
-> EmployeeName varchar(20) NOT NULL,
-> EmployeeSalary int,
-> EmployeeStatus varchar(20),
-> PRIMARY KEY(EmployeeId)
-> );
Query OK, 0 rows affected (0.53 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Sam',17650,'FullTime');
Query OK, 1 row affected (0.13 sec)
mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Carol',12000,'Trainee');
Query OK, 1 row affected (0.18 sec)
mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Bob',17650,'FullTime');
Query OK, 1 row affected (0.20 sec)
mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Mike',12000,'Trainee');
Query OK, 1 row affected (0.14 sec)
mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('John',17650,'FullTime');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement.
mysql> select *from Employee_Information;
The following is the output −
+------------+--------------+----------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeStatus |
+------------+--------------+----------------+----------------+
| 1 | Sam | 17650 | FullTime |
| 2 | Carol | 12000 | Trainee |
| 3 | Bob | 17650 | FullTime |
| 4 | Mike | 12000 | Trainee |
| 5 | John | 17650 | FullTime |
+------------+--------------+----------------+----------------+
5 rows in set (0.00 sec)
The following is the query to pass a variable to a MySQL script −
mysql> set @EmpStatus − = 'FullTime';
Query OK, 0 rows affected (0.03 sec)
mysql> update Employee_Information set EmployeeSalary = EmployeeSalary+6500 where EmployeeStatus = @EmpStatus;
Query OK, 3 rows affected (0.18 sec)
Rows matched − 3 Changed − 3 Warnings − 0
Now check the table records once again using SELECT statement. I have incremented the EmployeeSalary with 6500, for the employees working FullTime.
The query is as follows −
mysql> select *from Employee_Information;
The following is the output −
+------------+--------------+----------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeStatus |
+------------+--------------+----------------+----------------+
| 1 | Sam | 24150 | FullTime |
| 2 | Carol | 12000 | Trainee |
| 3 | Bob | 24150 | FullTime |
| 4 | Mike | 12000 | Trainee |
| 5 | John | 24150 | FullTime |
+------------+--------------+----------------+----------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "You can pass a variable to a MySQL script using session variable. First you need to set a session variable using SET command. After that you need to pass that variable to a MySQL script."
},
{
"code": null,
"e": 1276,
"s": 1249,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1308,
"s": 1276,
"text": "First Step: Use of Set command."
},
{
"code": null,
"e": 1346,
"s": 1308,
"text": "SET @anyVariableName − = ’yourValue’;"
},
{
"code": null,
"e": 1394,
"s": 1346,
"text": "Second Step: Pass a variable to a MySQL script."
},
{
"code": null,
"e": 1508,
"s": 1394,
"text": "UPDATE yourTableName SET yourColumnName1 = yourColumnName1+integerValue WHERE yourColumnName2 = @anyVariableName;"
},
{
"code": null,
"e": 1607,
"s": 1508,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1879,
"s": 1607,
"text": "mysql> create table Employee_Information\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT,\n -> EmployeeName varchar(20) NOT NULL,\n -> EmployeeSalary int,\n -> EmployeeStatus varchar(20),\n -> PRIMARY KEY(EmployeeId)\n -> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1972,
"s": 1879,
"text": "Now you can insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2738,
"s": 1972,
"text": "mysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Sam',17650,'FullTime');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Carol',12000,'Trainee');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Bob',17650,'FullTime');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('Mike',12000,'Trainee');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into Employee_Information(EmployeeName,EmployeeSalary,EmployeeStatus) values('John',17650,'FullTime');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2797,
"s": 2738,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2839,
"s": 2797,
"text": "mysql> select *from Employee_Information;"
},
{
"code": null,
"e": 2869,
"s": 2839,
"text": "The following is the output −"
},
{
"code": null,
"e": 3470,
"s": 2869,
"text": "+------------+--------------+----------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary | EmployeeStatus |\n+------------+--------------+----------------+----------------+\n| 1 | Sam | 17650 | FullTime |\n| 2 | Carol | 12000 | Trainee |\n| 3 | Bob | 17650 | FullTime |\n| 4 | Mike | 12000 | Trainee |\n| 5 | John | 17650 | FullTime |\n+------------+--------------+----------------+----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3536,
"s": 3470,
"text": "The following is the query to pass a variable to a MySQL script −"
},
{
"code": null,
"e": 3802,
"s": 3536,
"text": "mysql> set @EmpStatus − = 'FullTime';\nQuery OK, 0 rows affected (0.03 sec)\n\nmysql> update Employee_Information set EmployeeSalary = EmployeeSalary+6500 where EmployeeStatus = @EmpStatus;\nQuery OK, 3 rows affected (0.18 sec)\nRows matched − 3 Changed − 3 Warnings − 0"
},
{
"code": null,
"e": 3950,
"s": 3802,
"text": "Now check the table records once again using SELECT statement. I have incremented the EmployeeSalary with 6500, for the employees working FullTime."
},
{
"code": null,
"e": 3976,
"s": 3950,
"text": "The query is as follows −"
},
{
"code": null,
"e": 4018,
"s": 3976,
"text": "mysql> select *from Employee_Information;"
},
{
"code": null,
"e": 4048,
"s": 4018,
"text": "The following is the output −"
},
{
"code": null,
"e": 4649,
"s": 4048,
"text": "+------------+--------------+----------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary | EmployeeStatus |\n+------------+--------------+----------------+----------------+\n| 1 | Sam | 24150 | FullTime |\n| 2 | Carol | 12000 | Trainee |\n| 3 | Bob | 24150 | FullTime |\n| 4 | Mike | 12000 | Trainee |\n| 5 | John | 24150 | FullTime |\n+------------+--------------+----------------+----------------+\n5 rows in set (0.00 sec)"
}
] |
Don’t waste your unlabeled data. Evaluate the weakness of your model and... | by Betty LD | Towards Data Science
|
In the last decade, the main trend in AI was focusing on building creative and complex models. But these last years, state-of-the-art architectures are made available to anyone in popular languages like Python and its libraries such as Pytorch, Tensorflow, JAX, etc. Now, AI's highest priority is to make these models valuable for each particular use case. This requires a deep understanding of available curated data, and unfortunately, data analysis and how to build a good training set are skills rarely taught in classical ML courses but learned with time and sweat.
So far, data was not thought to be a major issue: standard research datasets of variable size were available for free (ImageNet, COCO, GLUE, etc), as well as the pre-trained model’s weights (ModelZoo, Huggingface, etc) as prior knowledge for fine-tuning on a specific subset of data. Besides that, training locally models on small-scale datasets became a commodity. But in practice, making an ML model successful in a production stage is a hard problem.
One of the major causes of failure is the loss of accuracy between a model on research template and this model deployed in a real-world environment. In fact, 13% of models in the companies make it to production [7].
This seems quite surprising when we know that even model search has been automated with the rise of AutoML platforms. What is the bottleneck?
The bottleneck is the data. And the next challenge that needs a strong framework and standardization is the pipeline that massages the data. The AI in the industry may need to step back from the model-centric approach and shift to the data-centric approach [6]. The data-centric approach tries to reconcile the model development with the creation of the training dataset and the monitoring of the model performance.
“Not all data is created equal” — Jennifer Prendki
Because real-world data is messy, noisy, wrong, filled with outliers, and does not follow a normal distribution, quantifying uncertainty is crucial to building a trustworthy AI model. Choose well the data you let in. Kick out the suspicious data. Avoid the fatal garbage in, garbage out, and save time and money. A model prediction is almost useless unless we can trust it. To spot these sick data, we’ll explore the uncertainty of the model as a proxy for data quality. We want to identify where the data is confusing the model.
There are numerous causes for uncertainty. Uncertainties can appear in the inference when the distribution of the training and test dataset are unmatched. It also appears when the data classes overlap or when the data itself is noisy. In general, we should be aware of the original source of uncertainty in our dataset in order to create an efficient strategy to reduce it when possible.
In the active learning literature, these uncertainties are classified into two major types: epistemic and aleatoric uncertainty. On the one hand, aleatoric uncertainty is created by the noise of the data and will differ at every run of the same experiment. This uncertainty is irreducible because it is an inherent property of the data. On the other hand, epistemic uncertainty can be reduced by learning. By increasing the dataset size or making complexify the model.
By default, we often erroneously consider the probability for each label output by the softmax function as the model confidence into each label. This misconception can be avoided by using a simple technique: considering the relative value of each softmax output relative to other labels or other instances.
In this article, I’ll share standard techniques to scan all available data (labeled or unlabelled) to help make a data-centric conclusion on the current state of the data and model. These techniques rank each data point according to the confidence of the model on its predicted label. We can use different functions that can attribute an “uncertainty” score to each data point. High uncertainty means that the model was not sure about this data point and the inference is likely to be wrong.
leveraging both existing data and model
find edge cases in the dataset
find bad quality data to re-label or exclude from the training dataset
clarify labeling instructions by tracking down ambiguity
find the weakness of the current model
identify data drift with on new incoming data
error analysis to find which samples to label next
find outliers
Continuously improving the data is a necessary step given the evolving world where we put models in production. I’ve heard the story of a bowling picture classifier that was labeling empty toilet paper shelves images as bowling pictures when the COVID started because of social media trends on this matter. We never know what the future data will look like and we should always be aware of the data we let sneak into our model prediction.
In this article, we evaluate the images that feed a CNN model for classification. We’ll use EMNIST for experimentation.
We use softmax to create a probability distribution from the output logits computed by the last activation function. Softmax cannot provide the probability of certainty of the model and is losing information because it is using exponential so it loses the scale of the digits ([1,4,2,1] will produce the same distribution that [101, 104, 102, 101]). But we can still use softmax as a proxy for the model confidence and rank our data samples from high model certainty to low model certainty.
“No algorithm can survive bad data” — Robert Monarch
We want to label the data where our model is the most confused — uncertain. Therefore, for each data point, we will give a single uncertainty score for all unlabeled data points and rank them from the most uncertain to the least uncertain.
This method is the easiest and less expensive method for uncertainty quantification. You can identify the data points that lie near the decision boundary of your model.
It is the case when for one data point, your model:
give a similar softmax probability to different classes (for example, the input image is dog and output softmax are: dog 33.3%, cat 33.3%, bird 33.3%)
give a low probability to the highest probability (for example among ten classes the highest softmax is “frog” with a softmax at 10.5%)
We’ll list the scoring techniques from simplest to more complex.
We’ll call p_max the highest softmax score given to a class inferred for one image and p_2nd the second-highest confidence given to a class for one image. n is the number of classes for classification.
For each function below, the input prob_dist is the array of softmax output for one data point, and the output is an uncertainty score between 0 and 1 of the model for this data point. If the dataset is multiclass classification with three classes, prob_dist is of shape (3,).
least confidence (difference between the most confident prediction and 100% confidence)
We want to select the instance for which the confidence in the most likely class is the lowest. Let’s say we have two images A and B and the model's highest softmax logit is respectively 0.9 for A and 0.3 for B. In that case, we may want to understand how B looks like, process, (re-)label, or remove it.
We use a normalized “least” uncertainty score (formula (1)) computed for each data point. Since the minimum confidence level of the most likely instance cannot be lower than 1/n, we add the normalization score to scale the uncertainty score from 0 to 1.
This score will give a ranked order of the prediction where we want to sample the items with the lowest level of confidence for their predicted labels.
This scoring technique only depends on the confidence of the most confidence item, without caring about the second or nth confidence score.
margin of confidence
Margin confidence takes the difference between the two most confident predictions for one data point. We can convert this difference into a [0–1] range by subtracting the result to 1 (formula (2)). This time you care only about the difference between the two highest scores among the two highest categories. The smaller this difference, the closer to 1, and the less certain you are. This algorithm is less sensitive to the softmax base than the least confidence scoring but still sensitive.
ratio of confidence (ratio between the two most confident predictions)
The ratio scoring function is a variation of the margin of confidence scoring. This uncertainty score looks at the ratio of the two highest scores (3). The ratio is given as a multiplier of the base used for the softmax so, unlike the two previous methods, it is not sensitive to the softmax basis. It captures how much more likely is the first label compared to the second.
entropy-based (difference between all predictions)
The entropy score takes into account the prediction for all classes. It is computed by taking the negative sum of the probabilities multiplied by its log_2 probabilities.
We divide by log_2(n) to normalize the entropy between 0 and 1 (Equation (4)).
2 as a base for the log is an arbitrary base that does not change the ranking even if it will change monotonically the absolute uncertainty score.
We illustrate the results of two scoring functions (least and entropy). We first train a simple two-layers CNN on half of the EMNIST dataset (130,106 images). Then we predict the classes for all unseen data points and rank them according to their uncertainty score. We sample the top-1000 images given their uncertainty score.
Our CNN is made of two convolutional layers each one followed by RELU activation and then followed by two fully connected layers. We stop the training at the 6th epoch before the validation accuracy starts decreasing. We achieve an F1-score of 0.79 on the validation set.
You can find the code for training at: https://github.com/bledem/active-learning/blob/master/run_experiment.py
and for sampling the top-1000 images as a new dataset at: https://github.com/bledem/active-learning/blob/master/create_new_set.py
We look at the classes for which the per-class average F1 score is the highest and lowest on the validation set.
The classes with the lowest F1 score (F1<50%) are:
'k' 'o' 'i' 'r' 'Y' 'q' 'b' 'l' 'h' 'e' 'm'
and the classes with the highest F1 score (F1>95%) are:
'n' 'Z' 'A' 'a' '3'
Now let’s look at the top-1k images ranked after their uncertainty score. For comparison sake, we also sample a random 1k set.
We can see on the figure above, that we oversample characters that can be easily confused: “I”, “1”, “l” or “o”, “O”, “0”.
In the figure below, we compare the per-class F1 score with the distribution of instances between the different classes of the 1k sampled with the entropy uncertainty scoring function. We find a high peak in the “easily confused” classes that won’t happen in the randomly sampled dataset.
We show below some examples of the EMNIST images sampled as the top-1k uncertain inference. When we look at the “least” or “entropy” based samples, we can clearly see the noise in the labeling (e.g S labeled as 0) and the images themselves (blurry, non-readable characters).
Using uncertainty scores to sample data batches for new annotation tasks is an efficient way to label the most informative data point of the unseen dataset. However, as we saw, we should be careful not to systematically oversample similar data points in over-represented classes and their near-neighbor.
We list here the pro and cons of using the scoring score introduced above:
Pros:
use existing/standard models
fast and easy to compute and interpret.
create a new batch of informative data samples to label if your model uses traditional Machine Learning (not Deep Learning)
Cons:
these simple scoring functions should not be used to select data points for a new batch task with deep learning. Because of underlying sampling bias, the performance of the model after training on these sampled data may be worse than random sampling [5].
it is safer to use Bayesian Deep Learning to create a sampling strategy for high-dimensional data (image, text, etc.).
Using uncertainty quantification methods is very efficient to find in the unlabelled data the samples that lie on the boundary of your model. But, be careful when you select the data points to sample for your next annotation batch. This sampling assesses the informativeness of each unlabelled point individually. If you select only the highest uncertainty score data points, you will retrieve one informative data point and many near identical-copy. If you naively acquire the top-k most informative points, you may end up asking k near-identical points as well. This would make the contribution of your sample batch lower than a randomly sampled batch. For example, in the EMNIST experiment, if you look at the entropy sampling technique, you can see that the characters “i”, “1”, “l” were heavily sampled.
To avoid this duplicate sampling effect, some research papers propose complementary approaches like batch-aware sampling technique solutions such as BatchBALD [2]. In this paper, the author not only focuses on giving an uncertainty score to each sample but also on sampling for the next training batch that would provide the most informativeness.
Use wise sampling to build smart batch for annotation [1]:
minimize the sample size to ensure the most benefit is gained from each data point.
maximize the sample size to avoid retraining too often.
Another popular heuristic to assess the uncertainty of each unlabelled data point is called Query By Committee method. If you have an ensemble of models, you can also adapt the uncertainty scoring by taking all scores for each data point made by each model. You train several different models on your initial training set and you can look at their disagreement on the unlabelled data.
For example, I can train the same CNN with different hyperparameters on the same training set, then apply them on unlabelled data and use their disagreement to choose the next samples to label.
This method is particularly useful when you want to evaluate the uncertainty score for a regression task where softmax confidence in the prediction is not available.
Dropout strategy
If you don’t have an ensemble model, you can draw different predictions for each data point where each new prediction is made after dropping out a different random selection of neurons each time. Normally dropout is applied only during training, and all neurons are activated during testing. But if we apply dropout during testing too, we can infer a series of different predictions for each instance. The uncertainty for each sample can then be calculated as the variation across all predictions: the higher the disagreement, the more uncertainty [1]. This technique is often called the Monte Carlo dropout technique. Monte Carlo is a computational technique that randomly samples from a real distribution to obtain an estimate of this distribution. During the uncertainty estimation, we consider every prediction from the drop-out models as a Monte Carlo sample.
Open-source library for MC dropout and other active learning techniques: https://github.com/ElementAI/baal/ [paper]
You can use a generative Bayesian model to model the distribution of each class. In that case, you don’t need to use a probability proxy to infer the confidence of the model in its prediction since you can read directly the probability of each data point to belong to each class from the model output itself.
You can estimate the uncertainty of a Neural Net with a Bayesian Neural Network. In the Bayesian Neural Network framework, you don’t try learning single function f during the training but multiple functions similarly as ensemble models. After the training, we can take the average prediction for each data point, and compute the variance between these predictions. Bayesian NN can be built for various tasks from regression to segmentation. It considers the model parameters as normal distribution and the mean and variance of the distribution for each model parameter. These parameters are learned during training as usual.
I’ve been focusing on attributing an uncertainty score to each unlabeled sample. But, uncertainty quantification constitutes an infinitesimally small portion of the broader Active Learning field. AL is dedicated to obtaining as many performance gains as possible by labeling as few samples as possible [3]. In theory, an ideal system would query both the instances that lie on the decision boundary of the model and the instances that are far from the decision boundaries (outliers, diversity sampling, new classes to define). Unfortunately, there is no yet a standard way to build the best pipeline to query the smallest data sample for maximum performance.
Another very interesting research field tries to optimize learning by feeding the model with appropriate data points. It is not about focusing on unlabeled data but rather on already labeled data. Learning tasks require some time to feed the model with easy samples and to increase the difficulty of the samples little by little during the training, similarly to a human being. For the imbalanced dataset, the opposite strategy works well: we assign a higher penalty to hard (rare) instances to force the model to learn them. In practice, this easy-first and hard-first learning strategy is set by the choice of the loss function. I encourage you to read this article [4] to learn more about sampling techniques among labeled data.
https://github.com/bledem/active-learning
[1] Human-in-the-Loop Machine Learning: Active Learning and Annotation for Human-centered AI, Robert Monarch.
[2] BatchBALD: https://oatml.cs.ox.ac.uk/blog/2019/06/24/batchbald.html
[3] A Survey of Deep Active Learning. Pengzhen, Ren & Xiao, Yun & Chang, Xiaojun & Huang, Po-Yao & Li, Zhihui & Chen, Xiaojiang & Wang, Xin. (2020). https://arxiv.org/pdf/2009.00236.pdf
[4] Which Samples Should be Learned First: Easy or Hard? Xiaoling Zhou, Ou Wu, 2021. https://openreview.net/pdf?id=pSbqyZRKzbw
[5] Active Learning in CNNs via Expected Improvement Maximization. Nagpal, Udai & Knowles, David. (2020). https://openaccess.thecvf.com/content_WACV_2020/papers/Mayer_Adversarial_Sampling_for_Active_Learning_WACV_2020_paper.pdf
|
[
{
"code": null,
"e": 611,
"s": 40,
"text": "In the last decade, the main trend in AI was focusing on building creative and complex models. But these last years, state-of-the-art architectures are made available to anyone in popular languages like Python and its libraries such as Pytorch, Tensorflow, JAX, etc. Now, AI's highest priority is to make these models valuable for each particular use case. This requires a deep understanding of available curated data, and unfortunately, data analysis and how to build a good training set are skills rarely taught in classical ML courses but learned with time and sweat."
},
{
"code": null,
"e": 1065,
"s": 611,
"text": "So far, data was not thought to be a major issue: standard research datasets of variable size were available for free (ImageNet, COCO, GLUE, etc), as well as the pre-trained model’s weights (ModelZoo, Huggingface, etc) as prior knowledge for fine-tuning on a specific subset of data. Besides that, training locally models on small-scale datasets became a commodity. But in practice, making an ML model successful in a production stage is a hard problem."
},
{
"code": null,
"e": 1281,
"s": 1065,
"text": "One of the major causes of failure is the loss of accuracy between a model on research template and this model deployed in a real-world environment. In fact, 13% of models in the companies make it to production [7]."
},
{
"code": null,
"e": 1423,
"s": 1281,
"text": "This seems quite surprising when we know that even model search has been automated with the rise of AutoML platforms. What is the bottleneck?"
},
{
"code": null,
"e": 1839,
"s": 1423,
"text": "The bottleneck is the data. And the next challenge that needs a strong framework and standardization is the pipeline that massages the data. The AI in the industry may need to step back from the model-centric approach and shift to the data-centric approach [6]. The data-centric approach tries to reconcile the model development with the creation of the training dataset and the monitoring of the model performance."
},
{
"code": null,
"e": 1890,
"s": 1839,
"text": "“Not all data is created equal” — Jennifer Prendki"
},
{
"code": null,
"e": 2420,
"s": 1890,
"text": "Because real-world data is messy, noisy, wrong, filled with outliers, and does not follow a normal distribution, quantifying uncertainty is crucial to building a trustworthy AI model. Choose well the data you let in. Kick out the suspicious data. Avoid the fatal garbage in, garbage out, and save time and money. A model prediction is almost useless unless we can trust it. To spot these sick data, we’ll explore the uncertainty of the model as a proxy for data quality. We want to identify where the data is confusing the model."
},
{
"code": null,
"e": 2808,
"s": 2420,
"text": "There are numerous causes for uncertainty. Uncertainties can appear in the inference when the distribution of the training and test dataset are unmatched. It also appears when the data classes overlap or when the data itself is noisy. In general, we should be aware of the original source of uncertainty in our dataset in order to create an efficient strategy to reduce it when possible."
},
{
"code": null,
"e": 3277,
"s": 2808,
"text": "In the active learning literature, these uncertainties are classified into two major types: epistemic and aleatoric uncertainty. On the one hand, aleatoric uncertainty is created by the noise of the data and will differ at every run of the same experiment. This uncertainty is irreducible because it is an inherent property of the data. On the other hand, epistemic uncertainty can be reduced by learning. By increasing the dataset size or making complexify the model."
},
{
"code": null,
"e": 3584,
"s": 3277,
"text": "By default, we often erroneously consider the probability for each label output by the softmax function as the model confidence into each label. This misconception can be avoided by using a simple technique: considering the relative value of each softmax output relative to other labels or other instances."
},
{
"code": null,
"e": 4076,
"s": 3584,
"text": "In this article, I’ll share standard techniques to scan all available data (labeled or unlabelled) to help make a data-centric conclusion on the current state of the data and model. These techniques rank each data point according to the confidence of the model on its predicted label. We can use different functions that can attribute an “uncertainty” score to each data point. High uncertainty means that the model was not sure about this data point and the inference is likely to be wrong."
},
{
"code": null,
"e": 4116,
"s": 4076,
"text": "leveraging both existing data and model"
},
{
"code": null,
"e": 4147,
"s": 4116,
"text": "find edge cases in the dataset"
},
{
"code": null,
"e": 4218,
"s": 4147,
"text": "find bad quality data to re-label or exclude from the training dataset"
},
{
"code": null,
"e": 4275,
"s": 4218,
"text": "clarify labeling instructions by tracking down ambiguity"
},
{
"code": null,
"e": 4314,
"s": 4275,
"text": "find the weakness of the current model"
},
{
"code": null,
"e": 4360,
"s": 4314,
"text": "identify data drift with on new incoming data"
},
{
"code": null,
"e": 4411,
"s": 4360,
"text": "error analysis to find which samples to label next"
},
{
"code": null,
"e": 4425,
"s": 4411,
"text": "find outliers"
},
{
"code": null,
"e": 4864,
"s": 4425,
"text": "Continuously improving the data is a necessary step given the evolving world where we put models in production. I’ve heard the story of a bowling picture classifier that was labeling empty toilet paper shelves images as bowling pictures when the COVID started because of social media trends on this matter. We never know what the future data will look like and we should always be aware of the data we let sneak into our model prediction."
},
{
"code": null,
"e": 4984,
"s": 4864,
"text": "In this article, we evaluate the images that feed a CNN model for classification. We’ll use EMNIST for experimentation."
},
{
"code": null,
"e": 5475,
"s": 4984,
"text": "We use softmax to create a probability distribution from the output logits computed by the last activation function. Softmax cannot provide the probability of certainty of the model and is losing information because it is using exponential so it loses the scale of the digits ([1,4,2,1] will produce the same distribution that [101, 104, 102, 101]). But we can still use softmax as a proxy for the model confidence and rank our data samples from high model certainty to low model certainty."
},
{
"code": null,
"e": 5528,
"s": 5475,
"text": "“No algorithm can survive bad data” — Robert Monarch"
},
{
"code": null,
"e": 5768,
"s": 5528,
"text": "We want to label the data where our model is the most confused — uncertain. Therefore, for each data point, we will give a single uncertainty score for all unlabeled data points and rank them from the most uncertain to the least uncertain."
},
{
"code": null,
"e": 5937,
"s": 5768,
"text": "This method is the easiest and less expensive method for uncertainty quantification. You can identify the data points that lie near the decision boundary of your model."
},
{
"code": null,
"e": 5989,
"s": 5937,
"text": "It is the case when for one data point, your model:"
},
{
"code": null,
"e": 6140,
"s": 5989,
"text": "give a similar softmax probability to different classes (for example, the input image is dog and output softmax are: dog 33.3%, cat 33.3%, bird 33.3%)"
},
{
"code": null,
"e": 6276,
"s": 6140,
"text": "give a low probability to the highest probability (for example among ten classes the highest softmax is “frog” with a softmax at 10.5%)"
},
{
"code": null,
"e": 6341,
"s": 6276,
"text": "We’ll list the scoring techniques from simplest to more complex."
},
{
"code": null,
"e": 6543,
"s": 6341,
"text": "We’ll call p_max the highest softmax score given to a class inferred for one image and p_2nd the second-highest confidence given to a class for one image. n is the number of classes for classification."
},
{
"code": null,
"e": 6820,
"s": 6543,
"text": "For each function below, the input prob_dist is the array of softmax output for one data point, and the output is an uncertainty score between 0 and 1 of the model for this data point. If the dataset is multiclass classification with three classes, prob_dist is of shape (3,)."
},
{
"code": null,
"e": 6908,
"s": 6820,
"text": "least confidence (difference between the most confident prediction and 100% confidence)"
},
{
"code": null,
"e": 7213,
"s": 6908,
"text": "We want to select the instance for which the confidence in the most likely class is the lowest. Let’s say we have two images A and B and the model's highest softmax logit is respectively 0.9 for A and 0.3 for B. In that case, we may want to understand how B looks like, process, (re-)label, or remove it."
},
{
"code": null,
"e": 7467,
"s": 7213,
"text": "We use a normalized “least” uncertainty score (formula (1)) computed for each data point. Since the minimum confidence level of the most likely instance cannot be lower than 1/n, we add the normalization score to scale the uncertainty score from 0 to 1."
},
{
"code": null,
"e": 7619,
"s": 7467,
"text": "This score will give a ranked order of the prediction where we want to sample the items with the lowest level of confidence for their predicted labels."
},
{
"code": null,
"e": 7759,
"s": 7619,
"text": "This scoring technique only depends on the confidence of the most confidence item, without caring about the second or nth confidence score."
},
{
"code": null,
"e": 7780,
"s": 7759,
"text": "margin of confidence"
},
{
"code": null,
"e": 8272,
"s": 7780,
"text": "Margin confidence takes the difference between the two most confident predictions for one data point. We can convert this difference into a [0–1] range by subtracting the result to 1 (formula (2)). This time you care only about the difference between the two highest scores among the two highest categories. The smaller this difference, the closer to 1, and the less certain you are. This algorithm is less sensitive to the softmax base than the least confidence scoring but still sensitive."
},
{
"code": null,
"e": 8343,
"s": 8272,
"text": "ratio of confidence (ratio between the two most confident predictions)"
},
{
"code": null,
"e": 8718,
"s": 8343,
"text": "The ratio scoring function is a variation of the margin of confidence scoring. This uncertainty score looks at the ratio of the two highest scores (3). The ratio is given as a multiplier of the base used for the softmax so, unlike the two previous methods, it is not sensitive to the softmax basis. It captures how much more likely is the first label compared to the second."
},
{
"code": null,
"e": 8769,
"s": 8718,
"text": "entropy-based (difference between all predictions)"
},
{
"code": null,
"e": 8940,
"s": 8769,
"text": "The entropy score takes into account the prediction for all classes. It is computed by taking the negative sum of the probabilities multiplied by its log_2 probabilities."
},
{
"code": null,
"e": 9019,
"s": 8940,
"text": "We divide by log_2(n) to normalize the entropy between 0 and 1 (Equation (4))."
},
{
"code": null,
"e": 9166,
"s": 9019,
"text": "2 as a base for the log is an arbitrary base that does not change the ranking even if it will change monotonically the absolute uncertainty score."
},
{
"code": null,
"e": 9493,
"s": 9166,
"text": "We illustrate the results of two scoring functions (least and entropy). We first train a simple two-layers CNN on half of the EMNIST dataset (130,106 images). Then we predict the classes for all unseen data points and rank them according to their uncertainty score. We sample the top-1000 images given their uncertainty score."
},
{
"code": null,
"e": 9765,
"s": 9493,
"text": "Our CNN is made of two convolutional layers each one followed by RELU activation and then followed by two fully connected layers. We stop the training at the 6th epoch before the validation accuracy starts decreasing. We achieve an F1-score of 0.79 on the validation set."
},
{
"code": null,
"e": 9876,
"s": 9765,
"text": "You can find the code for training at: https://github.com/bledem/active-learning/blob/master/run_experiment.py"
},
{
"code": null,
"e": 10006,
"s": 9876,
"text": "and for sampling the top-1000 images as a new dataset at: https://github.com/bledem/active-learning/blob/master/create_new_set.py"
},
{
"code": null,
"e": 10119,
"s": 10006,
"text": "We look at the classes for which the per-class average F1 score is the highest and lowest on the validation set."
},
{
"code": null,
"e": 10170,
"s": 10119,
"text": "The classes with the lowest F1 score (F1<50%) are:"
},
{
"code": null,
"e": 10214,
"s": 10170,
"text": "'k' 'o' 'i' 'r' 'Y' 'q' 'b' 'l' 'h' 'e' 'm'"
},
{
"code": null,
"e": 10270,
"s": 10214,
"text": "and the classes with the highest F1 score (F1>95%) are:"
},
{
"code": null,
"e": 10290,
"s": 10270,
"text": "'n' 'Z' 'A' 'a' '3'"
},
{
"code": null,
"e": 10417,
"s": 10290,
"text": "Now let’s look at the top-1k images ranked after their uncertainty score. For comparison sake, we also sample a random 1k set."
},
{
"code": null,
"e": 10540,
"s": 10417,
"text": "We can see on the figure above, that we oversample characters that can be easily confused: “I”, “1”, “l” or “o”, “O”, “0”."
},
{
"code": null,
"e": 10829,
"s": 10540,
"text": "In the figure below, we compare the per-class F1 score with the distribution of instances between the different classes of the 1k sampled with the entropy uncertainty scoring function. We find a high peak in the “easily confused” classes that won’t happen in the randomly sampled dataset."
},
{
"code": null,
"e": 11104,
"s": 10829,
"text": "We show below some examples of the EMNIST images sampled as the top-1k uncertain inference. When we look at the “least” or “entropy” based samples, we can clearly see the noise in the labeling (e.g S labeled as 0) and the images themselves (blurry, non-readable characters)."
},
{
"code": null,
"e": 11408,
"s": 11104,
"text": "Using uncertainty scores to sample data batches for new annotation tasks is an efficient way to label the most informative data point of the unseen dataset. However, as we saw, we should be careful not to systematically oversample similar data points in over-represented classes and their near-neighbor."
},
{
"code": null,
"e": 11483,
"s": 11408,
"text": "We list here the pro and cons of using the scoring score introduced above:"
},
{
"code": null,
"e": 11489,
"s": 11483,
"text": "Pros:"
},
{
"code": null,
"e": 11518,
"s": 11489,
"text": "use existing/standard models"
},
{
"code": null,
"e": 11558,
"s": 11518,
"text": "fast and easy to compute and interpret."
},
{
"code": null,
"e": 11682,
"s": 11558,
"text": "create a new batch of informative data samples to label if your model uses traditional Machine Learning (not Deep Learning)"
},
{
"code": null,
"e": 11688,
"s": 11682,
"text": "Cons:"
},
{
"code": null,
"e": 11943,
"s": 11688,
"text": "these simple scoring functions should not be used to select data points for a new batch task with deep learning. Because of underlying sampling bias, the performance of the model after training on these sampled data may be worse than random sampling [5]."
},
{
"code": null,
"e": 12062,
"s": 11943,
"text": "it is safer to use Bayesian Deep Learning to create a sampling strategy for high-dimensional data (image, text, etc.)."
},
{
"code": null,
"e": 12871,
"s": 12062,
"text": "Using uncertainty quantification methods is very efficient to find in the unlabelled data the samples that lie on the boundary of your model. But, be careful when you select the data points to sample for your next annotation batch. This sampling assesses the informativeness of each unlabelled point individually. If you select only the highest uncertainty score data points, you will retrieve one informative data point and many near identical-copy. If you naively acquire the top-k most informative points, you may end up asking k near-identical points as well. This would make the contribution of your sample batch lower than a randomly sampled batch. For example, in the EMNIST experiment, if you look at the entropy sampling technique, you can see that the characters “i”, “1”, “l” were heavily sampled."
},
{
"code": null,
"e": 13218,
"s": 12871,
"text": "To avoid this duplicate sampling effect, some research papers propose complementary approaches like batch-aware sampling technique solutions such as BatchBALD [2]. In this paper, the author not only focuses on giving an uncertainty score to each sample but also on sampling for the next training batch that would provide the most informativeness."
},
{
"code": null,
"e": 13277,
"s": 13218,
"text": "Use wise sampling to build smart batch for annotation [1]:"
},
{
"code": null,
"e": 13361,
"s": 13277,
"text": "minimize the sample size to ensure the most benefit is gained from each data point."
},
{
"code": null,
"e": 13417,
"s": 13361,
"text": "maximize the sample size to avoid retraining too often."
},
{
"code": null,
"e": 13802,
"s": 13417,
"text": "Another popular heuristic to assess the uncertainty of each unlabelled data point is called Query By Committee method. If you have an ensemble of models, you can also adapt the uncertainty scoring by taking all scores for each data point made by each model. You train several different models on your initial training set and you can look at their disagreement on the unlabelled data."
},
{
"code": null,
"e": 13996,
"s": 13802,
"text": "For example, I can train the same CNN with different hyperparameters on the same training set, then apply them on unlabelled data and use their disagreement to choose the next samples to label."
},
{
"code": null,
"e": 14162,
"s": 13996,
"text": "This method is particularly useful when you want to evaluate the uncertainty score for a regression task where softmax confidence in the prediction is not available."
},
{
"code": null,
"e": 14179,
"s": 14162,
"text": "Dropout strategy"
},
{
"code": null,
"e": 15044,
"s": 14179,
"text": "If you don’t have an ensemble model, you can draw different predictions for each data point where each new prediction is made after dropping out a different random selection of neurons each time. Normally dropout is applied only during training, and all neurons are activated during testing. But if we apply dropout during testing too, we can infer a series of different predictions for each instance. The uncertainty for each sample can then be calculated as the variation across all predictions: the higher the disagreement, the more uncertainty [1]. This technique is often called the Monte Carlo dropout technique. Monte Carlo is a computational technique that randomly samples from a real distribution to obtain an estimate of this distribution. During the uncertainty estimation, we consider every prediction from the drop-out models as a Monte Carlo sample."
},
{
"code": null,
"e": 15160,
"s": 15044,
"text": "Open-source library for MC dropout and other active learning techniques: https://github.com/ElementAI/baal/ [paper]"
},
{
"code": null,
"e": 15469,
"s": 15160,
"text": "You can use a generative Bayesian model to model the distribution of each class. In that case, you don’t need to use a probability proxy to infer the confidence of the model in its prediction since you can read directly the probability of each data point to belong to each class from the model output itself."
},
{
"code": null,
"e": 16094,
"s": 15469,
"text": "You can estimate the uncertainty of a Neural Net with a Bayesian Neural Network. In the Bayesian Neural Network framework, you don’t try learning single function f during the training but multiple functions similarly as ensemble models. After the training, we can take the average prediction for each data point, and compute the variance between these predictions. Bayesian NN can be built for various tasks from regression to segmentation. It considers the model parameters as normal distribution and the mean and variance of the distribution for each model parameter. These parameters are learned during training as usual."
},
{
"code": null,
"e": 16753,
"s": 16094,
"text": "I’ve been focusing on attributing an uncertainty score to each unlabeled sample. But, uncertainty quantification constitutes an infinitesimally small portion of the broader Active Learning field. AL is dedicated to obtaining as many performance gains as possible by labeling as few samples as possible [3]. In theory, an ideal system would query both the instances that lie on the decision boundary of the model and the instances that are far from the decision boundaries (outliers, diversity sampling, new classes to define). Unfortunately, there is no yet a standard way to build the best pipeline to query the smallest data sample for maximum performance."
},
{
"code": null,
"e": 17485,
"s": 16753,
"text": "Another very interesting research field tries to optimize learning by feeding the model with appropriate data points. It is not about focusing on unlabeled data but rather on already labeled data. Learning tasks require some time to feed the model with easy samples and to increase the difficulty of the samples little by little during the training, similarly to a human being. For the imbalanced dataset, the opposite strategy works well: we assign a higher penalty to hard (rare) instances to force the model to learn them. In practice, this easy-first and hard-first learning strategy is set by the choice of the loss function. I encourage you to read this article [4] to learn more about sampling techniques among labeled data."
},
{
"code": null,
"e": 17527,
"s": 17485,
"text": "https://github.com/bledem/active-learning"
},
{
"code": null,
"e": 17637,
"s": 17527,
"text": "[1] Human-in-the-Loop Machine Learning: Active Learning and Annotation for Human-centered AI, Robert Monarch."
},
{
"code": null,
"e": 17709,
"s": 17637,
"text": "[2] BatchBALD: https://oatml.cs.ox.ac.uk/blog/2019/06/24/batchbald.html"
},
{
"code": null,
"e": 17895,
"s": 17709,
"text": "[3] A Survey of Deep Active Learning. Pengzhen, Ren & Xiao, Yun & Chang, Xiaojun & Huang, Po-Yao & Li, Zhihui & Chen, Xiaojiang & Wang, Xin. (2020). https://arxiv.org/pdf/2009.00236.pdf"
},
{
"code": null,
"e": 18022,
"s": 17895,
"text": "[4] Which Samples Should be Learned First: Easy or Hard? Xiaoling Zhou, Ou Wu, 2021. https://openreview.net/pdf?id=pSbqyZRKzbw"
}
] |
Gradle - Tasks
|
Gradle build script describes about one or more Projects. Each project is made up of different tasks and a task is a piece of work which a build performs.
The task might be compiling some classes, storing class files into separate target folder, creating JAR, generating Javadoc, or publishing some achieves to the repositories.
This chapter explains about what is task and how to generate and execute a task.
Task is a keyword which is used to define a task into build script.
Take a look at the following example which represents a task named hello that prints tutorialspoint. Copy and save the following script into a file named build.gradle.
This build script defines a task name hello which is used to print tutorialspoint string.
task hello {
doLast {
println 'tutorialspoint'
}
}
Execute the following command in the command prompt. It executes the above script. You should execute this, where the build.gradle file is stored.
C:\> gradle –q hello
Output
Given below is the output of the code −
tutorialspoint
You can simplify this hello task by specifying a shortcut (represents a symbol <<) to the doLast statement. If you add this shortcut to the above task hello, it will be as follows −
task hello << {
println 'tutorialspoint'
}
You can execute the above script using gradle –q hello command.
The following example defines a task hello.
Copy and save the following code into build.gradle file.
task (hello) << {
println "tutorialspoint"
}
Execute the following command in the command prompt. It executes the script given above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
The output is shown below −
tutorialspoint
You can also use strings for the task names. Take a look at the same hello example. Here we will use String as task.
Copy and save the following code into build.gradle file.
task('hello') << {
println "tutorialspoint"
}
Execute the following command in the command prompt. It executes the script which is mentioned above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
When you execute the above code, you should see the following output −
tutorialspoint
You can also use an alternative syntax for defining a task. That is, using create() method to define a task. Take a look into the same hello example which is given below.
Copy and save the below given code into build.gradle file.
tasks.create(name: 'hello') << {
println "tutorialspoint"
}
Execute the following command in the command prompt. It executes the script stated above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
Upon execution, you will receive the following output −
tutorialspoint
If you want to locate tasks that you have defined in the build file, then, you have to use the respective standard project properties. That means, each task is available as a property of the project, in which, the task name is used as the property name.
Take a look into the following code that accesses the tasks as properties.
Copy and save the below given code into build.gradle file.
task hello
println hello.name
println project.hello.name
Execute the following command in the command prompt. It executes the script given above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
The output is mentioned below −
hello
hello
You can also use all the properties through the tasks collection.
Copy and save the following code into build.gradle file.
task hello
println tasks.hello.name
println tasks['hello'].name
Execute the following command in the command prompt. It executes the script which is mentioned above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
This produces the following output −
hello
hello
You can also access the task's path by using the tasks. For this, you can call the getByPath() method with a task name, or a relative path, or an absolute path.
Copy and save the below given code into build.gradle file.
project(':projectA') {
task hello
}
task hello
println tasks.getByPath('hello').path
println tasks.getByPath(':hello').path
println tasks.getByPath('projectA:hello').path
println tasks.getByPath(':projectA:hello').path
Execute the following command in the command prompt. It executes the script which is given above. You should execute this, where the build.gradle file stores.
C:\> gradle –q hello
Output
The output is stated below −
:hello
:hello
:projectA:hello
:projectA:hello
You can make a task dependent on another task and that means, when one task is done then only other task will begin.
Each task is differentiated with the task name. The collection of task names is referred by its tasks collection. To refer to a task in another project, you should use path of the project as a prefix to the respective task name.
The following example adds a dependency from taskX to taskY.
Copy and save the below given code into build.gradle file. Take a look at the following code.
task taskX << {
println 'taskX'
}
task taskY(dependsOn: 'taskX') << {
println "taskY"
}
Execute the following command in the command prompt. It executes the script stated above. You should execute this, where the build.gradle file stores.
C:\> gradle –q taskY
Output
The output is given herewith −
taskX
taskY
The above example is adding dependency on task by using its names. There is another way to achieve task dependency which is, to define the dependency using a Task object.
Let us take the same example of taskY being dependent on taskX, but here, we are using task objects instead of task reference names.
Copy and save the following code into build.gradle file.
task taskY << {
println 'taskY'
}
task taskX << {
println 'taskX'
}
taskY.dependsOn taskX
Execute the following command in the command prompt. You should execute this where the build.gradle file is stored.
C:\> gradle –q taskY
Output
The output is given below −
taskX
taskY
The above example is adding dependency on task by using its names.
There is another way to achieve task dependency which is, to define dependency using a Task object.
Here, we take the same example that taskY is dependent on taskX but, we are using task objects instead of task references names.
Copy and save the below given code into build.gradle file. Take a look into the following code.
task taskX << {
println 'taskX'
}
taskX.dependsOn {
tasks.findAll {
task → task.name.startsWith('lib')
}
}
task lib1 << {
println 'lib1'
}
task lib2 << {
println 'lib2'
}
task notALib << {
println 'notALib'
}
Execute the following command in the command prompt. It executes the above given script. You should execute this, where the build.gradle file stores.
C:\> gradle –q taskX
Output
The output is cited below −
lib1
lib2
taskX
You can add a description to your task. This description is displayed when you execute the Gradle tasks and this is possible by using, the description keyword.
Copy and save the following code into build.gradle file. Take a look into the following code.
task copy(type: Copy) {
description 'Copies the resource directory to the target directory.'
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
println("description applied")
}
Execute the following command in the command prompt. You should execute this, where the build.gradle file is stored.
C:\> gradle –q copy
If the command is executed successfully, you will get the following output
description applied
Skipping tasks can be done by passing a predicate closure. This is possible only if method of a task or a closure throwing a StopExecutionException before the actual work of a task is executed.
Copy and save the following code into build.gradle file.
task eclipse << {
println 'Hello Eclipse'
}
// #1st approach - closure returning true, if the task should be executed, false if not.
eclipse.onlyIf {
project.hasProperty('usingEclipse')
}
// #2nd approach - alternatively throw an StopExecutionException() like this
eclipse.doFirst {
if(!usingEclipse) {
throw new StopExecutionException()
}
}
Execute the following command in the command prompt. You should execute this, where the build.gradle file is stored.
C:\> gradle –q eclipse
Gradle has different phases, when it comes to working with the tasks. First of all, there is a configuration phase, where the code, which is specified directly in a task's closure, is executed. The configuration block is executed for every available task and not only, for those tasks, which are later actually executed.
After the configuration phase, the execution phase runs the code inside the doFirst or doLast closures of those tasks, which are actually executed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2037,
"s": 1882,
"text": "Gradle build script describes about one or more Projects. Each project is made up of different tasks and a task is a piece of work which a build performs."
},
{
"code": null,
"e": 2211,
"s": 2037,
"text": "The task might be compiling some classes, storing class files into separate target folder, creating JAR, generating Javadoc, or publishing some achieves to the repositories."
},
{
"code": null,
"e": 2292,
"s": 2211,
"text": "This chapter explains about what is task and how to generate and execute a task."
},
{
"code": null,
"e": 2360,
"s": 2292,
"text": "Task is a keyword which is used to define a task into build script."
},
{
"code": null,
"e": 2528,
"s": 2360,
"text": "Take a look at the following example which represents a task named hello that prints tutorialspoint. Copy and save the following script into a file named build.gradle."
},
{
"code": null,
"e": 2618,
"s": 2528,
"text": "This build script defines a task name hello which is used to print tutorialspoint string."
},
{
"code": null,
"e": 2680,
"s": 2618,
"text": "task hello {\n doLast {\n println 'tutorialspoint'\n }\n}\n"
},
{
"code": null,
"e": 2827,
"s": 2680,
"text": "Execute the following command in the command prompt. It executes the above script. You should execute this, where the build.gradle file is stored."
},
{
"code": null,
"e": 2849,
"s": 2827,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 2856,
"s": 2849,
"text": "Output"
},
{
"code": null,
"e": 2896,
"s": 2856,
"text": "Given below is the output of the code −"
},
{
"code": null,
"e": 2912,
"s": 2896,
"text": "tutorialspoint\n"
},
{
"code": null,
"e": 3094,
"s": 2912,
"text": "You can simplify this hello task by specifying a shortcut (represents a symbol <<) to the doLast statement. If you add this shortcut to the above task hello, it will be as follows −"
},
{
"code": null,
"e": 3141,
"s": 3094,
"text": "task hello << {\n println 'tutorialspoint'\n}\n"
},
{
"code": null,
"e": 3205,
"s": 3141,
"text": "You can execute the above script using gradle –q hello command."
},
{
"code": null,
"e": 3249,
"s": 3205,
"text": "The following example defines a task hello."
},
{
"code": null,
"e": 3306,
"s": 3249,
"text": "Copy and save the following code into build.gradle file."
},
{
"code": null,
"e": 3355,
"s": 3306,
"text": "task (hello) << {\n println \"tutorialspoint\"\n}\n"
},
{
"code": null,
"e": 3505,
"s": 3355,
"text": "Execute the following command in the command prompt. It executes the script given above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 3527,
"s": 3505,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 3534,
"s": 3527,
"text": "Output"
},
{
"code": null,
"e": 3562,
"s": 3534,
"text": "The output is shown below −"
},
{
"code": null,
"e": 3578,
"s": 3562,
"text": "tutorialspoint\n"
},
{
"code": null,
"e": 3695,
"s": 3578,
"text": "You can also use strings for the task names. Take a look at the same hello example. Here we will use String as task."
},
{
"code": null,
"e": 3752,
"s": 3695,
"text": "Copy and save the following code into build.gradle file."
},
{
"code": null,
"e": 3802,
"s": 3752,
"text": "task('hello') << {\n println \"tutorialspoint\"\n}\n"
},
{
"code": null,
"e": 3965,
"s": 3802,
"text": "Execute the following command in the command prompt. It executes the script which is mentioned above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 3987,
"s": 3965,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 3994,
"s": 3987,
"text": "Output"
},
{
"code": null,
"e": 4065,
"s": 3994,
"text": "When you execute the above code, you should see the following output −"
},
{
"code": null,
"e": 4081,
"s": 4065,
"text": "tutorialspoint\n"
},
{
"code": null,
"e": 4252,
"s": 4081,
"text": "You can also use an alternative syntax for defining a task. That is, using create() method to define a task. Take a look into the same hello example which is given below."
},
{
"code": null,
"e": 4311,
"s": 4252,
"text": "Copy and save the below given code into build.gradle file."
},
{
"code": null,
"e": 4375,
"s": 4311,
"text": "tasks.create(name: 'hello') << {\n println \"tutorialspoint\"\n}\n"
},
{
"code": null,
"e": 4526,
"s": 4375,
"text": "Execute the following command in the command prompt. It executes the script stated above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 4548,
"s": 4526,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 4555,
"s": 4548,
"text": "Output"
},
{
"code": null,
"e": 4611,
"s": 4555,
"text": "Upon execution, you will receive the following output −"
},
{
"code": null,
"e": 4627,
"s": 4611,
"text": "tutorialspoint\n"
},
{
"code": null,
"e": 4881,
"s": 4627,
"text": "If you want to locate tasks that you have defined in the build file, then, you have to use the respective standard project properties. That means, each task is available as a property of the project, in which, the task name is used as the property name."
},
{
"code": null,
"e": 4956,
"s": 4881,
"text": "Take a look into the following code that accesses the tasks as properties."
},
{
"code": null,
"e": 5015,
"s": 4956,
"text": "Copy and save the below given code into build.gradle file."
},
{
"code": null,
"e": 5074,
"s": 5015,
"text": "task hello\n\nprintln hello.name\nprintln project.hello.name\n"
},
{
"code": null,
"e": 5224,
"s": 5074,
"text": "Execute the following command in the command prompt. It executes the script given above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 5246,
"s": 5224,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 5253,
"s": 5246,
"text": "Output"
},
{
"code": null,
"e": 5285,
"s": 5253,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 5298,
"s": 5285,
"text": "hello\nhello\n"
},
{
"code": null,
"e": 5364,
"s": 5298,
"text": "You can also use all the properties through the tasks collection."
},
{
"code": null,
"e": 5421,
"s": 5364,
"text": "Copy and save the following code into build.gradle file."
},
{
"code": null,
"e": 5487,
"s": 5421,
"text": "task hello\n\nprintln tasks.hello.name\nprintln tasks['hello'].name\n"
},
{
"code": null,
"e": 5650,
"s": 5487,
"text": "Execute the following command in the command prompt. It executes the script which is mentioned above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 5672,
"s": 5650,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 5679,
"s": 5672,
"text": "Output"
},
{
"code": null,
"e": 5716,
"s": 5679,
"text": "This produces the following output −"
},
{
"code": null,
"e": 5729,
"s": 5716,
"text": "hello\nhello\n"
},
{
"code": null,
"e": 5890,
"s": 5729,
"text": "You can also access the task's path by using the tasks. For this, you can call the getByPath() method with a task name, or a relative path, or an absolute path."
},
{
"code": null,
"e": 5949,
"s": 5890,
"text": "Copy and save the below given code into build.gradle file."
},
{
"code": null,
"e": 6173,
"s": 5949,
"text": "project(':projectA') {\n task hello\n}\ntask hello\n\nprintln tasks.getByPath('hello').path\nprintln tasks.getByPath(':hello').path\nprintln tasks.getByPath('projectA:hello').path\nprintln tasks.getByPath(':projectA:hello').path\n"
},
{
"code": null,
"e": 6332,
"s": 6173,
"text": "Execute the following command in the command prompt. It executes the script which is given above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 6354,
"s": 6332,
"text": "C:\\> gradle –q hello\n"
},
{
"code": null,
"e": 6361,
"s": 6354,
"text": "Output"
},
{
"code": null,
"e": 6390,
"s": 6361,
"text": "The output is stated below −"
},
{
"code": null,
"e": 6437,
"s": 6390,
"text": ":hello\n:hello\n:projectA:hello\n:projectA:hello\n"
},
{
"code": null,
"e": 6554,
"s": 6437,
"text": "You can make a task dependent on another task and that means, when one task is done then only other task will begin."
},
{
"code": null,
"e": 6783,
"s": 6554,
"text": "Each task is differentiated with the task name. The collection of task names is referred by its tasks collection. To refer to a task in another project, you should use path of the project as a prefix to the respective task name."
},
{
"code": null,
"e": 6844,
"s": 6783,
"text": "The following example adds a dependency from taskX to taskY."
},
{
"code": null,
"e": 6938,
"s": 6844,
"text": "Copy and save the below given code into build.gradle file. Take a look at the following code."
},
{
"code": null,
"e": 7033,
"s": 6938,
"text": "task taskX << {\n println 'taskX'\n}\ntask taskY(dependsOn: 'taskX') << {\n println \"taskY\"\n}\n"
},
{
"code": null,
"e": 7184,
"s": 7033,
"text": "Execute the following command in the command prompt. It executes the script stated above. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 7206,
"s": 7184,
"text": "C:\\> gradle –q taskY\n"
},
{
"code": null,
"e": 7213,
"s": 7206,
"text": "Output"
},
{
"code": null,
"e": 7244,
"s": 7213,
"text": "The output is given herewith −"
},
{
"code": null,
"e": 7257,
"s": 7244,
"text": "taskX\ntaskY\n"
},
{
"code": null,
"e": 7428,
"s": 7257,
"text": "The above example is adding dependency on task by using its names. There is another way to achieve task dependency which is, to define the dependency using a Task object."
},
{
"code": null,
"e": 7561,
"s": 7428,
"text": "Let us take the same example of taskY being dependent on taskX, but here, we are using task objects instead of task reference names."
},
{
"code": null,
"e": 7618,
"s": 7561,
"text": "Copy and save the following code into build.gradle file."
},
{
"code": null,
"e": 7715,
"s": 7618,
"text": "task taskY << {\n println 'taskY'\n}\ntask taskX << {\n println 'taskX'\n}\ntaskY.dependsOn taskX\n"
},
{
"code": null,
"e": 7831,
"s": 7715,
"text": "Execute the following command in the command prompt. You should execute this where the build.gradle file is stored."
},
{
"code": null,
"e": 7853,
"s": 7831,
"text": "C:\\> gradle –q taskY\n"
},
{
"code": null,
"e": 7860,
"s": 7853,
"text": "Output"
},
{
"code": null,
"e": 7888,
"s": 7860,
"text": "The output is given below −"
},
{
"code": null,
"e": 7901,
"s": 7888,
"text": "taskX\ntaskY\n"
},
{
"code": null,
"e": 7968,
"s": 7901,
"text": "The above example is adding dependency on task by using its names."
},
{
"code": null,
"e": 8068,
"s": 7968,
"text": "There is another way to achieve task dependency which is, to define dependency using a Task object."
},
{
"code": null,
"e": 8197,
"s": 8068,
"text": "Here, we take the same example that taskY is dependent on taskX but, we are using task objects instead of task references names."
},
{
"code": null,
"e": 8293,
"s": 8197,
"text": "Copy and save the below given code into build.gradle file. Take a look into the following code."
},
{
"code": null,
"e": 8526,
"s": 8293,
"text": "task taskX << {\n println 'taskX'\n}\ntaskX.dependsOn {\n tasks.findAll { \n task → task.name.startsWith('lib') \n }\n}\ntask lib1 << {\n println 'lib1'\n}\ntask lib2 << {\n println 'lib2'\n}\ntask notALib << {\n println 'notALib'\n}"
},
{
"code": null,
"e": 8676,
"s": 8526,
"text": "Execute the following command in the command prompt. It executes the above given script. You should execute this, where the build.gradle file stores."
},
{
"code": null,
"e": 8698,
"s": 8676,
"text": "C:\\> gradle –q taskX\n"
},
{
"code": null,
"e": 8705,
"s": 8698,
"text": "Output"
},
{
"code": null,
"e": 8733,
"s": 8705,
"text": "The output is cited below −"
},
{
"code": null,
"e": 8750,
"s": 8733,
"text": "lib1\nlib2\ntaskX\n"
},
{
"code": null,
"e": 8910,
"s": 8750,
"text": "You can add a description to your task. This description is displayed when you execute the Gradle tasks and this is possible by using, the description keyword."
},
{
"code": null,
"e": 9004,
"s": 8910,
"text": "Copy and save the following code into build.gradle file. Take a look into the following code."
},
{
"code": null,
"e": 9228,
"s": 9004,
"text": "task copy(type: Copy) {\n description 'Copies the resource directory to the target directory.'\n from 'resources'\n into 'target'\n include('**/*.txt', '**/*.xml', '**/*.properties')\n println(\"description applied\")\n}\n"
},
{
"code": null,
"e": 9345,
"s": 9228,
"text": "Execute the following command in the command prompt. You should execute this, where the build.gradle file is stored."
},
{
"code": null,
"e": 9366,
"s": 9345,
"text": "C:\\> gradle –q copy\n"
},
{
"code": null,
"e": 9441,
"s": 9366,
"text": "If the command is executed successfully, you will get the following output"
},
{
"code": null,
"e": 9462,
"s": 9441,
"text": "description applied\n"
},
{
"code": null,
"e": 9656,
"s": 9462,
"text": "Skipping tasks can be done by passing a predicate closure. This is possible only if method of a task or a closure throwing a StopExecutionException before the actual work of a task is executed."
},
{
"code": null,
"e": 9713,
"s": 9656,
"text": "Copy and save the following code into build.gradle file."
},
{
"code": null,
"e": 10075,
"s": 9713,
"text": "task eclipse << {\n println 'Hello Eclipse'\n}\n\n// #1st approach - closure returning true, if the task should be executed, false if not.\neclipse.onlyIf {\n project.hasProperty('usingEclipse')\n}\n\n// #2nd approach - alternatively throw an StopExecutionException() like this\neclipse.doFirst {\n if(!usingEclipse) {\n throw new StopExecutionException()\n }\n}"
},
{
"code": null,
"e": 10192,
"s": 10075,
"text": "Execute the following command in the command prompt. You should execute this, where the build.gradle file is stored."
},
{
"code": null,
"e": 10216,
"s": 10192,
"text": "C:\\> gradle –q eclipse\n"
},
{
"code": null,
"e": 10537,
"s": 10216,
"text": "Gradle has different phases, when it comes to working with the tasks. First of all, there is a configuration phase, where the code, which is specified directly in a task's closure, is executed. The configuration block is executed for every available task and not only, for those tasks, which are later actually executed."
},
{
"code": null,
"e": 10685,
"s": 10537,
"text": "After the configuration phase, the execution phase runs the code inside the doFirst or doLast closures of those tasks, which are actually executed."
},
{
"code": null,
"e": 10692,
"s": 10685,
"text": " Print"
},
{
"code": null,
"e": 10703,
"s": 10692,
"text": " Add Notes"
}
] |
Multiply two linked lists | Practice | GeeksforGeeks
|
Given elements as nodes of the two linked lists. The task is to multiply these two linked lists, say L1 and L2.
Note: The output could be large take modulo 109+7.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow, the first line of each test case contains an integer N denoting the size of the first linked list (L1). In the next line are the space separated values of the first linked list. The third line of each test case contains an integer M denoting the size of the second linked list (L2). In the forth line are space separated values of the second linked list.
Output:
For each test case output will be an integer denoting the product of the two linked list.
User Task:
The task is to complete the function multiplyTwoLists() which should multiply the given two linked lists and return the result.
Constraints:
1 <= T <= 100
1 <= N, M <= 100
Example:
Input:
2
2
3 2
1
2
3
1 0 0
2
1 0
Output:
64
1000
Explanation:
Testcase 1: 32*2 = 64.
Testcase 2: 100*10 = 1000.
0
tthakare735 days ago
//java Solution -> TC -> 0.3
//hint ->
class GfG{
public long multiplyTwoLists(Node l1,Node l2){
//add code here.
long num1 = 0, num2 = 0, mod = 1000000007;
while(l1 != null){
num1 = ((num1 * 10) + l1.data)%mod;
l1 = l1.next;
}
while(l2 != null){
num2 = ((num2 * 10) + l2.data)%mod;
l2 = l2.next;
}
return (num1*num2)%mod;
}
}
+1
shahabuddinbravo405 days ago
long long multiplyTwoLists (Node* l1, Node* l2){ long long mod=1000000007; Node *ptr1=l1,*ptr2=l2; long long first=0,second=0; while(ptr1) { first=(first*10)%mod+ptr1->data; ptr1=ptr1->next; } while(ptr2) { second=(second*10)%mod+ptr2->data; ptr2=ptr2->next; } long long ans=((first%mod)*(second%mod))%mod; return ans;}
0
badgujarsachin832 weeks ago
long long multiplyTwoLists (Node* l1, Node* l2)
{
//Your code her
long long mod=1000000007;
Node* temp1=l1;;
Node*temp2=l2;
long long a=0,b=0;
while(temp1!=NULL){
a=((a)*10)%mod+temp1->data;
temp1=temp1->next;
}
while(temp2!=NULL){
b=((b)*10)%mod+temp2->data;
temp2=temp2->next;
}
return ((a%mod)*(b%mod)%mod);
}
-1
19bcs40691 month ago
long long multiplyTwoLists (Node* l1, Node* l2){ long long num1=0; long long num2=0; Node *a=l1; Node *b=l2; while(a){ num1=(num1*10+a->data)%1000000007; a=a->next; } while(b){ num2=(num2*10+b->data)%1000000007; b=b->next; } return (num1*num2)%1000000007; //Your code here}
0
mishra07adi2 months ago
Java Solution
class GfG{
/*You are required to complete this method */
public long multiplyTwoLists(Node l1,Node l2)
{
//add code here.
long N = 1000000007;
long num1 = 0, num2 = 0;
while(l1!=null || l2!=null)
{
if(l1 != null)
{
num1 = ((num1)*10)%N + l1.data;
l1=l1.next;
}
if(l2 != null)
{
num2 = ((num2)*10)%N + l2.data;
l2=l2.next;
}
}
return ((num1%N)*(num2%N)%N);
}
}
0
riteshnaik443 months ago
#define p 1000000007
long long multiplyTwoLists (Node* l1, Node* l2)
{
Node* curr1=l1;
Node* curr2=l2;
long long num1=0;
long long num2=0;
while(curr1!=NULL){
num1=( num1*10 + curr1->data ) % p;
curr1=curr1->next;
}
while(curr2!=NULL){
num2=( num2*10 + curr2->data ) % p;
curr2=curr2->next;
}
long long ans=(num1*num2) % p;
return ans;
}
0
codewithmitesh3 months ago
+5
manishpritmani063 months ago
long long multiplyTwoLists (Node* l1, Node* l2)
{
long long num1 = 0;
long long num2 = 0;
while(l1!=nullptr){
num1 = (num1*10 + l1->data)%1000000007;
l1 = l1->next;
}
while(l2!=nullptr){
num2 = (num2*10 + l2->data)%1000000007;
l2 = l2->next;
}
return (num1*num2)%1000000007;
}
0
hemantsoni3 months ago
0
sajalgupta2433 months ago
#define g 1000000007long long multiplyTwoLists (Node* l1, Node* l2){ //Your code here long long int r1 = 0; while(l1 != NULL){ r1 = (r1*10 + l1->data)%g; l1 = l1->next; } long long int r2 = 0; while(l2 != NULL){ r2 = (r2*10 + l2->data)%g; l2 = l2->next; } return (r1*r2)%g;}
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": 351,
"s": 238,
"text": "Given elements as nodes of the two linked lists. The task is to multiply these two linked lists, say L1 and L2. "
},
{
"code": null,
"e": 402,
"s": 351,
"text": "Note: The output could be large take modulo 109+7."
},
{
"code": null,
"e": 871,
"s": 402,
"text": "Input:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow, the first line of each test case contains an integer N denoting the size of the first linked list (L1). In the next line are the space separated values of the first linked list. The third line of each test case contains an integer M denoting the size of the second linked list (L2). In the forth line are space separated values of the second linked list."
},
{
"code": null,
"e": 969,
"s": 871,
"text": "Output:\nFor each test case output will be an integer denoting the product of the two linked list."
},
{
"code": null,
"e": 1108,
"s": 969,
"text": "User Task:\nThe task is to complete the function multiplyTwoLists() which should multiply the given two linked lists and return the result."
},
{
"code": null,
"e": 1152,
"s": 1108,
"text": "Constraints:\n1 <= T <= 100\n1 <= N, M <= 100"
},
{
"code": null,
"e": 1195,
"s": 1152,
"text": "Example:\nInput:\n2\n2\n3 2\n1\n2\n3\n1 0 0\n2\n1 0 "
},
{
"code": null,
"e": 1211,
"s": 1195,
"text": "Output:\n64\n1000"
},
{
"code": null,
"e": 1247,
"s": 1211,
"text": "Explanation:\nTestcase 1: 32*2 = 64."
},
{
"code": null,
"e": 1276,
"s": 1247,
"text": "Testcase 2: 100*10 = 1000.\n "
},
{
"code": null,
"e": 1278,
"s": 1276,
"text": "0"
},
{
"code": null,
"e": 1299,
"s": 1278,
"text": "tthakare735 days ago"
},
{
"code": null,
"e": 1338,
"s": 1299,
"text": "//java Solution -> TC -> 0.3\n//hint ->"
},
{
"code": null,
"e": 1766,
"s": 1338,
"text": " class GfG{\n public long multiplyTwoLists(Node l1,Node l2){\n //add code here.\n long num1 = 0, num2 = 0, mod = 1000000007;\n \n while(l1 != null){\n num1 = ((num1 * 10) + l1.data)%mod;\n l1 = l1.next;\n }\n \n while(l2 != null){\n num2 = ((num2 * 10) + l2.data)%mod;\n l2 = l2.next;\n }\n \n return (num1*num2)%mod;\n }\n}"
},
{
"code": null,
"e": 1769,
"s": 1766,
"text": "+1"
},
{
"code": null,
"e": 1798,
"s": 1769,
"text": "shahabuddinbravo405 days ago"
},
{
"code": null,
"e": 2162,
"s": 1798,
"text": "long long multiplyTwoLists (Node* l1, Node* l2){ long long mod=1000000007; Node *ptr1=l1,*ptr2=l2; long long first=0,second=0; while(ptr1) { first=(first*10)%mod+ptr1->data; ptr1=ptr1->next; } while(ptr2) { second=(second*10)%mod+ptr2->data; ptr2=ptr2->next; } long long ans=((first%mod)*(second%mod))%mod; return ans;}"
},
{
"code": null,
"e": 2164,
"s": 2162,
"text": "0"
},
{
"code": null,
"e": 2192,
"s": 2164,
"text": "badgujarsachin832 weeks ago"
},
{
"code": null,
"e": 2550,
"s": 2192,
"text": "long long multiplyTwoLists (Node* l1, Node* l2)\n{\n //Your code her\n long long mod=1000000007;\n Node* temp1=l1;;\n Node*temp2=l2;\n long long a=0,b=0;\n while(temp1!=NULL){\n a=((a)*10)%mod+temp1->data;\n temp1=temp1->next;\n }\n while(temp2!=NULL){\n b=((b)*10)%mod+temp2->data;\n temp2=temp2->next;\n }\n return ((a%mod)*(b%mod)%mod);\n}"
},
{
"code": null,
"e": 2553,
"s": 2550,
"text": "-1"
},
{
"code": null,
"e": 2574,
"s": 2553,
"text": "19bcs40691 month ago"
},
{
"code": null,
"e": 2891,
"s": 2574,
"text": "long long multiplyTwoLists (Node* l1, Node* l2){ long long num1=0; long long num2=0; Node *a=l1; Node *b=l2; while(a){ num1=(num1*10+a->data)%1000000007; a=a->next; } while(b){ num2=(num2*10+b->data)%1000000007; b=b->next; } return (num1*num2)%1000000007; //Your code here}"
},
{
"code": null,
"e": 2893,
"s": 2891,
"text": "0"
},
{
"code": null,
"e": 2917,
"s": 2893,
"text": "mishra07adi2 months ago"
},
{
"code": null,
"e": 2931,
"s": 2917,
"text": "Java Solution"
},
{
"code": null,
"e": 3540,
"s": 2931,
"text": "class GfG{\n /*You are required to complete this method */\n \n public long multiplyTwoLists(Node l1,Node l2)\n {\n //add code here.\n \n long N = 1000000007;\n long num1 = 0, num2 = 0;\n \n while(l1!=null || l2!=null)\n {\n if(l1 != null)\n {\n num1 = ((num1)*10)%N + l1.data;\n l1=l1.next;\n }\n \n if(l2 != null)\n {\n num2 = ((num2)*10)%N + l2.data;\n l2=l2.next;\n }\n }\n \n return ((num1%N)*(num2%N)%N);\n }\n}"
},
{
"code": null,
"e": 3542,
"s": 3540,
"text": "0"
},
{
"code": null,
"e": 3567,
"s": 3542,
"text": "riteshnaik443 months ago"
},
{
"code": null,
"e": 4014,
"s": 3567,
"text": "#define p 1000000007\n\nlong long multiplyTwoLists (Node* l1, Node* l2)\n{\n Node* curr1=l1;\n Node* curr2=l2;\n long long num1=0;\n long long num2=0;\n \n while(curr1!=NULL){\n num1=( num1*10 + curr1->data ) % p;\n curr1=curr1->next;\n }\n \n while(curr2!=NULL){\n num2=( num2*10 + curr2->data ) % p;\n curr2=curr2->next;\n }\n long long ans=(num1*num2) % p;\n \n \n return ans;\n \n \n \n}"
},
{
"code": null,
"e": 4016,
"s": 4014,
"text": "0"
},
{
"code": null,
"e": 4043,
"s": 4016,
"text": "codewithmitesh3 months ago"
},
{
"code": null,
"e": 4048,
"s": 4045,
"text": "+5"
},
{
"code": null,
"e": 4077,
"s": 4048,
"text": "manishpritmani063 months ago"
},
{
"code": null,
"e": 4393,
"s": 4077,
"text": "long long multiplyTwoLists (Node* l1, Node* l2)\n{\n long long num1 = 0;\n long long num2 = 0;\n while(l1!=nullptr){\n num1 = (num1*10 + l1->data)%1000000007;\n l1 = l1->next;\n }\n while(l2!=nullptr){\n num2 = (num2*10 + l2->data)%1000000007;\n l2 = l2->next;\n }\n return (num1*num2)%1000000007;\n}"
},
{
"code": null,
"e": 4395,
"s": 4393,
"text": "0"
},
{
"code": null,
"e": 4418,
"s": 4395,
"text": "hemantsoni3 months ago"
},
{
"code": null,
"e": 4420,
"s": 4418,
"text": "0"
},
{
"code": null,
"e": 4446,
"s": 4420,
"text": "sajalgupta2433 months ago"
},
{
"code": null,
"e": 4766,
"s": 4446,
"text": "#define g 1000000007long long multiplyTwoLists (Node* l1, Node* l2){ //Your code here long long int r1 = 0; while(l1 != NULL){ r1 = (r1*10 + l1->data)%g; l1 = l1->next; } long long int r2 = 0; while(l2 != NULL){ r2 = (r2*10 + l2->data)%g; l2 = l2->next; } return (r1*r2)%g;}"
},
{
"code": null,
"e": 4912,
"s": 4766,
"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": 4948,
"s": 4912,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4958,
"s": 4948,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4968,
"s": 4958,
"text": "\nContest\n"
},
{
"code": null,
"e": 5031,
"s": 4968,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5179,
"s": 5031,
"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": 5387,
"s": 5179,
"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": 5493,
"s": 5387,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Erlang - Basic Syntax
|
In order to understand the basic syntax of Erlang, let’s first look at a simple Hello World program.
% hello world program
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite("Hello, world!\n").
The following things need to be noted about the above program −
The % sign is used to add comments to the program.
The % sign is used to add comments to the program.
The module statement is like adding a namespace as in any programming language. So over here, we are mentioning that this code will part of a module called helloworld.
The module statement is like adding a namespace as in any programming language. So over here, we are mentioning that this code will part of a module called helloworld.
The export function is used so that any function defined within the program can be used. We are defining a function called start and in order to use the start function, we have to use the export statement. The /0 means that our function ‘start’ accepts 0 parameters.
The export function is used so that any function defined within the program can be used. We are defining a function called start and in order to use the start function, we have to use the export statement. The /0 means that our function ‘start’ accepts 0 parameters.
We finally define our start function. Here we use another module called io which has all the required Input Output functions in Erlang. We used the fwrite function to output “Hello World” to the console.
We finally define our start function. Here we use another module called io which has all the required Input Output functions in Erlang. We used the fwrite function to output “Hello World” to the console.
The output of the above program will be −
Hello, world!
In Erlang, you have seen that there are different symbols used in Erlang language. Let’s go through what we have seen from a simple Hello World program −
The hyphen symbol (–) is generally used along with the module, import and export statement. The hyphen symbol is used to give meaning to each statement accordingly. So examples from the Hello world program are shown in the following program −
The hyphen symbol (–) is generally used along with the module, import and export statement. The hyphen symbol is used to give meaning to each statement accordingly. So examples from the Hello world program are shown in the following program −
-module(helloworld).
-export([start/0]).
Each statement is delimited with the dot (.) symbol. Each statement in Erlang needs to end with this delimiter. An example from the Hello world program is as shown in the following program −
io:fwrite("Hello, world!\n").
The slash (/) symbol is used along with the function to define the number of parameters which is accepted by the function.
The slash (/) symbol is used along with the function to define the number of parameters which is accepted by the function.
-export([start/0]).
In Erlang, all the code is divided into modules. A module consists of a sequence of attributes and function declarations. It is just like a concept of a namespace in other programming languages which is used to logically separate different units of code.
A module is defined with the module identifier. The general syntax and example is as follows.
-module(ModuleName)
The ModuleName needs to be same as the file name minus the extension .erl. Otherwise code loading will not work as intended.
-module(helloworld)
These Modules will be covered in detail in the ensuing chapters, this was just to get you at a basic understanding of how a module should be defined.
In Erlang, if one wants to use the functionality of an existing Erlang module, one can use the import statement. The general form of the import statement is depicted in the following program −
-import (modulename, [functionname/parameter]).
Where,
Modulename − This is the name of the module which needs to be imported.
Modulename − This is the name of the module which needs to be imported.
functionname/parameter − The function in the module which needs to be imported.
functionname/parameter − The function in the module which needs to be imported.
Let’s change the way we write our hello world program to use an import statement. The example would be as shown in the following program.
% hello world program
-module(helloworld).
-import(io,[fwrite/1]).
-export([start/0]).
start() ->
fwrite("Hello, world!\n").
In the above code, we are using the import keyword to import the library ‘io’ and specifically the fwrite function. So now whenever we invoke the fwrite function, we don’t have to mention the io module name everywhere.
A Keyword is a reserved word in Erlang which should not be used for any different purposes other than the purpose which it has been intended for. Following are the list of keywords in Erlang.
Comments are used to document your code. Single line comments are identified by using the % symbol at any position in the line. Following is an example for the same −
% hello world program
-module(helloworld).
% import function used to import the io module
-import(io,[fwrite/1]).
% export function used to ensure the start function can be accessed.
-export([start/0]).
start() ->
fwrite("Hello, world!\n").
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2402,
"s": 2301,
"text": "In order to understand the basic syntax of Erlang, let’s first look at a simple Hello World program."
},
{
"code": null,
"e": 2513,
"s": 2402,
"text": "% hello world program\n-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(\"Hello, world!\\n\")."
},
{
"code": null,
"e": 2577,
"s": 2513,
"text": "The following things need to be noted about the above program −"
},
{
"code": null,
"e": 2628,
"s": 2577,
"text": "The % sign is used to add comments to the program."
},
{
"code": null,
"e": 2679,
"s": 2628,
"text": "The % sign is used to add comments to the program."
},
{
"code": null,
"e": 2847,
"s": 2679,
"text": "The module statement is like adding a namespace as in any programming language. So over here, we are mentioning that this code will part of a module called helloworld."
},
{
"code": null,
"e": 3015,
"s": 2847,
"text": "The module statement is like adding a namespace as in any programming language. So over here, we are mentioning that this code will part of a module called helloworld."
},
{
"code": null,
"e": 3282,
"s": 3015,
"text": "The export function is used so that any function defined within the program can be used. We are defining a function called start and in order to use the start function, we have to use the export statement. The /0 means that our function ‘start’ accepts 0 parameters."
},
{
"code": null,
"e": 3549,
"s": 3282,
"text": "The export function is used so that any function defined within the program can be used. We are defining a function called start and in order to use the start function, we have to use the export statement. The /0 means that our function ‘start’ accepts 0 parameters."
},
{
"code": null,
"e": 3753,
"s": 3549,
"text": "We finally define our start function. Here we use another module called io which has all the required Input Output functions in Erlang. We used the fwrite function to output “Hello World” to the console."
},
{
"code": null,
"e": 3957,
"s": 3753,
"text": "We finally define our start function. Here we use another module called io which has all the required Input Output functions in Erlang. We used the fwrite function to output “Hello World” to the console."
},
{
"code": null,
"e": 3999,
"s": 3957,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 4014,
"s": 3999,
"text": "Hello, world!\n"
},
{
"code": null,
"e": 4168,
"s": 4014,
"text": "In Erlang, you have seen that there are different symbols used in Erlang language. Let’s go through what we have seen from a simple Hello World program −"
},
{
"code": null,
"e": 4411,
"s": 4168,
"text": "The hyphen symbol (–) is generally used along with the module, import and export statement. The hyphen symbol is used to give meaning to each statement accordingly. So examples from the Hello world program are shown in the following program −"
},
{
"code": null,
"e": 4654,
"s": 4411,
"text": "The hyphen symbol (–) is generally used along with the module, import and export statement. The hyphen symbol is used to give meaning to each statement accordingly. So examples from the Hello world program are shown in the following program −"
},
{
"code": null,
"e": 4696,
"s": 4654,
"text": "-module(helloworld).\n-export([start/0]).\n"
},
{
"code": null,
"e": 4887,
"s": 4696,
"text": "Each statement is delimited with the dot (.) symbol. Each statement in Erlang needs to end with this delimiter. An example from the Hello world program is as shown in the following program −"
},
{
"code": null,
"e": 4918,
"s": 4887,
"text": "io:fwrite(\"Hello, world!\\n\").\n"
},
{
"code": null,
"e": 5041,
"s": 4918,
"text": "The slash (/) symbol is used along with the function to define the number of parameters which is accepted by the function."
},
{
"code": null,
"e": 5164,
"s": 5041,
"text": "The slash (/) symbol is used along with the function to define the number of parameters which is accepted by the function."
},
{
"code": null,
"e": 5185,
"s": 5164,
"text": "-export([start/0]).\n"
},
{
"code": null,
"e": 5440,
"s": 5185,
"text": "In Erlang, all the code is divided into modules. A module consists of a sequence of attributes and function declarations. It is just like a concept of a namespace in other programming languages which is used to logically separate different units of code."
},
{
"code": null,
"e": 5534,
"s": 5440,
"text": "A module is defined with the module identifier. The general syntax and example is as follows."
},
{
"code": null,
"e": 5555,
"s": 5534,
"text": "-module(ModuleName)\n"
},
{
"code": null,
"e": 5680,
"s": 5555,
"text": "The ModuleName needs to be same as the file name minus the extension .erl. Otherwise code loading will not work as intended."
},
{
"code": null,
"e": 5701,
"s": 5680,
"text": "-module(helloworld)\n"
},
{
"code": null,
"e": 5851,
"s": 5701,
"text": "These Modules will be covered in detail in the ensuing chapters, this was just to get you at a basic understanding of how a module should be defined."
},
{
"code": null,
"e": 6044,
"s": 5851,
"text": "In Erlang, if one wants to use the functionality of an existing Erlang module, one can use the import statement. The general form of the import statement is depicted in the following program −"
},
{
"code": null,
"e": 6093,
"s": 6044,
"text": "-import (modulename, [functionname/parameter]).\n"
},
{
"code": null,
"e": 6100,
"s": 6093,
"text": "Where,"
},
{
"code": null,
"e": 6172,
"s": 6100,
"text": "Modulename − This is the name of the module which needs to be imported."
},
{
"code": null,
"e": 6244,
"s": 6172,
"text": "Modulename − This is the name of the module which needs to be imported."
},
{
"code": null,
"e": 6324,
"s": 6244,
"text": "functionname/parameter − The function in the module which needs to be imported."
},
{
"code": null,
"e": 6404,
"s": 6324,
"text": "functionname/parameter − The function in the module which needs to be imported."
},
{
"code": null,
"e": 6542,
"s": 6404,
"text": "Let’s change the way we write our hello world program to use an import statement. The example would be as shown in the following program."
},
{
"code": null,
"e": 6671,
"s": 6542,
"text": "% hello world program\n-module(helloworld).\n-import(io,[fwrite/1]).\n-export([start/0]).\n\nstart() ->\n fwrite(\"Hello, world!\\n\")."
},
{
"code": null,
"e": 6890,
"s": 6671,
"text": "In the above code, we are using the import keyword to import the library ‘io’ and specifically the fwrite function. So now whenever we invoke the fwrite function, we don’t have to mention the io module name everywhere."
},
{
"code": null,
"e": 7082,
"s": 6890,
"text": "A Keyword is a reserved word in Erlang which should not be used for any different purposes other than the purpose which it has been intended for. Following are the list of keywords in Erlang."
},
{
"code": null,
"e": 7249,
"s": 7082,
"text": "Comments are used to document your code. Single line comments are identified by using the % symbol at any position in the line. Following is an example for the same −"
},
{
"code": null,
"e": 7494,
"s": 7249,
"text": "% hello world program\n-module(helloworld).\n% import function used to import the io module\n-import(io,[fwrite/1]).\n% export function used to ensure the start function can be accessed.\n-export([start/0]).\n\nstart() ->\n fwrite(\"Hello, world!\\n\")."
},
{
"code": null,
"e": 7501,
"s": 7494,
"text": " Print"
},
{
"code": null,
"e": 7512,
"s": 7501,
"text": " Add Notes"
}
] |
Java program to convert the contents of a Map to list
|
The Map class’s object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately.
To convert a map to list −
Create a Map object.
Using the put() method insert elements to it as key, value pairs
Create an ArrayList of integer type to hold the keys of the map. In its constructor call the method keySet() of the Map class.
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Print the contents of both lists.
import java.util.HashMap;
import java.uitl.ArrayList;
import java.util.Map;
public class MapTohashMap {
public static void main(String args[]){
Map<Integer, String> myMap = new HashMap<>();
myMap.put(1, "Java");
myMap.put(2, "JavaFX");
myMap.put(3, "CoffeeScript");
myMap.put(4, "TypeScript");
ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet());
ArrayList<String> valueList = new ArrayList<String>(myMap.values());
System.out.println("contents of the list holding keys the map ::"+keyList);
System.out.println("contents of the list holding values of the map ::"+valueList);
}
}
contents of the list holding keys the map::[1, 2, 3, 4]
contents of the list holding values of the map::[Java, JavaFX, CoffeeScript, Typescript]
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "The Map class’s object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately."
},
{
"code": null,
"e": 1263,
"s": 1236,
"text": "To convert a map to list −"
},
{
"code": null,
"e": 1284,
"s": 1263,
"text": "Create a Map object."
},
{
"code": null,
"e": 1349,
"s": 1284,
"text": "Using the put() method insert elements to it as key, value pairs"
},
{
"code": null,
"e": 1476,
"s": 1349,
"text": "Create an ArrayList of integer type to hold the keys of the map. In its constructor call the method keySet() of the Map class."
},
{
"code": null,
"e": 1604,
"s": 1476,
"text": "Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class."
},
{
"code": null,
"e": 1638,
"s": 1604,
"text": "Print the contents of both lists."
},
{
"code": null,
"e": 2297,
"s": 1638,
"text": "import java.util.HashMap;\nimport java.uitl.ArrayList;\nimport java.util.Map;\n\npublic class MapTohashMap {\n public static void main(String args[]){\n Map<Integer, String> myMap = new HashMap<>();\n myMap.put(1, \"Java\");\n myMap.put(2, \"JavaFX\");\n myMap.put(3, \"CoffeeScript\");\n myMap.put(4, \"TypeScript\");\n\n ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet());\n ArrayList<String> valueList = new ArrayList<String>(myMap.values());\n\n System.out.println(\"contents of the list holding keys the map ::\"+keyList);\n System.out.println(\"contents of the list holding values of the map ::\"+valueList);\n }\n}\n"
},
{
"code": null,
"e": 2442,
"s": 2297,
"text": "contents of the list holding keys the map::[1, 2, 3, 4]\ncontents of the list holding values of the map::[Java, JavaFX, CoffeeScript, Typescript]"
}
] |
Ngx-Bootstrap - Modals
|
ngx-bootstrap modal component is a flexible and highly configurable dialog prompt and provides multiple defaults and can be used with minimum code.
[bsModal]
[bsModal]
config − ModalOptions, allows to set modal configuration via element property
config − ModalOptions, allows to set modal configuration via element property
onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
onHide − This event is fired immediately when the hide instance method has been called.
onHide − This event is fired immediately when the hide instance method has been called.
onShow − This event fires immediately when the show instance method is called.
onShow − This event fires immediately when the show instance method is called.
onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete).
onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete).
show() − Allows to manually open modal.
show() − Allows to manually open modal.
hide() − Allows to manually close modal.
hide() − Allows to manually close modal.
toggle() − Allows to manually toggle modal visibility.
toggle() − Allows to manually toggle modal visibility.
showElement() − Show dialog.
showElement() − Show dialog.
focusOtherModal() − Events tricks.
focusOtherModal() − Events tricks.
As we're going to use a modal, We've to update app.module.ts used in ngx-bootstrap Dropdowns chapter to use ModalModule and BsModalService.
Update app.module.ts to use the ModalModule and BsModalService.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AccordionModule } from 'ngx-bootstrap/accordion';
import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';
import { ButtonsModule } from 'ngx-bootstrap/buttons';
import { FormsModule } from '@angular/forms';
import { CarouselModule } from 'ngx-bootstrap/carousel';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';
import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';
import { ModalModule, BsModalService } from 'ngx-bootstrap/modal';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
AccordionModule,
AlertModule,
ButtonsModule,
FormsModule,
CarouselModule,
CollapseModule,
BsDatepickerModule.forRoot(),
BsDropdownModule,
ModalModule
],
providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig,BsModalService],
bootstrap: [AppComponent]
})
export class AppModule { }
Update test.component.html to use the modal.
test.component.html
<button type="button" class="btn btn-primary" (click)="openModal(template)">Open modal</button>
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is a sample modal dialog box.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="modalRef.hide()">Close</button>
</div>
</ng-template>
Update test.component.ts for corresponding variables and methods.
test.component.ts
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
modalRef: BsModalRef;
constructor(private modalService: BsModalService) {}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
ngOnInit(): void {
}
}
Run the following command to start the angular server.
ng serve
Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2248,
"s": 2100,
"text": "ngx-bootstrap modal component is a flexible and highly configurable dialog prompt and provides multiple defaults and can be used with minimum code."
},
{
"code": null,
"e": 2258,
"s": 2248,
"text": "[bsModal]"
},
{
"code": null,
"e": 2268,
"s": 2258,
"text": "[bsModal]"
},
{
"code": null,
"e": 2346,
"s": 2268,
"text": "config − ModalOptions, allows to set modal configuration via element property"
},
{
"code": null,
"e": 2424,
"s": 2346,
"text": "config − ModalOptions, allows to set modal configuration via element property"
},
{
"code": null,
"e": 2555,
"s": 2424,
"text": "onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete)."
},
{
"code": null,
"e": 2686,
"s": 2555,
"text": "onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete)."
},
{
"code": null,
"e": 2774,
"s": 2686,
"text": "onHide − This event is fired immediately when the hide instance method has been called."
},
{
"code": null,
"e": 2862,
"s": 2774,
"text": "onHide − This event is fired immediately when the hide instance method has been called."
},
{
"code": null,
"e": 2941,
"s": 2862,
"text": "onShow − This event fires immediately when the show instance method is called."
},
{
"code": null,
"e": 3020,
"s": 2941,
"text": "onShow − This event fires immediately when the show instance method is called."
},
{
"code": null,
"e": 3144,
"s": 3020,
"text": "onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete)."
},
{
"code": null,
"e": 3268,
"s": 3144,
"text": "onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete)."
},
{
"code": null,
"e": 3308,
"s": 3268,
"text": "show() − Allows to manually open modal."
},
{
"code": null,
"e": 3348,
"s": 3308,
"text": "show() − Allows to manually open modal."
},
{
"code": null,
"e": 3389,
"s": 3348,
"text": "hide() − Allows to manually close modal."
},
{
"code": null,
"e": 3430,
"s": 3389,
"text": "hide() − Allows to manually close modal."
},
{
"code": null,
"e": 3485,
"s": 3430,
"text": "toggle() − Allows to manually toggle modal visibility."
},
{
"code": null,
"e": 3540,
"s": 3485,
"text": "toggle() − Allows to manually toggle modal visibility."
},
{
"code": null,
"e": 3569,
"s": 3540,
"text": "showElement() − Show dialog."
},
{
"code": null,
"e": 3598,
"s": 3569,
"text": "showElement() − Show dialog."
},
{
"code": null,
"e": 3633,
"s": 3598,
"text": "focusOtherModal() − Events tricks."
},
{
"code": null,
"e": 3668,
"s": 3633,
"text": "focusOtherModal() − Events tricks."
},
{
"code": null,
"e": 3808,
"s": 3668,
"text": "As we're going to use a modal, We've to update app.module.ts used in ngx-bootstrap Dropdowns chapter to use ModalModule and BsModalService."
},
{
"code": null,
"e": 3872,
"s": 3808,
"text": "Update app.module.ts to use the ModalModule and BsModalService."
},
{
"code": null,
"e": 3886,
"s": 3872,
"text": "app.module.ts"
},
{
"code": null,
"e": 5228,
"s": 3886,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { ModalModule, BsModalService } from 'ngx-bootstrap/modal';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule\n ],\n providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig,BsModalService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 5273,
"s": 5228,
"text": "Update test.component.html to use the modal."
},
{
"code": null,
"e": 5293,
"s": 5273,
"text": "test.component.html"
},
{
"code": null,
"e": 5890,
"s": 5293,
"text": "<button type=\"button\" class=\"btn btn-primary\" (click)=\"openModal(template)\">Open modal</button>\n\n<ng-template #template>\n <div class=\"modal-header\">\n <h4 class=\"modal-title pull-left\">Modal</h4>\n <button type=\"button\" class=\"close pull-right\" aria-label=\"Close\" (click)=\"modalRef.hide()\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <div class=\"modal-body\">\n This is a sample modal dialog box.\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" (click)=\"modalRef.hide()\">Close</button>\n </div>\n</ng-template>"
},
{
"code": null,
"e": 5956,
"s": 5890,
"text": "Update test.component.ts for corresponding variables and methods."
},
{
"code": null,
"e": 5974,
"s": 5956,
"text": "test.component.ts"
},
{
"code": null,
"e": 6490,
"s": 5974,
"text": "import { Component, OnInit, TemplateRef } from '@angular/core';\nimport { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n\n modalRef: BsModalRef;\n constructor(private modalService: BsModalService) {}\n\n openModal(template: TemplateRef<any>) {\n this.modalRef = this.modalService.show(template);\n }\n\n ngOnInit(): void {\n }\n}"
},
{
"code": null,
"e": 6545,
"s": 6490,
"text": "Run the following command to start the angular server."
},
{
"code": null,
"e": 6555,
"s": 6545,
"text": "ng serve\n"
},
{
"code": null,
"e": 6674,
"s": 6555,
"text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output."
},
{
"code": null,
"e": 6681,
"s": 6674,
"text": " Print"
},
{
"code": null,
"e": 6692,
"s": 6681,
"text": " Add Notes"
}
] |
How many levels of pointers can we have in C/C++ - GeeksforGeeks
|
18 Jan, 2022
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as:
datatype *variable name;
This above declaration is a single pointer but there can be more than this. This is called levels of pointers. According to ANSI C, each compiler must have at least 12 levels of pointers. This means we can use 12 * symbols with a variable name.Level Of Pointers in C/C++: Level of pointers or say chain can go up to N level depending upon the memory size. If you want to create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of declaration. Syntax:
// level-1 pointer declaration
datatype *pointer;
// level-2 pointer declaration
datatype **pointer;
// level-3 pointer declaration
datatype ***pointer;
.
.
and so on
The level of the pointer depends on how many asterisks the pointer variable is preceded with at the time of declaration.Declaration:
int *pointer_1;
int **pointer_2;
int ***pointer_3;
.
.
and so on
Below are the programs to illustrate the various level of pointers:Program 1:
C
C++
// C program to illustrate levels of pointer#include <stdio.h> // Driver Codeint main(){ int var = 10; // Pointer level-1 // Declaring pointer to var int* ptr1; // Pointer level-2 // Declaring pointer to pointer // variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double // pointer **ptr2 int*** ptr3; // Storing address of var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer // ptr1 to level-2 ptr2 ptr2 = &ptr1; // Storing address of level-2 // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values printf("Value of variable " "var = %d\n", var); printf("Value of variable var using" " pointer ptr1 = %d\n", *ptr1); printf("Value of variable var using" " pointer ptr2 = %d\n", **ptr2); printf("Value of variable var using" " pointer ptr3 = %d\n", ***ptr3); return 0;}
// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int var = 10; // Pointer level-1 // Declaring pointer to var int* ptr1; // Pointer level-2 // Declaring pointer to pointer // variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double // pointer **ptr2 int*** ptr3; // Storing address of var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer // ptr1 to level-2 ptr2 ptr2 = &ptr1; // Storing address of level-2 // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values cout << "Value of variable var is " << var << endl; cout << "Value of variable var " << "using pointer ptr1 is " << *ptr1 << endl; cout << "Value of variable var " << "using pointer ptr2 is " << **ptr2 << endl; cout << "Value of variable var " << "using pointer ptr3 is " << ***ptr3 << endl; return 0;}
Value of variable var = 10
Value of variable var using pointer ptr1 = 10
Value of variable var using pointer ptr2 = 10
Value of variable var using pointer ptr3 = 10
Program 2:
C
C++
// C program to illustrate// levels of pointer#include <stdio.h> // Driver Codeint main(){ float var = 23.564327; // Declaring pointer variables // upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer // variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values printf("Value of var = %f\n", var); printf("Value of var using level-1" " pointer = %f\n", *ptr1); printf("Value of var using level-2" " pointer = %f\n", **ptr2); printf("Value of var using level-3" " pointer = %f\n", ***ptr3); printf("Value of var using level-4" " pointer = %f\n", ****ptr4); return 0;}
// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ float var = 23.564327; // Declaring pointer variables // upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer // variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values cout << "Value of var is " << var << endl; cout << "Value of var using level-1" << " pointer is " << *ptr1 << endl; cout << "Value of var using level-2" << " pointer is " << **ptr2 << endl; cout << "Value of var using level-3" << " pointer is " << ***ptr3 << endl; cout << "Value of var using level-4" << " pointer is " << ****ptr4 << endl; return 0;}
Value of var = 23.564327
Value of var using level-1 pointer = 23.564327
Value of var using level-2 pointer = 23.564327
Value of var using level-3 pointer = 23.564327
Value of var using level-4 pointer = 23.564327
Explanation: The above code where we have taken float data type of the variable, so now we have to take the same data type for the chain of pointers too. As the pointer and the variable, it is pointing to should have the same data type.Program 3:
C
C++
// C program to illustrate// levels of pointer#include <stdio.h> // Driver Codeint main(){ // Initializing integer variable int var = 10; // Declaring pointer variables // upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation printf("Before:\n"); printf("Value of var = %d\n", var); printf("Value of var using level-1" " pointer = %d\n", *ptr1); printf("Value of var using level-2" " pointer = %d\n", **ptr2); printf("Value of var using level-3" " pointer = %d\n", ***ptr3); // Updating var's value using // level-3 pointer ***ptr3 = 35; // Printing values AFTER updation printf("After:\n"); printf("Value of var = %d\n", var); printf("Value of var using level-1" " pointer = %d\n", *ptr1); printf("Value of var using level-2" " pointer = %d\n", **ptr2); printf("Value of var using level-3" " pointer = %d\n", ***ptr3); return 0;}
// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initializing integer variable int var = 10; // Declaring pointer variables // upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation cout << "Before:" << endl; cout << "Value of var is " << var << endl; cout << "Value of var using level-1" << " pointer is " << *ptr1 << endl; cout << "Value of var using level-2" << " pointer is " << **ptr2 << endl; cout << "Value of var using level-3" << " pointer is " << ***ptr3 << endl; // Updating var's value using // level-3 pointer ***ptr3 = 35; // Printing values AFTER updation cout << "After:" << endl; cout << "Value of var is " << var << endl; cout << "Value of var using level-1" << " pointer is " << *ptr1 << endl; cout << "Value of var using level-2" << " pointer is " << **ptr2 << endl; cout << "Value of var using level-3" << " pointer is " << ***ptr3 << endl; return 0;}
Before:
Value of var = 10
Value of var using level-1 pointer = 10
Value of var using level-2 pointer = 10
Value of var using level-3 pointer = 10
After:
Value of var = 35
Value of var using level-1 pointer = 35
Value of var using level-2 pointer = 35
Value of var using level-3 pointer = 35
Explanation: As we already know that a pointer points to address the location of a variable so when we access the value of a pointer that points to the variable’s value. Now to update the value of the variable, we can use any level of pointer as ultimately every pointer is directly or indirectly pointing to that variable only. It will directly change the value present at the address location of the variable.
surinderdawra388
C-Advanced Pointer
C-Pointer Basics
C-Pointers
cpp-double-pointer
cpp-pointer
Picked
pointer
Pointers
C Language
C++
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Operator Overloading in C++
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 24732,
"s": 24429,
"text": "Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: "
},
{
"code": null,
"e": 24757,
"s": 24732,
"text": "datatype *variable name;"
},
{
"code": null,
"e": 25259,
"s": 24757,
"text": "This above declaration is a single pointer but there can be more than this. This is called levels of pointers. According to ANSI C, each compiler must have at least 12 levels of pointers. This means we can use 12 * symbols with a variable name.Level Of Pointers in C/C++: Level of pointers or say chain can go up to N level depending upon the memory size. If you want to create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of declaration. Syntax: "
},
{
"code": null,
"e": 25431,
"s": 25259,
"text": "// level-1 pointer declaration\ndatatype *pointer; \n\n// level-2 pointer declaration\ndatatype **pointer; \n\n// level-3 pointer declaration\ndatatype ***pointer; \n.\n.\nand so on"
},
{
"code": null,
"e": 25566,
"s": 25431,
"text": "The level of the pointer depends on how many asterisks the pointer variable is preceded with at the time of declaration.Declaration: "
},
{
"code": null,
"e": 25631,
"s": 25566,
"text": "int *pointer_1;\nint **pointer_2;\nint ***pointer_3;\n.\n.\nand so on"
},
{
"code": null,
"e": 25711,
"s": 25631,
"text": "Below are the programs to illustrate the various level of pointers:Program 1: "
},
{
"code": null,
"e": 25713,
"s": 25711,
"text": "C"
},
{
"code": null,
"e": 25717,
"s": 25713,
"text": "C++"
},
{
"code": "// C program to illustrate levels of pointer#include <stdio.h> // Driver Codeint main(){ int var = 10; // Pointer level-1 // Declaring pointer to var int* ptr1; // Pointer level-2 // Declaring pointer to pointer // variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double // pointer **ptr2 int*** ptr3; // Storing address of var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer // ptr1 to level-2 ptr2 ptr2 = &ptr1; // Storing address of level-2 // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values printf(\"Value of variable \" \"var = %d\\n\", var); printf(\"Value of variable var using\" \" pointer ptr1 = %d\\n\", *ptr1); printf(\"Value of variable var using\" \" pointer ptr2 = %d\\n\", **ptr2); printf(\"Value of variable var using\" \" pointer ptr3 = %d\\n\", ***ptr3); return 0;}",
"e": 26711,
"s": 25717,
"text": null
},
{
"code": "// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int var = 10; // Pointer level-1 // Declaring pointer to var int* ptr1; // Pointer level-2 // Declaring pointer to pointer // variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double // pointer **ptr2 int*** ptr3; // Storing address of var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer // ptr1 to level-2 ptr2 ptr2 = &ptr1; // Storing address of level-2 // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values cout << \"Value of variable var is \" << var << endl; cout << \"Value of variable var \" << \"using pointer ptr1 is \" << *ptr1 << endl; cout << \"Value of variable var \" << \"using pointer ptr2 is \" << **ptr2 << endl; cout << \"Value of variable var \" << \"using pointer ptr3 is \" << ***ptr3 << endl; return 0;}",
"e": 27748,
"s": 26711,
"text": null
},
{
"code": null,
"e": 27913,
"s": 27748,
"text": "Value of variable var = 10\nValue of variable var using pointer ptr1 = 10\nValue of variable var using pointer ptr2 = 10\nValue of variable var using pointer ptr3 = 10"
},
{
"code": null,
"e": 27928,
"s": 27915,
"text": "Program 2: "
},
{
"code": null,
"e": 27930,
"s": 27928,
"text": "C"
},
{
"code": null,
"e": 27934,
"s": 27930,
"text": "C++"
},
{
"code": "// C program to illustrate// levels of pointer#include <stdio.h> // Driver Codeint main(){ float var = 23.564327; // Declaring pointer variables // upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer // variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values printf(\"Value of var = %f\\n\", var); printf(\"Value of var using level-1\" \" pointer = %f\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %f\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %f\\n\", ***ptr3); printf(\"Value of var using level-4\" \" pointer = %f\\n\", ****ptr4); return 0;}",
"e": 28689,
"s": 27934,
"text": null
},
{
"code": "// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ float var = 23.564327; // Declaring pointer variables // upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer // variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values cout << \"Value of var is \" << var << endl; cout << \"Value of var using level-1\" << \" pointer is \" << *ptr1 << endl; cout << \"Value of var using level-2\" << \" pointer is \" << **ptr2 << endl; cout << \"Value of var using level-3\" << \" pointer is \" << ***ptr3 << endl; cout << \"Value of var using level-4\" << \" pointer is \" << ****ptr4 << endl; return 0;}",
"e": 29512,
"s": 28689,
"text": null
},
{
"code": null,
"e": 29725,
"s": 29512,
"text": "Value of var = 23.564327\nValue of var using level-1 pointer = 23.564327\nValue of var using level-2 pointer = 23.564327\nValue of var using level-3 pointer = 23.564327\nValue of var using level-4 pointer = 23.564327"
},
{
"code": null,
"e": 29976,
"s": 29727,
"text": "Explanation: The above code where we have taken float data type of the variable, so now we have to take the same data type for the chain of pointers too. As the pointer and the variable, it is pointing to should have the same data type.Program 3: "
},
{
"code": null,
"e": 29978,
"s": 29976,
"text": "C"
},
{
"code": null,
"e": 29982,
"s": 29978,
"text": "C++"
},
{
"code": "// C program to illustrate// levels of pointer#include <stdio.h> // Driver Codeint main(){ // Initializing integer variable int var = 10; // Declaring pointer variables // upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation printf(\"Before:\\n\"); printf(\"Value of var = %d\\n\", var); printf(\"Value of var using level-1\" \" pointer = %d\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %d\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %d\\n\", ***ptr3); // Updating var's value using // level-3 pointer ***ptr3 = 35; // Printing values AFTER updation printf(\"After:\\n\"); printf(\"Value of var = %d\\n\", var); printf(\"Value of var using level-1\" \" pointer = %d\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %d\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %d\\n\", ***ptr3); return 0;}",
"e": 31117,
"s": 29982,
"text": null
},
{
"code": "// C++ program to illustrate// levels of pointer#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initializing integer variable int var = 10; // Declaring pointer variables // upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation cout << \"Before:\" << endl; cout << \"Value of var is \" << var << endl; cout << \"Value of var using level-1\" << \" pointer is \" << *ptr1 << endl; cout << \"Value of var using level-2\" << \" pointer is \" << **ptr2 << endl; cout << \"Value of var using level-3\" << \" pointer is \" << ***ptr3 << endl; // Updating var's value using // level-3 pointer ***ptr3 = 35; // Printing values AFTER updation cout << \"After:\" << endl; cout << \"Value of var is \" << var << endl; cout << \"Value of var using level-1\" << \" pointer is \" << *ptr1 << endl; cout << \"Value of var using level-2\" << \" pointer is \" << **ptr2 << endl; cout << \"Value of var using level-3\" << \" pointer is \" << ***ptr3 << endl; return 0;}",
"e": 32360,
"s": 31117,
"text": null
},
{
"code": null,
"e": 32651,
"s": 32360,
"text": "Before:\nValue of var = 10\nValue of var using level-1 pointer = 10\nValue of var using level-2 pointer = 10\nValue of var using level-3 pointer = 10\nAfter:\nValue of var = 35\nValue of var using level-1 pointer = 35\nValue of var using level-2 pointer = 35\nValue of var using level-3 pointer = 35"
},
{
"code": null,
"e": 33066,
"s": 32653,
"text": "Explanation: As we already know that a pointer points to address the location of a variable so when we access the value of a pointer that points to the variable’s value. Now to update the value of the variable, we can use any level of pointer as ultimately every pointer is directly or indirectly pointing to that variable only. It will directly change the value present at the address location of the variable. "
},
{
"code": null,
"e": 33083,
"s": 33066,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33102,
"s": 33083,
"text": "C-Advanced Pointer"
},
{
"code": null,
"e": 33119,
"s": 33102,
"text": "C-Pointer Basics"
},
{
"code": null,
"e": 33130,
"s": 33119,
"text": "C-Pointers"
},
{
"code": null,
"e": 33149,
"s": 33130,
"text": "cpp-double-pointer"
},
{
"code": null,
"e": 33161,
"s": 33149,
"text": "cpp-pointer"
},
{
"code": null,
"e": 33168,
"s": 33161,
"text": "Picked"
},
{
"code": null,
"e": 33176,
"s": 33168,
"text": "pointer"
},
{
"code": null,
"e": 33185,
"s": 33176,
"text": "Pointers"
},
{
"code": null,
"e": 33196,
"s": 33185,
"text": "C Language"
},
{
"code": null,
"e": 33200,
"s": 33196,
"text": "C++"
},
{
"code": null,
"e": 33209,
"s": 33200,
"text": "Pointers"
},
{
"code": null,
"e": 33213,
"s": 33209,
"text": "CPP"
},
{
"code": null,
"e": 33311,
"s": 33213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33346,
"s": 33311,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 33374,
"s": 33346,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 33420,
"s": 33374,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 33460,
"s": 33420,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 33472,
"s": 33460,
"text": "fork() in C"
},
{
"code": null,
"e": 33490,
"s": 33472,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 33536,
"s": 33490,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 33579,
"s": 33536,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33607,
"s": 33579,
"text": "Operator Overloading in C++"
}
] |
How to adjust display settings of MySQL command line?
|
To adjust display settings of MySQL command line, use the /G at the end of MySQL queries instead of semicolon(;).
The syntax is as follows −
SELECT *FROM yourTableName \G
The above syntax adjusts the display settings. Here we will display records in row format from our sample ‘studenttable’ table which we created using CREATE −
mysql> create table StudentTable
−> (
−> Id int,
−> Name varchar(100)
−> );
Query OK, 0 rows affected (0.65 sec)
To get all the records −
mysql> select *from StudentTable;
The following displays the records −
+------+---------+
| Id | Name |
+------+---------+
| 1 | Carol |
| 2 | John |
| 3 | Johnson |
+------+---------+
3 rows in set (0.00 sec)
The table ‘studenttable’ have some records that display all records in row format. The query is as follows to adjust display settings −
select *from studenttable \G
The following is the output −
*************************** 1. row ***************************
Id: 1
Name: Carol
*************************** 2. row ***************************
Id: 2
Name: John
*************************** 3. row ***************************
Id: 3
Name: Johnson
3 rows in set (0.04 sec)
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To adjust display settings of MySQL command line, use the /G at the end of MySQL queries instead of semicolon(;)."
},
{
"code": null,
"e": 1203,
"s": 1176,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1233,
"s": 1203,
"text": "SELECT *FROM yourTableName \\G"
},
{
"code": null,
"e": 1392,
"s": 1233,
"text": "The above syntax adjusts the display settings. Here we will display records in row format from our sample ‘studenttable’ table which we created using CREATE −"
},
{
"code": null,
"e": 1518,
"s": 1392,
"text": "mysql> create table StudentTable\n −> (\n −> Id int, \n −> Name varchar(100)\n −> );\nQuery OK, 0 rows affected (0.65 sec)"
},
{
"code": null,
"e": 1543,
"s": 1518,
"text": "To get all the records −"
},
{
"code": null,
"e": 1577,
"s": 1543,
"text": "mysql> select *from StudentTable;"
},
{
"code": null,
"e": 1614,
"s": 1577,
"text": "The following displays the records −"
},
{
"code": null,
"e": 1772,
"s": 1614,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 1 | Carol |\n| 2 | John |\n| 3 | Johnson |\n+------+---------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1908,
"s": 1772,
"text": "The table ‘studenttable’ have some records that display all records in row format. The query is as follows to adjust display settings −"
},
{
"code": null,
"e": 1937,
"s": 1908,
"text": "select *from studenttable \\G"
},
{
"code": null,
"e": 1967,
"s": 1937,
"text": "The following is the output −"
},
{
"code": null,
"e": 2236,
"s": 1967,
"text": "*************************** 1. row ***************************\nId: 1\nName: Carol\n*************************** 2. row ***************************\nId: 2\nName: John\n*************************** 3. row ***************************\nId: 3\nName: Johnson\n3 rows in set (0.04 sec)"
}
] |
Using LDA Topic Models as a Classification Model Input | by Marc Kelechava | Towards Data Science
|
Topic Modeling in NLP seeks to find hidden semantic structure in documents. They are probabilistic models that can help you comb through massive amounts of raw text and cluster similar groups of documents together in an unsupervised way.
This post specifically focuses on Latent Dirichlet Allocation (LDA), which was a technique proposed in 2000 for population genetics and re-discovered independently by ML-hero Andrew Ng et al. in 2003. LDA states that each document in a corpus is a combination of a fixed number of topics. A topic has a probability of generating various words, where the words are all the observed words in the corpus. These ‘hidden’ topics are then surfaced based on the likelihood of word co-occurrence. Formally, this is Bayesian Inference problem [1].
Once LDA topic modeling is applied to set of documents, you‘re able to see the words that make up each hidden topic. In my case, I took 100,000 reviews from Yelp Restaurants in 2016 using the Yelp dataset [2]. Here are two examples of topics discovered via LDA:
You can see the first topic group seems to have identified word co-occurrences for negative burger reviews, and the second topic group seems to have identified positive Italian restaurant experiences. The third topic isn’t as clear-cut, but generally seems to touch on terrible, dry salty food.
I was more interested to see if this hidden semantic structure (generated unsupervised) could be converted to be used in a supervised classification problem. Assume for a minute that I had only trained a LDA model to find 3 topics as above. After training, I could then take all 100,000 reviews and see the distribution of topics for every review. In other words, some documents might be 100% Topic 1, others might be 33%/33%/33% of Topic 1/2/3, etc. That output is just a vector for every review showing the distribution. The idea here is to test whether the distribution per review of hidden semantic information could predict positive and negative sentiment.
With that intro out of the way, here was my goal:
Specifically:
Train LDA Model on 100,000 Restaurant Reviews from 2016Grab Topic distributions for every review using the LDA ModelUse Topic Distributions directly as feature vectors in supervised classification models (Logistic Regression, SVC, etc) and get F1-score.Use the same 2016 LDA model to get topic distributions from 2017 (the LDA model did not see this data!)Run supervised classification models again on the 2017 vectors and see if this generalizes.
Train LDA Model on 100,000 Restaurant Reviews from 2016
Grab Topic distributions for every review using the LDA Model
Use Topic Distributions directly as feature vectors in supervised classification models (Logistic Regression, SVC, etc) and get F1-score.
Use the same 2016 LDA model to get topic distributions from 2017 (the LDA model did not see this data!)
Run supervised classification models again on the 2017 vectors and see if this generalizes.
If the supervised F1-scores on the unseen data generalizes, then we can posit that the 2016 topic model has identified latent semantic structure that persists over time in this restaurant review domain.
UPDATE (9/23/19): I’ve added a README to the Repo which shows how to create a MongoDB using the source data. I’ve also included a preprocessing script which will allow you to create the exact training and test DataFrames I use below. However, I realize that might be a lot of work, so I also included pickle files of my Train and Test DataFrames in the directory here. This will allow you to follow along with the notebooks in the repo directly, namely, here and then here. If you’d rather just get the highlights/takeaways, I point out all the key bits in the rest of this blog post below with code snippets.
I used the truly wonderful gensim library to create bi-gram representations of the reviews and to run LDA. Gensim’s LDA implementation needs reviews as a sparse vector. Conveniently, gensim also provides convenience utilities to convert NumPy dense matrices or scipy sparse matrices into the required form.
I’ll show how I got to the requisite representation using gensim functions. I started with a pandas DataFrame containing the text of every review in a column named'text’, which can be extracted to a list of list of strings, where each list represents a review. This is the object namedwords in my example below:
from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['come','order','try','go','get','make','drink','plate','dish','restaurant','place','would','really','like','great','service','came','got']) def remove_stopwords(texts): out = [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts] return outdef bigrams(words, bi_min=15, tri_min=10): bigram = gensim.models.Phrases(words, min_count = bi_min) bigram_mod = gensim.models.phrases.Phraser(bigram) return bigram_moddef get_corpus(df): df['text'] = strip_newline(df.text) words = list(sent_to_words(df.text)) words = remove_stopwords(words) bigram_mod = bigrams(words) bigram = [bigram_mod[review] for review in words] id2word = gensim.corpora.Dictionary(bigram) id2word.filter_extremes(no_below=10, no_above=0.35) id2word.compactify() corpus = [id2word.doc2bow(text) for text in bigram] return corpus, id2word, bigramtrain_corpus, train_id2word, bigram_train = get_corpus(rev_train)
I’m omitting showing a few steps of additional pre-processing (punctuation, stripping newlines, etc) for brevity in this post.
There are really 2 key items in this code block:
Gensim’s Phrases class allows you to group related phrases into one token for LDA. For example, note that in the list of found topics toward the start of this post that ice_cream was listed as a single token. Thus the output of this line bigram = [bigram_mod[review] for review in words] is a list of lists where each list represents a review and the strings in each list are a mix of unigrams and bigrams. This is the case since the what we’ve done is apply the bigram_mod phrase modeling model to every review.Once you have that list of lists of unigrams and bigrams, you can pass it to gensim’s Dictionary class. This will output the word frequency count of each word for each review. I found that I had the best results with LDA when I additionally did some processing to remove the most common and the rarest words in the corpus as shown in line 21 of the above code block. Finally here’s what doc2bow() is doing, from their official examples [3]:
Gensim’s Phrases class allows you to group related phrases into one token for LDA. For example, note that in the list of found topics toward the start of this post that ice_cream was listed as a single token. Thus the output of this line bigram = [bigram_mod[review] for review in words] is a list of lists where each list represents a review and the strings in each list are a mix of unigrams and bigrams. This is the case since the what we’ve done is apply the bigram_mod phrase modeling model to every review.
Once you have that list of lists of unigrams and bigrams, you can pass it to gensim’s Dictionary class. This will output the word frequency count of each word for each review. I found that I had the best results with LDA when I additionally did some processing to remove the most common and the rarest words in the corpus as shown in line 21 of the above code block. Finally here’s what doc2bow() is doing, from their official examples [3]:
“The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector. The sparse vector [(0, 1), (1, 1)] therefore reads: in the document “Human computer interaction”, the words computer (id 0) and human (id 1) appear once; the other ten dictionary words appear (implicitly) zero times.”
Line 23 above then gives us the corpus in the representation needed for LDA.
To give an example of the type of text we’re dealing with, here’s a snapshot of a Yelp review:
In order to train a LDA model you need to provide a fixed assume number of topics across your corpus. There are a number of ways you could approach this:
Run LDA on your corpus with different numbers of topics and see if word distribution per topic looks sensible.Examine the coherence scores of your LDA model, and effectively grid search to choose the highest coherence [4].Create a handful of LDA models with different topic values, then see how these perform in the supervised classification model training. This is specific to my goals here, since my ultimate aim is to see if the topic distributions have predictive value.
Run LDA on your corpus with different numbers of topics and see if word distribution per topic looks sensible.
Examine the coherence scores of your LDA model, and effectively grid search to choose the highest coherence [4].
Create a handful of LDA models with different topic values, then see how these perform in the supervised classification model training. This is specific to my goals here, since my ultimate aim is to see if the topic distributions have predictive value.
Of these: I don’t trust #1 as a method at all. Who am I to say what’s sensible or not in this context? I’m relying on LDA to identify latent topic representations of 100,000 documents, and it’s possible that it won’t necessarily be intuitive. For #2: I talked to some former NLP professionals and they dissuaded me from relying on coherence scores based on their experience in industry. Approach #3 would be reasonable for my purpose but there’s a reality that LDA takes a non-trivial of time to train even though I was using a 16GB 8-Core AWS instance.
Thus I came up with an idea that I think is fairly novel — at the very least, I haven’t seen anyone do this online or in papers:
Gensim also provides a Hierarchical Dirichlet Process (HDP) class [5]. HDP is similar to LDA, except it seeks to learn the correct number of topics from the data; that is, you don’t need to provide a fixed number of topics. I figured I would run HDP on my 100,000 reviews a few times and see the number of topics it was learning. In my case this was always 20 topics, so I went with that.
To get an intuitive feel for HDP: I found a number of sources online that said it’s most similar to a Chinese Restaurant Process. This is explained brilliantly by Edwin Chen here [6], and beautifully visualized in [7] here. Here’s the visualization from [7]:
In this example, we need to assign 8 to a topic. There’s a 3/8 probability 8 will land in topic C1, a 4/8 probability 8 will land in topic C2, and a 1/8 probability a new topic C3 will be created. In this way a number of topics is discovered. So the bigger a cluster is, the more likely it is for someone to join that cluster. I felt this was just as reasonable as any other method to choose a fixed topic number for LDA. If anyone with a heavier Bayesian Inference background has thoughts on this please weigh in!
UPDATE [4/13/2020] — Eduardo Coronado has kindly provided some more precise info on HDP, via the comments:
“It is true that HDPs non-parametric property allow us to learn the topics from the data however Dirichlet Process mixtures do that already. The main advantage of HDPs is they allowing distinct corpora (groups) to share statistical strength when modeling — in this case share a common set of potentially infinite topics. So it is an extension of Dirichlet Process mixtures.”
Here’s the code to run LDA with Gensim:
import gensimwith warnings.catch_warnings(): warnings.simplefilter('ignore') lda_train = gensim.models.ldamulticore.LdaMulticore( corpus=train_corpus, num_topics=20, id2word=train_id2word, chunksize=100, workers=7, # Num. Processing Cores - 1 passes=50, eval_every = 1, per_word_topics=True) lda_train.save('lda_train.model')
By turning on the eval_every flag we’re able to process the corpus in chunks: in my case chunks of 100 documents worked fairly well for convergence. The number of passes is separate passes over the entire corpus.
Once that’s done, you can view the words making up each topic as follows:
lda_train.print_topics(20, num_words=15)[:10]
With that code you’ll see 10 of the 20 topics and the 15 top words for each.
Now comes the interesting bit. We’re going to use the LDA model to grab the distribution of these 20 topics for every review. This 20-vector will be our feature vector for supervised classification, with the supervised learning goal being to determine positive or negative sentiment.
Note that I think this approach for supervised classification using topic model vectors is not very common. When I did it I wasn’t aware of any example online of people trying this, though later on when I was done I discovered this paper where it was done in 2008 [8]. Please let me know if there are other examples out there!
The ultimate goal is not only to see how this performs in a train/test CV split of the current data, but whether the topics have hit on something fundamental that translates to unseen test data in the future (in my case, data from a year later).
Here’s what I did to grab the feature vectors for every review:
train_vecs = []for i in range(len(rev_train)): top_topics = ( lda_train.get_document_topics(train_corpus[i], minimum_probability=0.0) ) topic_vec = [top_topics[i][1] for i in range(20)] topic_vec.extend([rev_train.iloc[i].real_counts]) topic_vec.extend([len(rev_train.iloc[i].text)]) train_vecs.append(topic_vec)
The key bit is using minimum_probability=0.0 in line 3. This ensures that we’ll capture the instances where a review is presented with 0% in some topics, and the representation for each review will add up to 100%.
Lines 5 and 6 are two hand-engineered features I added.
Thus a single observation for a review for supervised classification now looks like this:
The first 20 items represent the distribution for the 20 found topics for each review.
We’re now ready to train! Here I’m using 100,000 2016 restaurant reviews and their topic-model distribution feature vector + two hand-engineered features:
X = np.array(train_vecs)y = np.array(rev_train.target)kf = KFold(5, shuffle=True, random_state=42)cv_lr_f1, cv_lrsgd_f1, cv_svcsgd_f1, = [], [], []for train_ind, val_ind in kf.split(X, y): # Assign CV IDX X_train, y_train = X[train_ind], y[train_ind] X_val, y_val = X[val_ind], y[val_ind] # Scale Data scaler = StandardScaler() X_train_scale = scaler.fit_transform(X_train) X_val_scale = scaler.transform(X_val) # Logisitic Regression lr = LogisticRegression( class_weight= 'balanced', solver='newton-cg', fit_intercept=True ).fit(X_train_scale, y_train) y_pred = lr.predict(X_val_scale) cv_lr_f1.append(f1_score(y_val, y_pred, average='binary')) # Logistic Regression SGD sgd = linear_model.SGDClassifier( max_iter=1000, tol=1e-3, loss='log', class_weight='balanced' ).fit(X_train_scale, y_train) y_pred = sgd.predict(X_val_scale) cv_lrsgd_f1.append(f1_score(y_val, y_pred, average='binary')) # SGD Modified Huber sgd_huber = linear_model.SGDClassifier( max_iter=1000, tol=1e-3, alpha=20, loss='modified_huber', class_weight='balanced' ).fit(X_train_scale, y_train) y_pred = sgd_huber.predict(X_val_scale) cv_svcsgd_f1.append(f1_score(y_val, y_pred, average='binary'))print(f'Logistic Regression Val f1: {np.mean(cv_lr_f1):.3f} +- {np.std(cv_lr_f1):.3f}')print(f'Logisitic Regression SGD Val f1: {np.mean(cv_lrsgd_f1):.3f} +- {np.std(cv_lrsgd_f1):.3f}')print(f'SVM Huber Val f1: {np.mean(cv_svcsgd_f1):.3f} +- {np.std(cv_svcsgd_f1):.3f}')
A couple notes on this:
I landed on a comparison between standard Logistic Regression, Stochastic Gradient Descent with Log Loss, and Stochastic Gradient Descent with Modified Huber loss.I’m running a 5-fold CV, so that in each run 1/5 of the reviews are held-out as validation data, and the other 4/5 are training data. This is repeated for every fold, and the f1 score results are averaged at the end.My classes are imbalanced. In particular, there are a disproportionate amount of 4 and 5 star reviews in the Yelp review dataset. The class_weight='balanced' line in the models approximates undersampling to correct for this. See [9] for a justification of this choice.I’ve also restricted the analysis to just restaurants that had above the 25th percentile in total reviews in the dataset. This was more of a restriction to speed things up since the initial dataset was something like 4 million+ reviews.
I landed on a comparison between standard Logistic Regression, Stochastic Gradient Descent with Log Loss, and Stochastic Gradient Descent with Modified Huber loss.
I’m running a 5-fold CV, so that in each run 1/5 of the reviews are held-out as validation data, and the other 4/5 are training data. This is repeated for every fold, and the f1 score results are averaged at the end.
My classes are imbalanced. In particular, there are a disproportionate amount of 4 and 5 star reviews in the Yelp review dataset. The class_weight='balanced' line in the models approximates undersampling to correct for this. See [9] for a justification of this choice.
I’ve also restricted the analysis to just restaurants that had above the 25th percentile in total reviews in the dataset. This was more of a restriction to speed things up since the initial dataset was something like 4 million+ reviews.
Here are the f1-score results:
I’ll first walk-through the lower .53 and .62 f1-scores using Logisitic Regression. When I initially started training I tried to predict the individual review ratings: 1,2,3,4 or 5 stars. As you can see this was not successful. I was a bit discouraged with the initial .53 score, so went back to examine my initial EDA charts to see if I could notice anything in the data. I had run this chart earlier on:
This shows the word count IQR range by rating. Since the main IQR range was pretty compact, I decided to try re-running the LDA pre-processing and model restricted to just (roughly) the IQR range. Making this change increased my Logistic Regression score on f1 to .62 for 1,2,3,4,5 star classification. Still not great.
At this point I decided to see what would happen if I got rid of the 3-stars, and grouped the 1,2 stars as ‘bad’ and 4,5 stars as ‘good’ sentiment scores. As you’ll see in the graph above, this worked wonder! Now Logistic Regression yieled a .869 f1-score.
When I was running these, I noticed a ‘modified huber’ loss option in SKLearn’s Stochastic Gradient Descent implementation [10]. In this case, the penalty for being wrong is much worse than either Hinge (SVC) or Log Loss:
I’m still grappling with why this worked so well, but my initial thought is that these punishing penalties caused SGD (remember, 1 by 1 weight updates) to learn quickly. Regularization helped immensely here as well. The alpha in line 42 in the code above is a regularization parameter (think like in Ridge or Lasso regularization), and this helped in getting my f1-score up to .936.
At this point I was pretty thrilled by these results, but wanted to further see what would happen on completely unseen data.
Specifically:
Take the LDA Model from the 2016 reviews, and grab feature vectors on test data. It’s important to note that the same 2016 model can be used to do this!Re-run the models on the test-vectors.
Take the LDA Model from the 2016 reviews, and grab feature vectors on test data. It’s important to note that the same 2016 model can be used to do this!
Re-run the models on the test-vectors.
All that’s required is making bigrams for the test corpus, then throwing this into the test-vector extraction approach as before:
def get_bigram(df): df['text'] = strip_newline(df.text) words = list(sent_to_words(df.text)) words = remove_stopwords(words) bigram = bigrams(words) bigram = [bigram[review] for review in words] return bigram bigram_test = get_bigram(rev_test)test_corpus = [train_id2word.doc2bow(text) for text in bigram_test]test_vecs = []for i in range(len(rev_test)): top_topics = ( lda_train.get_document_topics(test_corpus[i], minimum_probability=0.0) topic_vec = [top_topics[i][1] for i in range(20)] topic_vec.extend([rev_test.iloc[i].real_counts]) topic_vec.extend([len(rev_test.iloc[i].text)]) test_vecs.append(topic_vec)
Finally, the results:
Somewhat shockingly to me, this generalizes!
I was thrilled with this result, as I believe this approach could work generally for any company trying to train a classifier in this way. I also did a hypothesis test at the end using mlxtend [11] and the final result is indeed statistically significant.
I intend on extending this a bit in the future, and I’ll leave you with that:
I’ve also hosted all the code for this and the trained LDA model on my GitHub here.
Thanks for reading!
[1] https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation[2] https://www.yelp.com/dataset[3] https://radimrehurek.com/gensim/tut1.html[4] https://radimrehurek.com/gensim/models/coherencemodel.html[5] https://radimrehurek.com/gensim/models/hdpmodel.html[6] http://blog.echen.me/2012/03/20/infinite-mixture-models-with-nonparametric-bayes-and-the-dirichlet-process/[7] http://gerin.perso.math.cnrs.fr/ChineseRestaurant.html[8] http://gibbslda.sourceforge.net/fp224-phan.pdf[9] http://blog.madhukaraphatak.com/class-imbalance-part-2/[10] https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html[11] http://rasbt.github.io/mlxtend/user_guide/evaluate/mcnemar/
|
[
{
"code": null,
"e": 409,
"s": 171,
"text": "Topic Modeling in NLP seeks to find hidden semantic structure in documents. They are probabilistic models that can help you comb through massive amounts of raw text and cluster similar groups of documents together in an unsupervised way."
},
{
"code": null,
"e": 948,
"s": 409,
"text": "This post specifically focuses on Latent Dirichlet Allocation (LDA), which was a technique proposed in 2000 for population genetics and re-discovered independently by ML-hero Andrew Ng et al. in 2003. LDA states that each document in a corpus is a combination of a fixed number of topics. A topic has a probability of generating various words, where the words are all the observed words in the corpus. These ‘hidden’ topics are then surfaced based on the likelihood of word co-occurrence. Formally, this is Bayesian Inference problem [1]."
},
{
"code": null,
"e": 1210,
"s": 948,
"text": "Once LDA topic modeling is applied to set of documents, you‘re able to see the words that make up each hidden topic. In my case, I took 100,000 reviews from Yelp Restaurants in 2016 using the Yelp dataset [2]. Here are two examples of topics discovered via LDA:"
},
{
"code": null,
"e": 1505,
"s": 1210,
"text": "You can see the first topic group seems to have identified word co-occurrences for negative burger reviews, and the second topic group seems to have identified positive Italian restaurant experiences. The third topic isn’t as clear-cut, but generally seems to touch on terrible, dry salty food."
},
{
"code": null,
"e": 2167,
"s": 1505,
"text": "I was more interested to see if this hidden semantic structure (generated unsupervised) could be converted to be used in a supervised classification problem. Assume for a minute that I had only trained a LDA model to find 3 topics as above. After training, I could then take all 100,000 reviews and see the distribution of topics for every review. In other words, some documents might be 100% Topic 1, others might be 33%/33%/33% of Topic 1/2/3, etc. That output is just a vector for every review showing the distribution. The idea here is to test whether the distribution per review of hidden semantic information could predict positive and negative sentiment."
},
{
"code": null,
"e": 2217,
"s": 2167,
"text": "With that intro out of the way, here was my goal:"
},
{
"code": null,
"e": 2231,
"s": 2217,
"text": "Specifically:"
},
{
"code": null,
"e": 2679,
"s": 2231,
"text": "Train LDA Model on 100,000 Restaurant Reviews from 2016Grab Topic distributions for every review using the LDA ModelUse Topic Distributions directly as feature vectors in supervised classification models (Logistic Regression, SVC, etc) and get F1-score.Use the same 2016 LDA model to get topic distributions from 2017 (the LDA model did not see this data!)Run supervised classification models again on the 2017 vectors and see if this generalizes."
},
{
"code": null,
"e": 2735,
"s": 2679,
"text": "Train LDA Model on 100,000 Restaurant Reviews from 2016"
},
{
"code": null,
"e": 2797,
"s": 2735,
"text": "Grab Topic distributions for every review using the LDA Model"
},
{
"code": null,
"e": 2935,
"s": 2797,
"text": "Use Topic Distributions directly as feature vectors in supervised classification models (Logistic Regression, SVC, etc) and get F1-score."
},
{
"code": null,
"e": 3039,
"s": 2935,
"text": "Use the same 2016 LDA model to get topic distributions from 2017 (the LDA model did not see this data!)"
},
{
"code": null,
"e": 3131,
"s": 3039,
"text": "Run supervised classification models again on the 2017 vectors and see if this generalizes."
},
{
"code": null,
"e": 3334,
"s": 3131,
"text": "If the supervised F1-scores on the unseen data generalizes, then we can posit that the 2016 topic model has identified latent semantic structure that persists over time in this restaurant review domain."
},
{
"code": null,
"e": 3944,
"s": 3334,
"text": "UPDATE (9/23/19): I’ve added a README to the Repo which shows how to create a MongoDB using the source data. I’ve also included a preprocessing script which will allow you to create the exact training and test DataFrames I use below. However, I realize that might be a lot of work, so I also included pickle files of my Train and Test DataFrames in the directory here. This will allow you to follow along with the notebooks in the repo directly, namely, here and then here. If you’d rather just get the highlights/takeaways, I point out all the key bits in the rest of this blog post below with code snippets."
},
{
"code": null,
"e": 4251,
"s": 3944,
"text": "I used the truly wonderful gensim library to create bi-gram representations of the reviews and to run LDA. Gensim’s LDA implementation needs reviews as a sparse vector. Conveniently, gensim also provides convenience utilities to convert NumPy dense matrices or scipy sparse matrices into the required form."
},
{
"code": null,
"e": 4563,
"s": 4251,
"text": "I’ll show how I got to the requisite representation using gensim functions. I started with a pandas DataFrame containing the text of every review in a column named'text’, which can be extracted to a list of list of strings, where each list represents a review. This is the object namedwords in my example below:"
},
{
"code": null,
"e": 5639,
"s": 4563,
"text": "from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['come','order','try','go','get','make','drink','plate','dish','restaurant','place','would','really','like','great','service','came','got']) def remove_stopwords(texts): out = [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts] return outdef bigrams(words, bi_min=15, tri_min=10): bigram = gensim.models.Phrases(words, min_count = bi_min) bigram_mod = gensim.models.phrases.Phraser(bigram) return bigram_moddef get_corpus(df): df['text'] = strip_newline(df.text) words = list(sent_to_words(df.text)) words = remove_stopwords(words) bigram_mod = bigrams(words) bigram = [bigram_mod[review] for review in words] id2word = gensim.corpora.Dictionary(bigram) id2word.filter_extremes(no_below=10, no_above=0.35) id2word.compactify() corpus = [id2word.doc2bow(text) for text in bigram] return corpus, id2word, bigramtrain_corpus, train_id2word, bigram_train = get_corpus(rev_train)"
},
{
"code": null,
"e": 5766,
"s": 5639,
"text": "I’m omitting showing a few steps of additional pre-processing (punctuation, stripping newlines, etc) for brevity in this post."
},
{
"code": null,
"e": 5815,
"s": 5766,
"text": "There are really 2 key items in this code block:"
},
{
"code": null,
"e": 6768,
"s": 5815,
"text": "Gensim’s Phrases class allows you to group related phrases into one token for LDA. For example, note that in the list of found topics toward the start of this post that ice_cream was listed as a single token. Thus the output of this line bigram = [bigram_mod[review] for review in words] is a list of lists where each list represents a review and the strings in each list are a mix of unigrams and bigrams. This is the case since the what we’ve done is apply the bigram_mod phrase modeling model to every review.Once you have that list of lists of unigrams and bigrams, you can pass it to gensim’s Dictionary class. This will output the word frequency count of each word for each review. I found that I had the best results with LDA when I additionally did some processing to remove the most common and the rarest words in the corpus as shown in line 21 of the above code block. Finally here’s what doc2bow() is doing, from their official examples [3]:"
},
{
"code": null,
"e": 7281,
"s": 6768,
"text": "Gensim’s Phrases class allows you to group related phrases into one token for LDA. For example, note that in the list of found topics toward the start of this post that ice_cream was listed as a single token. Thus the output of this line bigram = [bigram_mod[review] for review in words] is a list of lists where each list represents a review and the strings in each list are a mix of unigrams and bigrams. This is the case since the what we’ve done is apply the bigram_mod phrase modeling model to every review."
},
{
"code": null,
"e": 7722,
"s": 7281,
"text": "Once you have that list of lists of unigrams and bigrams, you can pass it to gensim’s Dictionary class. This will output the word frequency count of each word for each review. I found that I had the best results with LDA when I additionally did some processing to remove the most common and the rarest words in the corpus as shown in line 21 of the above code block. Finally here’s what doc2bow() is doing, from their official examples [3]:"
},
{
"code": null,
"e": 8111,
"s": 7722,
"text": "“The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector. The sparse vector [(0, 1), (1, 1)] therefore reads: in the document “Human computer interaction”, the words computer (id 0) and human (id 1) appear once; the other ten dictionary words appear (implicitly) zero times.”"
},
{
"code": null,
"e": 8188,
"s": 8111,
"text": "Line 23 above then gives us the corpus in the representation needed for LDA."
},
{
"code": null,
"e": 8283,
"s": 8188,
"text": "To give an example of the type of text we’re dealing with, here’s a snapshot of a Yelp review:"
},
{
"code": null,
"e": 8437,
"s": 8283,
"text": "In order to train a LDA model you need to provide a fixed assume number of topics across your corpus. There are a number of ways you could approach this:"
},
{
"code": null,
"e": 8912,
"s": 8437,
"text": "Run LDA on your corpus with different numbers of topics and see if word distribution per topic looks sensible.Examine the coherence scores of your LDA model, and effectively grid search to choose the highest coherence [4].Create a handful of LDA models with different topic values, then see how these perform in the supervised classification model training. This is specific to my goals here, since my ultimate aim is to see if the topic distributions have predictive value."
},
{
"code": null,
"e": 9023,
"s": 8912,
"text": "Run LDA on your corpus with different numbers of topics and see if word distribution per topic looks sensible."
},
{
"code": null,
"e": 9136,
"s": 9023,
"text": "Examine the coherence scores of your LDA model, and effectively grid search to choose the highest coherence [4]."
},
{
"code": null,
"e": 9389,
"s": 9136,
"text": "Create a handful of LDA models with different topic values, then see how these perform in the supervised classification model training. This is specific to my goals here, since my ultimate aim is to see if the topic distributions have predictive value."
},
{
"code": null,
"e": 9943,
"s": 9389,
"text": "Of these: I don’t trust #1 as a method at all. Who am I to say what’s sensible or not in this context? I’m relying on LDA to identify latent topic representations of 100,000 documents, and it’s possible that it won’t necessarily be intuitive. For #2: I talked to some former NLP professionals and they dissuaded me from relying on coherence scores based on their experience in industry. Approach #3 would be reasonable for my purpose but there’s a reality that LDA takes a non-trivial of time to train even though I was using a 16GB 8-Core AWS instance."
},
{
"code": null,
"e": 10072,
"s": 9943,
"text": "Thus I came up with an idea that I think is fairly novel — at the very least, I haven’t seen anyone do this online or in papers:"
},
{
"code": null,
"e": 10461,
"s": 10072,
"text": "Gensim also provides a Hierarchical Dirichlet Process (HDP) class [5]. HDP is similar to LDA, except it seeks to learn the correct number of topics from the data; that is, you don’t need to provide a fixed number of topics. I figured I would run HDP on my 100,000 reviews a few times and see the number of topics it was learning. In my case this was always 20 topics, so I went with that."
},
{
"code": null,
"e": 10720,
"s": 10461,
"text": "To get an intuitive feel for HDP: I found a number of sources online that said it’s most similar to a Chinese Restaurant Process. This is explained brilliantly by Edwin Chen here [6], and beautifully visualized in [7] here. Here’s the visualization from [7]:"
},
{
"code": null,
"e": 11235,
"s": 10720,
"text": "In this example, we need to assign 8 to a topic. There’s a 3/8 probability 8 will land in topic C1, a 4/8 probability 8 will land in topic C2, and a 1/8 probability a new topic C3 will be created. In this way a number of topics is discovered. So the bigger a cluster is, the more likely it is for someone to join that cluster. I felt this was just as reasonable as any other method to choose a fixed topic number for LDA. If anyone with a heavier Bayesian Inference background has thoughts on this please weigh in!"
},
{
"code": null,
"e": 11342,
"s": 11235,
"text": "UPDATE [4/13/2020] — Eduardo Coronado has kindly provided some more precise info on HDP, via the comments:"
},
{
"code": null,
"e": 11717,
"s": 11342,
"text": "“It is true that HDPs non-parametric property allow us to learn the topics from the data however Dirichlet Process mixtures do that already. The main advantage of HDPs is they allowing distinct corpora (groups) to share statistical strength when modeling — in this case share a common set of potentially infinite topics. So it is an extension of Dirichlet Process mixtures.”"
},
{
"code": null,
"e": 11757,
"s": 11717,
"text": "Here’s the code to run LDA with Gensim:"
},
{
"code": null,
"e": 12300,
"s": 11757,
"text": "import gensimwith warnings.catch_warnings(): warnings.simplefilter('ignore') lda_train = gensim.models.ldamulticore.LdaMulticore( corpus=train_corpus, num_topics=20, id2word=train_id2word, chunksize=100, workers=7, # Num. Processing Cores - 1 passes=50, eval_every = 1, per_word_topics=True) lda_train.save('lda_train.model')"
},
{
"code": null,
"e": 12513,
"s": 12300,
"text": "By turning on the eval_every flag we’re able to process the corpus in chunks: in my case chunks of 100 documents worked fairly well for convergence. The number of passes is separate passes over the entire corpus."
},
{
"code": null,
"e": 12587,
"s": 12513,
"text": "Once that’s done, you can view the words making up each topic as follows:"
},
{
"code": null,
"e": 12633,
"s": 12587,
"text": "lda_train.print_topics(20, num_words=15)[:10]"
},
{
"code": null,
"e": 12710,
"s": 12633,
"text": "With that code you’ll see 10 of the 20 topics and the 15 top words for each."
},
{
"code": null,
"e": 12994,
"s": 12710,
"text": "Now comes the interesting bit. We’re going to use the LDA model to grab the distribution of these 20 topics for every review. This 20-vector will be our feature vector for supervised classification, with the supervised learning goal being to determine positive or negative sentiment."
},
{
"code": null,
"e": 13321,
"s": 12994,
"text": "Note that I think this approach for supervised classification using topic model vectors is not very common. When I did it I wasn’t aware of any example online of people trying this, though later on when I was done I discovered this paper where it was done in 2008 [8]. Please let me know if there are other examples out there!"
},
{
"code": null,
"e": 13567,
"s": 13321,
"text": "The ultimate goal is not only to see how this performs in a train/test CV split of the current data, but whether the topics have hit on something fundamental that translates to unseen test data in the future (in my case, data from a year later)."
},
{
"code": null,
"e": 13631,
"s": 13567,
"text": "Here’s what I did to grab the feature vectors for every review:"
},
{
"code": null,
"e": 14006,
"s": 13631,
"text": "train_vecs = []for i in range(len(rev_train)): top_topics = ( lda_train.get_document_topics(train_corpus[i], minimum_probability=0.0) ) topic_vec = [top_topics[i][1] for i in range(20)] topic_vec.extend([rev_train.iloc[i].real_counts]) topic_vec.extend([len(rev_train.iloc[i].text)]) train_vecs.append(topic_vec)"
},
{
"code": null,
"e": 14220,
"s": 14006,
"text": "The key bit is using minimum_probability=0.0 in line 3. This ensures that we’ll capture the instances where a review is presented with 0% in some topics, and the representation for each review will add up to 100%."
},
{
"code": null,
"e": 14276,
"s": 14220,
"text": "Lines 5 and 6 are two hand-engineered features I added."
},
{
"code": null,
"e": 14366,
"s": 14276,
"text": "Thus a single observation for a review for supervised classification now looks like this:"
},
{
"code": null,
"e": 14453,
"s": 14366,
"text": "The first 20 items represent the distribution for the 20 found topics for each review."
},
{
"code": null,
"e": 14608,
"s": 14453,
"text": "We’re now ready to train! Here I’m using 100,000 2016 restaurant reviews and their topic-model distribution feature vector + two hand-engineered features:"
},
{
"code": null,
"e": 16219,
"s": 14608,
"text": "X = np.array(train_vecs)y = np.array(rev_train.target)kf = KFold(5, shuffle=True, random_state=42)cv_lr_f1, cv_lrsgd_f1, cv_svcsgd_f1, = [], [], []for train_ind, val_ind in kf.split(X, y): # Assign CV IDX X_train, y_train = X[train_ind], y[train_ind] X_val, y_val = X[val_ind], y[val_ind] # Scale Data scaler = StandardScaler() X_train_scale = scaler.fit_transform(X_train) X_val_scale = scaler.transform(X_val) # Logisitic Regression lr = LogisticRegression( class_weight= 'balanced', solver='newton-cg', fit_intercept=True ).fit(X_train_scale, y_train) y_pred = lr.predict(X_val_scale) cv_lr_f1.append(f1_score(y_val, y_pred, average='binary')) # Logistic Regression SGD sgd = linear_model.SGDClassifier( max_iter=1000, tol=1e-3, loss='log', class_weight='balanced' ).fit(X_train_scale, y_train) y_pred = sgd.predict(X_val_scale) cv_lrsgd_f1.append(f1_score(y_val, y_pred, average='binary')) # SGD Modified Huber sgd_huber = linear_model.SGDClassifier( max_iter=1000, tol=1e-3, alpha=20, loss='modified_huber', class_weight='balanced' ).fit(X_train_scale, y_train) y_pred = sgd_huber.predict(X_val_scale) cv_svcsgd_f1.append(f1_score(y_val, y_pred, average='binary'))print(f'Logistic Regression Val f1: {np.mean(cv_lr_f1):.3f} +- {np.std(cv_lr_f1):.3f}')print(f'Logisitic Regression SGD Val f1: {np.mean(cv_lrsgd_f1):.3f} +- {np.std(cv_lrsgd_f1):.3f}')print(f'SVM Huber Val f1: {np.mean(cv_svcsgd_f1):.3f} +- {np.std(cv_svcsgd_f1):.3f}')"
},
{
"code": null,
"e": 16243,
"s": 16219,
"text": "A couple notes on this:"
},
{
"code": null,
"e": 17127,
"s": 16243,
"text": "I landed on a comparison between standard Logistic Regression, Stochastic Gradient Descent with Log Loss, and Stochastic Gradient Descent with Modified Huber loss.I’m running a 5-fold CV, so that in each run 1/5 of the reviews are held-out as validation data, and the other 4/5 are training data. This is repeated for every fold, and the f1 score results are averaged at the end.My classes are imbalanced. In particular, there are a disproportionate amount of 4 and 5 star reviews in the Yelp review dataset. The class_weight='balanced' line in the models approximates undersampling to correct for this. See [9] for a justification of this choice.I’ve also restricted the analysis to just restaurants that had above the 25th percentile in total reviews in the dataset. This was more of a restriction to speed things up since the initial dataset was something like 4 million+ reviews."
},
{
"code": null,
"e": 17291,
"s": 17127,
"text": "I landed on a comparison between standard Logistic Regression, Stochastic Gradient Descent with Log Loss, and Stochastic Gradient Descent with Modified Huber loss."
},
{
"code": null,
"e": 17508,
"s": 17291,
"text": "I’m running a 5-fold CV, so that in each run 1/5 of the reviews are held-out as validation data, and the other 4/5 are training data. This is repeated for every fold, and the f1 score results are averaged at the end."
},
{
"code": null,
"e": 17777,
"s": 17508,
"text": "My classes are imbalanced. In particular, there are a disproportionate amount of 4 and 5 star reviews in the Yelp review dataset. The class_weight='balanced' line in the models approximates undersampling to correct for this. See [9] for a justification of this choice."
},
{
"code": null,
"e": 18014,
"s": 17777,
"text": "I’ve also restricted the analysis to just restaurants that had above the 25th percentile in total reviews in the dataset. This was more of a restriction to speed things up since the initial dataset was something like 4 million+ reviews."
},
{
"code": null,
"e": 18045,
"s": 18014,
"text": "Here are the f1-score results:"
},
{
"code": null,
"e": 18451,
"s": 18045,
"text": "I’ll first walk-through the lower .53 and .62 f1-scores using Logisitic Regression. When I initially started training I tried to predict the individual review ratings: 1,2,3,4 or 5 stars. As you can see this was not successful. I was a bit discouraged with the initial .53 score, so went back to examine my initial EDA charts to see if I could notice anything in the data. I had run this chart earlier on:"
},
{
"code": null,
"e": 18771,
"s": 18451,
"text": "This shows the word count IQR range by rating. Since the main IQR range was pretty compact, I decided to try re-running the LDA pre-processing and model restricted to just (roughly) the IQR range. Making this change increased my Logistic Regression score on f1 to .62 for 1,2,3,4,5 star classification. Still not great."
},
{
"code": null,
"e": 19028,
"s": 18771,
"text": "At this point I decided to see what would happen if I got rid of the 3-stars, and grouped the 1,2 stars as ‘bad’ and 4,5 stars as ‘good’ sentiment scores. As you’ll see in the graph above, this worked wonder! Now Logistic Regression yieled a .869 f1-score."
},
{
"code": null,
"e": 19250,
"s": 19028,
"text": "When I was running these, I noticed a ‘modified huber’ loss option in SKLearn’s Stochastic Gradient Descent implementation [10]. In this case, the penalty for being wrong is much worse than either Hinge (SVC) or Log Loss:"
},
{
"code": null,
"e": 19633,
"s": 19250,
"text": "I’m still grappling with why this worked so well, but my initial thought is that these punishing penalties caused SGD (remember, 1 by 1 weight updates) to learn quickly. Regularization helped immensely here as well. The alpha in line 42 in the code above is a regularization parameter (think like in Ridge or Lasso regularization), and this helped in getting my f1-score up to .936."
},
{
"code": null,
"e": 19758,
"s": 19633,
"text": "At this point I was pretty thrilled by these results, but wanted to further see what would happen on completely unseen data."
},
{
"code": null,
"e": 19772,
"s": 19758,
"text": "Specifically:"
},
{
"code": null,
"e": 19963,
"s": 19772,
"text": "Take the LDA Model from the 2016 reviews, and grab feature vectors on test data. It’s important to note that the same 2016 model can be used to do this!Re-run the models on the test-vectors."
},
{
"code": null,
"e": 20116,
"s": 19963,
"text": "Take the LDA Model from the 2016 reviews, and grab feature vectors on test data. It’s important to note that the same 2016 model can be used to do this!"
},
{
"code": null,
"e": 20155,
"s": 20116,
"text": "Re-run the models on the test-vectors."
},
{
"code": null,
"e": 20285,
"s": 20155,
"text": "All that’s required is making bigrams for the test corpus, then throwing this into the test-vector extraction approach as before:"
},
{
"code": null,
"e": 20986,
"s": 20285,
"text": "def get_bigram(df): df['text'] = strip_newline(df.text) words = list(sent_to_words(df.text)) words = remove_stopwords(words) bigram = bigrams(words) bigram = [bigram[review] for review in words] return bigram bigram_test = get_bigram(rev_test)test_corpus = [train_id2word.doc2bow(text) for text in bigram_test]test_vecs = []for i in range(len(rev_test)): top_topics = ( lda_train.get_document_topics(test_corpus[i], minimum_probability=0.0) topic_vec = [top_topics[i][1] for i in range(20)] topic_vec.extend([rev_test.iloc[i].real_counts]) topic_vec.extend([len(rev_test.iloc[i].text)]) test_vecs.append(topic_vec)"
},
{
"code": null,
"e": 21008,
"s": 20986,
"text": "Finally, the results:"
},
{
"code": null,
"e": 21053,
"s": 21008,
"text": "Somewhat shockingly to me, this generalizes!"
},
{
"code": null,
"e": 21309,
"s": 21053,
"text": "I was thrilled with this result, as I believe this approach could work generally for any company trying to train a classifier in this way. I also did a hypothesis test at the end using mlxtend [11] and the final result is indeed statistically significant."
},
{
"code": null,
"e": 21387,
"s": 21309,
"text": "I intend on extending this a bit in the future, and I’ll leave you with that:"
},
{
"code": null,
"e": 21471,
"s": 21387,
"text": "I’ve also hosted all the code for this and the trained LDA model on my GitHub here."
},
{
"code": null,
"e": 21491,
"s": 21471,
"text": "Thanks for reading!"
}
] |
AI, Cluster Analysis of Categorical Data (Part II) | by Michelangiolo Mazzeschi | Towards Data Science
|
Entire Procedure
Full code available at my repository. The notebook is called: CRL_Clustering.
Downloading match datasets with APIPre-processing: personalized sorting of every rowPre-processing: label encoding of the entire datasetPre-processing: one_hot encoding of the entire datasetPerform cluster analysisTrain K-Node algorithmTuning number of clusters to get an accurate resultEstimate the top meta-decks
Downloading match datasets with API
Pre-processing: personalized sorting of every row
Pre-processing: label encoding of the entire dataset
Pre-processing: one_hot encoding of the entire dataset
Perform cluster analysis
Train K-Node algorithm
Tuning number of clusters to get an accurate result
Estimate the top meta-decks
So far, Part I covered up to step 3: label encoding the entire dataset. In this final part of the tutorial, I will be covering the next five steps.
In step 3 we have labeled each element in the dataset, obtaining the following result:
To feed our dataset into the AI we will need to use one_hot encoding. Only in this way, the model will be able to process categorical data. All our columns are interchangeable: this means that we will need a single giant chunk of one_hot variables.
If we had to apply one_hot encoding to every single column we would be obtaining a one_hot chunk per column: that is now what we want. With 8 existing features, the data will be considered independent between columns, and the labels will be applied to individual columns, not a single dataset:
As you can see from the picture above, this is what would happen if we had to apply one_hot encoding to each column. In the example above, b is in both columns, but it will be decomposed in 1_b and 2_b, and b will be split into two separate variables. What that would mean is that a card, ex. Giant, in column 1 and Giant in column 2 will be completely different. Because this is not the case (the order of the decks should have no impact on the way meta-decks are chosen), we have to find a way to avoid the separation of the same variables in the dataset when they are situated in different columns.
print(max(one_row_labeled+1), len(X_labeled))95 664
Our dataset has a total of 94 cards used among players in any possible deck. This means that for every row there have to be 94 columns, each one representing a dummy variable.
# one_hot of multiple columns at the same time#create an empty dataset of equal lenght of max. label (94), but equal width of our X (664)m = [[0 for x in range(max(one_row_labeled)+1)] for x in range(len(X_labeled))]
I have first created this empty dataset as a multidimensional array:
I will now iterate through each row of X. Each row will contain 8 different numbers, I will find the corresponding dummy variable row and set it to 1.
#turn each corresponding label to 1for row in range(len(X_labeled.values)):for num in range(len(X_labeled.values[1])):m[row][X_labeled.values[row][num]] = 1m = pd.DataFrame(m)m
After having added the 1 in the right spots, I will convert the list into a DataFrame. This is what we end up with:
Now we can feed it to the model.
Now that we prepared our data, we will need to identify the optimal number of clusters:
#graph the number of clustersfrom sklearn.cluster import KMeansimport matplotlib.pyplot as pltwcss = []for i in range(1, 100):km = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 20, random_state = 0)km.fit(m)wcss.append(km.inertia_)plt.plot(range(1, 100), wcss)plt.title('The Elbow Method')plt.xlabel('No. of Clusters')plt.ylabel('wcss')plt.show()
We are trying to assess the number of optimal clusters through the elbow method. Usually, we would look for the spot where the line in the graph bends the most. Unfortunately, we can immediately see that there are no clear signs of a defined number of clusters (maybe around 20 clusters there is a possible bend). Especially in K-Mode, it is very hard to estimate the best number of clusters due to the categorical nature of the features. We will need to find the optimal number of clusters by using several iterations and comparing the results.
!pip install kmodes
***Because I am using Google Colab I will install the package kmodes using the line above, however, depending on if you are running your algorithms on your local machine or remotely, it may vary.
Let us now run an experiment using K-Mode on our dataset. I will need to indicate the number of clusters to group our dataset. Essentially, the output is an array of 664 numbers. Each number maps one row with its corresponding cluster.
#mapping each row to its correponding clusterfrom kmodes.kmodes import KModestest=KModes(n_clusters=20, init='Cao') #Huang in another possibilcluster=test.fit_predict(m, categorical=list(m.columns))clusterarray([11, 0, 11, 4, 5, 3, 3, 11, 11, 9, 11, 11, 16, 5, 5, 0, 6, 1, 11, 3, 15, 0, 8, 1, 8, 0, 15, 5, 7, 15, 8, 17, 1, 15, 5, 2, 19, 13, 1, 9, 7, 16, 7, 1, 16, 3, 5, 1, 8, 7, 6, 16, 18, 7, 0, 3, 3, 3, 13, 19, 15, 11, 8, 4, 14, 4, 2, 14, 5, 7, 6, 1, 8, 1, 3, 8, 4, 3, 5, 19, 2, 1, 5, 0, 1, 6, 14, 8, 3, 4, 7, 4, 1, 14, 1, 5, 11, 18, 5, 1, 0, 2, 12, 3, 8, 9, 2, 4, 7, 7, 16, 11, 4, 11, 11, 1, 16, 6, 0, 16, 12, 0, 3, 7, 18, 1, 12, 0, 16, 18, 16, 3, 4, 7, 1, 1, 1, 2, 3, 19, 5, 11, 4, 16, 4, 0, 3, 12, 0, 12, 0, 12, 5, 2, 14, 11, 12, 15, 1, 11, 7, 2, 12, 0, 3, 3, 12, 7, 7, 18, 1, 16, 7, 17, 1, 12, 11, 14, 15, 3, 5, 0, 8, 14, 2, 2, 0, 4, 7, 16, 8, 11, 0, 6, 1, 5, 19, 7, 7, 16, 0, 2, 11, 4, 7, 5, 1, 8, 14, 0, 0, 19, 11, 7, 15, 5, 9, 2, 11, 7, 19, 14, 3, 11, 11, 1, 9, 5, 12, 12, 7, 12, 14, 14, 11, 0, 8, 3, 4, 11, 4, 5, 8, 15, 15, 14, 7, 4, 3, 6, 3, 5, 7, 4, 6, 15, 5, 13, 11, 4, 16, 7, 0, 14, 16, 7, 3, 9, 15, 0, 7, 0, 1, 8, 15, 5, 11, 3, 6, 4, 12, 15, 1, 2, 7, 1, 6, 1, 3, 8, 1, 0, 17, 5, 5, 14, 11, 3, 4, 2, 3, 7, 7, 11, 3, 0, 4, 1, 3, 7, 7, 4, 8, 3, 0, 3, 3, 9, 12, 3, 7, 7, 8, 12, 2, 3, 2, 19, 5, 7, 2, 14, 7, 2, 4, 1, 5, 19, 3, 2, 13, 5, 5, 3, 19, 4, 2, 15, 19, 1, 0, 12, 13, 8, 13, 0, 17, 7, 14, 3, 4, 0, 14, 12, 0, 1, 8, 12, 4, 3, 17, 15, 7, 4, 3, 14, 0, 12, 0, 9, 1, 14, 4, 12, 7, 4, 3, 2, 3, 15, 16, 2, 4, 0, 2, 15, 12, 7, 15, 2, 1, 1, 4, 0, 19, 6, 5, 11, 12, 8, 3, 16, 2, 3, 19, 0, 0, 1, 3, 17, 11, 10, 2, 15, 2, 0, 3, 7, 4, 17, 5, 5, 1, 8, 6, 6, 12, 5, 13, 19, 2, 6, 3, 3, 4, 3, 12, 17, 5, 15, 0, 19, 6, 0, 3, 2, 3, 0, 12, 11, 2, 14, 1, 1, 0, 7, 7, 12, 8, 4, 1, 12, 14, 17, 17, 8, 0, 2, 3, 2, 0, 16, 2, 6, 2, 0, 6, 3, 1, 0, 8, 3, 7, 11, 15, 0, 11, 11, 7, 2, 6, 5, 11, 4, 3, 5, 17, 15, 2, 0, 11, 11, 4, 3, 16, 19, 8, 15, 14, 0, 5, 13, 2, 0, 2, 14, 19, 8, 0, 1, 1, 14, 6, 15, 19, 19, 2, 0, 1, 1, 11, 5, 3, 3, 6, 8, 8, 1, 0, 19, 7, 2, 8, 4, 0, 12, 12, 12, 14, 4, 2, 16, 9, 0, 0, 4, 0, 2, 8, 4, 0, 2, 15, 4, 13, 15, 3, 0, 0, 4, 5, 6, 9, 0, 4, 14, 19, 1, 15, 15, 14, 2, 17, 4, 0, 15, 2, 12, 8, 14, 2, 1, 15, 2, 2, 2, 11, 12, 6, 0, 0, 12, 3, 17, 14, 11, 4, 0, 2, 4, 17, 0, 3, 5, 16, 0, 12, 0, 17, 17, 6, 4, 0, 16, 16, 0, 14, 3, 12, 11, 19, 6, 8, 2, 0, 4, 0, 7, 17, 1, 0, 15, 16, 13, 1, 7, 16, 0, 14, 6, 0, 0, 16, 5], dtype=uint16)
Now, how do we isolate the clusters and understand what characteristics they need to have?
test.cluster_centroids_array([[0, 0, 0, ..., 0, 0, 0], [0, 1, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 1], [0, 0, 0, ..., 0, 0, 1]])
These 20 lists of one_hot numbers describe the features of every single cluster. Each one is composed of 94 elements, some of them are 1, the majority is 0. If for every single list, we will convert these 94 binary values to numbers, then the numbers to card names, we will obtain the 20 meta-decks.
For now, the results are incomprehensible to us. We need to translate them into a language we can comprehend. The algorithm below takes the output of a K-Mode algorithm and translates it into its original strings:
#convert one_hot numbers to final decksdef archetypes(knode_list): archetypes_list = list()#for each 1 inside the one_hot cluster form return its number #not all clusters have the same lenght #store all number is arrays cc = list() for n_centroids in range(len(km.cluster_centroids_)): for k in range(len(km.cluster_centroids_[n_centroids])): if km.cluster_centroids_[n_centroids][k] == 1: cc.append(k) len(cc)#determines number of chunks per cluster n_chunks = list() for am in range(len(km.cluster_centroids_)): n_chunks.append((list(km.cluster_centroids_[am]).count(1))) n_chunks#creates the meta-decks from itertools import islice it = iter(cc) sliced =[list(islice(it, 0, i)) for i in n_chunks] slicedsliced_list = list() #convertion numbers to card names for o in sliced: sliced_list.append(order_row(list(le.inverse_transform(o))))#we only conserve the win conditions card_dictionary = dict(zip(cards_classifier[0], cards_classifier[1])) card_dictionary#an absurd way of making a copy of our dataset, .copy() does not work list_tot_classification = [x[:] for x in sliced_list] #un modo assurdo per fare copia, altrimenti non funzionafor o1 in range(len(list_tot_classification)): for o2 in range(len(list_tot_classification[o1])): a = card_dictionary.get(list_tot_classification[o1][o2]) list_tot_classification[o1][o2] = aonly_win_conditions = list() #only conserve lists with win conditions for o3 in range(len(list_tot_classification)): if 'Win Condition' in list_tot_classification[o3]: only_win_conditions.append(sliced_list[o3])#we store all the lists with a lenght of 8: full decks for _ in sorted(only_win_conditions): if len(_) == 8: archetypes_list.append(_)return archetypes_list
Now, let us try different configurations of the algorithm we have just written and compare the results. I will run a total of 60 clusters, storing both results and the number of meta-decks for every iteration:
import numpy as npfrom kmodes.kmodes import KModesarchetypes_len = list()for clus in range (8, 60): ###FUNZIONA IN UN FOR CYCLE, MA NON IN UNA FUNZIONE km = KModes(n_clusters=clus, init='Cao', n_init=100, verbose=0) clusters = km.fit_predict(m)#one_hot results to archetypes sorted by win condition archetypes_list = archetypes(km.cluster_centroids_) archetypes_len.append(len(archetypes_list)) for _ in archetypes_list: print(clus, _)#25 is the optimal number of meta-decks
As we can see from the last image, the higher the number of clusters, the higher the number of similar meta-decks. Essentially, at one point also the deck variations are included in the calculation.
I have now stored the number of clusters in archetypes_len. I will create a list that contains the range of clusters, so we can graph the relationship between the number of clusters and the number of meta-decks.
import seaborn as snsarchetypes_iteration = [x for x in range(8, 60)]archetypes_iterationsns.set(rc={‘figure.figsize’:(11.7,8.27)})sns.scatterplot(archetypes_iteration, archetypes_len)
How does this translate into our hierarchy of meta-decks?
If the number of clusters is too small, we end up with only a few meta-decks. They will be correct, probably the ones at the top of the list, but they only represent one small batch among the pool of meta-decks.
If the number of clusters is too big, not only we will list the top decks, but also all their variations, ending up with a list of decks that blurs the notion of meta-decks.
Only with the right amount, we can have a notion of the most used meta-decks in the current Season.
Finally, after looking at the data, I have selected a number of clusters that show the top-meta decks with minimum variations. We can conclude that these are the meta-decks for Season 11, the current Clash Royale season:
#questo funzionan_clusters = 25km = KModes(n_clusters=n_clusters, init='Cao', n_init=100, verbose=0)clusters = km.fit_predict(m)#one_hot results to archetypes sorted by win conditionarchetypes_list = archetypes(km.cluster_centroids_)for _ in archetypes_list: print(_)
|
[
{
"code": null,
"e": 189,
"s": 172,
"text": "Entire Procedure"
},
{
"code": null,
"e": 267,
"s": 189,
"text": "Full code available at my repository. The notebook is called: CRL_Clustering."
},
{
"code": null,
"e": 582,
"s": 267,
"text": "Downloading match datasets with APIPre-processing: personalized sorting of every rowPre-processing: label encoding of the entire datasetPre-processing: one_hot encoding of the entire datasetPerform cluster analysisTrain K-Node algorithmTuning number of clusters to get an accurate resultEstimate the top meta-decks"
},
{
"code": null,
"e": 618,
"s": 582,
"text": "Downloading match datasets with API"
},
{
"code": null,
"e": 668,
"s": 618,
"text": "Pre-processing: personalized sorting of every row"
},
{
"code": null,
"e": 721,
"s": 668,
"text": "Pre-processing: label encoding of the entire dataset"
},
{
"code": null,
"e": 776,
"s": 721,
"text": "Pre-processing: one_hot encoding of the entire dataset"
},
{
"code": null,
"e": 801,
"s": 776,
"text": "Perform cluster analysis"
},
{
"code": null,
"e": 824,
"s": 801,
"text": "Train K-Node algorithm"
},
{
"code": null,
"e": 876,
"s": 824,
"text": "Tuning number of clusters to get an accurate result"
},
{
"code": null,
"e": 904,
"s": 876,
"text": "Estimate the top meta-decks"
},
{
"code": null,
"e": 1052,
"s": 904,
"text": "So far, Part I covered up to step 3: label encoding the entire dataset. In this final part of the tutorial, I will be covering the next five steps."
},
{
"code": null,
"e": 1139,
"s": 1052,
"text": "In step 3 we have labeled each element in the dataset, obtaining the following result:"
},
{
"code": null,
"e": 1388,
"s": 1139,
"text": "To feed our dataset into the AI we will need to use one_hot encoding. Only in this way, the model will be able to process categorical data. All our columns are interchangeable: this means that we will need a single giant chunk of one_hot variables."
},
{
"code": null,
"e": 1682,
"s": 1388,
"text": "If we had to apply one_hot encoding to every single column we would be obtaining a one_hot chunk per column: that is now what we want. With 8 existing features, the data will be considered independent between columns, and the labels will be applied to individual columns, not a single dataset:"
},
{
"code": null,
"e": 2284,
"s": 1682,
"text": "As you can see from the picture above, this is what would happen if we had to apply one_hot encoding to each column. In the example above, b is in both columns, but it will be decomposed in 1_b and 2_b, and b will be split into two separate variables. What that would mean is that a card, ex. Giant, in column 1 and Giant in column 2 will be completely different. Because this is not the case (the order of the decks should have no impact on the way meta-decks are chosen), we have to find a way to avoid the separation of the same variables in the dataset when they are situated in different columns."
},
{
"code": null,
"e": 2336,
"s": 2284,
"text": "print(max(one_row_labeled+1), len(X_labeled))95 664"
},
{
"code": null,
"e": 2512,
"s": 2336,
"text": "Our dataset has a total of 94 cards used among players in any possible deck. This means that for every row there have to be 94 columns, each one representing a dummy variable."
},
{
"code": null,
"e": 2730,
"s": 2512,
"text": "# one_hot of multiple columns at the same time#create an empty dataset of equal lenght of max. label (94), but equal width of our X (664)m = [[0 for x in range(max(one_row_labeled)+1)] for x in range(len(X_labeled))]"
},
{
"code": null,
"e": 2799,
"s": 2730,
"text": "I have first created this empty dataset as a multidimensional array:"
},
{
"code": null,
"e": 2950,
"s": 2799,
"text": "I will now iterate through each row of X. Each row will contain 8 different numbers, I will find the corresponding dummy variable row and set it to 1."
},
{
"code": null,
"e": 3127,
"s": 2950,
"text": "#turn each corresponding label to 1for row in range(len(X_labeled.values)):for num in range(len(X_labeled.values[1])):m[row][X_labeled.values[row][num]] = 1m = pd.DataFrame(m)m"
},
{
"code": null,
"e": 3243,
"s": 3127,
"text": "After having added the 1 in the right spots, I will convert the list into a DataFrame. This is what we end up with:"
},
{
"code": null,
"e": 3276,
"s": 3243,
"text": "Now we can feed it to the model."
},
{
"code": null,
"e": 3364,
"s": 3276,
"text": "Now that we prepared our data, we will need to identify the optimal number of clusters:"
},
{
"code": null,
"e": 3733,
"s": 3364,
"text": "#graph the number of clustersfrom sklearn.cluster import KMeansimport matplotlib.pyplot as pltwcss = []for i in range(1, 100):km = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 20, random_state = 0)km.fit(m)wcss.append(km.inertia_)plt.plot(range(1, 100), wcss)plt.title('The Elbow Method')plt.xlabel('No. of Clusters')plt.ylabel('wcss')plt.show()"
},
{
"code": null,
"e": 4279,
"s": 3733,
"text": "We are trying to assess the number of optimal clusters through the elbow method. Usually, we would look for the spot where the line in the graph bends the most. Unfortunately, we can immediately see that there are no clear signs of a defined number of clusters (maybe around 20 clusters there is a possible bend). Especially in K-Mode, it is very hard to estimate the best number of clusters due to the categorical nature of the features. We will need to find the optimal number of clusters by using several iterations and comparing the results."
},
{
"code": null,
"e": 4299,
"s": 4279,
"text": "!pip install kmodes"
},
{
"code": null,
"e": 4495,
"s": 4299,
"text": "***Because I am using Google Colab I will install the package kmodes using the line above, however, depending on if you are running your algorithms on your local machine or remotely, it may vary."
},
{
"code": null,
"e": 4731,
"s": 4495,
"text": "Let us now run an experiment using K-Mode on our dataset. I will need to indicate the number of clusters to group our dataset. Essentially, the output is an array of 664 numbers. Each number maps one row with its corresponding cluster."
},
{
"code": null,
"e": 7887,
"s": 4731,
"text": "#mapping each row to its correponding clusterfrom kmodes.kmodes import KModestest=KModes(n_clusters=20, init='Cao') #Huang in another possibilcluster=test.fit_predict(m, categorical=list(m.columns))clusterarray([11, 0, 11, 4, 5, 3, 3, 11, 11, 9, 11, 11, 16, 5, 5, 0, 6, 1, 11, 3, 15, 0, 8, 1, 8, 0, 15, 5, 7, 15, 8, 17, 1, 15, 5, 2, 19, 13, 1, 9, 7, 16, 7, 1, 16, 3, 5, 1, 8, 7, 6, 16, 18, 7, 0, 3, 3, 3, 13, 19, 15, 11, 8, 4, 14, 4, 2, 14, 5, 7, 6, 1, 8, 1, 3, 8, 4, 3, 5, 19, 2, 1, 5, 0, 1, 6, 14, 8, 3, 4, 7, 4, 1, 14, 1, 5, 11, 18, 5, 1, 0, 2, 12, 3, 8, 9, 2, 4, 7, 7, 16, 11, 4, 11, 11, 1, 16, 6, 0, 16, 12, 0, 3, 7, 18, 1, 12, 0, 16, 18, 16, 3, 4, 7, 1, 1, 1, 2, 3, 19, 5, 11, 4, 16, 4, 0, 3, 12, 0, 12, 0, 12, 5, 2, 14, 11, 12, 15, 1, 11, 7, 2, 12, 0, 3, 3, 12, 7, 7, 18, 1, 16, 7, 17, 1, 12, 11, 14, 15, 3, 5, 0, 8, 14, 2, 2, 0, 4, 7, 16, 8, 11, 0, 6, 1, 5, 19, 7, 7, 16, 0, 2, 11, 4, 7, 5, 1, 8, 14, 0, 0, 19, 11, 7, 15, 5, 9, 2, 11, 7, 19, 14, 3, 11, 11, 1, 9, 5, 12, 12, 7, 12, 14, 14, 11, 0, 8, 3, 4, 11, 4, 5, 8, 15, 15, 14, 7, 4, 3, 6, 3, 5, 7, 4, 6, 15, 5, 13, 11, 4, 16, 7, 0, 14, 16, 7, 3, 9, 15, 0, 7, 0, 1, 8, 15, 5, 11, 3, 6, 4, 12, 15, 1, 2, 7, 1, 6, 1, 3, 8, 1, 0, 17, 5, 5, 14, 11, 3, 4, 2, 3, 7, 7, 11, 3, 0, 4, 1, 3, 7, 7, 4, 8, 3, 0, 3, 3, 9, 12, 3, 7, 7, 8, 12, 2, 3, 2, 19, 5, 7, 2, 14, 7, 2, 4, 1, 5, 19, 3, 2, 13, 5, 5, 3, 19, 4, 2, 15, 19, 1, 0, 12, 13, 8, 13, 0, 17, 7, 14, 3, 4, 0, 14, 12, 0, 1, 8, 12, 4, 3, 17, 15, 7, 4, 3, 14, 0, 12, 0, 9, 1, 14, 4, 12, 7, 4, 3, 2, 3, 15, 16, 2, 4, 0, 2, 15, 12, 7, 15, 2, 1, 1, 4, 0, 19, 6, 5, 11, 12, 8, 3, 16, 2, 3, 19, 0, 0, 1, 3, 17, 11, 10, 2, 15, 2, 0, 3, 7, 4, 17, 5, 5, 1, 8, 6, 6, 12, 5, 13, 19, 2, 6, 3, 3, 4, 3, 12, 17, 5, 15, 0, 19, 6, 0, 3, 2, 3, 0, 12, 11, 2, 14, 1, 1, 0, 7, 7, 12, 8, 4, 1, 12, 14, 17, 17, 8, 0, 2, 3, 2, 0, 16, 2, 6, 2, 0, 6, 3, 1, 0, 8, 3, 7, 11, 15, 0, 11, 11, 7, 2, 6, 5, 11, 4, 3, 5, 17, 15, 2, 0, 11, 11, 4, 3, 16, 19, 8, 15, 14, 0, 5, 13, 2, 0, 2, 14, 19, 8, 0, 1, 1, 14, 6, 15, 19, 19, 2, 0, 1, 1, 11, 5, 3, 3, 6, 8, 8, 1, 0, 19, 7, 2, 8, 4, 0, 12, 12, 12, 14, 4, 2, 16, 9, 0, 0, 4, 0, 2, 8, 4, 0, 2, 15, 4, 13, 15, 3, 0, 0, 4, 5, 6, 9, 0, 4, 14, 19, 1, 15, 15, 14, 2, 17, 4, 0, 15, 2, 12, 8, 14, 2, 1, 15, 2, 2, 2, 11, 12, 6, 0, 0, 12, 3, 17, 14, 11, 4, 0, 2, 4, 17, 0, 3, 5, 16, 0, 12, 0, 17, 17, 6, 4, 0, 16, 16, 0, 14, 3, 12, 11, 19, 6, 8, 2, 0, 4, 0, 7, 17, 1, 0, 15, 16, 13, 1, 7, 16, 0, 14, 6, 0, 0, 16, 5], dtype=uint16)"
},
{
"code": null,
"e": 7978,
"s": 7887,
"text": "Now, how do we isolate the clusters and understand what characteristics they need to have?"
},
{
"code": null,
"e": 8164,
"s": 7978,
"text": "test.cluster_centroids_array([[0, 0, 0, ..., 0, 0, 0], [0, 1, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 1], [0, 0, 0, ..., 0, 0, 1]])"
},
{
"code": null,
"e": 8464,
"s": 8164,
"text": "These 20 lists of one_hot numbers describe the features of every single cluster. Each one is composed of 94 elements, some of them are 1, the majority is 0. If for every single list, we will convert these 94 binary values to numbers, then the numbers to card names, we will obtain the 20 meta-decks."
},
{
"code": null,
"e": 8678,
"s": 8464,
"text": "For now, the results are incomprehensible to us. We need to translate them into a language we can comprehend. The algorithm below takes the output of a K-Mode algorithm and translates it into its original strings:"
},
{
"code": null,
"e": 10448,
"s": 8678,
"text": "#convert one_hot numbers to final decksdef archetypes(knode_list): archetypes_list = list()#for each 1 inside the one_hot cluster form return its number #not all clusters have the same lenght #store all number is arrays cc = list() for n_centroids in range(len(km.cluster_centroids_)): for k in range(len(km.cluster_centroids_[n_centroids])): if km.cluster_centroids_[n_centroids][k] == 1: cc.append(k) len(cc)#determines number of chunks per cluster n_chunks = list() for am in range(len(km.cluster_centroids_)): n_chunks.append((list(km.cluster_centroids_[am]).count(1))) n_chunks#creates the meta-decks from itertools import islice it = iter(cc) sliced =[list(islice(it, 0, i)) for i in n_chunks] slicedsliced_list = list() #convertion numbers to card names for o in sliced: sliced_list.append(order_row(list(le.inverse_transform(o))))#we only conserve the win conditions card_dictionary = dict(zip(cards_classifier[0], cards_classifier[1])) card_dictionary#an absurd way of making a copy of our dataset, .copy() does not work list_tot_classification = [x[:] for x in sliced_list] #un modo assurdo per fare copia, altrimenti non funzionafor o1 in range(len(list_tot_classification)): for o2 in range(len(list_tot_classification[o1])): a = card_dictionary.get(list_tot_classification[o1][o2]) list_tot_classification[o1][o2] = aonly_win_conditions = list() #only conserve lists with win conditions for o3 in range(len(list_tot_classification)): if 'Win Condition' in list_tot_classification[o3]: only_win_conditions.append(sliced_list[o3])#we store all the lists with a lenght of 8: full decks for _ in sorted(only_win_conditions): if len(_) == 8: archetypes_list.append(_)return archetypes_list"
},
{
"code": null,
"e": 10658,
"s": 10448,
"text": "Now, let us try different configurations of the algorithm we have just written and compare the results. I will run a total of 60 clusters, storing both results and the number of meta-decks for every iteration:"
},
{
"code": null,
"e": 11141,
"s": 10658,
"text": "import numpy as npfrom kmodes.kmodes import KModesarchetypes_len = list()for clus in range (8, 60): ###FUNZIONA IN UN FOR CYCLE, MA NON IN UNA FUNZIONE km = KModes(n_clusters=clus, init='Cao', n_init=100, verbose=0) clusters = km.fit_predict(m)#one_hot results to archetypes sorted by win condition archetypes_list = archetypes(km.cluster_centroids_) archetypes_len.append(len(archetypes_list)) for _ in archetypes_list: print(clus, _)#25 is the optimal number of meta-decks"
},
{
"code": null,
"e": 11340,
"s": 11141,
"text": "As we can see from the last image, the higher the number of clusters, the higher the number of similar meta-decks. Essentially, at one point also the deck variations are included in the calculation."
},
{
"code": null,
"e": 11552,
"s": 11340,
"text": "I have now stored the number of clusters in archetypes_len. I will create a list that contains the range of clusters, so we can graph the relationship between the number of clusters and the number of meta-decks."
},
{
"code": null,
"e": 11737,
"s": 11552,
"text": "import seaborn as snsarchetypes_iteration = [x for x in range(8, 60)]archetypes_iterationsns.set(rc={‘figure.figsize’:(11.7,8.27)})sns.scatterplot(archetypes_iteration, archetypes_len)"
},
{
"code": null,
"e": 11795,
"s": 11737,
"text": "How does this translate into our hierarchy of meta-decks?"
},
{
"code": null,
"e": 12007,
"s": 11795,
"text": "If the number of clusters is too small, we end up with only a few meta-decks. They will be correct, probably the ones at the top of the list, but they only represent one small batch among the pool of meta-decks."
},
{
"code": null,
"e": 12181,
"s": 12007,
"text": "If the number of clusters is too big, not only we will list the top decks, but also all their variations, ending up with a list of decks that blurs the notion of meta-decks."
},
{
"code": null,
"e": 12281,
"s": 12181,
"text": "Only with the right amount, we can have a notion of the most used meta-decks in the current Season."
},
{
"code": null,
"e": 12502,
"s": 12281,
"text": "Finally, after looking at the data, I have selected a number of clusters that show the top-meta decks with minimum variations. We can conclude that these are the meta-decks for Season 11, the current Clash Royale season:"
}
] |
VBA - Ltrim
|
The Ltrim function removes the blank spaces from the left side of the string.
LTrim(String)
Add a button and add the following function.
Private Sub Constant_demo_Click()
Dim var as Variant
var = " Microsoft VBScript"
msgbox "After Ltrim : " & LTrim(var)
End Sub
When you execute the function, it produces the following output.
After Ltrim : Microsoft VBScript
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2013,
"s": 1935,
"text": "The Ltrim function removes the blank spaces from the left side of the string."
},
{
"code": null,
"e": 2028,
"s": 2013,
"text": "LTrim(String)\n"
},
{
"code": null,
"e": 2073,
"s": 2028,
"text": "Add a button and add the following function."
},
{
"code": null,
"e": 2226,
"s": 2073,
"text": "Private Sub Constant_demo_Click()\n Dim var as Variant\n var = \" Microsoft VBScript\"\n msgbox \"After Ltrim : \" & LTrim(var)\nEnd Sub"
},
{
"code": null,
"e": 2291,
"s": 2226,
"text": "When you execute the function, it produces the following output."
},
{
"code": null,
"e": 2325,
"s": 2291,
"text": "After Ltrim : Microsoft VBScript\n"
},
{
"code": null,
"e": 2359,
"s": 2325,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2374,
"s": 2359,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2407,
"s": 2374,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2422,
"s": 2407,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2457,
"s": 2422,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2475,
"s": 2457,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2508,
"s": 2475,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2526,
"s": 2508,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2559,
"s": 2526,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2574,
"s": 2559,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2610,
"s": 2574,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 2638,
"s": 2610,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 2645,
"s": 2638,
"text": " Print"
},
{
"code": null,
"e": 2656,
"s": 2645,
"text": " Add Notes"
}
] |
How to create a WebView in an Android App using Kotlin?
|
This example demonstrates how to create a WebView in an Android App using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
<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">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val webView: WebView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val webView = findViewById<WebView>(R.id.webView)
webView.webViewClient = WebViewClient()
webView.loadUrl("https://www.google.com")
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
}
override fun onBackPressed() {
if (webView!!.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
}
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.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrates how to create a WebView in an Android App using Kotlin."
},
{
"code": null,
"e": 1273,
"s": 1144,
"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": 1670,
"s": 1273,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n </WebView>\n</RelativeLayout>"
},
{
"code": null,
"e": 1725,
"s": 1670,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2510,
"s": 1725,
"text": "import android.os.Bundle\nimport android.webkit.WebView\nimport android.webkit.WebViewClient\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private val webView: WebView? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val webView = findViewById<WebView>(R.id.webView)\n webView.webViewClient = WebViewClient()\n webView.loadUrl(\"https://www.google.com\")\n val webSettings = webView.settings\n webSettings.javaScriptEnabled = true\n }\n override fun onBackPressed() {\n if (webView!!.canGoBack()) {\n webView.goBack()\n } else {\n super.onBackPressed()\n }\n }\n}"
},
{
"code": null,
"e": 2565,
"s": 2510,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3224,
"s": 2565,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <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": 3572,
"s": 3224,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Remove vowels from a String in C++
|
The following C++ program illustrates how to remove the vowels (a,e, i,u,o) from a given string. In this context, we create a new string and process input string character by character, and if a vowel is found it is excluded in the new string, otherwise the character is added to the new string
after the string ends we copy the new string into the original string. The algorithm is as follows;
START
Step-1: Input the string
Step-3: Check vowel presence, if found return TRUE
Step-4: Copy it to another array
Step-5: Increment the counter
Step-6: Print
END
In pursuance of the above algorithm, the following code in c++ language essayed as following;
#include <iostream>
#include <string.h>
#include <conio.h>
#include <cstring>
using namespace std;
int vowelChk(char);
int main(){
char s[50], t[50];
int c, d = 0;
cout<<"Enter a string to delete vowels\n";
cin>>s;
for(c = 0; s[c] != '\0'; c++) {
// check for If not a vowel
if(vowelChk(s[c]) == 0){
t[d] = s[c];
d++;
}
}
t[d] = '\0';
strcpy(s, t);
cout<<"String after delete vowels:"<<s;
return 0;
}
int vowelChk(char ch){
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
return 1;
else
return 0;
}
This C++ program deletes vowels from a string: if the input string is "ajaykumar" then it yields results as "jykmr". Finally, we obtain a string without vowels.
Enter a string to delete vowels
ajaykumar
String after delete vowels:jykmr
|
[
{
"code": null,
"e": 1457,
"s": 1062,
"text": "The following C++ program illustrates how to remove the vowels (a,e, i,u,o) from a given string. In this context, we create a new string and process input string character by character, and if a vowel is found it is excluded in the new string, otherwise the character is added to the new string\nafter the string ends we copy the new string into the original string. The algorithm is as follows;"
},
{
"code": null,
"e": 1635,
"s": 1457,
"text": "START\n Step-1: Input the string\n Step-3: Check vowel presence, if found return TRUE\n Step-4: Copy it to another array\n Step-5: Increment the counter\n Step-6: Print\nEND"
},
{
"code": null,
"e": 1729,
"s": 1635,
"text": "In pursuance of the above algorithm, the following code in c++ language essayed as following;"
},
{
"code": null,
"e": 2393,
"s": 1729,
"text": "#include <iostream>\n#include <string.h>\n#include <conio.h>\n#include <cstring>\nusing namespace std;\nint vowelChk(char);\nint main(){\n char s[50], t[50];\n int c, d = 0;\n cout<<\"Enter a string to delete vowels\\n\";\n cin>>s;\n for(c = 0; s[c] != '\\0'; c++) {\n // check for If not a vowel\n if(vowelChk(s[c]) == 0){\n t[d] = s[c];\n d++;\n }\n }\n t[d] = '\\0';\n strcpy(s, t);\n cout<<\"String after delete vowels:\"<<s;\n return 0;\n}\nint vowelChk(char ch){\n if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')\n return 1;\n else\n return 0;\n}"
},
{
"code": null,
"e": 2554,
"s": 2393,
"text": "This C++ program deletes vowels from a string: if the input string is \"ajaykumar\" then it yields results as \"jykmr\". Finally, we obtain a string without vowels."
},
{
"code": null,
"e": 2629,
"s": 2554,
"text": "Enter a string to delete vowels\najaykumar\nString after delete vowels:jykmr"
}
] |
Find the Nth term in series 12, 35, 81, 173, 357, ... - GeeksforGeeks
|
18 Mar, 2021
Given a number N, the task is to find the Nth term in series 12, 35, 81, 173, 357, ...Example:
Input: N = 2
Output: 35
2nd term = (12*2) + 11
= 35
Input: N = 5
Output: 357
5th term = (12*(2^4))+11*((2^4)-1)
= 357
Approach:
Each and every number is obtained by multiplying the previous number by 2 and the addition of 11 to it.
Since starting number is 12.
1st term = 12
2nd term = (12 * 2) / 11 = 35
3rd term = (35 * 2) / 11 = 81
4th term = (81 * 2) / 11 = 173
And, so on....
In general, Nth number is obtained by formula:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the Nth term// in series 12, 35, 81, 173, 357, ... #include <bits/stdc++.h>using namespace std; // Function to find Nth termint nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (first_term * (pow(2, N - 1))) + 11 * ((pow(2, N - 1)) - 1); return nth;} // Driver Methodint main(){ int N = 5; cout << nthTerm(N) << endl; return 0;}
// Java program to find the Nth term// in series 12, 35, 81, 173, 357, ...class GFG{ // Function to find Nth termstatic int nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (int) ((first_term * (Math.pow(2, N - 1))) + 11 * ((Math.pow(2, N - 1)) - 1)); return nth;} // Driver codepublic static void main(String[] args){ int N = 5; System.out.print(nthTerm(N) +"\n");}} // This code is contributed by Rajput-Ji
# Python3 program to find the Nth term# in series 12, 35, 81, 173, 357, ... # Function to find Nth termdef nthTerm(N) : nth = 0; first_term = 12; # Nth term nth = (first_term * (pow(2, N - 1))) + \ 11 * ((pow(2, N - 1)) - 1); return nth; # Driver Methodif __name__ == "__main__" : N = 5; print(nthTerm(N)) ; # This code is contributed by AnkitRai01
// C# program to find the Nth term// in series 12, 35, 81, 173, 357, ...using System; class GFG{ // Function to find Nth termstatic int nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (int) ((first_term * (Math.Pow(2, N - 1))) + 11 * ((Math.Pow(2, N - 1)) - 1)); return nth;} // Driver codepublic static void Main(String[] args){ int N = 5; Console.Write(nthTerm(N) +"\n");}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find the Nth term // in series 12, 35, 81, 173, 357, ... // Function to find Nth term function nthTerm(N) { let nth = 0, first_term = 12; // Nth term nth = (first_term * (Math.pow(2, N - 1))) + 11 * ((Math.pow(2, N - 1)) - 1); return nth; } let N = 5; document.write(nthTerm(N)); // This code is contributed by divyeshrabadiya07.</script>
357
ankthon
Rajput-Ji
princiraj1992
divyeshrabadiya07
series
Mathematical
Pattern Searching
Mathematical
series
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Sieve of Eratosthenes
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Naive algorithm for Pattern Searching
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 24785,
"s": 24757,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 24882,
"s": 24785,
"text": "Given a number N, the task is to find the Nth term in series 12, 35, 81, 173, 357, ...Example: "
},
{
"code": null,
"e": 25019,
"s": 24882,
"text": "Input: N = 2\nOutput: 35\n2nd term = (12*2) + 11\n = 35\n\nInput: N = 5\nOutput: 357\n5th term = (12*(2^4))+11*((2^4)-1)\n = 357"
},
{
"code": null,
"e": 25033,
"s": 25021,
"text": "Approach: "
},
{
"code": null,
"e": 25137,
"s": 25033,
"text": "Each and every number is obtained by multiplying the previous number by 2 and the addition of 11 to it."
},
{
"code": null,
"e": 25168,
"s": 25137,
"text": "Since starting number is 12. "
},
{
"code": null,
"e": 25288,
"s": 25168,
"text": "1st term = 12\n2nd term = (12 * 2) / 11 = 35\n3rd term = (35 * 2) / 11 = 81\n4th term = (81 * 2) / 11 = 173\nAnd, so on...."
},
{
"code": null,
"e": 25339,
"s": 25290,
"text": "In general, Nth number is obtained by formula: "
},
{
"code": null,
"e": 25394,
"s": 25341,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25398,
"s": 25394,
"text": "C++"
},
{
"code": null,
"e": 25403,
"s": 25398,
"text": "Java"
},
{
"code": null,
"e": 25411,
"s": 25403,
"text": "Python3"
},
{
"code": null,
"e": 25414,
"s": 25411,
"text": "C#"
},
{
"code": null,
"e": 25425,
"s": 25414,
"text": "Javascript"
},
{
"code": "// C++ program to find the Nth term// in series 12, 35, 81, 173, 357, ... #include <bits/stdc++.h>using namespace std; // Function to find Nth termint nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (first_term * (pow(2, N - 1))) + 11 * ((pow(2, N - 1)) - 1); return nth;} // Driver Methodint main(){ int N = 5; cout << nthTerm(N) << endl; return 0;}",
"e": 25825,
"s": 25425,
"text": null
},
{
"code": "// Java program to find the Nth term// in series 12, 35, 81, 173, 357, ...class GFG{ // Function to find Nth termstatic int nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (int) ((first_term * (Math.pow(2, N - 1))) + 11 * ((Math.pow(2, N - 1)) - 1)); return nth;} // Driver codepublic static void main(String[] args){ int N = 5; System.out.print(nthTerm(N) +\"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 26276,
"s": 25825,
"text": null
},
{
"code": "# Python3 program to find the Nth term# in series 12, 35, 81, 173, 357, ... # Function to find Nth termdef nthTerm(N) : nth = 0; first_term = 12; # Nth term nth = (first_term * (pow(2, N - 1))) + \\ 11 * ((pow(2, N - 1)) - 1); return nth; # Driver Methodif __name__ == \"__main__\" : N = 5; print(nthTerm(N)) ; # This code is contributed by AnkitRai01",
"e": 26658,
"s": 26276,
"text": null
},
{
"code": "// C# program to find the Nth term// in series 12, 35, 81, 173, 357, ...using System; class GFG{ // Function to find Nth termstatic int nthTerm(int N){ int nth = 0, first_term = 12; // Nth term nth = (int) ((first_term * (Math.Pow(2, N - 1))) + 11 * ((Math.Pow(2, N - 1)) - 1)); return nth;} // Driver codepublic static void Main(String[] args){ int N = 5; Console.Write(nthTerm(N) +\"\\n\");}} // This code is contributed by PrinciRaj1992",
"e": 27122,
"s": 26658,
"text": null
},
{
"code": "<script> // Javascript program to find the Nth term // in series 12, 35, 81, 173, 357, ... // Function to find Nth term function nthTerm(N) { let nth = 0, first_term = 12; // Nth term nth = (first_term * (Math.pow(2, N - 1))) + 11 * ((Math.pow(2, N - 1)) - 1); return nth; } let N = 5; document.write(nthTerm(N)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 27572,
"s": 27122,
"text": null
},
{
"code": null,
"e": 27576,
"s": 27572,
"text": "357"
},
{
"code": null,
"e": 27586,
"s": 27578,
"text": "ankthon"
},
{
"code": null,
"e": 27596,
"s": 27586,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27610,
"s": 27596,
"text": "princiraj1992"
},
{
"code": null,
"e": 27628,
"s": 27610,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 27635,
"s": 27628,
"text": "series"
},
{
"code": null,
"e": 27648,
"s": 27635,
"text": "Mathematical"
},
{
"code": null,
"e": 27666,
"s": 27648,
"text": "Pattern Searching"
},
{
"code": null,
"e": 27679,
"s": 27666,
"text": "Mathematical"
},
{
"code": null,
"e": 27686,
"s": 27679,
"text": "series"
},
{
"code": null,
"e": 27704,
"s": 27686,
"text": "Pattern Searching"
},
{
"code": null,
"e": 27802,
"s": 27704,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27811,
"s": 27802,
"text": "Comments"
},
{
"code": null,
"e": 27824,
"s": 27811,
"text": "Old Comments"
},
{
"code": null,
"e": 27848,
"s": 27824,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 27890,
"s": 27848,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 27933,
"s": 27890,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 27947,
"s": 27933,
"text": "Prime Numbers"
},
{
"code": null,
"e": 27969,
"s": 27947,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 28005,
"s": 27969,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 28048,
"s": 28005,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 28090,
"s": 28048,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 28128,
"s": 28090,
"text": "Naive algorithm for Pattern Searching"
}
] |
Unix / Linux - Shell Loop Types
|
In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −
The while loop
The for loop
The until loop
The select loop
You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.
Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc.
All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −
It is possible to use a while loop as part of the body of another while loop.
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
done
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used to count to nine −
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
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": 2992,
"s": 2747,
"text": "In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −"
},
{
"code": null,
"e": 3007,
"s": 2992,
"text": "The while loop"
},
{
"code": null,
"e": 3020,
"s": 3007,
"text": "The for loop"
},
{
"code": null,
"e": 3035,
"s": 3020,
"text": "The until loop"
},
{
"code": null,
"e": 3051,
"s": 3035,
"text": "The select loop"
},
{
"code": null,
"e": 3262,
"s": 3051,
"text": "You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true."
},
{
"code": null,
"e": 3506,
"s": 3262,
"text": "Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc."
},
{
"code": null,
"e": 3703,
"s": 3506,
"text": "All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement."
},
{
"code": null,
"e": 3831,
"s": 3703,
"text": "Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −"
},
{
"code": null,
"e": 3909,
"s": 3831,
"text": "It is possible to use a while loop as part of the body of another while loop."
},
{
"code": null,
"e": 4191,
"s": 3909,
"text": "while command1 ; # this is loop1, the outer loop\ndo\n Statement(s) to be executed if command1 is true\n\n while command2 ; # this is loop2, the inner loop\n do\n Statement(s) to be executed if command2 is true\n done\n\n Statement(s) to be executed if command1 is true\ndone\n"
},
{
"code": null,
"e": 4315,
"s": 4191,
"text": "Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used to count to nine −"
},
{
"code": null,
"e": 4513,
"s": 4315,
"text": "#!/bin/sh\n\na=0\nwhile [ \"$a\" -lt 10 ] # this is loop1\ndo\n b=\"$a\"\n while [ \"$b\" -ge 0 ] # this is loop2\n do\n echo -n \"$b \"\n b=`expr $b - 1`\n done\n echo\n a=`expr $a + 1`\ndone"
},
{
"code": null,
"e": 4663,
"s": 4513,
"text": "This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character."
},
{
"code": null,
"e": 4774,
"s": 4663,
"text": "0\n1 0\n2 1 0\n3 2 1 0\n4 3 2 1 0\n5 4 3 2 1 0\n6 5 4 3 2 1 0\n7 6 5 4 3 2 1 0\n8 7 6 5 4 3 2 1 0\n9 8 7 6 5 4 3 2 1 0\n"
},
{
"code": null,
"e": 4809,
"s": 4774,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4837,
"s": 4809,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4871,
"s": 4837,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4888,
"s": 4871,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4921,
"s": 4888,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4932,
"s": 4921,
"text": " Pradeep D"
},
{
"code": null,
"e": 4967,
"s": 4932,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4983,
"s": 4967,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5016,
"s": 4983,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5028,
"s": 5016,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5060,
"s": 5028,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5068,
"s": 5060,
"text": " Uplatz"
},
{
"code": null,
"e": 5075,
"s": 5068,
"text": " Print"
},
{
"code": null,
"e": 5086,
"s": 5075,
"text": " Add Notes"
}
] |
Backpropagation in a convolutional layer | by Pierre JAUMIER | Towards Data Science
|
The aim of this post is to detail how gradient backpropagation is working in a convolutional layer of a neural network. Typically the output of this layer will be the input of a chosen activation function (relufor instance). We are making the assumption that we are given the gradient dy backpropagated from this activation function. As I was unable to find on the web a complete, detailed, and “simple” explanation of how it works. I decided to do the maths, trying to understand step by step how it’s working on simple examples before generalizing. Before further reading, you should be familiar with neural networks, and especially forward pass, backpropagation of gradient in a computational graph and basic linear algebra with tensors.
* will refer to the convolution of 2 tensors in the case of a neural network (an input x and a filter w).
When xand w are matrices:
if xand w share the same shape, x*w will be a scalar equal to the sum across the results of the element-wise multiplication between the arrays.
if wis smaller the x, we will obtain an activation map y where each value is the predefined convolution operation of a sub-region of x with the sizes of w. This sub-region activated by the filter is sliding all across the input array x.
if xand w have more than 2 dimensions, we are considering the last 3 ones for the convolution, and the last 2 ones for the highlighted sliding area (we just add one depth to our matrix)
Notations and variables are the same as the ones used in the excellent Stanford course on convolutional neural networks for visual recognition and especially the ones of assignment 2. Details on convolutional layer and forward pass will be found in this video and an instance of a naive implementation of the forward pass post.
Our goal is to find out how gradient is propagating backwards in a convolutional layer. The forward pass is defined like this:
The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width WW.
Input:
x: Input data of shape (N, C, H, W)
w: Filter weights of shape (F, C, HH, WW)
b: Biases, of shape (F,)
conv_param: A dictionary with the following keys:
‘stride’: The number of pixels between adjacent receptive fields in the horizontal and vertical directions.
‘pad’: The number of pixels that will be used to zero-pad the input.
During padding, ‘pad’ zeros should be placed symmetrically (i.e equally on both sides) along the height and width axes of the input.
Returns a tuple of:
out: Output data, of shape (N, F, H’, W’) where H’ and W’ are given by
H’ = 1 + (H + 2 * pad — HH) / stride
W’ = 1 + (W + 2 * pad — WW) / stride
cache: (x, w, b, conv_param)
N=1 one input, C=1 one channel, F=1 one filter.
x : H×Wx′=x with paddingw : HH×WWb bias : scalary : H′×W′stride s
We know:
We want to compute dx, dw and db, partial derivatives of our cost funcion L. We suppose that the gradient of this function has been backpropagated till y.
We are looking for an intuition of how it works on an easy setup and later on we will try to generalize.
We know the gradient of our cost function L with respect to y:
This can be written with the Jacobian notation:
dy and y share the same shape:
We are looking for
Using the chain rule and the forward pass formula (1), we can write:
We can notice that dw is a convolution of the input x with a filter dy. Let’s see if it’s still valid with a added dimension.
Once again, we have a convolution. A little bit more complex this time. We should consider an input dy with a 0-padding of size 1 convolved with an “inverted” filter w like (w2,w1)
Next step will be to have a look on how it works on small matrices.
Once again, we will choose the easiest case: stride = 1 and no padding. Shape of y will be (3,3)
We will have:
Written with subscripts:
We know:
Using the Einstein convention to alleviate the formulas (when an index variable appears twice in a multiplication, it implies summation of that term over all the values of the index)
Summation on i and j. And we have:
We are looking for
Using the formula (4) we have:
All terms
Except for (k,l)=(m,n) where it’s 1, case occurring just once in the double sum. Hence:
Using formula (3) we now have:
If we compare this equation with formula (1) giving the result of a convolution, we can distinguish a similar pattern where dy is a filter applied on an input x.
Using the chaine rule as we did for (5), we have:
This time, we are looking for
Using equation (4):
We now have:
In our example, range sets for indices are:
When we set k=m−i+1, we are going to be out of the defined boundaries:(m−i+1)∈[−1,4]
In order to keep confidence in formula above, we choose to extend the definition of matrix w with 0 values as soon as indices will go out of the defined range.
Once again in the double sum , we only have once partial derivative of x equals 1. So:
where w is our 0-extended initial filter, thus:
Lets visualize it on several chosen values for the indices.
Using ∗ notation for convolution, we have:
As dy remain the same, we will only look at the values of indices of w. For dx22, range for w: 3−i,3−j
We now have a convolution between dy and a w’ matrix defined by:
Another instance in order to see what’s happening. dx43, w : 4−i,3−j
Last one dx44
We do see poping up an “inverted filter” w’. This time we have a convolution between an input dy with a 0-padding border of size 1 and a filter w’ slidding with a stride of 1.
Things are becoming slightly more complex when we try to take depth into account (C channels for input x, and F distinct filters for w)
Inputs:
x: shape (C, H, W)
w: filter’s weights shape (F, C, HH, WW)
b: shape (F,)
Outputs:
y: shape (F, H’, W’)
Maths formulas see many indices emerging, making them more difficult to read. The forward pass formula in our example will be:
db computation remains easy as each b_f is related to an activation map y_f:
Using the forward pass formula, as the double sum does not use dy indices, we can write:
Now that we have the intuition of how it’s working, we choose not to write the entire set of equations (which can be pretty tedious), but we’ll use what has been coded for the forward pass, and playing with dimensions try to code the backprop for each gradient. Fortunately we can compute a numerical value of the gradient to check our implementation. This implementation is only valid for a stride=1, thing are becoming slightly more complex with a distinct stride, and another approach is needed. Maybe for another post!
Testing conv_backward_naive functiondx error: 7.489787768926947e-09dw error: 1.381022780971562e-10db error: 1.1299800330640326e-10
Almost 0 each time, everything seems tobe OK! :)
This post on my blog with mathjax equations :)
Stanford course on convolutional neural networks for visual recognition
Stanford CNN assignment 2
Convolutional neural network, forward pass
Convolution Layer : Naive implementation of the forward pass.
Backpropagation In Convolutional Neural Networks
Cet article en français
Comments are welcome to improve this post, feel free to contact me!
|
[
{
"code": null,
"e": 913,
"s": 172,
"text": "The aim of this post is to detail how gradient backpropagation is working in a convolutional layer of a neural network. Typically the output of this layer will be the input of a chosen activation function (relufor instance). We are making the assumption that we are given the gradient dy backpropagated from this activation function. As I was unable to find on the web a complete, detailed, and “simple” explanation of how it works. I decided to do the maths, trying to understand step by step how it’s working on simple examples before generalizing. Before further reading, you should be familiar with neural networks, and especially forward pass, backpropagation of gradient in a computational graph and basic linear algebra with tensors."
},
{
"code": null,
"e": 1019,
"s": 913,
"text": "* will refer to the convolution of 2 tensors in the case of a neural network (an input x and a filter w)."
},
{
"code": null,
"e": 1045,
"s": 1019,
"text": "When xand w are matrices:"
},
{
"code": null,
"e": 1189,
"s": 1045,
"text": "if xand w share the same shape, x*w will be a scalar equal to the sum across the results of the element-wise multiplication between the arrays."
},
{
"code": null,
"e": 1426,
"s": 1189,
"text": "if wis smaller the x, we will obtain an activation map y where each value is the predefined convolution operation of a sub-region of x with the sizes of w. This sub-region activated by the filter is sliding all across the input array x."
},
{
"code": null,
"e": 1612,
"s": 1426,
"text": "if xand w have more than 2 dimensions, we are considering the last 3 ones for the convolution, and the last 2 ones for the highlighted sliding area (we just add one depth to our matrix)"
},
{
"code": null,
"e": 1940,
"s": 1612,
"text": "Notations and variables are the same as the ones used in the excellent Stanford course on convolutional neural networks for visual recognition and especially the ones of assignment 2. Details on convolutional layer and forward pass will be found in this video and an instance of a naive implementation of the forward pass post."
},
{
"code": null,
"e": 2067,
"s": 1940,
"text": "Our goal is to find out how gradient is propagating backwards in a convolutional layer. The forward pass is defined like this:"
},
{
"code": null,
"e": 2268,
"s": 2067,
"text": "The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width WW."
},
{
"code": null,
"e": 2275,
"s": 2268,
"text": "Input:"
},
{
"code": null,
"e": 2311,
"s": 2275,
"text": "x: Input data of shape (N, C, H, W)"
},
{
"code": null,
"e": 2353,
"s": 2311,
"text": "w: Filter weights of shape (F, C, HH, WW)"
},
{
"code": null,
"e": 2378,
"s": 2353,
"text": "b: Biases, of shape (F,)"
},
{
"code": null,
"e": 2428,
"s": 2378,
"text": "conv_param: A dictionary with the following keys:"
},
{
"code": null,
"e": 2536,
"s": 2428,
"text": "‘stride’: The number of pixels between adjacent receptive fields in the horizontal and vertical directions."
},
{
"code": null,
"e": 2605,
"s": 2536,
"text": "‘pad’: The number of pixels that will be used to zero-pad the input."
},
{
"code": null,
"e": 2738,
"s": 2605,
"text": "During padding, ‘pad’ zeros should be placed symmetrically (i.e equally on both sides) along the height and width axes of the input."
},
{
"code": null,
"e": 2758,
"s": 2738,
"text": "Returns a tuple of:"
},
{
"code": null,
"e": 2829,
"s": 2758,
"text": "out: Output data, of shape (N, F, H’, W’) where H’ and W’ are given by"
},
{
"code": null,
"e": 2866,
"s": 2829,
"text": "H’ = 1 + (H + 2 * pad — HH) / stride"
},
{
"code": null,
"e": 2903,
"s": 2866,
"text": "W’ = 1 + (W + 2 * pad — WW) / stride"
},
{
"code": null,
"e": 2932,
"s": 2903,
"text": "cache: (x, w, b, conv_param)"
},
{
"code": null,
"e": 2980,
"s": 2932,
"text": "N=1 one input, C=1 one channel, F=1 one filter."
},
{
"code": null,
"e": 3046,
"s": 2980,
"text": "x : H×Wx′=x with paddingw : HH×WWb bias : scalary : H′×W′stride s"
},
{
"code": null,
"e": 3055,
"s": 3046,
"text": "We know:"
},
{
"code": null,
"e": 3210,
"s": 3055,
"text": "We want to compute dx, dw and db, partial derivatives of our cost funcion L. We suppose that the gradient of this function has been backpropagated till y."
},
{
"code": null,
"e": 3315,
"s": 3210,
"text": "We are looking for an intuition of how it works on an easy setup and later on we will try to generalize."
},
{
"code": null,
"e": 3378,
"s": 3315,
"text": "We know the gradient of our cost function L with respect to y:"
},
{
"code": null,
"e": 3426,
"s": 3378,
"text": "This can be written with the Jacobian notation:"
},
{
"code": null,
"e": 3457,
"s": 3426,
"text": "dy and y share the same shape:"
},
{
"code": null,
"e": 3476,
"s": 3457,
"text": "We are looking for"
},
{
"code": null,
"e": 3545,
"s": 3476,
"text": "Using the chain rule and the forward pass formula (1), we can write:"
},
{
"code": null,
"e": 3671,
"s": 3545,
"text": "We can notice that dw is a convolution of the input x with a filter dy. Let’s see if it’s still valid with a added dimension."
},
{
"code": null,
"e": 3852,
"s": 3671,
"text": "Once again, we have a convolution. A little bit more complex this time. We should consider an input dy with a 0-padding of size 1 convolved with an “inverted” filter w like (w2,w1)"
},
{
"code": null,
"e": 3920,
"s": 3852,
"text": "Next step will be to have a look on how it works on small matrices."
},
{
"code": null,
"e": 4017,
"s": 3920,
"text": "Once again, we will choose the easiest case: stride = 1 and no padding. Shape of y will be (3,3)"
},
{
"code": null,
"e": 4031,
"s": 4017,
"text": "We will have:"
},
{
"code": null,
"e": 4056,
"s": 4031,
"text": "Written with subscripts:"
},
{
"code": null,
"e": 4065,
"s": 4056,
"text": "We know:"
},
{
"code": null,
"e": 4248,
"s": 4065,
"text": "Using the Einstein convention to alleviate the formulas (when an index variable appears twice in a multiplication, it implies summation of that term over all the values of the index)"
},
{
"code": null,
"e": 4283,
"s": 4248,
"text": "Summation on i and j. And we have:"
},
{
"code": null,
"e": 4302,
"s": 4283,
"text": "We are looking for"
},
{
"code": null,
"e": 4333,
"s": 4302,
"text": "Using the formula (4) we have:"
},
{
"code": null,
"e": 4343,
"s": 4333,
"text": "All terms"
},
{
"code": null,
"e": 4431,
"s": 4343,
"text": "Except for (k,l)=(m,n) where it’s 1, case occurring just once in the double sum. Hence:"
},
{
"code": null,
"e": 4462,
"s": 4431,
"text": "Using formula (3) we now have:"
},
{
"code": null,
"e": 4624,
"s": 4462,
"text": "If we compare this equation with formula (1) giving the result of a convolution, we can distinguish a similar pattern where dy is a filter applied on an input x."
},
{
"code": null,
"e": 4674,
"s": 4624,
"text": "Using the chaine rule as we did for (5), we have:"
},
{
"code": null,
"e": 4704,
"s": 4674,
"text": "This time, we are looking for"
},
{
"code": null,
"e": 4724,
"s": 4704,
"text": "Using equation (4):"
},
{
"code": null,
"e": 4737,
"s": 4724,
"text": "We now have:"
},
{
"code": null,
"e": 4781,
"s": 4737,
"text": "In our example, range sets for indices are:"
},
{
"code": null,
"e": 4866,
"s": 4781,
"text": "When we set k=m−i+1, we are going to be out of the defined boundaries:(m−i+1)∈[−1,4]"
},
{
"code": null,
"e": 5026,
"s": 4866,
"text": "In order to keep confidence in formula above, we choose to extend the definition of matrix w with 0 values as soon as indices will go out of the defined range."
},
{
"code": null,
"e": 5113,
"s": 5026,
"text": "Once again in the double sum , we only have once partial derivative of x equals 1. So:"
},
{
"code": null,
"e": 5161,
"s": 5113,
"text": "where w is our 0-extended initial filter, thus:"
},
{
"code": null,
"e": 5221,
"s": 5161,
"text": "Lets visualize it on several chosen values for the indices."
},
{
"code": null,
"e": 5264,
"s": 5221,
"text": "Using ∗ notation for convolution, we have:"
},
{
"code": null,
"e": 5367,
"s": 5264,
"text": "As dy remain the same, we will only look at the values of indices of w. For dx22, range for w: 3−i,3−j"
},
{
"code": null,
"e": 5432,
"s": 5367,
"text": "We now have a convolution between dy and a w’ matrix defined by:"
},
{
"code": null,
"e": 5501,
"s": 5432,
"text": "Another instance in order to see what’s happening. dx43, w : 4−i,3−j"
},
{
"code": null,
"e": 5515,
"s": 5501,
"text": "Last one dx44"
},
{
"code": null,
"e": 5691,
"s": 5515,
"text": "We do see poping up an “inverted filter” w’. This time we have a convolution between an input dy with a 0-padding border of size 1 and a filter w’ slidding with a stride of 1."
},
{
"code": null,
"e": 5827,
"s": 5691,
"text": "Things are becoming slightly more complex when we try to take depth into account (C channels for input x, and F distinct filters for w)"
},
{
"code": null,
"e": 5835,
"s": 5827,
"text": "Inputs:"
},
{
"code": null,
"e": 5854,
"s": 5835,
"text": "x: shape (C, H, W)"
},
{
"code": null,
"e": 5895,
"s": 5854,
"text": "w: filter’s weights shape (F, C, HH, WW)"
},
{
"code": null,
"e": 5909,
"s": 5895,
"text": "b: shape (F,)"
},
{
"code": null,
"e": 5918,
"s": 5909,
"text": "Outputs:"
},
{
"code": null,
"e": 5939,
"s": 5918,
"text": "y: shape (F, H’, W’)"
},
{
"code": null,
"e": 6066,
"s": 5939,
"text": "Maths formulas see many indices emerging, making them more difficult to read. The forward pass formula in our example will be:"
},
{
"code": null,
"e": 6143,
"s": 6066,
"text": "db computation remains easy as each b_f is related to an activation map y_f:"
},
{
"code": null,
"e": 6232,
"s": 6143,
"text": "Using the forward pass formula, as the double sum does not use dy indices, we can write:"
},
{
"code": null,
"e": 6755,
"s": 6232,
"text": "Now that we have the intuition of how it’s working, we choose not to write the entire set of equations (which can be pretty tedious), but we’ll use what has been coded for the forward pass, and playing with dimensions try to code the backprop for each gradient. Fortunately we can compute a numerical value of the gradient to check our implementation. This implementation is only valid for a stride=1, thing are becoming slightly more complex with a distinct stride, and another approach is needed. Maybe for another post!"
},
{
"code": null,
"e": 6889,
"s": 6755,
"text": "Testing conv_backward_naive functiondx error: 7.489787768926947e-09dw error: 1.381022780971562e-10db error: 1.1299800330640326e-10"
},
{
"code": null,
"e": 6938,
"s": 6889,
"text": "Almost 0 each time, everything seems tobe OK! :)"
},
{
"code": null,
"e": 6985,
"s": 6938,
"text": "This post on my blog with mathjax equations :)"
},
{
"code": null,
"e": 7057,
"s": 6985,
"text": "Stanford course on convolutional neural networks for visual recognition"
},
{
"code": null,
"e": 7083,
"s": 7057,
"text": "Stanford CNN assignment 2"
},
{
"code": null,
"e": 7126,
"s": 7083,
"text": "Convolutional neural network, forward pass"
},
{
"code": null,
"e": 7188,
"s": 7126,
"text": "Convolution Layer : Naive implementation of the forward pass."
},
{
"code": null,
"e": 7237,
"s": 7188,
"text": "Backpropagation In Convolutional Neural Networks"
},
{
"code": null,
"e": 7262,
"s": 7237,
"text": "Cet article en français"
}
] |
PyQt5 Label - Adding shadow - GeeksforGeeks
|
10 May, 2020
In this article we will see how we can add shadow to the label by default there is no shadow to the label although we can create shadow to the label, below is the representation of how label with shadow box looks like
In order to do this we have to do the following –
1. Create a label2. Set geometry to the label3. Create a QGraphicsDropShadowEffect object4. Set blur radius to the object(optional)5. Add this object to the label with the help of setGraphicsEffect method
Syntax :
# creating a QGraphicsDropShadowEffect object
shadow = QGraphicsDropShadowEffect()
# setting blur radius (optional step)
shadow.setBlurRadius(15)
# adding shadow to the label
label.setGraphicsEffect(shadow)
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting background color of window # self.setStyleSheet("background-color : black;") # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Label", self) # setting alignment label.setAlignment(Qt.AlignCenter) # setting geometry to the label label.setGeometry(200, 150, 200, 80) # setting border label.setStyleSheet("border : 10px solid black") # creating a QGraphicsDropShadowEffect object shadow = QGraphicsDropShadowEffect() # setting blur radius shadow.setBlurRadius(15) # adding shadow to the label label.setGraphicsEffect(shadow) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24470,
"s": 24442,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24688,
"s": 24470,
"text": "In this article we will see how we can add shadow to the label by default there is no shadow to the label although we can create shadow to the label, below is the representation of how label with shadow box looks like"
},
{
"code": null,
"e": 24738,
"s": 24688,
"text": "In order to do this we have to do the following –"
},
{
"code": null,
"e": 24943,
"s": 24738,
"text": "1. Create a label2. Set geometry to the label3. Create a QGraphicsDropShadowEffect object4. Set blur radius to the object(optional)5. Add this object to the label with the help of setGraphicsEffect method"
},
{
"code": null,
"e": 24952,
"s": 24943,
"text": "Syntax :"
},
{
"code": null,
"e": 25162,
"s": 24952,
"text": "# creating a QGraphicsDropShadowEffect object\nshadow = QGraphicsDropShadowEffect()\n\n# setting blur radius (optional step)\nshadow.setBlurRadius(15)\n\n# adding shadow to the label\nlabel.setGraphicsEffect(shadow)\n"
},
{
"code": null,
"e": 25190,
"s": 25162,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting background color of window # self.setStyleSheet(\"background-color : black;\") # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Label\", self) # setting alignment label.setAlignment(Qt.AlignCenter) # setting geometry to the label label.setGeometry(200, 150, 200, 80) # setting border label.setStyleSheet(\"border : 10px solid black\") # creating a QGraphicsDropShadowEffect object shadow = QGraphicsDropShadowEffect() # setting blur radius shadow.setBlurRadius(15) # adding shadow to the label label.setGraphicsEffect(shadow) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26494,
"s": 25190,
"text": null
},
{
"code": null,
"e": 26503,
"s": 26494,
"text": "Output :"
},
{
"code": null,
"e": 26522,
"s": 26503,
"text": "Python PyQt5-Label"
},
{
"code": null,
"e": 26533,
"s": 26522,
"text": "Python-gui"
},
{
"code": null,
"e": 26545,
"s": 26533,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26552,
"s": 26545,
"text": "Python"
},
{
"code": null,
"e": 26650,
"s": 26552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26659,
"s": 26650,
"text": "Comments"
},
{
"code": null,
"e": 26672,
"s": 26659,
"text": "Old Comments"
},
{
"code": null,
"e": 26690,
"s": 26672,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26722,
"s": 26690,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26757,
"s": 26722,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26779,
"s": 26757,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26809,
"s": 26779,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26851,
"s": 26809,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26894,
"s": 26851,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26931,
"s": 26894,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26957,
"s": 26931,
"text": "Python String | replace()"
}
] |
Dataset deduplication using spark’s MLlib | by Ronald Ángel | Towards Data Science
|
A deduplication process is always important for companies with a huge amount of data. From one thing, deduplication minimizes the amount of space required to store business data and will bring a lower infrastructure cost and better performance for our pipelines. From another thing, reducing the number of duplicates will reduce the pipelines complexity and will increase the time to business via continuing integration and continuous delivery (CI/CD).
Sometimes a deduplication process consists of a simple text to text matching and you can simply choose either a CRC32-Checksum or an MD5 matching. However, there are some situations where the dataset rows differ only for some small text discrepancies on some of the columns, even though they represent the same entity. Thus, this article shows an entities recognition and linking process using two different spark approaches over a specific dataset of products collected by scrapping e-commerce websites will be used.
The entire code and process describe following could be found here:
github.com
The general process could be found on this trait (... Yes, I use scala for data science !!!):
package com.sample.utilsimport org.apache.spark.sql.DataFrametrait OperationsHelper { def ds: DataFrame def preparedDataSet()(df: DataFrame): DataFrame def deduplicateDataSet()(df: DataFrame): DataFrame def resultsDataFrame()(df: DataFrame): DataFrame}
As you will see the idea behind this helper will be having a functional pipe from where easily chain dataframe transforms could be called.
Techniques to reduce dimensionality are widely used by the data science community to get a smaller set of features to analyze and obtain better performance while training and evaluating models. The PCA method allows dimensionality reduction while keeping those features that describe a large amount of the information. Consequently, this pre-processing stage follows these steps:
Data Cleaning: Cleaning the data to have a common scale. For the case of the products, dataset consists of a simple text cleaning for cases, white spaces, encoding, and symbols.
Features Selection: Using the PCA technic a set of features are selected.(“titleChunk”, “contentChunk”, “color”, “ productType”)
The content found on the features above contains most of the discrepancies for candidate duplicate products.
Locality-sensitive hashing is a technic used for entity resolution, then records that represent the same entity will be found. The spark MLlib has a custom LSH implementation used here to find duplicates as follow:
First, hashes are generated using a concatenation of selected features (PC above). For a real-world example hashes for each feature could be generated. However, for this example and in order to get results faster a simple concatenated column is used.
Then, this column is used for generating LSH vectors as follow:
— A tokenizer generates the list of words for a record using a words stopper.
— A CountVectorizerModel creates the vectors with hashes and buckets (similar hashes) for the LSH algorithm.
val pccTokenizer = new Tokenizer() .setInputCol(OperationsHelperLSH.ConcatComments) .setOutputCol(OperationsHelperLSH.ColumnWordsArray)val wordsArrayDF = pccTokenizer.transform(df)val remover = new StopWordsRemover() .setCaseSensitive(false) .setStopWords(OperationsHelperLSH.stopWords) .setInputCol(OperationsHelperLSH.ColumnWordsArray) .setOutputCol(OperationsHelperLSH.ColumnFilteredWordsArray)val wordsFiltered = remover.transform(wordsArrayDF)val validateEmptyVector = udf({ v: Vector => v.numNonzeros > 0 }, DataTypes.BooleanType)val vectorModeler: CountVectorizerModel = new CountVectorizer() .setInputCol(OperationsHelperLSH.ColumnFilteredWordsArray) .setOutputCol(OperationsHelperLSH.ColumnFeaturesArray) .setVocabSize(VocabularySHLSize) .setMinDF(10) .fit(wordsFiltered)val vectorizedProductsDF = vectorModeler.transform(wordsFiltered) .filter(validateEmptyVector(col(OperationsHelperLSH.ColumnFeaturesArray))) .select(col(OperationsHelperWindowStrategy.ConcatComments), col(OperationsHelperLSH.ColumnUniqueId), col(OperationsHelperLSH.ColumnFilteredWordsArray), col(OperationsHelperLSH.ColumnFeaturesArray))(vectorizedProductsDF, vectorModeler)
Class: com.sample.products.OperationsHelperLSH.scala
In order to finish the training step, a MinHashLSHModel is used to train the products data, generating the final buckets of similar products.
Finally, using KNN similar hashes for a category could be found.
/** * Uses the dataset to train the model. * */ def deduplicateDataSet(df: DataFrame): (DataFrame, MinHashLSHModel) = { val minLshConfig = new MinHashLSH().setNumHashTables(hashesNumber) .setInputCol(OperationsHelperLSH.ColumnFeaturesArray) .setOutputCol(OperationsHelperLSH.hashValuesColumn) val lshModel = minLshConfig.fit(df) (lshModel.transform(df), lshModel) } /** * Applies KNN to find similar records. * */ def filterResults(df: DataFrame, vectorModeler: CountVectorizerModel, lshModel: MinHashLSHModel, categoryQuery: (String, String) ): DataFrame = { val key = Vectors.sparse(VocabularySHLSize, Seq((vectorModeler.vocabulary.indexOf(categoryQuery._1), 1.0), (vectorModeler.vocabulary.indexOf(categoryQuery._2), 1.0))) lshModel.approxNearestNeighbors(df, key, nearNeighboursNumber).toDF()}
To run an example: Go to the test com.sample.processor.products.ProcessorProductsLshTest and you will see a complete flow running.
Input Params:
category → color = ‘negro’ and productType = ‘tdi’.
nearNeighboursNumber → 4
hashesNumber → 3 (More hashes more precision but more computing cost).
Pros:
Accurate: If a complete set of fields (representing the string) is used, the correct value for hashes and neighbors could detect almost all the repeated values.
Faster: compared with other ML strategies as Term-frequency-inverse, etc.
Cons :
A cluster with good resources is needed.
Needs a process for data cleaning.
Levenshtein is an algorithm used for strings fuzzy matching. Basically, this method measures the difference between two strings. Furthermore, the spark windows functions allow dataset analytics function in a concise way, avoiding multiple groupBy and Join operations. Thus, this method defines a 2-level window to group similar data and then applies Levenshtein to values in the same windows to discover duplicates. The process is described here:
First of all, a set of records described as non-fuzzy is selected. The list contains columns that represent categories and are were free of errors most of the times in the PCA process: (“productType”, “city”, “country”, “region”, “year”).
This window represents the general windows hash for the analysis.
Secondly, a second window to discover quite similar records is applied. This list represents records that are neither part from the fuzzy list (PCA) nor from the non-fuzzy list: (“doors”, “fuel”, “make”, “mileage”, “model”, “color”, “price”)
Note: the “date” field helps to order and get only the most recent.
Then, For each group applies levenshtein (string difference only in the second window) over the concatenated most fuzzy fields from PCA results: (“titleChunk”, “contentChunk”).
As you can see an MD5 representation of the columns is used instead of each String to have better performance:
keyhash: MD5 for the category column set. The picture below shows many products within the same category.
hashDiff: MD5 hash that represents the non-fuzzy set. The picture below shows products within the same category but with a different description (> levenshteinThreshold) and also those with a small levenshtein (< levenshteinThreshold) difference having the same hashDiff.
Finally, the values with the same hashes (both) and rank only change the row_num. Filtering row_num == 1 is possible to get the deduplicate Data set.
/** * Applies windows functions and Levenshtein to group similar categories. * */override def deduplicateDataSet()(df: DataFrame): DataFrame = { df .withColumn(OperationsHelperWindowStrategy.ColumnRank, dense_rank().over(windowProductKeyHash)) .withColumn(OperationsHelperWindowStrategy.ColumnHashWithDiff, concat(col(OperationsHelperWindowStrategy.ColumnCategoryFieldsHash), when(levenshtein( first(OperationsHelperWindowStrategy.ConcatComments).over(windowProductsCategoryRank), col(OperationsHelperWindowStrategy.ConcatComments)) >= levenshteinThreshold, lit("1")) .otherwise(lit("")))) .withColumn(OperationsHelperWindowStrategy.ColumnRowNum, row_number().over(windowProductsCategoryRank))}
Class: com.sample.products.OperationsHelperWindowStrategy.scala
To run an example: Go to the test com.sample.processor.products.ProcessorProductsWindowsTest and you will see a complete flow running.
Input Params: levenshteinThreshold → 6
Results:
The results are deduplicated after filtering rn == 1. This removes > 1/3 of the data in the sample dataset.
Pros:
More control in the spark partitioner and functions.
Cons :
Could have much more false positives.
A deduplication process depends always on the company needs and the amount of data to analyze. This article describes two different strategies. As a result, Levenshtein with windows functions is good enough for small dimensionality problems; otherwise, LSH is always the best option
|
[
{
"code": null,
"e": 625,
"s": 172,
"text": "A deduplication process is always important for companies with a huge amount of data. From one thing, deduplication minimizes the amount of space required to store business data and will bring a lower infrastructure cost and better performance for our pipelines. From another thing, reducing the number of duplicates will reduce the pipelines complexity and will increase the time to business via continuing integration and continuous delivery (CI/CD)."
},
{
"code": null,
"e": 1143,
"s": 625,
"text": "Sometimes a deduplication process consists of a simple text to text matching and you can simply choose either a CRC32-Checksum or an MD5 matching. However, there are some situations where the dataset rows differ only for some small text discrepancies on some of the columns, even though they represent the same entity. Thus, this article shows an entities recognition and linking process using two different spark approaches over a specific dataset of products collected by scrapping e-commerce websites will be used."
},
{
"code": null,
"e": 1211,
"s": 1143,
"text": "The entire code and process describe following could be found here:"
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": "github.com"
},
{
"code": null,
"e": 1316,
"s": 1222,
"text": "The general process could be found on this trait (... Yes, I use scala for data science !!!):"
},
{
"code": null,
"e": 1573,
"s": 1316,
"text": "package com.sample.utilsimport org.apache.spark.sql.DataFrametrait OperationsHelper { def ds: DataFrame def preparedDataSet()(df: DataFrame): DataFrame def deduplicateDataSet()(df: DataFrame): DataFrame def resultsDataFrame()(df: DataFrame): DataFrame}"
},
{
"code": null,
"e": 1712,
"s": 1573,
"text": "As you will see the idea behind this helper will be having a functional pipe from where easily chain dataframe transforms could be called."
},
{
"code": null,
"e": 2092,
"s": 1712,
"text": "Techniques to reduce dimensionality are widely used by the data science community to get a smaller set of features to analyze and obtain better performance while training and evaluating models. The PCA method allows dimensionality reduction while keeping those features that describe a large amount of the information. Consequently, this pre-processing stage follows these steps:"
},
{
"code": null,
"e": 2270,
"s": 2092,
"text": "Data Cleaning: Cleaning the data to have a common scale. For the case of the products, dataset consists of a simple text cleaning for cases, white spaces, encoding, and symbols."
},
{
"code": null,
"e": 2399,
"s": 2270,
"text": "Features Selection: Using the PCA technic a set of features are selected.(“titleChunk”, “contentChunk”, “color”, “ productType”)"
},
{
"code": null,
"e": 2508,
"s": 2399,
"text": "The content found on the features above contains most of the discrepancies for candidate duplicate products."
},
{
"code": null,
"e": 2723,
"s": 2508,
"text": "Locality-sensitive hashing is a technic used for entity resolution, then records that represent the same entity will be found. The spark MLlib has a custom LSH implementation used here to find duplicates as follow:"
},
{
"code": null,
"e": 2974,
"s": 2723,
"text": "First, hashes are generated using a concatenation of selected features (PC above). For a real-world example hashes for each feature could be generated. However, for this example and in order to get results faster a simple concatenated column is used."
},
{
"code": null,
"e": 3038,
"s": 2974,
"text": "Then, this column is used for generating LSH vectors as follow:"
},
{
"code": null,
"e": 3116,
"s": 3038,
"text": "— A tokenizer generates the list of words for a record using a words stopper."
},
{
"code": null,
"e": 3225,
"s": 3116,
"text": "— A CountVectorizerModel creates the vectors with hashes and buckets (similar hashes) for the LSH algorithm."
},
{
"code": null,
"e": 4403,
"s": 3225,
"text": "val pccTokenizer = new Tokenizer() .setInputCol(OperationsHelperLSH.ConcatComments) .setOutputCol(OperationsHelperLSH.ColumnWordsArray)val wordsArrayDF = pccTokenizer.transform(df)val remover = new StopWordsRemover() .setCaseSensitive(false) .setStopWords(OperationsHelperLSH.stopWords) .setInputCol(OperationsHelperLSH.ColumnWordsArray) .setOutputCol(OperationsHelperLSH.ColumnFilteredWordsArray)val wordsFiltered = remover.transform(wordsArrayDF)val validateEmptyVector = udf({ v: Vector => v.numNonzeros > 0 }, DataTypes.BooleanType)val vectorModeler: CountVectorizerModel = new CountVectorizer() .setInputCol(OperationsHelperLSH.ColumnFilteredWordsArray) .setOutputCol(OperationsHelperLSH.ColumnFeaturesArray) .setVocabSize(VocabularySHLSize) .setMinDF(10) .fit(wordsFiltered)val vectorizedProductsDF = vectorModeler.transform(wordsFiltered) .filter(validateEmptyVector(col(OperationsHelperLSH.ColumnFeaturesArray))) .select(col(OperationsHelperWindowStrategy.ConcatComments), col(OperationsHelperLSH.ColumnUniqueId), col(OperationsHelperLSH.ColumnFilteredWordsArray), col(OperationsHelperLSH.ColumnFeaturesArray))(vectorizedProductsDF, vectorModeler)"
},
{
"code": null,
"e": 4456,
"s": 4403,
"text": "Class: com.sample.products.OperationsHelperLSH.scala"
},
{
"code": null,
"e": 4598,
"s": 4456,
"text": "In order to finish the training step, a MinHashLSHModel is used to train the products data, generating the final buckets of similar products."
},
{
"code": null,
"e": 4663,
"s": 4598,
"text": "Finally, using KNN similar hashes for a category could be found."
},
{
"code": null,
"e": 5597,
"s": 4663,
"text": " /** * Uses the dataset to train the model. * */ def deduplicateDataSet(df: DataFrame): (DataFrame, MinHashLSHModel) = { val minLshConfig = new MinHashLSH().setNumHashTables(hashesNumber) .setInputCol(OperationsHelperLSH.ColumnFeaturesArray) .setOutputCol(OperationsHelperLSH.hashValuesColumn) val lshModel = minLshConfig.fit(df) (lshModel.transform(df), lshModel) } /** * Applies KNN to find similar records. * */ def filterResults(df: DataFrame, vectorModeler: CountVectorizerModel, lshModel: MinHashLSHModel, categoryQuery: (String, String) ): DataFrame = { val key = Vectors.sparse(VocabularySHLSize, Seq((vectorModeler.vocabulary.indexOf(categoryQuery._1), 1.0), (vectorModeler.vocabulary.indexOf(categoryQuery._2), 1.0))) lshModel.approxNearestNeighbors(df, key, nearNeighboursNumber).toDF()}"
},
{
"code": null,
"e": 5728,
"s": 5597,
"text": "To run an example: Go to the test com.sample.processor.products.ProcessorProductsLshTest and you will see a complete flow running."
},
{
"code": null,
"e": 5742,
"s": 5728,
"text": "Input Params:"
},
{
"code": null,
"e": 5794,
"s": 5742,
"text": "category → color = ‘negro’ and productType = ‘tdi’."
},
{
"code": null,
"e": 5819,
"s": 5794,
"text": "nearNeighboursNumber → 4"
},
{
"code": null,
"e": 5890,
"s": 5819,
"text": "hashesNumber → 3 (More hashes more precision but more computing cost)."
},
{
"code": null,
"e": 5896,
"s": 5890,
"text": "Pros:"
},
{
"code": null,
"e": 6057,
"s": 5896,
"text": "Accurate: If a complete set of fields (representing the string) is used, the correct value for hashes and neighbors could detect almost all the repeated values."
},
{
"code": null,
"e": 6131,
"s": 6057,
"text": "Faster: compared with other ML strategies as Term-frequency-inverse, etc."
},
{
"code": null,
"e": 6138,
"s": 6131,
"text": "Cons :"
},
{
"code": null,
"e": 6179,
"s": 6138,
"text": "A cluster with good resources is needed."
},
{
"code": null,
"e": 6214,
"s": 6179,
"text": "Needs a process for data cleaning."
},
{
"code": null,
"e": 6661,
"s": 6214,
"text": "Levenshtein is an algorithm used for strings fuzzy matching. Basically, this method measures the difference between two strings. Furthermore, the spark windows functions allow dataset analytics function in a concise way, avoiding multiple groupBy and Join operations. Thus, this method defines a 2-level window to group similar data and then applies Levenshtein to values in the same windows to discover duplicates. The process is described here:"
},
{
"code": null,
"e": 6900,
"s": 6661,
"text": "First of all, a set of records described as non-fuzzy is selected. The list contains columns that represent categories and are were free of errors most of the times in the PCA process: (“productType”, “city”, “country”, “region”, “year”)."
},
{
"code": null,
"e": 6966,
"s": 6900,
"text": "This window represents the general windows hash for the analysis."
},
{
"code": null,
"e": 7208,
"s": 6966,
"text": "Secondly, a second window to discover quite similar records is applied. This list represents records that are neither part from the fuzzy list (PCA) nor from the non-fuzzy list: (“doors”, “fuel”, “make”, “mileage”, “model”, “color”, “price”)"
},
{
"code": null,
"e": 7276,
"s": 7208,
"text": "Note: the “date” field helps to order and get only the most recent."
},
{
"code": null,
"e": 7453,
"s": 7276,
"text": "Then, For each group applies levenshtein (string difference only in the second window) over the concatenated most fuzzy fields from PCA results: (“titleChunk”, “contentChunk”)."
},
{
"code": null,
"e": 7564,
"s": 7453,
"text": "As you can see an MD5 representation of the columns is used instead of each String to have better performance:"
},
{
"code": null,
"e": 7670,
"s": 7564,
"text": "keyhash: MD5 for the category column set. The picture below shows many products within the same category."
},
{
"code": null,
"e": 7942,
"s": 7670,
"text": "hashDiff: MD5 hash that represents the non-fuzzy set. The picture below shows products within the same category but with a different description (> levenshteinThreshold) and also those with a small levenshtein (< levenshteinThreshold) difference having the same hashDiff."
},
{
"code": null,
"e": 8092,
"s": 7942,
"text": "Finally, the values with the same hashes (both) and rank only change the row_num. Filtering row_num == 1 is possible to get the deduplicate Data set."
},
{
"code": null,
"e": 8840,
"s": 8092,
"text": "/** * Applies windows functions and Levenshtein to group similar categories. * */override def deduplicateDataSet()(df: DataFrame): DataFrame = { df .withColumn(OperationsHelperWindowStrategy.ColumnRank, dense_rank().over(windowProductKeyHash)) .withColumn(OperationsHelperWindowStrategy.ColumnHashWithDiff, concat(col(OperationsHelperWindowStrategy.ColumnCategoryFieldsHash), when(levenshtein( first(OperationsHelperWindowStrategy.ConcatComments).over(windowProductsCategoryRank), col(OperationsHelperWindowStrategy.ConcatComments)) >= levenshteinThreshold, lit(\"1\")) .otherwise(lit(\"\")))) .withColumn(OperationsHelperWindowStrategy.ColumnRowNum, row_number().over(windowProductsCategoryRank))}"
},
{
"code": null,
"e": 8904,
"s": 8840,
"text": "Class: com.sample.products.OperationsHelperWindowStrategy.scala"
},
{
"code": null,
"e": 9039,
"s": 8904,
"text": "To run an example: Go to the test com.sample.processor.products.ProcessorProductsWindowsTest and you will see a complete flow running."
},
{
"code": null,
"e": 9078,
"s": 9039,
"text": "Input Params: levenshteinThreshold → 6"
},
{
"code": null,
"e": 9087,
"s": 9078,
"text": "Results:"
},
{
"code": null,
"e": 9195,
"s": 9087,
"text": "The results are deduplicated after filtering rn == 1. This removes > 1/3 of the data in the sample dataset."
},
{
"code": null,
"e": 9201,
"s": 9195,
"text": "Pros:"
},
{
"code": null,
"e": 9254,
"s": 9201,
"text": "More control in the spark partitioner and functions."
},
{
"code": null,
"e": 9261,
"s": 9254,
"text": "Cons :"
},
{
"code": null,
"e": 9299,
"s": 9261,
"text": "Could have much more false positives."
}
] |
Program to find number of ways to arrange n rooks so that they cannot attack each other in Python
|
Suppose we have a number n representing a chessboard of size n x n. We have to find the
number of ways we can place n rooks, such that they cannot attack each other. Here two ways
will be considered different if in one of the ways, some cell of the chessboard is occupied, and
another way, the cell is not occupied. (We know that rooks can attack each other if they are
either on the same row or on the same column).
So, if the input is like 3, then the output will be 6
To solve this, we will follow these steps −
f = factorial of n
return f
Let us see the following implementation to get better understanding −
Live Demo
import math
class Solution:
def solve(self, n):
return math.factorial(n)
ob = Solution()
print(ob.solve(3))
3
6
|
[
{
"code": null,
"e": 1479,
"s": 1062,
"text": "Suppose we have a number n representing a chessboard of size n x n. We have to find the\nnumber of ways we can place n rooks, such that they cannot attack each other. Here two ways\nwill be considered different if in one of the ways, some cell of the chessboard is occupied, and\nanother way, the cell is not occupied. (We know that rooks can attack each other if they are\neither on the same row or on the same column)."
},
{
"code": null,
"e": 1533,
"s": 1479,
"text": "So, if the input is like 3, then the output will be 6"
},
{
"code": null,
"e": 1577,
"s": 1533,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1596,
"s": 1577,
"text": "f = factorial of n"
},
{
"code": null,
"e": 1605,
"s": 1596,
"text": "return f"
},
{
"code": null,
"e": 1675,
"s": 1605,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1686,
"s": 1675,
"text": " Live Demo"
},
{
"code": null,
"e": 1803,
"s": 1686,
"text": "import math\nclass Solution:\n def solve(self, n):\n return math.factorial(n)\nob = Solution()\nprint(ob.solve(3))"
},
{
"code": null,
"e": 1805,
"s": 1803,
"text": "3"
},
{
"code": null,
"e": 1807,
"s": 1805,
"text": "6"
}
] |
15 Git Commands To Master Before Your Very First Project | by AnBento | Towards Data Science
|
You just started your first project as a web developer and wish to keep track of a multitude of changes in your working directory? You finally got selected for an interview as a junior data engineer and feel a bit rusty on the version control topic? Or you simply work in data science and want to learn more about Git and the command line to show your team that you can achieve the same result without using any GUI at all?
If you answered “Yes, here I am!” to at least one of the profiles above, then this tutorial can definitely help you to learn more about version control through the command line and it will do it quickly!
As many other Data Analysts and BI Developers, I got to know version control trough the GitHub GUI. At that time, my company was using Looker as a visualisation tool and it could be configured with a handy Git integration to manage file versions while in development mode.
Every step was so visually appealing and user-friendly while committing and deploying changes, that I did not learn about the true Git potential until a data engineer one day told me: “Version control? I am always using the same 4–5 commands in my terminal and job done! I rarely access the user interface”.
And then he just typed another git push origin master while I stared at his laptop in admiration. And that’s when I realised that the next step would have been for me to learn the command line and how to version control with Git.
In the rest of this tutorial, you will find the 15 commands that I use the most while working on my projects.
towardsdatascience.com
Git is a command line tool used for version control, you can access by simply typing git in the shell. The first step is to create a new directory and initialise a repository:
$ mkdir medium_git$ cd medium_git/
I have created a medium_git folder that I will use for the rest of this tutorial and that will include a list of all the commands discussed below. It can be found in my code_tutorials repository in GitHub.
1. git init → This command initialize a repository inside the medium_git folder meaning that now on, it will track multiple versions of the files in the folder. Initializing a Git repository will also create a dir called .git inside the repository folder. Files and folders with a period prefix (.) are typically private, and don’t show up by default when you list the files in a folder unless the ls -a command is used:
$ git initInitialized empty Git repository in /Users/antonellobenedetto/Documents/medium_git/.git/$ ls -a. .. .git
Then let’s create a markdown file (.md) named git_commands, that only includes a brief description of what git init does and save it in the medium_git repository.
2. git add → In git, files can be in one of the following three states: modified, staged, committed. If you are ready to commit files you have modified, you can add them to the staging area with the git add [file name] command. Staged files are then marked for inclusion in the next commit without being committed yet:
$ cat git_commands.md1. git init <-- initializes a repository inside the folder$ git add git_commands.md
You could have achieved the same result with git add .(or using a wildcard git add *) . The only difference is that, in this way, all the files in the repository will be staged at the same time.
3. git config user.name/user.email → Before your first commit, it’s good practice to tell git who you are. This is particularly important when you are working in a team so that each member can identify who made a certain commit:
$ git config --global user.name ‘anbento’$ git config --global user.email ‘[email protected]’
If you wish to check your configuration settings, type git config -l.
4. git commit -m ‘ your message’ → A commit stores a snapshot of the files in the repository at a certain point in time. By building a history of these snapshots, you can rewind to an earlier point in time. The -m flag indicates that you’re adding a message and the text in quotes that comes after it is the commit message itself. It’s customary to make the commit message something informative, so if we do have to rewind or merge code, it’s obvious what changes have been made and when:
$ git commit -m ‘Adding git_commands.md file’[master (root-commit) 815d087] Adding git_commands.md file1 file changed, 3 insertions(+)create mode 100644 git_commands.md
5. git log → You can pull up a repository’s commit history using this command. Each commit is assigned with a 40 char long unique ID or hash. Commit hashes are permanent meaning that Git preserves them and includes them in transfers between the local and remote repos. Also notice how the name and email of the commit author are displayed under each commit history:
$ git logcommit 815d087f132288112b7e427617be0408e6db4974 (HEAD -> master)Author: anbento <[email protected]>Date: Sat Apr 4 08:19:16 2020 +0100Adding git_commands.md file
6. git remote add [remote name][remote url] → At some point, you may wish to push your changes to (for example) a repository on GitHub, so that you can access your full project history using other devices or just to collaborate with your team. In order to do that, you first have to create the repository itself and then run the command in the terminal:
$ git remote add origin https://github.com/anbento0490/code_tutorials.git$ git remote -vorigin https://github.com/anbento0490/code_tutorials.git (fetch)origin https://github.com/anbento0490/code_tutorials.git (push)
In this case, firstly I have created the code_tutorials repository on my GitHub account and then I added it as a remote under the origin alias. Bear in mind that “origin” is just a name assigned by convention, but you are free to name the remote differently if you wish. By specifying the -v option, you can retrieve the full remote url assigned to each alias. If you made a mistake and wish to remove the remote, simply run the git remote remove origin command.
7. git push [remote name] [branch name] → Once you have made changes to the local version of the repo, you can push them to the remote repo so that your project is safely stored in the cloud with its entire commits history. This means that even if your laptop crashes or gets stolen, your work won’t be lost and could be retrieved from your GitHub account. To accomplish that, you need to push the master branch to the remote “origin” repo:
$ git push origin masterCounting objects: 3, done.Delta compression using up to 4 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 282 bytes | 282.00 KiB/s, done.Total 3 (delta 0), reused 0 (delta 0)To https://github.com/anbento0490/code_tutorials.git* [new branch] master -> master
Once you do that, files that were originally only available in the local working directory will be uploaded in your remote repo as well as info about your commits:
8. git clone [repository url] [folder name]→ If you or one of your colleagues wished to download your project folder on another device, you could do that by cloning the remote repository locally. In my case, I moved back to the home directory and cloned the repository assigning the original name medium_git:
$ git clone https://github.com/anbento0490/code_tutorials.git medium_gitCloning into ‘medium_git’...remote: Enumerating objects: 3, done.remote: Counting objects: 100% (3/3), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.
The command above, not only creates a directory named “medium_git” but it will also initialise a .git directory inside it, pull down all the data for that repository, and checks out a working copy of the latest version.
The very first time you try to clone a private repo from a remote repository, you will be asked to provide username and password (unless already using SSH Key to connect to GitHub). Credentials can be embedded directly in the url in this way:
git clone https://your_username:[email protected]/anbento0490/repo_name.git
After you provide authentication once, Git caches your credentials in memory and hands them out on demand. If the git config credential.helper command return manager, the password is stored in the windows credential manager, if it returns store, password is stored in a .git-credentials file in the user folder and if it returns oskeychain it’s stored in keychain.
9. git pull [remote name] [branch name] → When the latest commit in the local repo is older than the latest commit in the remote repo, you can use git pull to update the working directory so that it has the same files as the latest commit. For this tutorial, to simulate what usually happens in a collaborative environment, I have edited the git_commands.md file directly in GitHub adding more commands to the list and committed the changes:
This action has created a new commit with a unique identifier. The commit and the changes are only visible in the remote repo, before the following command is run:
$ git pull origin masterremote: Enumerating objects: 5, done.remote: Counting objects: 100% (5/5), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.From https://github.com/anbento0490/code_tutorials* branch master -> FETCH_HEAD815d087..b3088e3 master -> origin/masterUpdating 815d087..b3088e3Fast-forwardgit_commands.md | 10 +++++++++-1 file changed, 9 insertions(+), 1 deletion(-)
10. git diff [HEAD~1] [HEAD]→ If you now run git log after pulling from the remote repo, you will see two commits, with the one on the top, being the most recent. To see the difference between the 2 commits just type:
$ git diff HEAD~1 HEADdiff — git a/git_commands.md b/git_commands.mdindex ddd61c8..3cb7e12 100644— — a/git_commands.md+++ b/git_commands.md@@ -1,3 +1,11 @@+Git 15 Most Used Commands1. git init ← initializes a repository inside the folder+2. git add+3. git config user.name/user.email+4. git commit -m ‘ your message’+5. git log+6. git remote add [remote name][remote url]+7. git push [remote name] [branch name]+8. git clone [repository url] [folder name]+9. git pull [remote name] [branch name]
Instead of typing the first 3–4 chars of each hash, you can use the special variable called HEAD that always refers to the most recent commit in the current branch. You can also use shortcuts to get older commit hashes with HEAD~1 being the second newest commit in the local repo, HEAD~2 the third newest commit, and so on.
11. git fetch [remote name] [branch name] → Exactly like git pull , this command is used to download files and commits from a remote repository into your local repo. You can consider git fetch the more conservative version of the two commands as it will download the remote content but not update your local repo’s working state, leaving your current work intact. If you have pending changes in progress in local git fetch will avoid conflicts to arise and than is often used in a collaborative environment to see what everybody else has been working on without forcing you to actually merge the changes into your repository.
To show how useful git fetch is, I have added another command to the list in GitHub and committed the change, so that the remote repository has again more commits than the local one. The third commit ID starts with 40ae0be and you can verify that by running the following 3 commands:
$ git fetch origin masterremote: Enumerating objects: 5, done.remote: Counting objects: 100% (5/5), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.From https://github.com/anbento0490/code_tutorialsb3088e3..40ae0be master -> origin/master$ git checkout origin/masterNote: checking out 'origin/master'.You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:git checkout -b <new-branch-name>HEAD is now at 40ae0be... Update git_commands.md$ git logcommit 40ae0bebb77b8df716439b94bb5005a65c0e6301 (HEAD, origin/master)Author: AnBento <[email protected]>Date: Sun Apr 5 06:56:07 2020 +0100Update git_commands.mdcommit b3088e373b881a526844826a2dade7b1443eefbb (master)Author: AnBento <[email protected]>Date: Sat Apr 4 18:39:48 2020 +0100Update git_commands.mdcommit 815d087f132288112b7e427617be0408e6db4974Author: anbento <[email protected]>Date: Sat Apr 4 08:19:16 2020 +0100Adding git_commands.md file
Because fetching does not add any of the new commits to the local repo, you should use git checkout origin/master to switch from the local branch (master) to the remote branch (origin/master) and enter a so called ‘detached HEAD state’. This allows you to explore what has been committed to remote repo by your colleagues, running familiar commands like git log and git diff .
12. git reset [ — flag][#hash] → Let’s imagine that after fetching the new commits you were happy with the changes made by your team so that you run git pull to update your local directory, but at a later stage you noticed a problem and wanted to revert back to the penultimate commit or you simply wished to see what the project looked like at an earlier point in time. In both cases you could run:
$ git reset — hard HEAD~1HEAD is now at b3088e3 Update git_commands.md
With this command Git switches back to the commit with that particular hash . As mentioned, to make your workflow quicker, you could take advantage of the special variable HEAD. The — hard flag resets both the working directory and the Git history to a specific state. If you omitted the flag, or used the — soft flag instead, it would skip making changes to the working directory, and only reset the Git history.
13. git branch [branch name] / git branch -d [branch name] → Git branches allow users to create several different work areas within the same repo. In a professional environment, is very common to create a new branch whenever you wish to make several changes to a project or to fix a bug, and then merge that branch back into the master branch when we’re done. When you initialize a new local repo, Git automatically creates the master branch:
$ git branch* master
To create new branches run the following command:
$ git branch project1/add_commands$ git branch project1/branch_to_delete$ git branch* masterproject1/add_commandsproject1/branch_to_delete
In this way you will create two branches (project1/add_commands and project1/branch_to_delete) that will now be listed together with the master branch. The name of branch should be meaningful and make apparent the reason why it has been created in the first place (add a new feature, fix a bug , perform a chore) . To delete a branch use the git branch delete [branch name] command:
$ git branch -d branch project1/branch_to_deleteDeleted branch project1/branch_to_delete (was b3088e3).
14. git checkout [branch name] → To switch to the new branch run the following command:
$ git checkout project1/add_commandsSwitched to branch ‘project1/add_commands’
A common shortcut would have been to use the git checkout -b [branch name] command that creates a new branch and switch to it right away. Once you’ve created a branch and added a commit, you can push the branch to the remote repo. This allows other people to see your changes and collaborate with you on that separate work area:
$ git push origin project1/add_commandsCounting objects: 3, done.Delta compression using up to 4 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 444 bytes | 444.00 KiB/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: Resolving deltas: 100% (1/1), completed with 1 local object.remote: Create a pull request for ‘project1/add_commands’ on GitHub by visiting:remote:https://github.com/anbento0490/code_tutorials/pull/new/project1/add_commandsremote: To https://github.com/anbento0490/code_tutorials.git* [new branch] project1/add_commands -> project1/add_commands
In my case, I have added the last 5 commands to the list and committed the changes through the project1/add_commands branch. Eventually, I pushed the commit to the remote repo so that now two branches are visible on the GitHub account, with project1/add_commands displaying one commit more than the master repo:
You can also use git branch -r to show all of the branches on the remote and confirm that yours is there. In contrast, git branch -a will show all of the branches available locally:
$ git branch -rorigin/masterorigin/project1/add_commands$ git branch -amaster* project1/add_commandsremotes/origin/masterremotes/origin/project1/add_commands
15. git merge [new_branch name] → Merging allows developers to to copy commits from one branch into another. This enables collaborative work as every team member can efficiently develop features for projects on their own branches without conflicts, then merge them into master so that end users will have access to them. To merge project1/add_commands into master, check out to to the master branch and then run the git merge command:
$ git checkout masterSwitched to branch ‘master’$ git merge project1/add_commandsUpdating b3088e3..cdb97d4Fast-forwardgit_commands.md | 8 +++++++-1 file changed, 7 insertions(+), 1 deletion(-)$ git branch -d project1/add_commandsDeleted branch project1/add_commands (was cdb97d4).
To avoid confusion, once the missing commits have been merged into the master branch, the newer local branch is often deleted.
To the ones that managed to get to the end of this tutorial I say: “Very well done!” I hope that what you learnt here, rewarded you for your patience. In this post I took you through the 15 Git commands to master before you start your first project in web development or data science, as version control is cool and will save you a lot of headaches! If you wish read even more, make sure to check this excellent Git tutorial provided by Bitbucket.
|
[
{
"code": null,
"e": 595,
"s": 171,
"text": "You just started your first project as a web developer and wish to keep track of a multitude of changes in your working directory? You finally got selected for an interview as a junior data engineer and feel a bit rusty on the version control topic? Or you simply work in data science and want to learn more about Git and the command line to show your team that you can achieve the same result without using any GUI at all?"
},
{
"code": null,
"e": 799,
"s": 595,
"text": "If you answered “Yes, here I am!” to at least one of the profiles above, then this tutorial can definitely help you to learn more about version control through the command line and it will do it quickly!"
},
{
"code": null,
"e": 1072,
"s": 799,
"text": "As many other Data Analysts and BI Developers, I got to know version control trough the GitHub GUI. At that time, my company was using Looker as a visualisation tool and it could be configured with a handy Git integration to manage file versions while in development mode."
},
{
"code": null,
"e": 1380,
"s": 1072,
"text": "Every step was so visually appealing and user-friendly while committing and deploying changes, that I did not learn about the true Git potential until a data engineer one day told me: “Version control? I am always using the same 4–5 commands in my terminal and job done! I rarely access the user interface”."
},
{
"code": null,
"e": 1610,
"s": 1380,
"text": "And then he just typed another git push origin master while I stared at his laptop in admiration. And that’s when I realised that the next step would have been for me to learn the command line and how to version control with Git."
},
{
"code": null,
"e": 1720,
"s": 1610,
"text": "In the rest of this tutorial, you will find the 15 commands that I use the most while working on my projects."
},
{
"code": null,
"e": 1743,
"s": 1720,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1919,
"s": 1743,
"text": "Git is a command line tool used for version control, you can access by simply typing git in the shell. The first step is to create a new directory and initialise a repository:"
},
{
"code": null,
"e": 1954,
"s": 1919,
"text": "$ mkdir medium_git$ cd medium_git/"
},
{
"code": null,
"e": 2160,
"s": 1954,
"text": "I have created a medium_git folder that I will use for the rest of this tutorial and that will include a list of all the commands discussed below. It can be found in my code_tutorials repository in GitHub."
},
{
"code": null,
"e": 2581,
"s": 2160,
"text": "1. git init → This command initialize a repository inside the medium_git folder meaning that now on, it will track multiple versions of the files in the folder. Initializing a Git repository will also create a dir called .git inside the repository folder. Files and folders with a period prefix (.) are typically private, and don’t show up by default when you list the files in a folder unless the ls -a command is used:"
},
{
"code": null,
"e": 2699,
"s": 2581,
"text": "$ git initInitialized empty Git repository in /Users/antonellobenedetto/Documents/medium_git/.git/$ ls -a. .. .git "
},
{
"code": null,
"e": 2862,
"s": 2699,
"text": "Then let’s create a markdown file (.md) named git_commands, that only includes a brief description of what git init does and save it in the medium_git repository."
},
{
"code": null,
"e": 3181,
"s": 2862,
"text": "2. git add → In git, files can be in one of the following three states: modified, staged, committed. If you are ready to commit files you have modified, you can add them to the staging area with the git add [file name] command. Staged files are then marked for inclusion in the next commit without being committed yet:"
},
{
"code": null,
"e": 3286,
"s": 3181,
"text": "$ cat git_commands.md1. git init <-- initializes a repository inside the folder$ git add git_commands.md"
},
{
"code": null,
"e": 3481,
"s": 3286,
"text": "You could have achieved the same result with git add .(or using a wildcard git add *) . The only difference is that, in this way, all the files in the repository will be staged at the same time."
},
{
"code": null,
"e": 3710,
"s": 3481,
"text": "3. git config user.name/user.email → Before your first commit, it’s good practice to tell git who you are. This is particularly important when you are working in a team so that each member can identify who made a certain commit:"
},
{
"code": null,
"e": 3806,
"s": 3710,
"text": "$ git config --global user.name ‘anbento’$ git config --global user.email ‘[email protected]’"
},
{
"code": null,
"e": 3876,
"s": 3806,
"text": "If you wish to check your configuration settings, type git config -l."
},
{
"code": null,
"e": 4365,
"s": 3876,
"text": "4. git commit -m ‘ your message’ → A commit stores a snapshot of the files in the repository at a certain point in time. By building a history of these snapshots, you can rewind to an earlier point in time. The -m flag indicates that you’re adding a message and the text in quotes that comes after it is the commit message itself. It’s customary to make the commit message something informative, so if we do have to rewind or merge code, it’s obvious what changes have been made and when:"
},
{
"code": null,
"e": 4534,
"s": 4365,
"text": "$ git commit -m ‘Adding git_commands.md file’[master (root-commit) 815d087] Adding git_commands.md file1 file changed, 3 insertions(+)create mode 100644 git_commands.md"
},
{
"code": null,
"e": 4900,
"s": 4534,
"text": "5. git log → You can pull up a repository’s commit history using this command. Each commit is assigned with a 40 char long unique ID or hash. Commit hashes are permanent meaning that Git preserves them and includes them in transfers between the local and remote repos. Also notice how the name and email of the commit author are displayed under each commit history:"
},
{
"code": null,
"e": 5073,
"s": 4900,
"text": "$ git logcommit 815d087f132288112b7e427617be0408e6db4974 (HEAD -> master)Author: anbento <[email protected]>Date: Sat Apr 4 08:19:16 2020 +0100Adding git_commands.md file"
},
{
"code": null,
"e": 5427,
"s": 5073,
"text": "6. git remote add [remote name][remote url] → At some point, you may wish to push your changes to (for example) a repository on GitHub, so that you can access your full project history using other devices or just to collaborate with your team. In order to do that, you first have to create the repository itself and then run the command in the terminal:"
},
{
"code": null,
"e": 5643,
"s": 5427,
"text": "$ git remote add origin https://github.com/anbento0490/code_tutorials.git$ git remote -vorigin https://github.com/anbento0490/code_tutorials.git (fetch)origin https://github.com/anbento0490/code_tutorials.git (push)"
},
{
"code": null,
"e": 6106,
"s": 5643,
"text": "In this case, firstly I have created the code_tutorials repository on my GitHub account and then I added it as a remote under the origin alias. Bear in mind that “origin” is just a name assigned by convention, but you are free to name the remote differently if you wish. By specifying the -v option, you can retrieve the full remote url assigned to each alias. If you made a mistake and wish to remove the remote, simply run the git remote remove origin command."
},
{
"code": null,
"e": 6547,
"s": 6106,
"text": "7. git push [remote name] [branch name] → Once you have made changes to the local version of the repo, you can push them to the remote repo so that your project is safely stored in the cloud with its entire commits history. This means that even if your laptop crashes or gets stolen, your work won’t be lost and could be retrieved from your GitHub account. To accomplish that, you need to push the master branch to the remote “origin” repo:"
},
{
"code": null,
"e": 6856,
"s": 6547,
"text": "$ git push origin masterCounting objects: 3, done.Delta compression using up to 4 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 282 bytes | 282.00 KiB/s, done.Total 3 (delta 0), reused 0 (delta 0)To https://github.com/anbento0490/code_tutorials.git* [new branch] master -> master"
},
{
"code": null,
"e": 7020,
"s": 6856,
"text": "Once you do that, files that were originally only available in the local working directory will be uploaded in your remote repo as well as info about your commits:"
},
{
"code": null,
"e": 7329,
"s": 7020,
"text": "8. git clone [repository url] [folder name]→ If you or one of your colleagues wished to download your project folder on another device, you could do that by cloning the remote repository locally. In my case, I moved back to the home directory and cloned the repository assigning the original name medium_git:"
},
{
"code": null,
"e": 7652,
"s": 7329,
"text": "$ git clone https://github.com/anbento0490/code_tutorials.git medium_gitCloning into ‘medium_git’...remote: Enumerating objects: 3, done.remote: Counting objects: 100% (3/3), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done."
},
{
"code": null,
"e": 7872,
"s": 7652,
"text": "The command above, not only creates a directory named “medium_git” but it will also initialise a .git directory inside it, pull down all the data for that repository, and checks out a working copy of the latest version."
},
{
"code": null,
"e": 8115,
"s": 7872,
"text": "The very first time you try to clone a private repo from a remote repository, you will be asked to provide username and password (unless already using SSH Key to connect to GitHub). Credentials can be embedded directly in the url in this way:"
},
{
"code": null,
"e": 8192,
"s": 8115,
"text": "git clone https://your_username:[email protected]/anbento0490/repo_name.git"
},
{
"code": null,
"e": 8557,
"s": 8192,
"text": "After you provide authentication once, Git caches your credentials in memory and hands them out on demand. If the git config credential.helper command return manager, the password is stored in the windows credential manager, if it returns store, password is stored in a .git-credentials file in the user folder and if it returns oskeychain it’s stored in keychain."
},
{
"code": null,
"e": 8999,
"s": 8557,
"text": "9. git pull [remote name] [branch name] → When the latest commit in the local repo is older than the latest commit in the remote repo, you can use git pull to update the working directory so that it has the same files as the latest commit. For this tutorial, to simulate what usually happens in a collaborative environment, I have edited the git_commands.md file directly in GitHub adding more commands to the list and committed the changes:"
},
{
"code": null,
"e": 9163,
"s": 8999,
"text": "This action has created a new commit with a unique identifier. The commit and the changes are only visible in the remote repo, before the following command is run:"
},
{
"code": null,
"e": 9643,
"s": 9163,
"text": "$ git pull origin masterremote: Enumerating objects: 5, done.remote: Counting objects: 100% (5/5), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.From https://github.com/anbento0490/code_tutorials* branch master -> FETCH_HEAD815d087..b3088e3 master -> origin/masterUpdating 815d087..b3088e3Fast-forwardgit_commands.md | 10 +++++++++-1 file changed, 9 insertions(+), 1 deletion(-)"
},
{
"code": null,
"e": 9861,
"s": 9643,
"text": "10. git diff [HEAD~1] [HEAD]→ If you now run git log after pulling from the remote repo, you will see two commits, with the one on the top, being the most recent. To see the difference between the 2 commits just type:"
},
{
"code": null,
"e": 10357,
"s": 9861,
"text": "$ git diff HEAD~1 HEADdiff — git a/git_commands.md b/git_commands.mdindex ddd61c8..3cb7e12 100644— — a/git_commands.md+++ b/git_commands.md@@ -1,3 +1,11 @@+Git 15 Most Used Commands1. git init ← initializes a repository inside the folder+2. git add+3. git config user.name/user.email+4. git commit -m ‘ your message’+5. git log+6. git remote add [remote name][remote url]+7. git push [remote name] [branch name]+8. git clone [repository url] [folder name]+9. git pull [remote name] [branch name]"
},
{
"code": null,
"e": 10681,
"s": 10357,
"text": "Instead of typing the first 3–4 chars of each hash, you can use the special variable called HEAD that always refers to the most recent commit in the current branch. You can also use shortcuts to get older commit hashes with HEAD~1 being the second newest commit in the local repo, HEAD~2 the third newest commit, and so on."
},
{
"code": null,
"e": 11307,
"s": 10681,
"text": "11. git fetch [remote name] [branch name] → Exactly like git pull , this command is used to download files and commits from a remote repository into your local repo. You can consider git fetch the more conservative version of the two commands as it will download the remote content but not update your local repo’s working state, leaving your current work intact. If you have pending changes in progress in local git fetch will avoid conflicts to arise and than is often used in a collaborative environment to see what everybody else has been working on without forcing you to actually merge the changes into your repository."
},
{
"code": null,
"e": 11591,
"s": 11307,
"text": "To show how useful git fetch is, I have added another command to the list in GitHub and committed the change, so that the remote repository has again more commits than the local one. The third commit ID starts with 40ae0be and you can verify that by running the following 3 commands:"
},
{
"code": null,
"e": 12962,
"s": 11591,
"text": "$ git fetch origin masterremote: Enumerating objects: 5, done.remote: Counting objects: 100% (5/5), done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.From https://github.com/anbento0490/code_tutorialsb3088e3..40ae0be master -> origin/master$ git checkout origin/masterNote: checking out 'origin/master'.You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:git checkout -b <new-branch-name>HEAD is now at 40ae0be... Update git_commands.md$ git logcommit 40ae0bebb77b8df716439b94bb5005a65c0e6301 (HEAD, origin/master)Author: AnBento <[email protected]>Date: Sun Apr 5 06:56:07 2020 +0100Update git_commands.mdcommit b3088e373b881a526844826a2dade7b1443eefbb (master)Author: AnBento <[email protected]>Date: Sat Apr 4 18:39:48 2020 +0100Update git_commands.mdcommit 815d087f132288112b7e427617be0408e6db4974Author: anbento <[email protected]>Date: Sat Apr 4 08:19:16 2020 +0100Adding git_commands.md file"
},
{
"code": null,
"e": 13339,
"s": 12962,
"text": "Because fetching does not add any of the new commits to the local repo, you should use git checkout origin/master to switch from the local branch (master) to the remote branch (origin/master) and enter a so called ‘detached HEAD state’. This allows you to explore what has been committed to remote repo by your colleagues, running familiar commands like git log and git diff ."
},
{
"code": null,
"e": 13739,
"s": 13339,
"text": "12. git reset [ — flag][#hash] → Let’s imagine that after fetching the new commits you were happy with the changes made by your team so that you run git pull to update your local directory, but at a later stage you noticed a problem and wanted to revert back to the penultimate commit or you simply wished to see what the project looked like at an earlier point in time. In both cases you could run:"
},
{
"code": null,
"e": 13810,
"s": 13739,
"text": "$ git reset — hard HEAD~1HEAD is now at b3088e3 Update git_commands.md"
},
{
"code": null,
"e": 14224,
"s": 13810,
"text": "With this command Git switches back to the commit with that particular hash . As mentioned, to make your workflow quicker, you could take advantage of the special variable HEAD. The — hard flag resets both the working directory and the Git history to a specific state. If you omitted the flag, or used the — soft flag instead, it would skip making changes to the working directory, and only reset the Git history."
},
{
"code": null,
"e": 14667,
"s": 14224,
"text": "13. git branch [branch name] / git branch -d [branch name] → Git branches allow users to create several different work areas within the same repo. In a professional environment, is very common to create a new branch whenever you wish to make several changes to a project or to fix a bug, and then merge that branch back into the master branch when we’re done. When you initialize a new local repo, Git automatically creates the master branch:"
},
{
"code": null,
"e": 14688,
"s": 14667,
"text": "$ git branch* master"
},
{
"code": null,
"e": 14738,
"s": 14688,
"text": "To create new branches run the following command:"
},
{
"code": null,
"e": 14877,
"s": 14738,
"text": "$ git branch project1/add_commands$ git branch project1/branch_to_delete$ git branch* masterproject1/add_commandsproject1/branch_to_delete"
},
{
"code": null,
"e": 15260,
"s": 14877,
"text": "In this way you will create two branches (project1/add_commands and project1/branch_to_delete) that will now be listed together with the master branch. The name of branch should be meaningful and make apparent the reason why it has been created in the first place (add a new feature, fix a bug , perform a chore) . To delete a branch use the git branch delete [branch name] command:"
},
{
"code": null,
"e": 15364,
"s": 15260,
"text": "$ git branch -d branch project1/branch_to_deleteDeleted branch project1/branch_to_delete (was b3088e3)."
},
{
"code": null,
"e": 15452,
"s": 15364,
"text": "14. git checkout [branch name] → To switch to the new branch run the following command:"
},
{
"code": null,
"e": 15531,
"s": 15452,
"text": "$ git checkout project1/add_commandsSwitched to branch ‘project1/add_commands’"
},
{
"code": null,
"e": 15860,
"s": 15531,
"text": "A common shortcut would have been to use the git checkout -b [branch name] command that creates a new branch and switch to it right away. Once you’ve created a branch and added a commit, you can push the branch to the remote repo. This allows other people to see your changes and collaborate with you on that separate work area:"
},
{
"code": null,
"e": 16453,
"s": 15860,
"text": "$ git push origin project1/add_commandsCounting objects: 3, done.Delta compression using up to 4 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 444 bytes | 444.00 KiB/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: Resolving deltas: 100% (1/1), completed with 1 local object.remote: Create a pull request for ‘project1/add_commands’ on GitHub by visiting:remote:https://github.com/anbento0490/code_tutorials/pull/new/project1/add_commandsremote: To https://github.com/anbento0490/code_tutorials.git* [new branch] project1/add_commands -> project1/add_commands"
},
{
"code": null,
"e": 16765,
"s": 16453,
"text": "In my case, I have added the last 5 commands to the list and committed the changes through the project1/add_commands branch. Eventually, I pushed the commit to the remote repo so that now two branches are visible on the GitHub account, with project1/add_commands displaying one commit more than the master repo:"
},
{
"code": null,
"e": 16947,
"s": 16765,
"text": "You can also use git branch -r to show all of the branches on the remote and confirm that yours is there. In contrast, git branch -a will show all of the branches available locally:"
},
{
"code": null,
"e": 17105,
"s": 16947,
"text": "$ git branch -rorigin/masterorigin/project1/add_commands$ git branch -amaster* project1/add_commandsremotes/origin/masterremotes/origin/project1/add_commands"
},
{
"code": null,
"e": 17540,
"s": 17105,
"text": "15. git merge [new_branch name] → Merging allows developers to to copy commits from one branch into another. This enables collaborative work as every team member can efficiently develop features for projects on their own branches without conflicts, then merge them into master so that end users will have access to them. To merge project1/add_commands into master, check out to to the master branch and then run the git merge command:"
},
{
"code": null,
"e": 17821,
"s": 17540,
"text": "$ git checkout masterSwitched to branch ‘master’$ git merge project1/add_commandsUpdating b3088e3..cdb97d4Fast-forwardgit_commands.md | 8 +++++++-1 file changed, 7 insertions(+), 1 deletion(-)$ git branch -d project1/add_commandsDeleted branch project1/add_commands (was cdb97d4)."
},
{
"code": null,
"e": 17948,
"s": 17821,
"text": "To avoid confusion, once the missing commits have been merged into the master branch, the newer local branch is often deleted."
}
] |
Java program to calculate the factorial of a given number using while loop
|
A factorial of a particular number (n) is the product of all the numbers from 0 to n (including n) i.e. Factorial of the number 5 will be 1*2*3*4*5 = 120.
To find the factorial of a given number.
Create a variable factorial initialize it with 1.
start while loop with condition i (initial value 1) less than the given number.
In the loop, multiple factorials with i and assign it to factorial and increment i.
Finally, print the value of factorial.
import java.util.Scanner;
public class FactorialWithWhileLoop {
public static void main(String args[]){
int i =1, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
while(i <=number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: "+factorial);
}
}
Enter the number to which you need to find the factorial:
5
Factorial of the given number is:: 120
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "A factorial of a particular number (n) is the product of all the numbers from 0 to n (including n) i.e. Factorial of the number 5 will be 1*2*3*4*5 = 120."
},
{
"code": null,
"e": 1259,
"s": 1217,
"text": " To find the factorial of a given number."
},
{
"code": null,
"e": 1310,
"s": 1259,
"text": " Create a variable factorial initialize it with 1."
},
{
"code": null,
"e": 1391,
"s": 1310,
"text": " start while loop with condition i (initial value 1) less than the given number."
},
{
"code": null,
"e": 1476,
"s": 1391,
"text": " In the loop, multiple factorials with i and assign it to factorial and increment i."
},
{
"code": null,
"e": 1516,
"s": 1476,
"text": " Finally, print the value of factorial."
},
{
"code": null,
"e": 1986,
"s": 1516,
"text": "import java.util.Scanner;\npublic class FactorialWithWhileLoop {\n public static void main(String args[]){\n int i =1, factorial=1, number;\n System.out.println(\"Enter the number to which you need to find the factorial:\");\n Scanner sc = new Scanner(System.in);\n number = sc.nextInt();\n\n while(i <=number) {\n factorial = factorial * i;\n i++;\n }\n System.out.println(\"Factorial of the given number is:: \"+factorial);\n }\n}"
},
{
"code": null,
"e": 2085,
"s": 1986,
"text": "Enter the number to which you need to find the factorial:\n5\nFactorial of the given number is:: 120"
}
] |
Generating fake data with Python, Numpy, and Faker | Towards Data Science
|
The first step in data analysis is finding data to analyze.
All too often, this crucial first step is next to impossible. Data that meets our needs may be proprietary, expensive, hard to collect, or simply may not exist.
Finding a suitable dataset is the most common problem I face when wanting to try out a new library or technique — or beginning to write a new article.
Here we solve this problem, once and for all, by creating our own dataset!
Here we will create a dataset for an imaginary widget factory.
Our widget factory has employees whose only job is to make widgets. The factory monitors widget making productivity by counting the number of widgets made and how fast the workers can make them. Making a widget consists of three steps, all of which are timed by the widget monitoring system.
Let’s get started making our fake widget factory dataset!
We can use the amazing package, Faker to get started. Faker is self described as “a Python package that generates fake data for you.”
Faker is available on PYPI and is easily installable with pip install faker.
Let’s initialize a faker generator and start making some data:
# initialize a generatorfake = Faker()#create some fake dataprint(fake.name())print(fake.date_between(start_date='-30y', end_date='today'))print(fake.color_name())>>> Bruce Clark>>> 1996-08-24>>> LimeGreen
Faker also has a method to quickly generate a fake profile!
print(fake.profile()>>> { 'address': '56393 Steve Lock\nNew Paul, FL 14937',>>> 'birthdate': datetime.date(1968, 1, 2),>>> 'blood_group': 'O+',>>> 'company': 'Hernandez, Keller and Montes',>>> 'current_location': (Decimal('66.6508355'),>>> Decimal('54.569691')),>>> 'job': 'Museum education officer',>>> 'mail': '[email protected]',>>> 'name': 'Kim Stephens',>>> 'residence': '0248 Patricia Street >>> Apt. 507\nEast Dustin, WV 65366',>>> 'sex': 'F',>>> 'ssn': '248-78-5827',>>> 'username': 'ruizdavid',>>> 'website': ['https://www.garcia-garza.org/',>>> 'https://www.williamson.info/']}
While this is very cool, it's not super helpful for our widget factory just yet.
We need to create multiple examples of each element. We can do this with a list comprehension:
# create a list of color namescolors = [fake.color_name() for x in range(4)]print(colors)>>> ['LightCoral', 'Yellow', 'WhiteSmoke', 'LightGray']
Now we’re getting somewhere! The profile method gives a little bit more information for each worker than what we need — Our widget factory keeps minimal records on each worker!
Let’s start creating a dataframe of workers, with only the information we’re interested in. We’ll use a list comprehension to generate a dictionary of worker information with the worker’s name and hire date:
fake_workers = [ {'Worker Name':fake.name(), 'Hire Date':fake.date_between(start_date='-30y', end_date='today') } for x in range(10)] print(fake_workers)
This is a great start! But, what if we want to assign each worker to a team? If we just use Faker we would have a huge number of teams with potentially only one worker per team.
Let’s say we want to create four teams and evenly divide the workers between them. We can use NumPy’s random sampling for this task.
Numpy’s random sampling module contains many methods for generating pseudo random numbers. Here we’ll explore just a few of the available options.
We can use numpy.random.choice to randomly select a color from our colors list we created using Faker above:
# numpys random choice to select a color from our colors listnp.random.choice(colors)>>> Yellow
Alone, this is not super useful, as we only have one randomly selected color. Let's\ use a list comprehension to randomly select several colors:
# generate an array of colors with a list comprehension[np.random.choice(colors) for x in range(5)]>>> ['WhiteSmoke',>>> 'WhiteSmoke', >>> 'Yellow', >>> 'WhiteSmoke', >>> 'LightGray']
Now we’re getting somewhere! What if we want to select colors from the colors list with differing probabilities?
numpy.random.choice takes an optional argument p that allows us to specify the probability of each item. (When p is not specified a uniform distribution is assumed.)
Let’s specify probabilities for our colors:
# generate an array of colors with differing probabilities[np.random.choice(colors, p=[0.1, 0.6, 0.1, 0.2]) for x in range(10)]>>>['LightGray',>>> 'LightCoral',>>> 'LightGray',>>> 'LightGray',>>> 'LightCoral',>>> 'WhiteSmoke',>>> 'Yellow',>>> 'Yellow',>>> 'Yellow',>>> 'Yellow']
We can see that yellow and light gray are more common in the output! Due to the small sample size the distributions are not exactly as specified. We would need to increase the sample size to approach our specified probabilities.
We can also generate data based on a specified distribution. Here we randomly generate several distributions and visualize with a histogram:
# generate normal distributionnormal_dist = np.random.normal(loc=5, scale=1, size=1000)# generate gamma distributiongamma_dist = np.random.gamma(shape=3, scale=1, size=1000)# generate exponential distributionexp_dist = np.random.exponential(scale=4, size=1000)# histograms to visualize the distributionsfig, [ax1, ax2, ax3] = plt.subplots(1,3)ax1.hist(normal_dist)ax1.set_title('Normal Distribution')ax2.hist(gamma_dist)ax2.set_title('Gamma Distribution')ax3.hist(exp_dist)ax3.set_title('Exponential Distribution')plt.show()
These are looking good! Let’s put everything together and create our fake widget factory dataset!
We’ll create two dataframes: One for worker data and one for widget data.
We will create an employee roster dataset that contains employee id, name, hire date, status, and team using Faker, Numpy, and list comprehensions.
First, we create a function, make_workers(). This function will take one argument, num, which will represent the number of employees to generate.
We use np.random.choice to assign each employee to a team, using the default uniform distribution, and to assign each employee to a status of full time, part time, or per diem by specifying probabilities.
This looks great! Now let’s create some widget data.
We’ll begin by randomly assigning each widget an item number using the built in id() method.
From the documentation, id() “return[s] the ‘identity’ of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime”. Because we’re iterating through the same range each time our make_widget_data() function is called, we will create duplicate item numbers. To solve this problem we’ll append the worker id to the item number to guarantee uniqueness.
Next, we’ll assume in widget creation there are three steps. For each step, we’ll generate a different random distribution that will represent the amount of time the step took to complete.
Next, we assume that employees do not all work at the same rate — and that full time workers will complete more widgets than part time workers.
To reflect this in the data, we iterate through the worker_df, created above and randomly select a number of widgets created by each worker based on their status.
We’ll create an empty list to store dataframes for each worker’s widgets, and then finally concatenate the list of dataframes into one final widget dataframe:
The widget factory workers were busy! They created 2817285 widgets!
Finally, we can save our datasets to be used for future analyses:
worker_df.to_csv('data/workers.csv', index=False)widget_df.to_csv('data/widgets.csv', index=False)
Here we explored the Python package Faker and Numpy’s Random Sampling module.
Faker makes it easy to generate a wide variety of data, including names, addresses, and dates.
Numpy’s random sampling module allows us to generate specific distributions and pseudo randomly select items from lists.
We were able to generate fake data for an imaginary widget factory. We created two datasets, one with worker details, and the second with widget creation data.
In future articles, we’ll explore this fake data, perform exploratory analysis, and generate reports for the widget managers.
|
[
{
"code": null,
"e": 232,
"s": 172,
"text": "The first step in data analysis is finding data to analyze."
},
{
"code": null,
"e": 393,
"s": 232,
"text": "All too often, this crucial first step is next to impossible. Data that meets our needs may be proprietary, expensive, hard to collect, or simply may not exist."
},
{
"code": null,
"e": 544,
"s": 393,
"text": "Finding a suitable dataset is the most common problem I face when wanting to try out a new library or technique — or beginning to write a new article."
},
{
"code": null,
"e": 619,
"s": 544,
"text": "Here we solve this problem, once and for all, by creating our own dataset!"
},
{
"code": null,
"e": 682,
"s": 619,
"text": "Here we will create a dataset for an imaginary widget factory."
},
{
"code": null,
"e": 974,
"s": 682,
"text": "Our widget factory has employees whose only job is to make widgets. The factory monitors widget making productivity by counting the number of widgets made and how fast the workers can make them. Making a widget consists of three steps, all of which are timed by the widget monitoring system."
},
{
"code": null,
"e": 1032,
"s": 974,
"text": "Let’s get started making our fake widget factory dataset!"
},
{
"code": null,
"e": 1166,
"s": 1032,
"text": "We can use the amazing package, Faker to get started. Faker is self described as “a Python package that generates fake data for you.”"
},
{
"code": null,
"e": 1243,
"s": 1166,
"text": "Faker is available on PYPI and is easily installable with pip install faker."
},
{
"code": null,
"e": 1306,
"s": 1243,
"text": "Let’s initialize a faker generator and start making some data:"
},
{
"code": null,
"e": 1512,
"s": 1306,
"text": "# initialize a generatorfake = Faker()#create some fake dataprint(fake.name())print(fake.date_between(start_date='-30y', end_date='today'))print(fake.color_name())>>> Bruce Clark>>> 1996-08-24>>> LimeGreen"
},
{
"code": null,
"e": 1572,
"s": 1512,
"text": "Faker also has a method to quickly generate a fake profile!"
},
{
"code": null,
"e": 2189,
"s": 1572,
"text": "print(fake.profile()>>> { 'address': '56393 Steve Lock\\nNew Paul, FL 14937',>>> 'birthdate': datetime.date(1968, 1, 2),>>> 'blood_group': 'O+',>>> 'company': 'Hernandez, Keller and Montes',>>> 'current_location': (Decimal('66.6508355'),>>> Decimal('54.569691')),>>> 'job': 'Museum education officer',>>> 'mail': '[email protected]',>>> 'name': 'Kim Stephens',>>> 'residence': '0248 Patricia Street >>> Apt. 507\\nEast Dustin, WV 65366',>>> 'sex': 'F',>>> 'ssn': '248-78-5827',>>> 'username': 'ruizdavid',>>> 'website': ['https://www.garcia-garza.org/',>>> 'https://www.williamson.info/']}"
},
{
"code": null,
"e": 2270,
"s": 2189,
"text": "While this is very cool, it's not super helpful for our widget factory just yet."
},
{
"code": null,
"e": 2365,
"s": 2270,
"text": "We need to create multiple examples of each element. We can do this with a list comprehension:"
},
{
"code": null,
"e": 2510,
"s": 2365,
"text": "# create a list of color namescolors = [fake.color_name() for x in range(4)]print(colors)>>> ['LightCoral', 'Yellow', 'WhiteSmoke', 'LightGray']"
},
{
"code": null,
"e": 2687,
"s": 2510,
"text": "Now we’re getting somewhere! The profile method gives a little bit more information for each worker than what we need — Our widget factory keeps minimal records on each worker!"
},
{
"code": null,
"e": 2895,
"s": 2687,
"text": "Let’s start creating a dataframe of workers, with only the information we’re interested in. We’ll use a list comprehension to generate a dictionary of worker information with the worker’s name and hire date:"
},
{
"code": null,
"e": 3076,
"s": 2895,
"text": "fake_workers = [ {'Worker Name':fake.name(), 'Hire Date':fake.date_between(start_date='-30y', end_date='today') } for x in range(10)] print(fake_workers)"
},
{
"code": null,
"e": 3254,
"s": 3076,
"text": "This is a great start! But, what if we want to assign each worker to a team? If we just use Faker we would have a huge number of teams with potentially only one worker per team."
},
{
"code": null,
"e": 3387,
"s": 3254,
"text": "Let’s say we want to create four teams and evenly divide the workers between them. We can use NumPy’s random sampling for this task."
},
{
"code": null,
"e": 3534,
"s": 3387,
"text": "Numpy’s random sampling module contains many methods for generating pseudo random numbers. Here we’ll explore just a few of the available options."
},
{
"code": null,
"e": 3643,
"s": 3534,
"text": "We can use numpy.random.choice to randomly select a color from our colors list we created using Faker above:"
},
{
"code": null,
"e": 3739,
"s": 3643,
"text": "# numpys random choice to select a color from our colors listnp.random.choice(colors)>>> Yellow"
},
{
"code": null,
"e": 3884,
"s": 3739,
"text": "Alone, this is not super useful, as we only have one randomly selected color. Let's\\ use a list comprehension to randomly select several colors:"
},
{
"code": null,
"e": 4076,
"s": 3884,
"text": "# generate an array of colors with a list comprehension[np.random.choice(colors) for x in range(5)]>>> ['WhiteSmoke',>>> 'WhiteSmoke', >>> 'Yellow', >>> 'WhiteSmoke', >>> 'LightGray']"
},
{
"code": null,
"e": 4189,
"s": 4076,
"text": "Now we’re getting somewhere! What if we want to select colors from the colors list with differing probabilities?"
},
{
"code": null,
"e": 4355,
"s": 4189,
"text": "numpy.random.choice takes an optional argument p that allows us to specify the probability of each item. (When p is not specified a uniform distribution is assumed.)"
},
{
"code": null,
"e": 4399,
"s": 4355,
"text": "Let’s specify probabilities for our colors:"
},
{
"code": null,
"e": 4678,
"s": 4399,
"text": "# generate an array of colors with differing probabilities[np.random.choice(colors, p=[0.1, 0.6, 0.1, 0.2]) for x in range(10)]>>>['LightGray',>>> 'LightCoral',>>> 'LightGray',>>> 'LightGray',>>> 'LightCoral',>>> 'WhiteSmoke',>>> 'Yellow',>>> 'Yellow',>>> 'Yellow',>>> 'Yellow']"
},
{
"code": null,
"e": 4907,
"s": 4678,
"text": "We can see that yellow and light gray are more common in the output! Due to the small sample size the distributions are not exactly as specified. We would need to increase the sample size to approach our specified probabilities."
},
{
"code": null,
"e": 5048,
"s": 4907,
"text": "We can also generate data based on a specified distribution. Here we randomly generate several distributions and visualize with a histogram:"
},
{
"code": null,
"e": 5573,
"s": 5048,
"text": "# generate normal distributionnormal_dist = np.random.normal(loc=5, scale=1, size=1000)# generate gamma distributiongamma_dist = np.random.gamma(shape=3, scale=1, size=1000)# generate exponential distributionexp_dist = np.random.exponential(scale=4, size=1000)# histograms to visualize the distributionsfig, [ax1, ax2, ax3] = plt.subplots(1,3)ax1.hist(normal_dist)ax1.set_title('Normal Distribution')ax2.hist(gamma_dist)ax2.set_title('Gamma Distribution')ax3.hist(exp_dist)ax3.set_title('Exponential Distribution')plt.show()"
},
{
"code": null,
"e": 5671,
"s": 5573,
"text": "These are looking good! Let’s put everything together and create our fake widget factory dataset!"
},
{
"code": null,
"e": 5745,
"s": 5671,
"text": "We’ll create two dataframes: One for worker data and one for widget data."
},
{
"code": null,
"e": 5893,
"s": 5745,
"text": "We will create an employee roster dataset that contains employee id, name, hire date, status, and team using Faker, Numpy, and list comprehensions."
},
{
"code": null,
"e": 6039,
"s": 5893,
"text": "First, we create a function, make_workers(). This function will take one argument, num, which will represent the number of employees to generate."
},
{
"code": null,
"e": 6244,
"s": 6039,
"text": "We use np.random.choice to assign each employee to a team, using the default uniform distribution, and to assign each employee to a status of full time, part time, or per diem by specifying probabilities."
},
{
"code": null,
"e": 6297,
"s": 6244,
"text": "This looks great! Now let’s create some widget data."
},
{
"code": null,
"e": 6390,
"s": 6297,
"text": "We’ll begin by randomly assigning each widget an item number using the built in id() method."
},
{
"code": null,
"e": 6794,
"s": 6390,
"text": "From the documentation, id() “return[s] the ‘identity’ of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime”. Because we’re iterating through the same range each time our make_widget_data() function is called, we will create duplicate item numbers. To solve this problem we’ll append the worker id to the item number to guarantee uniqueness."
},
{
"code": null,
"e": 6983,
"s": 6794,
"text": "Next, we’ll assume in widget creation there are three steps. For each step, we’ll generate a different random distribution that will represent the amount of time the step took to complete."
},
{
"code": null,
"e": 7127,
"s": 6983,
"text": "Next, we assume that employees do not all work at the same rate — and that full time workers will complete more widgets than part time workers."
},
{
"code": null,
"e": 7290,
"s": 7127,
"text": "To reflect this in the data, we iterate through the worker_df, created above and randomly select a number of widgets created by each worker based on their status."
},
{
"code": null,
"e": 7449,
"s": 7290,
"text": "We’ll create an empty list to store dataframes for each worker’s widgets, and then finally concatenate the list of dataframes into one final widget dataframe:"
},
{
"code": null,
"e": 7517,
"s": 7449,
"text": "The widget factory workers were busy! They created 2817285 widgets!"
},
{
"code": null,
"e": 7583,
"s": 7517,
"text": "Finally, we can save our datasets to be used for future analyses:"
},
{
"code": null,
"e": 7682,
"s": 7583,
"text": "worker_df.to_csv('data/workers.csv', index=False)widget_df.to_csv('data/widgets.csv', index=False)"
},
{
"code": null,
"e": 7760,
"s": 7682,
"text": "Here we explored the Python package Faker and Numpy’s Random Sampling module."
},
{
"code": null,
"e": 7855,
"s": 7760,
"text": "Faker makes it easy to generate a wide variety of data, including names, addresses, and dates."
},
{
"code": null,
"e": 7976,
"s": 7855,
"text": "Numpy’s random sampling module allows us to generate specific distributions and pseudo randomly select items from lists."
},
{
"code": null,
"e": 8136,
"s": 7976,
"text": "We were able to generate fake data for an imaginary widget factory. We created two datasets, one with worker details, and the second with widget creation data."
}
] |
Bias-Variance Tradeoff in Time Series | by Nikhil Gupta | Towards Data Science
|
When building a model for any machine learning problem, we must pay attention to bias-variance tradeoffs. Specifically, for time series:
Having too much bias (underfitting) means that the model is not able to capture all the signals in the data and hence leads to a higher error during the training phase (and in turn during the prediction phase as well).Having too much variance (overfitting) in the model means that the model is not able to generalize well to unseen future data (i.e. it can do well on the training data but is not able to predict the future data as well as it trained).
Having too much bias (underfitting) means that the model is not able to capture all the signals in the data and hence leads to a higher error during the training phase (and in turn during the prediction phase as well).
Having too much variance (overfitting) in the model means that the model is not able to generalize well to unseen future data (i.e. it can do well on the training data but is not able to predict the future data as well as it trained).
Let’s see how this can be diagnosed with PyCaret.
The solution in PyCaret is based on the recommendation by Andrew Ng [1]. I would highly recommend the readers go through this short video first before continuing with this article. The steps followed in PyCaret are:
The time-series data is first split into train and test splits.The train split is then cross-validated across multiple folds. The cross-validation error is used to select from multiple models during the hyperparameter tuning phase.The model with the best hyperparameters is trained on the entire “training split”This model is then used to make predictions corresponding to the time points in the “test split”. The final generalization error can then be reported by comparing these “test” predictions to the actual data in the test split.Once satisfied, the user can train the entire dataset (train + test split) using the “best hyperparameters” obtained in the previous steps and make future predictions.
The time-series data is first split into train and test splits.
The train split is then cross-validated across multiple folds. The cross-validation error is used to select from multiple models during the hyperparameter tuning phase.
The model with the best hyperparameters is trained on the entire “training split”
This model is then used to make predictions corresponding to the time points in the “test split”. The final generalization error can then be reported by comparing these “test” predictions to the actual data in the test split.
Once satisfied, the user can train the entire dataset (train + test split) using the “best hyperparameters” obtained in the previous steps and make future predictions.
We will use the classical “airline” dataset [6] to demonstrate this in PyCaret. A Jupyter notebook for this article can be found here and also at the end of the article under the “Resources” section.
from pycaret.datasets import get_datafrom pycaret.internal.pycaret_experiment import TimeSeriesExperiment#### Get data ----y = get_data(“airline”, verbose=False)#### Setup Experiment ----exp = TimeSeriesExperiment()#### Forecast Horizon = 12 months & 3 fold cross validation ----exp.setup(data=y, fh=12, fold=3, session_id=42)
To diagnose bias-variance tradeoffs, PyCaret initially splits the time series data into a train and test split. The temporal dependence of the data is maintained when performing this split. The length of the test set is the same as the forecast horizon that is specified while setting up the experiment (12 in this example). This is shown in the setup summary.
This split can also be visualized using the plot_model functionality.
exp.plot_model(plot="train_test_split")
Next, the training split is broken into cross-validation folds. This is done so that the training is not biased by just one set of training data. For example, if the last 12 months in the data were an anomaly (say due to Covid), then that might impact the performance of an otherwise good model. Alternately, it might make an otherwise bad model look good. We want to avoid such situations. Hence, we train multiple times over different datasets and average the performance.
It is important to again maintain the temporal dependence when training across these multiple datasets (also called “folds”). Many strategies can be applied like expanding or sliding window strategies. More information about this can be found in [2].
The number of folds can be controlled during the setup stage. By default PyCaret time series module uses 3 folds. The folds in the training data can be visualized using plot_model again. The blue dots represent the time points that are used for training in each fold and the orange dots represent the time points used to validate the performance of the training fold. Again, the length of the orange dots is the same as the forecast horizon (12)
exp.plot_model(plot="cv")
We will take the example of a reduced regression model for this article. More information about reduced regression models can be found in [3].
model = exp.create_model("lr_cds_dt")
The performance is displayed across the 3 folds. The average Mean Absolute Error (MAE) across the 3 folds is > 30 and the Mean Absolute Percentage Error (MAPE) is > 8%. Depending on the application, this may not be good enough.
Once the cross-validation is done, PyCaret returns the model that is trained on the entire training split. This is done so that the generalization of the model can then be tested on the test dataset that we held out previously.
exp.predict_model(model)exp.plot_model(model)
Prediction using this model now shows the forecasts for the time points corresponding to the test dataset (blue line). The metrics for these “test” forecasts are also displayed. These are worse than the metrics obtained during the cross-validation. Since the metrics were bad to begin with (high cross-validation errors), this is indicative of a high bias in the model (i.e. the model is not able to capture the trends in the dataset well at this point). Also, the test metrics are worse than the cross-validation metrics. This is indicative of high variance (refer to [1] for details). This is also visible in the prediction plot as well which shows that the blue prediction line is not close to the corresponding black line during the test period.
Let’s see if we can improve the bias by tuning the model’s hyperparameters.
The tuning process tries various hyperparameter combinations to see which ones fit the model the best. More information can be found in [4] and [5]. Once the various hyperparameter combinations are tried out, the best hyperparameters are picked based on the mean cross-validation error across the “folds”. The cross-validation metrics using these best hyperparameters are then displayed.
tuned_model = exp.tune_model(model)
So, we have been able to reduce the errors during the cross-validation stage to approximately <= 20 and the MAPE is < 5% by performing hyper-parameter tuning. This is much better than before and we have reduced the underfitting significantly. But now we need to ensure we are not overfitting the data. Let’s look at the performance across the test dataset again.
exp.predict_model(tuned_model)exp.plot_model(tuned_model)
The forecasts across the test dataset show better performance than the cross-validation metrics indicative of a lack of overfitting. The plot also shows a good match to the actual data points during the test period.
So this model looks good. But what we need is the ability to predict the true “unknown” future data. This can be done by finalizing the model.
Finalizing the model takes the hyperparameters from the model (tuned_model in this case), and fits the entire dataset using these hyperparameters.
final_model = exp.finalize_model(tuned_model)print(exp.predict_model(final_model))exp.plot_model(final_model)
And there you have it. Our best model is now able to make future predictions. Note that metrics are not displayed at this point since we do not know the actual values for the future yet.
Hopefully, this workflow example has shown why it is important to diagnose bias-variance tradeoff. For time series, this process is complicated by the fact that the temporal dependence must be maintained when performing the splits and cross-validation. Luckily, the PyCaret Time Series module makes managing this process a breeze.
That’s it for this article. If you would like to connect with me on my social channels (I post about Time Series Analysis frequently), you can find me below. Happy forecasting!
🔗 LinkedIn
🐦 Twitter
📘 GitHub
Jupyter Notebook containing the code for this article
Jupyter Notebook containing the code for this article
[1] Model Selection and Training/Validation/Test Sets by Andrew Ng.
[2] Time Series Cross Validation in PyCaret
[3] Reduced Regression Models for Time Series Forecasting
[4] Basic Hyperparameter Tuning for Time Series Models in PyCaret
[5] Advanced Hyperparameter Tuning for Time Series Models in PyCaret
[6] Airline Dataset available through sktime python package under BSD 3-Clause License.
|
[
{
"code": null,
"e": 309,
"s": 172,
"text": "When building a model for any machine learning problem, we must pay attention to bias-variance tradeoffs. Specifically, for time series:"
},
{
"code": null,
"e": 762,
"s": 309,
"text": "Having too much bias (underfitting) means that the model is not able to capture all the signals in the data and hence leads to a higher error during the training phase (and in turn during the prediction phase as well).Having too much variance (overfitting) in the model means that the model is not able to generalize well to unseen future data (i.e. it can do well on the training data but is not able to predict the future data as well as it trained)."
},
{
"code": null,
"e": 981,
"s": 762,
"text": "Having too much bias (underfitting) means that the model is not able to capture all the signals in the data and hence leads to a higher error during the training phase (and in turn during the prediction phase as well)."
},
{
"code": null,
"e": 1216,
"s": 981,
"text": "Having too much variance (overfitting) in the model means that the model is not able to generalize well to unseen future data (i.e. it can do well on the training data but is not able to predict the future data as well as it trained)."
},
{
"code": null,
"e": 1266,
"s": 1216,
"text": "Let’s see how this can be diagnosed with PyCaret."
},
{
"code": null,
"e": 1482,
"s": 1266,
"text": "The solution in PyCaret is based on the recommendation by Andrew Ng [1]. I would highly recommend the readers go through this short video first before continuing with this article. The steps followed in PyCaret are:"
},
{
"code": null,
"e": 2187,
"s": 1482,
"text": "The time-series data is first split into train and test splits.The train split is then cross-validated across multiple folds. The cross-validation error is used to select from multiple models during the hyperparameter tuning phase.The model with the best hyperparameters is trained on the entire “training split”This model is then used to make predictions corresponding to the time points in the “test split”. The final generalization error can then be reported by comparing these “test” predictions to the actual data in the test split.Once satisfied, the user can train the entire dataset (train + test split) using the “best hyperparameters” obtained in the previous steps and make future predictions."
},
{
"code": null,
"e": 2251,
"s": 2187,
"text": "The time-series data is first split into train and test splits."
},
{
"code": null,
"e": 2420,
"s": 2251,
"text": "The train split is then cross-validated across multiple folds. The cross-validation error is used to select from multiple models during the hyperparameter tuning phase."
},
{
"code": null,
"e": 2502,
"s": 2420,
"text": "The model with the best hyperparameters is trained on the entire “training split”"
},
{
"code": null,
"e": 2728,
"s": 2502,
"text": "This model is then used to make predictions corresponding to the time points in the “test split”. The final generalization error can then be reported by comparing these “test” predictions to the actual data in the test split."
},
{
"code": null,
"e": 2896,
"s": 2728,
"text": "Once satisfied, the user can train the entire dataset (train + test split) using the “best hyperparameters” obtained in the previous steps and make future predictions."
},
{
"code": null,
"e": 3096,
"s": 2896,
"text": "We will use the classical “airline” dataset [6] to demonstrate this in PyCaret. A Jupyter notebook for this article can be found here and also at the end of the article under the “Resources” section."
},
{
"code": null,
"e": 3423,
"s": 3096,
"text": "from pycaret.datasets import get_datafrom pycaret.internal.pycaret_experiment import TimeSeriesExperiment#### Get data ----y = get_data(“airline”, verbose=False)#### Setup Experiment ----exp = TimeSeriesExperiment()#### Forecast Horizon = 12 months & 3 fold cross validation ----exp.setup(data=y, fh=12, fold=3, session_id=42)"
},
{
"code": null,
"e": 3784,
"s": 3423,
"text": "To diagnose bias-variance tradeoffs, PyCaret initially splits the time series data into a train and test split. The temporal dependence of the data is maintained when performing this split. The length of the test set is the same as the forecast horizon that is specified while setting up the experiment (12 in this example). This is shown in the setup summary."
},
{
"code": null,
"e": 3854,
"s": 3784,
"text": "This split can also be visualized using the plot_model functionality."
},
{
"code": null,
"e": 3894,
"s": 3854,
"text": "exp.plot_model(plot=\"train_test_split\")"
},
{
"code": null,
"e": 4369,
"s": 3894,
"text": "Next, the training split is broken into cross-validation folds. This is done so that the training is not biased by just one set of training data. For example, if the last 12 months in the data were an anomaly (say due to Covid), then that might impact the performance of an otherwise good model. Alternately, it might make an otherwise bad model look good. We want to avoid such situations. Hence, we train multiple times over different datasets and average the performance."
},
{
"code": null,
"e": 4620,
"s": 4369,
"text": "It is important to again maintain the temporal dependence when training across these multiple datasets (also called “folds”). Many strategies can be applied like expanding or sliding window strategies. More information about this can be found in [2]."
},
{
"code": null,
"e": 5066,
"s": 4620,
"text": "The number of folds can be controlled during the setup stage. By default PyCaret time series module uses 3 folds. The folds in the training data can be visualized using plot_model again. The blue dots represent the time points that are used for training in each fold and the orange dots represent the time points used to validate the performance of the training fold. Again, the length of the orange dots is the same as the forecast horizon (12)"
},
{
"code": null,
"e": 5092,
"s": 5066,
"text": "exp.plot_model(plot=\"cv\")"
},
{
"code": null,
"e": 5235,
"s": 5092,
"text": "We will take the example of a reduced regression model for this article. More information about reduced regression models can be found in [3]."
},
{
"code": null,
"e": 5273,
"s": 5235,
"text": "model = exp.create_model(\"lr_cds_dt\")"
},
{
"code": null,
"e": 5501,
"s": 5273,
"text": "The performance is displayed across the 3 folds. The average Mean Absolute Error (MAE) across the 3 folds is > 30 and the Mean Absolute Percentage Error (MAPE) is > 8%. Depending on the application, this may not be good enough."
},
{
"code": null,
"e": 5729,
"s": 5501,
"text": "Once the cross-validation is done, PyCaret returns the model that is trained on the entire training split. This is done so that the generalization of the model can then be tested on the test dataset that we held out previously."
},
{
"code": null,
"e": 5775,
"s": 5729,
"text": "exp.predict_model(model)exp.plot_model(model)"
},
{
"code": null,
"e": 6525,
"s": 5775,
"text": "Prediction using this model now shows the forecasts for the time points corresponding to the test dataset (blue line). The metrics for these “test” forecasts are also displayed. These are worse than the metrics obtained during the cross-validation. Since the metrics were bad to begin with (high cross-validation errors), this is indicative of a high bias in the model (i.e. the model is not able to capture the trends in the dataset well at this point). Also, the test metrics are worse than the cross-validation metrics. This is indicative of high variance (refer to [1] for details). This is also visible in the prediction plot as well which shows that the blue prediction line is not close to the corresponding black line during the test period."
},
{
"code": null,
"e": 6601,
"s": 6525,
"text": "Let’s see if we can improve the bias by tuning the model’s hyperparameters."
},
{
"code": null,
"e": 6989,
"s": 6601,
"text": "The tuning process tries various hyperparameter combinations to see which ones fit the model the best. More information can be found in [4] and [5]. Once the various hyperparameter combinations are tried out, the best hyperparameters are picked based on the mean cross-validation error across the “folds”. The cross-validation metrics using these best hyperparameters are then displayed."
},
{
"code": null,
"e": 7025,
"s": 6989,
"text": "tuned_model = exp.tune_model(model)"
},
{
"code": null,
"e": 7388,
"s": 7025,
"text": "So, we have been able to reduce the errors during the cross-validation stage to approximately <= 20 and the MAPE is < 5% by performing hyper-parameter tuning. This is much better than before and we have reduced the underfitting significantly. But now we need to ensure we are not overfitting the data. Let’s look at the performance across the test dataset again."
},
{
"code": null,
"e": 7446,
"s": 7388,
"text": "exp.predict_model(tuned_model)exp.plot_model(tuned_model)"
},
{
"code": null,
"e": 7662,
"s": 7446,
"text": "The forecasts across the test dataset show better performance than the cross-validation metrics indicative of a lack of overfitting. The plot also shows a good match to the actual data points during the test period."
},
{
"code": null,
"e": 7805,
"s": 7662,
"text": "So this model looks good. But what we need is the ability to predict the true “unknown” future data. This can be done by finalizing the model."
},
{
"code": null,
"e": 7952,
"s": 7805,
"text": "Finalizing the model takes the hyperparameters from the model (tuned_model in this case), and fits the entire dataset using these hyperparameters."
},
{
"code": null,
"e": 8062,
"s": 7952,
"text": "final_model = exp.finalize_model(tuned_model)print(exp.predict_model(final_model))exp.plot_model(final_model)"
},
{
"code": null,
"e": 8249,
"s": 8062,
"text": "And there you have it. Our best model is now able to make future predictions. Note that metrics are not displayed at this point since we do not know the actual values for the future yet."
},
{
"code": null,
"e": 8580,
"s": 8249,
"text": "Hopefully, this workflow example has shown why it is important to diagnose bias-variance tradeoff. For time series, this process is complicated by the fact that the temporal dependence must be maintained when performing the splits and cross-validation. Luckily, the PyCaret Time Series module makes managing this process a breeze."
},
{
"code": null,
"e": 8757,
"s": 8580,
"text": "That’s it for this article. If you would like to connect with me on my social channels (I post about Time Series Analysis frequently), you can find me below. Happy forecasting!"
},
{
"code": null,
"e": 8768,
"s": 8757,
"text": "🔗 LinkedIn"
},
{
"code": null,
"e": 8778,
"s": 8768,
"text": "🐦 Twitter"
},
{
"code": null,
"e": 8787,
"s": 8778,
"text": "📘 GitHub"
},
{
"code": null,
"e": 8841,
"s": 8787,
"text": "Jupyter Notebook containing the code for this article"
},
{
"code": null,
"e": 8895,
"s": 8841,
"text": "Jupyter Notebook containing the code for this article"
},
{
"code": null,
"e": 8963,
"s": 8895,
"text": "[1] Model Selection and Training/Validation/Test Sets by Andrew Ng."
},
{
"code": null,
"e": 9007,
"s": 8963,
"text": "[2] Time Series Cross Validation in PyCaret"
},
{
"code": null,
"e": 9065,
"s": 9007,
"text": "[3] Reduced Regression Models for Time Series Forecasting"
},
{
"code": null,
"e": 9131,
"s": 9065,
"text": "[4] Basic Hyperparameter Tuning for Time Series Models in PyCaret"
},
{
"code": null,
"e": 9200,
"s": 9131,
"text": "[5] Advanced Hyperparameter Tuning for Time Series Models in PyCaret"
}
] |
Ptpython: A Better Python REPL | by Khuyen Tran | Towards Data Science
|
Have you ever wanted to quickly try some ideas popping up in your head using a Python Shell (REPL)? You might not want to open a new Jupyter Notebook to experiment with only a few lines of code.
But you might also be hesitant to use a classic Python shell since it doesn’t support auto-completion or docstring as Jupyter Notebook does. You also cannot fix the mistake in the code after hitting Enter.
What if you can turn your boring Python shell into a multi-functional shell like below?
That is when ptpython comes in handy.
Ptpython can be considered as a better REPL. To install ptpython, type:
pip install ptpython
Then type:
ptpython
... to start using ptpython.
If you make a mistake on a classical Python shell and hit Enter, you will not be able to go back to fix the mistake.
Luckily, ptpython allows you to validate the input when hitting the Enter button. In the GIF below, I miss a closing bracket and receive an error, but I can go back and fix my code until there is no more error!
Have you ever wished to get the suggestion based on the history? That could be done with ptpython.
By default, this feature is not enabled. But you can enable it by pressing F2 to access the menu. Then use the right or left arrow to turn on the “Auto suggestion” feature. Finally, hit Enter to hide the menu.
Now, you should see the suggestion based on history when typing. To accept the suggestion, simply press the right arrow.
You can also view all methods that belong to a specific class after typing dot (.) like below:
Use the down arrow to get to a certain suggestion, then continue typing the rest of the code.
You can also access the history by pressing F3. Use the up or down arrow to get to the line of code you want to copy, then type Space to choose the code for insertion.
Whenever you are done with selecting code, press Enter and these lines of code will be pasted in your current shell!
Note that the code will be inserted by the order of execution.
Have you ever wished to edit the code pasted on your Python shell? A classic Python shell will not allow you to do that.
Ptpython allows you to edit the pasted code until you are happy with it:
To turn on the paste mode, press F6. When the paste mode is on, the code will not be executed when you press Enter. Whenever you are ready to execute the code, press F6 again to turn off the paste mode, then press Enter twice.
Ptpython allows you to view the parameters of your Python functions or classes like below:
You can also view the docstring of a class or a function. To enable this feature, press F2 then turning on the “Show docstring” feature.
Now you can see the docstring of the function or the class you are using!
Ptpython also makes it easier to distinguish between parentheses by highlighting matching parathesis.
If you want to increase readability, you can also increase the blank line after the output.
To enable this feature, press F2 then turn on “Blank line after input” and “Blank line after output”.
Ptpython also supports beautiful syntax highlighting like below!
You can change the theme by pressing the right arrow until you find your favorite theme.
There are a total of 39 themes available. If you want to have the same theme as Sublime Text, choose the Monokai theme.
Ptpython also supports IPython. Run ptipython , to get a nice interactive shell with all the power that IPython has to offer, including the magic commands!
The changes you make to the setting of the current ptpython shell will be undone when you quit the shell.
To change the configuration permanently, copy this file to $XDG_CONFIG_HOME/ptpython/config.py . On Linux, this is: ~/.config/ptpython/config.py .
After copying the config file to your local directory, you should have all the features I show above enabled. Feel free to change the config files based on your preferences.
Congratulations! You have just learned what ptpython is and how it can be helpful. I only cover a few of my favorite features in this article so I encourage you to install ptpython and try it yourself.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "Have you ever wanted to quickly try some ideas popping up in your head using a Python Shell (REPL)? You might not want to open a new Jupyter Notebook to experiment with only a few lines of code."
},
{
"code": null,
"e": 573,
"s": 367,
"text": "But you might also be hesitant to use a classic Python shell since it doesn’t support auto-completion or docstring as Jupyter Notebook does. You also cannot fix the mistake in the code after hitting Enter."
},
{
"code": null,
"e": 661,
"s": 573,
"text": "What if you can turn your boring Python shell into a multi-functional shell like below?"
},
{
"code": null,
"e": 699,
"s": 661,
"text": "That is when ptpython comes in handy."
},
{
"code": null,
"e": 771,
"s": 699,
"text": "Ptpython can be considered as a better REPL. To install ptpython, type:"
},
{
"code": null,
"e": 792,
"s": 771,
"text": "pip install ptpython"
},
{
"code": null,
"e": 803,
"s": 792,
"text": "Then type:"
},
{
"code": null,
"e": 812,
"s": 803,
"text": "ptpython"
},
{
"code": null,
"e": 841,
"s": 812,
"text": "... to start using ptpython."
},
{
"code": null,
"e": 958,
"s": 841,
"text": "If you make a mistake on a classical Python shell and hit Enter, you will not be able to go back to fix the mistake."
},
{
"code": null,
"e": 1169,
"s": 958,
"text": "Luckily, ptpython allows you to validate the input when hitting the Enter button. In the GIF below, I miss a closing bracket and receive an error, but I can go back and fix my code until there is no more error!"
},
{
"code": null,
"e": 1268,
"s": 1169,
"text": "Have you ever wished to get the suggestion based on the history? That could be done with ptpython."
},
{
"code": null,
"e": 1478,
"s": 1268,
"text": "By default, this feature is not enabled. But you can enable it by pressing F2 to access the menu. Then use the right or left arrow to turn on the “Auto suggestion” feature. Finally, hit Enter to hide the menu."
},
{
"code": null,
"e": 1599,
"s": 1478,
"text": "Now, you should see the suggestion based on history when typing. To accept the suggestion, simply press the right arrow."
},
{
"code": null,
"e": 1694,
"s": 1599,
"text": "You can also view all methods that belong to a specific class after typing dot (.) like below:"
},
{
"code": null,
"e": 1788,
"s": 1694,
"text": "Use the down arrow to get to a certain suggestion, then continue typing the rest of the code."
},
{
"code": null,
"e": 1956,
"s": 1788,
"text": "You can also access the history by pressing F3. Use the up or down arrow to get to the line of code you want to copy, then type Space to choose the code for insertion."
},
{
"code": null,
"e": 2073,
"s": 1956,
"text": "Whenever you are done with selecting code, press Enter and these lines of code will be pasted in your current shell!"
},
{
"code": null,
"e": 2136,
"s": 2073,
"text": "Note that the code will be inserted by the order of execution."
},
{
"code": null,
"e": 2257,
"s": 2136,
"text": "Have you ever wished to edit the code pasted on your Python shell? A classic Python shell will not allow you to do that."
},
{
"code": null,
"e": 2330,
"s": 2257,
"text": "Ptpython allows you to edit the pasted code until you are happy with it:"
},
{
"code": null,
"e": 2557,
"s": 2330,
"text": "To turn on the paste mode, press F6. When the paste mode is on, the code will not be executed when you press Enter. Whenever you are ready to execute the code, press F6 again to turn off the paste mode, then press Enter twice."
},
{
"code": null,
"e": 2648,
"s": 2557,
"text": "Ptpython allows you to view the parameters of your Python functions or classes like below:"
},
{
"code": null,
"e": 2785,
"s": 2648,
"text": "You can also view the docstring of a class or a function. To enable this feature, press F2 then turning on the “Show docstring” feature."
},
{
"code": null,
"e": 2859,
"s": 2785,
"text": "Now you can see the docstring of the function or the class you are using!"
},
{
"code": null,
"e": 2961,
"s": 2859,
"text": "Ptpython also makes it easier to distinguish between parentheses by highlighting matching parathesis."
},
{
"code": null,
"e": 3053,
"s": 2961,
"text": "If you want to increase readability, you can also increase the blank line after the output."
},
{
"code": null,
"e": 3155,
"s": 3053,
"text": "To enable this feature, press F2 then turn on “Blank line after input” and “Blank line after output”."
},
{
"code": null,
"e": 3220,
"s": 3155,
"text": "Ptpython also supports beautiful syntax highlighting like below!"
},
{
"code": null,
"e": 3309,
"s": 3220,
"text": "You can change the theme by pressing the right arrow until you find your favorite theme."
},
{
"code": null,
"e": 3429,
"s": 3309,
"text": "There are a total of 39 themes available. If you want to have the same theme as Sublime Text, choose the Monokai theme."
},
{
"code": null,
"e": 3585,
"s": 3429,
"text": "Ptpython also supports IPython. Run ptipython , to get a nice interactive shell with all the power that IPython has to offer, including the magic commands!"
},
{
"code": null,
"e": 3691,
"s": 3585,
"text": "The changes you make to the setting of the current ptpython shell will be undone when you quit the shell."
},
{
"code": null,
"e": 3838,
"s": 3691,
"text": "To change the configuration permanently, copy this file to $XDG_CONFIG_HOME/ptpython/config.py . On Linux, this is: ~/.config/ptpython/config.py ."
},
{
"code": null,
"e": 4012,
"s": 3838,
"text": "After copying the config file to your local directory, you should have all the features I show above enabled. Feel free to change the config files based on your preferences."
},
{
"code": null,
"e": 4214,
"s": 4012,
"text": "Congratulations! You have just learned what ptpython is and how it can be helpful. I only cover a few of my favorite features in this article so I encourage you to install ptpython and try it yourself."
},
{
"code": null,
"e": 4374,
"s": 4214,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Computer Vision for Beginners: Part 2 | by Jiwon Jeong | Towards Data Science
|
Preparation refers to the process of getting ready for a task before actually starting it. It could be a preparing step of writing a story, job interview or data modeling. And having a thorough preparation can’t be overemphasized of its importance. If we get off without enough preprocessing, it’s hard to expect to get a desirable result no matter how good data we have.
This is the second part of OpenCV tutorial for beginners and the complete set of the series is as follows:
Understanding color models and drawing figures on imagesThe basics of image processing with filteringFrom feature detection to face detectionContour detection and having a little bit of fun
Understanding color models and drawing figures on images
The basics of image processing with filtering
From feature detection to face detection
Contour detection and having a little bit of fun
Today we’re going to talk about how to manipulate images. These are going to be a preprocessing stage. When it comes to detecting edges and contours, noise gives a great impact on the accuracy of detection. Therefore removing noises and controlling the intensity of the pixel values can help the model to focus on the general details and get higher accuracy. Blurring, thresholding, and morphological transformation are the techniques we use for this purpose.
This post assumes you are already familiar with the concept of convolution. But if it’s not the case, I’d like to recommend you check this post first. The complete code for this tutorial is also available on Github. Now let’s walk through how to apply image filtering with OpenCV one by one.
The goal of blurring is to perform noise reduction. But we have to pay extra care here. If we apply edge detection algorithms to the images with high resolution, we’ll get too many detected outcomes that we aren’t interested in.
On the contrary, if we blur the images too much, we‘ll lose the data. Therefore we need to find an adequate amount of blurring we’re going to apply without losing desirable edges.
There are several techniques used to achieve blurring effects but we’re going to talk about the four major ones used in OpenCV: Averaging blurring, Gaussian blurring, median blurring and bilateral filtering. All four techniques have a common basic principle, which is applying convolutional operations to the image with a filter (kernel). The values of the applying filters are different between the four blurring methods.
Average blurring is taking the average of all the pixel values under the given kernel area and replace the value at the center. For example, suppose we have a kernel with the size of 5X5. We calculate the average of the convoluted outcome and put that result to the center of the given area.
Then what will it be like if we increase the size of the kernel? As the size of filters gets bigger, the pixel values will be normalized more. Therefore we can expect the image to get blurred the more. Let’s check out the result with the code as follows. (For comparison, I’ll keep attaching the original image to the result)
# Import the image and convert to RGB img = cv2.imread('text.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# Plot the image with different kernel sizeskernels = [5, 11, 17]fig, axs = plt.subplots(nrows = 1, ncols = 3, figsize = (20, 20))for ind, s in enumerate(kernels): img_blurred = cv2.blur(img, ksize = (s, s)) ax = axs[ind] ax.imshow(img_blurred) ax.axis('off')plt.show()
Medium blurring is the same with average blurring except that it uses the median value instead of the average. Therefore when we have to handle sudden noises in the image such as ‘salt and pepper noise,’ it’ll be better to use medium blurring than average blurring.
Gaussian blurring is nothing but using the kernel whose values have a Gaussian distribution. The values are generated by a Gaussian function so it requires a sigma value for its parameter. As you can see the image above, the values of the kernel go higher near the center and go smaller near the corner. It’s good to apply this method to the noises that have a normal distribution such as white noise.
Bilateral Filtering is an advanced version of Gaussian blurring. Blurring produces not only dissolving noises but also smoothing edges. And bilateral filter can keep edges sharp while removing noises. It uses Gaussian-distributed values but takes both distance and the pixel value differences into account. Therefore it requires sigmaSpace and sigmaColor for the parameters.
# Blur the image img_0 = cv2.blur(img, ksize = (7, 7))img_1 = cv2.GaussianBlur(img, ksize = (7, 7), sigmaX = 0) img_2 = cv2.medianBlur(img, 7)img_3 = cv2.bilateralFilter(img, 7, sigmaSpace = 75, sigmaColor =75)# Plot the imagesimages = [img_0, img_1, img_2, img_3]fig, axs = plt.subplots(nrows = 1, ncols = 4, figsize = (20, 20))for ind, p in enumerate(images): ax = axs[ind] ax.imshow(p) ax.axis('off')plt.show()
Thresholding transforms images into binary images. We need to set the threshold value and max values and then we convert the pixel values accordingly. There are five different types of thresholding: Binary, the inverse of Binary, Threshold to zero, the inverse of Threshold to Zero, and Threshold truncation.
img = cv2.imread('gradation.png')# Thresholding _, thresh_0 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)_, thresh_1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)_, thresh_2 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)_, thresh_3 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)_, thresh_4 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)# Plot the imagesimages = [img, thresh_0, thresh_1, thresh_2, thresh_3, thresh_4]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (13, 13))for ind, p in enumerate(images): ax = axs[ind//3, ind%3] ax.imshow(p)plt.show()
You can see how each type of thresholding can be expressed in a mathematical way and I(x, y) is the intensity at the point, or the pixel value at (x, y). But I prefer to understand the concept visually. Take a look at the picture on the right. The images are way better for you to comprehend the difference between the types.
But don’t you think it’s too harsh to take just one value of threshold and apply it to all parts of an image? What if we have a picture with various amount of lighting in different areas? In this case, applying one value to the whole image would be a bad choice. A better approach would be using different thresholds for each part of the image. There is another technique called Adaptive thresholding, which serves this issue. By calculating the threshold within the neighborhood area of the image, we can achieve a better result from images with varying illumination.
# Convert the image to grayscaleimg = cv2.imread('text.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# Adaptive Thresholding_, thresh_binary = cv2.threshold(img, thresh = 127, maxval = 255, type = cv2.THRESH_BINARY)adap_mean_2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 2)adap_mean_2_inv = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 7, 2)adap_mean_8 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 8)adap_gaussian_8 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 8)
We need to convert the color mode to grayscale to apply adaptive thresholding. The parameters of adaptive thresholding are maxValue (which I set 255 above), adaptiveMethod , thresholdType , blockSize and C . And the adaptive method here has two kinds: ADAPTIVE_THRESH_MEAN_C , ADAPTIVE_THRESH_GAUSSIAN_C . Let’s just see how images are produced differently.
# Plot the imagesimages = [img, thresh_binary, adap_mean_2, adap_mean_2_inv, adap_mean_8, adap_gaussian_8]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (15, 15))for ind, p in enumerate(images): ax = axs[ind%2, ind//2] ax.imshow(p, cmap = 'gray') ax.axis('off')plt.show()
We have the original image and the one with binary thresholding on the left line. Compare this with the second and third image on the upper line, which is produced by ADAPTIVE_THRESH_MEAN_C . It shows a more detailed result than that of binary thresholding. We can also see that it gets more explicit when the C value is bigger. C indicates how much we’ll subtract from the mean or weighted mean. With the two images on the right line, we can also compare the effect of ADAPTIVE_THRESH_MEAN_C and ADAPTIVE_THRESH_GAUSSIAN_C with the same C value.
I believe we are already familiar with the concept of gradients. In mathematics, the gradient geometrically represents the slope of the graph of a function with multi-variables. As it is a vector-valued function, it takes a direction and a magnitude as its components. Here we can also bring the same concept to the pixel values of images as well. The image gradient represents directional changes in the intensity or color mode and we can use this concept for locating edges.
# Apply gradient filteringsobel_x = cv2.Sobel(img, cv2.CV_64F, dx = 1, dy = 0, ksize = 5)sobel_y = cv2.Sobel(img, cv2.CV_64F, dx = 0, dy = 1, ksize = 5)blended = cv2.addWeighted(src1=sobel_x, alpha=0.5, src2=sobel_y, beta=0.5, gamma=0)laplacian = cv2.Laplacian(img, cv2.CV_64F)
Sobel operation uses both Gaussian smoothing and differentiation. We apply it by cv2.Sobel() and two different directions are available: vertical (sobel_x) and horizontal (sobel_y). dx and dy indicates the derivatives. When dx = 1 , the operator calculates the derivatives of the pixel values along the horizontal direction to make a filter.
We can also apply in both directions by summing the two filters of sobel_x and sobel_y . With the function cv2.addWeighted() , we can calculate the weighted sum of the filters. As you can see above in the code cell, I gave the same amount of weight to the two filters.
Laplacian operation uses the second derivatives of x and y. The mathematical expression is shown below.
A picture is worth a thousand words. Let’s see how the images are like.
# Plot the imagesimages = [sobel_x, sobel_y, blended, laplacian]plt.figure(figsize = (20, 20))for i in range(4): plt.subplot(1, 4, i+1) plt.imshow(images[i], cmap = 'gray') plt.axis('off')plt.show()
It’s apparent that the first and second image have a directional pattern. With the first image, we can clearly see the edges in the vertical direction. With the second image, we can see the horizontal edges. And both the third and fourth images, the edges on both directions are shown.
It’s also possible to manipulate the figures of images by filtering, which is called as morphological transformation. Let’s talk about erosion and dilation first.
Erosion is the technique for shrinking figures and it’s usually processed in a grayscale. The shape of filters can be a rectangle, an ellipse, and a cross shape. By applying a filter we remove any 0 values under the given area.
Let’s see how these can be implemented in codes.
img = cv2.imread('simpson.jpg')# Create erosion kernels kernel_0 = np.ones((9, 9), np.uint8)kernel_1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))kernel_2 = cv2.getStructuringElement(cv2.MORPH_CROSS, (9, 9))kernels = [kernel_0, kernel_1, kernel_2]# Plot the imagesplt.figure(figsize = (20, 20))for i in range(3): img_copy = img.copy() img_copy = cv2.erode(img_copy, kernels[i], iterations = 3) plt.subplot(1, 3, i+1) plt.imshow(img_copy) plt.axis('off')plt.show()
Check out how the Simpson’s family shrank with different types of kernels applied. (Sorry to Simpson for losing his hands!) We can see the image with the ellipse filter is eroded in a “round” way while the one with the basic filter with a squared shape is eroded in a “linear” way. The last one with the cross filter shows it shrank in a “diagonal” way.
Dilation is the opposite to erosion. It is making objects expand and the operation will be also opposite to that of erosion. Let’s check out the result with the code as follows.
# Apply dilationkernel = np.ones((9, 9), np.uint8)img_dilate = cv2.dilate(img, kernel, iterations = 3)plt.figure(figsize = (20, 10))plt.subplot(1, 2, 1); plt.imshow(img, cmap="gray")plt.subplot(1, 2, 2); plt.imshow(img_dilate, cmap="gray")plt.show()
Opening and closing operation is the mixed version of erosion and dilation. Opening performs erosion first and then dilation is performed on the result from the erosion while closing performs dilation first and the erosion.
As you can see the picture above, closing is useful to detect the overall contour of a figure and opening is suitable to detect subpatterns. We can implement these operators with the function cv2.morphologyEx() shown below. The parameter op indicates which type of operator we’re going to use.
# Apply the operationskernel = np.ones((9, 9), np.uint8)img_open = cv2.morphologyEx(img, op= cv2.MORPH_OPEN, kernel)img_close = cv2.morphologyEx(img, op= cv2.MORPH_CLOSE, kernel)img_grad = cv2.morphologyEx(img, op= cv2.MORPH_GRADIENT, kernel)img_tophat = cv2.morphologyEx(img, op= cv2.MORPH_TOPHAT, kernel)img_blackhat = cv2.morphologyEx(img, op= cv2.MORPH_BLACKHAT, kernel)# Plot the imagesimages = [img, img_open, img_close, img_grad, img_tophat, img_blackhat]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (15, 15))for ind, p in enumerate(images): ax = axs[ind//3, ind%3] ax.imshow(p, cmap = 'gray') ax.axis('off')plt.show()
Note that the Simpson’s hand is depicted differently in the images with the opening filter and closing filter. Gradient filter (MORPH_CGRADIENT) is the subtracted area from dilation to erosion. Top hat filter (MORPH_TOPHAT) is the subtracted area from opening to the original image while black hot filter (MORPH_BLACKHAT) is that from closing. I’d recommend you to visit here to get further explanations on morphological operators.
Did you enjoy the various image manipulation techniques? Besides the things we’ve discussed, there are other things available in OpenCV. So don’t hesitate to take a visit and check out OpenCV documentation. Next time will be about the detection techniques such as contour detection and face detections.
Are there errors you would love to correct? Please share your insight with us. I’m always open to talk, so feel free to leave comments below and share your thoughts. I also share interesting and useful resources on LinkedIn so feel free to follow or reach out to me. I’ll be back with the next series of the story. Stay tuned!
|
[
{
"code": null,
"e": 544,
"s": 172,
"text": "Preparation refers to the process of getting ready for a task before actually starting it. It could be a preparing step of writing a story, job interview or data modeling. And having a thorough preparation can’t be overemphasized of its importance. If we get off without enough preprocessing, it’s hard to expect to get a desirable result no matter how good data we have."
},
{
"code": null,
"e": 651,
"s": 544,
"text": "This is the second part of OpenCV tutorial for beginners and the complete set of the series is as follows:"
},
{
"code": null,
"e": 841,
"s": 651,
"text": "Understanding color models and drawing figures on imagesThe basics of image processing with filteringFrom feature detection to face detectionContour detection and having a little bit of fun"
},
{
"code": null,
"e": 898,
"s": 841,
"text": "Understanding color models and drawing figures on images"
},
{
"code": null,
"e": 944,
"s": 898,
"text": "The basics of image processing with filtering"
},
{
"code": null,
"e": 985,
"s": 944,
"text": "From feature detection to face detection"
},
{
"code": null,
"e": 1034,
"s": 985,
"text": "Contour detection and having a little bit of fun"
},
{
"code": null,
"e": 1494,
"s": 1034,
"text": "Today we’re going to talk about how to manipulate images. These are going to be a preprocessing stage. When it comes to detecting edges and contours, noise gives a great impact on the accuracy of detection. Therefore removing noises and controlling the intensity of the pixel values can help the model to focus on the general details and get higher accuracy. Blurring, thresholding, and morphological transformation are the techniques we use for this purpose."
},
{
"code": null,
"e": 1786,
"s": 1494,
"text": "This post assumes you are already familiar with the concept of convolution. But if it’s not the case, I’d like to recommend you check this post first. The complete code for this tutorial is also available on Github. Now let’s walk through how to apply image filtering with OpenCV one by one."
},
{
"code": null,
"e": 2015,
"s": 1786,
"text": "The goal of blurring is to perform noise reduction. But we have to pay extra care here. If we apply edge detection algorithms to the images with high resolution, we’ll get too many detected outcomes that we aren’t interested in."
},
{
"code": null,
"e": 2195,
"s": 2015,
"text": "On the contrary, if we blur the images too much, we‘ll lose the data. Therefore we need to find an adequate amount of blurring we’re going to apply without losing desirable edges."
},
{
"code": null,
"e": 2618,
"s": 2195,
"text": "There are several techniques used to achieve blurring effects but we’re going to talk about the four major ones used in OpenCV: Averaging blurring, Gaussian blurring, median blurring and bilateral filtering. All four techniques have a common basic principle, which is applying convolutional operations to the image with a filter (kernel). The values of the applying filters are different between the four blurring methods."
},
{
"code": null,
"e": 2910,
"s": 2618,
"text": "Average blurring is taking the average of all the pixel values under the given kernel area and replace the value at the center. For example, suppose we have a kernel with the size of 5X5. We calculate the average of the convoluted outcome and put that result to the center of the given area."
},
{
"code": null,
"e": 3236,
"s": 2910,
"text": "Then what will it be like if we increase the size of the kernel? As the size of filters gets bigger, the pixel values will be normalized more. Therefore we can expect the image to get blurred the more. Let’s check out the result with the code as follows. (For comparison, I’ll keep attaching the original image to the result)"
},
{
"code": null,
"e": 3626,
"s": 3236,
"text": "# Import the image and convert to RGB img = cv2.imread('text.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# Plot the image with different kernel sizeskernels = [5, 11, 17]fig, axs = plt.subplots(nrows = 1, ncols = 3, figsize = (20, 20))for ind, s in enumerate(kernels): img_blurred = cv2.blur(img, ksize = (s, s)) ax = axs[ind] ax.imshow(img_blurred) ax.axis('off')plt.show()"
},
{
"code": null,
"e": 3892,
"s": 3626,
"text": "Medium blurring is the same with average blurring except that it uses the median value instead of the average. Therefore when we have to handle sudden noises in the image such as ‘salt and pepper noise,’ it’ll be better to use medium blurring than average blurring."
},
{
"code": null,
"e": 4294,
"s": 3892,
"text": "Gaussian blurring is nothing but using the kernel whose values have a Gaussian distribution. The values are generated by a Gaussian function so it requires a sigma value for its parameter. As you can see the image above, the values of the kernel go higher near the center and go smaller near the corner. It’s good to apply this method to the noises that have a normal distribution such as white noise."
},
{
"code": null,
"e": 4669,
"s": 4294,
"text": "Bilateral Filtering is an advanced version of Gaussian blurring. Blurring produces not only dissolving noises but also smoothing edges. And bilateral filter can keep edges sharp while removing noises. It uses Gaussian-distributed values but takes both distance and the pixel value differences into account. Therefore it requires sigmaSpace and sigmaColor for the parameters."
},
{
"code": null,
"e": 5094,
"s": 4669,
"text": "# Blur the image img_0 = cv2.blur(img, ksize = (7, 7))img_1 = cv2.GaussianBlur(img, ksize = (7, 7), sigmaX = 0) img_2 = cv2.medianBlur(img, 7)img_3 = cv2.bilateralFilter(img, 7, sigmaSpace = 75, sigmaColor =75)# Plot the imagesimages = [img_0, img_1, img_2, img_3]fig, axs = plt.subplots(nrows = 1, ncols = 4, figsize = (20, 20))for ind, p in enumerate(images): ax = axs[ind] ax.imshow(p) ax.axis('off')plt.show()"
},
{
"code": null,
"e": 5403,
"s": 5094,
"text": "Thresholding transforms images into binary images. We need to set the threshold value and max values and then we convert the pixel values accordingly. There are five different types of thresholding: Binary, the inverse of Binary, Threshold to zero, the inverse of Threshold to Zero, and Threshold truncation."
},
{
"code": null,
"e": 5995,
"s": 5403,
"text": "img = cv2.imread('gradation.png')# Thresholding _, thresh_0 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)_, thresh_1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)_, thresh_2 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)_, thresh_3 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)_, thresh_4 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)# Plot the imagesimages = [img, thresh_0, thresh_1, thresh_2, thresh_3, thresh_4]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (13, 13))for ind, p in enumerate(images): ax = axs[ind//3, ind%3] ax.imshow(p)plt.show()"
},
{
"code": null,
"e": 6321,
"s": 5995,
"text": "You can see how each type of thresholding can be expressed in a mathematical way and I(x, y) is the intensity at the point, or the pixel value at (x, y). But I prefer to understand the concept visually. Take a look at the picture on the right. The images are way better for you to comprehend the difference between the types."
},
{
"code": null,
"e": 6890,
"s": 6321,
"text": "But don’t you think it’s too harsh to take just one value of threshold and apply it to all parts of an image? What if we have a picture with various amount of lighting in different areas? In this case, applying one value to the whole image would be a bad choice. A better approach would be using different thresholds for each part of the image. There is another technique called Adaptive thresholding, which serves this issue. By calculating the threshold within the neighborhood area of the image, we can achieve a better result from images with varying illumination."
},
{
"code": null,
"e": 7812,
"s": 6890,
"text": "# Convert the image to grayscaleimg = cv2.imread('text.jpg')img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# Adaptive Thresholding_, thresh_binary = cv2.threshold(img, thresh = 127, maxval = 255, type = cv2.THRESH_BINARY)adap_mean_2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 2)adap_mean_2_inv = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 7, 2)adap_mean_8 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 8)adap_gaussian_8 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 8)"
},
{
"code": null,
"e": 8170,
"s": 7812,
"text": "We need to convert the color mode to grayscale to apply adaptive thresholding. The parameters of adaptive thresholding are maxValue (which I set 255 above), adaptiveMethod , thresholdType , blockSize and C . And the adaptive method here has two kinds: ADAPTIVE_THRESH_MEAN_C , ADAPTIVE_THRESH_GAUSSIAN_C . Let’s just see how images are produced differently."
},
{
"code": null,
"e": 8470,
"s": 8170,
"text": "# Plot the imagesimages = [img, thresh_binary, adap_mean_2, adap_mean_2_inv, adap_mean_8, adap_gaussian_8]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (15, 15))for ind, p in enumerate(images): ax = axs[ind%2, ind//2] ax.imshow(p, cmap = 'gray') ax.axis('off')plt.show()"
},
{
"code": null,
"e": 9017,
"s": 8470,
"text": "We have the original image and the one with binary thresholding on the left line. Compare this with the second and third image on the upper line, which is produced by ADAPTIVE_THRESH_MEAN_C . It shows a more detailed result than that of binary thresholding. We can also see that it gets more explicit when the C value is bigger. C indicates how much we’ll subtract from the mean or weighted mean. With the two images on the right line, we can also compare the effect of ADAPTIVE_THRESH_MEAN_C and ADAPTIVE_THRESH_GAUSSIAN_C with the same C value."
},
{
"code": null,
"e": 9494,
"s": 9017,
"text": "I believe we are already familiar with the concept of gradients. In mathematics, the gradient geometrically represents the slope of the graph of a function with multi-variables. As it is a vector-valued function, it takes a direction and a magnitude as its components. Here we can also bring the same concept to the pixel values of images as well. The image gradient represents directional changes in the intensity or color mode and we can use this concept for locating edges."
},
{
"code": null,
"e": 9797,
"s": 9494,
"text": "# Apply gradient filteringsobel_x = cv2.Sobel(img, cv2.CV_64F, dx = 1, dy = 0, ksize = 5)sobel_y = cv2.Sobel(img, cv2.CV_64F, dx = 0, dy = 1, ksize = 5)blended = cv2.addWeighted(src1=sobel_x, alpha=0.5, src2=sobel_y, beta=0.5, gamma=0)laplacian = cv2.Laplacian(img, cv2.CV_64F)"
},
{
"code": null,
"e": 10139,
"s": 9797,
"text": "Sobel operation uses both Gaussian smoothing and differentiation. We apply it by cv2.Sobel() and two different directions are available: vertical (sobel_x) and horizontal (sobel_y). dx and dy indicates the derivatives. When dx = 1 , the operator calculates the derivatives of the pixel values along the horizontal direction to make a filter."
},
{
"code": null,
"e": 10408,
"s": 10139,
"text": "We can also apply in both directions by summing the two filters of sobel_x and sobel_y . With the function cv2.addWeighted() , we can calculate the weighted sum of the filters. As you can see above in the code cell, I gave the same amount of weight to the two filters."
},
{
"code": null,
"e": 10512,
"s": 10408,
"text": "Laplacian operation uses the second derivatives of x and y. The mathematical expression is shown below."
},
{
"code": null,
"e": 10584,
"s": 10512,
"text": "A picture is worth a thousand words. Let’s see how the images are like."
},
{
"code": null,
"e": 10792,
"s": 10584,
"text": "# Plot the imagesimages = [sobel_x, sobel_y, blended, laplacian]plt.figure(figsize = (20, 20))for i in range(4): plt.subplot(1, 4, i+1) plt.imshow(images[i], cmap = 'gray') plt.axis('off')plt.show()"
},
{
"code": null,
"e": 11078,
"s": 10792,
"text": "It’s apparent that the first and second image have a directional pattern. With the first image, we can clearly see the edges in the vertical direction. With the second image, we can see the horizontal edges. And both the third and fourth images, the edges on both directions are shown."
},
{
"code": null,
"e": 11241,
"s": 11078,
"text": "It’s also possible to manipulate the figures of images by filtering, which is called as morphological transformation. Let’s talk about erosion and dilation first."
},
{
"code": null,
"e": 11469,
"s": 11241,
"text": "Erosion is the technique for shrinking figures and it’s usually processed in a grayscale. The shape of filters can be a rectangle, an ellipse, and a cross shape. By applying a filter we remove any 0 values under the given area."
},
{
"code": null,
"e": 11518,
"s": 11469,
"text": "Let’s see how these can be implemented in codes."
},
{
"code": null,
"e": 12006,
"s": 11518,
"text": "img = cv2.imread('simpson.jpg')# Create erosion kernels kernel_0 = np.ones((9, 9), np.uint8)kernel_1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))kernel_2 = cv2.getStructuringElement(cv2.MORPH_CROSS, (9, 9))kernels = [kernel_0, kernel_1, kernel_2]# Plot the imagesplt.figure(figsize = (20, 20))for i in range(3): img_copy = img.copy() img_copy = cv2.erode(img_copy, kernels[i], iterations = 3) plt.subplot(1, 3, i+1) plt.imshow(img_copy) plt.axis('off')plt.show()"
},
{
"code": null,
"e": 12360,
"s": 12006,
"text": "Check out how the Simpson’s family shrank with different types of kernels applied. (Sorry to Simpson for losing his hands!) We can see the image with the ellipse filter is eroded in a “round” way while the one with the basic filter with a squared shape is eroded in a “linear” way. The last one with the cross filter shows it shrank in a “diagonal” way."
},
{
"code": null,
"e": 12538,
"s": 12360,
"text": "Dilation is the opposite to erosion. It is making objects expand and the operation will be also opposite to that of erosion. Let’s check out the result with the code as follows."
},
{
"code": null,
"e": 12788,
"s": 12538,
"text": "# Apply dilationkernel = np.ones((9, 9), np.uint8)img_dilate = cv2.dilate(img, kernel, iterations = 3)plt.figure(figsize = (20, 10))plt.subplot(1, 2, 1); plt.imshow(img, cmap=\"gray\")plt.subplot(1, 2, 2); plt.imshow(img_dilate, cmap=\"gray\")plt.show()"
},
{
"code": null,
"e": 13012,
"s": 12788,
"text": "Opening and closing operation is the mixed version of erosion and dilation. Opening performs erosion first and then dilation is performed on the result from the erosion while closing performs dilation first and the erosion."
},
{
"code": null,
"e": 13306,
"s": 13012,
"text": "As you can see the picture above, closing is useful to detect the overall contour of a figure and opening is suitable to detect subpatterns. We can implement these operators with the function cv2.morphologyEx() shown below. The parameter op indicates which type of operator we’re going to use."
},
{
"code": null,
"e": 13962,
"s": 13306,
"text": "# Apply the operationskernel = np.ones((9, 9), np.uint8)img_open = cv2.morphologyEx(img, op= cv2.MORPH_OPEN, kernel)img_close = cv2.morphologyEx(img, op= cv2.MORPH_CLOSE, kernel)img_grad = cv2.morphologyEx(img, op= cv2.MORPH_GRADIENT, kernel)img_tophat = cv2.morphologyEx(img, op= cv2.MORPH_TOPHAT, kernel)img_blackhat = cv2.morphologyEx(img, op= cv2.MORPH_BLACKHAT, kernel)# Plot the imagesimages = [img, img_open, img_close, img_grad, img_tophat, img_blackhat]fig, axs = plt.subplots(nrows = 2, ncols = 3, figsize = (15, 15))for ind, p in enumerate(images): ax = axs[ind//3, ind%3] ax.imshow(p, cmap = 'gray') ax.axis('off')plt.show()"
},
{
"code": null,
"e": 14394,
"s": 13962,
"text": "Note that the Simpson’s hand is depicted differently in the images with the opening filter and closing filter. Gradient filter (MORPH_CGRADIENT) is the subtracted area from dilation to erosion. Top hat filter (MORPH_TOPHAT) is the subtracted area from opening to the original image while black hot filter (MORPH_BLACKHAT) is that from closing. I’d recommend you to visit here to get further explanations on morphological operators."
},
{
"code": null,
"e": 14697,
"s": 14394,
"text": "Did you enjoy the various image manipulation techniques? Besides the things we’ve discussed, there are other things available in OpenCV. So don’t hesitate to take a visit and check out OpenCV documentation. Next time will be about the detection techniques such as contour detection and face detections."
}
] |
Java.util.Observable class in Java - GeeksforGeeks
|
08 Jul, 2017
java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change.
Note: Observing class must implement the Observer interface, which defines the update( ) method.
An object that is being observed must follow two simple rules :
If it is changed, it must call setChanged( ) method.When it is ready to notify observers of this change, it must call notifyObservers( ) method. This causes the update( ) method in the observing object(s) to be called.
If it is changed, it must call setChanged( ) method.
When it is ready to notify observers of this change, it must call notifyObservers( ) method. This causes the update( ) method in the observing object(s) to be called.
Be careful, if the object calls notifyObservers( ) method without having previously called
setChanged( ) method, no action will take place.
The observed object must call both setChanged( ) and notifyObservers( ) method, before update( ) will be called.Constructor of java.util.Observable :
Observable( )Construct an Observable with zero Observers.
Methods:
addObserver(Observer observer) : Adds observer to the list of objects observing the invoking object.Syntax : public void addObserver(Observer observer)
Exception : NullPointerException -> if the parameter observer is null
// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 is added"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}Output :Observer1 is addedsetChanged() : Called when the invoking object has changed.Syntax : protected void setChanged( )
Exception : NA.
// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println("Change status with setChanged :" + hasChanged()); notifyObservers(); } void func2() { System.out.println("Change status without setChanged :" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}Output :Change status with setChanged :true
Change status without setChanged :falseclearChanged(): Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged( ) method will now return false.Syntax : protected void clearChanged( )
Exception : NA
// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Inside Observer1"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}Output :No OutputNo output is obtained because clearChanged( ) method has removed all the changes.notifyObservers() : Notifies all observers of the invoking object that it has changed by calling update( ).A null is passed as the second argument to update( ).Syntax : public void notifyObservers( )
Exception : NA
// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified
Observer1 NotifiednotifyObservers(Object obj) : Notifies all observers of the invoking object that it has changed by calling update( ).obj is passed as an argument to update( ).Syntax : public void notifyObservers(Object obj)
Exception : NA
// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified with value : " + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified with value : " + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified with value : 10
Observer1 Notified with value : 10countObservers( ) : Returns the number of objects observing the invoking object.Syntax : public int countObservers( )
Returns : the number of observers of this object
Exception : NA
// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println("Number of observers is " + count_observer); beingObserved.func1(); }}Output :Number of observers is 2
Observer2
Observer1deleteObserver(Observer observer): Removes observer from the list of objects observing the invoking object.Passing null to this method will have no effect.Syntax : public void deleteObserver(Observer observer)
Exception : NA
// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after"+ " calling deleteObserver(): " + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers aftercalling deleteObserver(): 1
Observer2deleteObservers() : Removes all observers for the invoking object.Syntax : public void deleteObservers()
Exception : NA
// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after "+ "calling deleteObserver(): " + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers after calling deleteObserver(): 0
addObserver(Observer observer) : Adds observer to the list of objects observing the invoking object.Syntax : public void addObserver(Observer observer)
Exception : NullPointerException -> if the parameter observer is null
// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 is added"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}Output :Observer1 is added
Syntax : public void addObserver(Observer observer)
Exception : NullPointerException -> if the parameter observer is null
// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 is added"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}
Output :
Observer1 is added
setChanged() : Called when the invoking object has changed.Syntax : protected void setChanged( )
Exception : NA.
// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println("Change status with setChanged :" + hasChanged()); notifyObservers(); } void func2() { System.out.println("Change status without setChanged :" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}Output :Change status with setChanged :true
Change status without setChanged :false
Syntax : protected void setChanged( )
Exception : NA.
// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println("Change status with setChanged :" + hasChanged()); notifyObservers(); } void func2() { System.out.println("Change status without setChanged :" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}
Output :
Change status with setChanged :true
Change status without setChanged :false
clearChanged(): Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged( ) method will now return false.Syntax : protected void clearChanged( )
Exception : NA
// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Inside Observer1"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}Output :No OutputNo output is obtained because clearChanged( ) method has removed all the changes.
Syntax : protected void clearChanged( )
Exception : NA
// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Inside Observer1"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}
Output :
No Output
No output is obtained because clearChanged( ) method has removed all the changes.
notifyObservers() : Notifies all observers of the invoking object that it has changed by calling update( ).A null is passed as the second argument to update( ).Syntax : public void notifyObservers( )
Exception : NA
// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified
Observer1 Notified
Syntax : public void notifyObservers( )
Exception : NA
// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}
Output :
Observer2 Notified
Observer1 Notified
notifyObservers(Object obj) : Notifies all observers of the invoking object that it has changed by calling update( ).obj is passed as an argument to update( ).Syntax : public void notifyObservers(Object obj)
Exception : NA
// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified with value : " + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified with value : " + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified with value : 10
Observer1 Notified with value : 10
Syntax : public void notifyObservers(Object obj)
Exception : NA
// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1 Notified with value : " + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2 Notified with value : " + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}
Output :
Observer2 Notified with value : 10
Observer1 Notified with value : 10
countObservers( ) : Returns the number of objects observing the invoking object.Syntax : public int countObservers( )
Returns : the number of observers of this object
Exception : NA
// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println("Number of observers is " + count_observer); beingObserved.func1(); }}Output :Number of observers is 2
Observer2
Observer1
Syntax : public int countObservers( )
Returns : the number of observers of this object
Exception : NA
// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println("Number of observers is " + count_observer); beingObserved.func1(); }}
Output :
Number of observers is 2
Observer2
Observer1
deleteObserver(Observer observer): Removes observer from the list of objects observing the invoking object.Passing null to this method will have no effect.Syntax : public void deleteObserver(Observer observer)
Exception : NA
// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after"+ " calling deleteObserver(): " + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers aftercalling deleteObserver(): 1
Observer2
Syntax : public void deleteObserver(Observer observer)
Exception : NA
// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after"+ " calling deleteObserver(): " + count_observer); beingObserved.func1(); }}
Output :
Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers aftercalling deleteObserver(): 1
Observer2
deleteObservers() : Removes all observers for the invoking object.Syntax : public void deleteObservers()
Exception : NA
// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after "+ "calling deleteObserver(): " + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers after calling deleteObserver(): 0
Syntax : public void deleteObservers()
Exception : NA
// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer1"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println("Observer2"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println("Number of observers before" + " calling deleteObserver(): " + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println("No. of observers after "+ "calling deleteObserver(): " + count_observer); beingObserved.func1(); }}
Output :
Number of observers before calling deleteObserver(): 2
Observer2
Observer1
No. of observers after calling deleteObserver(): 0
Ref: Observables in Java
This article is contributed by Dipak Chouhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
LinkedList in Java
Collections in Java
|
[
{
"code": null,
"e": 24449,
"s": 24421,
"text": "\n08 Jul, 2017"
},
{
"code": null,
"e": 24701,
"s": 24449,
"text": "java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change."
},
{
"code": null,
"e": 24798,
"s": 24701,
"text": "Note: Observing class must implement the Observer interface, which defines the update( ) method."
},
{
"code": null,
"e": 24862,
"s": 24798,
"text": "An object that is being observed must follow two simple rules :"
},
{
"code": null,
"e": 25081,
"s": 24862,
"text": "If it is changed, it must call setChanged( ) method.When it is ready to notify observers of this change, it must call notifyObservers( ) method. This causes the update( ) method in the observing object(s) to be called."
},
{
"code": null,
"e": 25134,
"s": 25081,
"text": "If it is changed, it must call setChanged( ) method."
},
{
"code": null,
"e": 25301,
"s": 25134,
"text": "When it is ready to notify observers of this change, it must call notifyObservers( ) method. This causes the update( ) method in the observing object(s) to be called."
},
{
"code": null,
"e": 25441,
"s": 25301,
"text": "Be careful, if the object calls notifyObservers( ) method without having previously called\nsetChanged( ) method, no action will take place."
},
{
"code": null,
"e": 25591,
"s": 25441,
"text": "The observed object must call both setChanged( ) and notifyObservers( ) method, before update( ) will be called.Constructor of java.util.Observable :"
},
{
"code": null,
"e": 25649,
"s": 25591,
"text": "Observable( )Construct an Observable with zero Observers."
},
{
"code": null,
"e": 25658,
"s": 25649,
"text": "Methods:"
},
{
"code": null,
"e": 36426,
"s": 25658,
"text": "addObserver(Observer observer) : Adds observer to the list of objects observing the invoking object.Syntax : public void addObserver(Observer observer)\nException : NullPointerException -> if the parameter observer is null\n// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 is added\"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}Output :Observer1 is addedsetChanged() : Called when the invoking object has changed.Syntax : protected void setChanged( )\nException : NA.\n// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println(\"Change status with setChanged :\" + hasChanged()); notifyObservers(); } void func2() { System.out.println(\"Change status without setChanged :\" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}Output :Change status with setChanged :true\nChange status without setChanged :falseclearChanged(): Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged( ) method will now return false.Syntax : protected void clearChanged( )\nException : NA\n// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Inside Observer1\"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}Output :No OutputNo output is obtained because clearChanged( ) method has removed all the changes.notifyObservers() : Notifies all observers of the invoking object that it has changed by calling update( ).A null is passed as the second argument to update( ).Syntax : public void notifyObservers( )\nException : NA\n// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified\nObserver1 NotifiednotifyObservers(Object obj) : Notifies all observers of the invoking object that it has changed by calling update( ).obj is passed as an argument to update( ).Syntax : public void notifyObservers(Object obj)\nException : NA\n// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified with value : \" + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified with value : \" + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified with value : 10\nObserver1 Notified with value : 10countObservers( ) : Returns the number of objects observing the invoking object.Syntax : public int countObservers( )\nReturns : the number of observers of this object\nException : NA\n// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers is \" + count_observer); beingObserved.func1(); }}Output :Number of observers is 2\nObserver2\nObserver1deleteObserver(Observer observer): Removes observer from the list of objects observing the invoking object.Passing null to this method will have no effect.Syntax : public void deleteObserver(Observer observer)\nException : NA\n// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after\"+ \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers aftercalling deleteObserver(): 1\nObserver2deleteObservers() : Removes all observers for the invoking object.Syntax : public void deleteObservers()\nException : NA\n// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after \"+ \"calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers after calling deleteObserver(): 0"
},
{
"code": null,
"e": 37351,
"s": 36426,
"text": "addObserver(Observer observer) : Adds observer to the list of objects observing the invoking object.Syntax : public void addObserver(Observer observer)\nException : NullPointerException -> if the parameter observer is null\n// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 is added\"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}Output :Observer1 is added"
},
{
"code": null,
"e": 37474,
"s": 37351,
"text": "Syntax : public void addObserver(Observer observer)\nException : NullPointerException -> if the parameter observer is null\n"
},
{
"code": "// Java code to demonstrate addObserver() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 is added\"); }} // This is class being observedclass BeingObserved extends Observable{ void incre() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.incre(); }}",
"e": 38151,
"s": 37474,
"text": null
},
{
"code": null,
"e": 38160,
"s": 38151,
"text": "Output :"
},
{
"code": null,
"e": 38179,
"s": 38160,
"text": "Observer1 is added"
},
{
"code": null,
"e": 39264,
"s": 38179,
"text": "setChanged() : Called when the invoking object has changed.Syntax : protected void setChanged( )\nException : NA.\n// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println(\"Change status with setChanged :\" + hasChanged()); notifyObservers(); } void func2() { System.out.println(\"Change status without setChanged :\" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}Output :Change status with setChanged :true\nChange status without setChanged :false"
},
{
"code": null,
"e": 39319,
"s": 39264,
"text": "Syntax : protected void setChanged( )\nException : NA.\n"
},
{
"code": "// Java code to demonstrate setChanged() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); System.out.println(\"Change status with setChanged :\" + hasChanged()); notifyObservers(); } void func2() { System.out.println(\"Change status without setChanged :\" + hasChanged()); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { boolean status; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); beingObserved.func2(); }}",
"e": 40208,
"s": 39319,
"text": null
},
{
"code": null,
"e": 40217,
"s": 40208,
"text": "Output :"
},
{
"code": null,
"e": 40293,
"s": 40217,
"text": "Change status with setChanged :true\nChange status without setChanged :false"
},
{
"code": null,
"e": 41435,
"s": 40293,
"text": "clearChanged(): Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged( ) method will now return false.Syntax : protected void clearChanged( )\nException : NA\n// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Inside Observer1\"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}Output :No OutputNo output is obtained because clearChanged( ) method has removed all the changes."
},
{
"code": null,
"e": 41491,
"s": 41435,
"text": "Syntax : protected void clearChanged( )\nException : NA\n"
},
{
"code": "// Java code to demonstrate clearChanged() methodimport java.util.*; // This is the observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Inside Observer1\"); }} // This is the class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); // clearChanged method removes all the changes made by setChanged method clearChanged(); notifyObservers(); }} class ObserverDemo {// Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); beingObserved.addObserver(observer1); beingObserved.func1(); }}",
"e": 42279,
"s": 41491,
"text": null
},
{
"code": null,
"e": 42288,
"s": 42279,
"text": "Output :"
},
{
"code": null,
"e": 42298,
"s": 42288,
"text": "No Output"
},
{
"code": null,
"e": 42380,
"s": 42298,
"text": "No output is obtained because clearChanged( ) method has removed all the changes."
},
{
"code": null,
"e": 43692,
"s": 42380,
"text": "notifyObservers() : Notifies all observers of the invoking object that it has changed by calling update( ).A null is passed as the second argument to update( ).Syntax : public void notifyObservers( )\nException : NA\n// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified\nObserver1 Notified"
},
{
"code": null,
"e": 43748,
"s": 43692,
"text": "Syntax : public void notifyObservers( )\nException : NA\n"
},
{
"code": "// Java code to demonstrate notifyObservers( ) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered*/ notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}",
"e": 44800,
"s": 43748,
"text": null
},
{
"code": null,
"e": 44809,
"s": 44800,
"text": "Output :"
},
{
"code": null,
"e": 44847,
"s": 44809,
"text": "Observer2 Notified\nObserver1 Notified"
},
{
"code": null,
"e": 46359,
"s": 44847,
"text": "notifyObservers(Object obj) : Notifies all observers of the invoking object that it has changed by calling update( ).obj is passed as an argument to update( ).Syntax : public void notifyObservers(Object obj)\nException : NA\n// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified with value : \" + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified with value : \" + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}Output :Observer2 Notified with value : 10\nObserver1 Notified with value : 10"
},
{
"code": null,
"e": 46424,
"s": 46359,
"text": "Syntax : public void notifyObservers(Object obj)\nException : NA\n"
},
{
"code": "// Java code to demonstrate notifyObservers(Object obj) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1 Notified with value : \" + ((Integer)arg).intValue()); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2 Notified with value : \" + ((Integer)arg).intValue()); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); /*This method notifies the change to all the observers that are registered and passes an object*/ notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); beingObserved.func1(); }}",
"e": 47636,
"s": 46424,
"text": null
},
{
"code": null,
"e": 47645,
"s": 47636,
"text": "Output :"
},
{
"code": null,
"e": 47715,
"s": 47645,
"text": "Observer2 Notified with value : 10\nObserver1 Notified with value : 10"
},
{
"code": null,
"e": 49009,
"s": 47715,
"text": "countObservers( ) : Returns the number of objects observing the invoking object.Syntax : public int countObservers( )\nReturns : the number of observers of this object\nException : NA\n// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers is \" + count_observer); beingObserved.func1(); }}Output :Number of observers is 2\nObserver2\nObserver1"
},
{
"code": null,
"e": 49112,
"s": 49009,
"text": "Syntax : public int countObservers( )\nReturns : the number of observers of this object\nException : NA\n"
},
{
"code": "// Java code to demonstrate countObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); int count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers is \" + count_observer); beingObserved.func1(); }}",
"e": 50172,
"s": 49112,
"text": null
},
{
"code": null,
"e": 50181,
"s": 50172,
"text": "Output :"
},
{
"code": null,
"e": 50226,
"s": 50181,
"text": "Number of observers is 2\nObserver2\nObserver1"
},
{
"code": null,
"e": 52038,
"s": 50226,
"text": "deleteObserver(Observer observer): Removes observer from the list of objects observing the invoking object.Passing null to this method will have no effect.Syntax : public void deleteObserver(Observer observer)\nException : NA\n// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after\"+ \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers aftercalling deleteObserver(): 1\nObserver2"
},
{
"code": null,
"e": 52109,
"s": 52038,
"text": "Syntax : public void deleteObserver(Observer observer)\nException : NA\n"
},
{
"code": "// Java code to demonstrate deleteObserver(Observer observer) methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting observer1 beingObserved.deleteObserver(observer1); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after\"+ \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}",
"e": 53554,
"s": 52109,
"text": null
},
{
"code": null,
"e": 53563,
"s": 53554,
"text": "Output :"
},
{
"code": null,
"e": 53698,
"s": 53563,
"text": "Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers aftercalling deleteObserver(): 1\nObserver2"
},
{
"code": null,
"e": 55391,
"s": 53698,
"text": "deleteObservers() : Removes all observers for the invoking object.Syntax : public void deleteObservers()\nException : NA\n// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after \"+ \"calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}Output :Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers after calling deleteObserver(): 0"
},
{
"code": null,
"e": 55446,
"s": 55391,
"text": "Syntax : public void deleteObservers()\nException : NA\n"
},
{
"code": "// Java code to demonstrate deleteObservers() methodimport java.util.*; // This is first observerclass Observer1 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer1\"); }} // This is second observerclass Observer2 implements Observer{ public void update(Observable obj, Object arg) { System.out.println(\"Observer2\"); }} // This is class being observedclass BeingObserved extends Observable{ void func1() { setChanged(); notifyObservers(new Integer(10)); }} class ObserverDemo { // Driver method of the program public static void main(String args[]) { int count_observer; BeingObserved beingObserved = new BeingObserved(); Observer1 observer1 = new Observer1(); Observer2 observer2 = new Observer2(); beingObserved.addObserver(observer1); beingObserved.addObserver(observer2); count_observer = beingObserved.countObservers(); System.out.println(\"Number of observers before\" + \" calling deleteObserver(): \" + count_observer); beingObserved.func1(); // Deleting all observers beingObserved.deleteObservers(); count_observer = beingObserved.countObservers(); System.out.println(\"No. of observers after \"+ \"calling deleteObserver(): \" + count_observer); beingObserved.func1(); }}",
"e": 56886,
"s": 55446,
"text": null
},
{
"code": null,
"e": 56895,
"s": 56886,
"text": "Output :"
},
{
"code": null,
"e": 57021,
"s": 56895,
"text": "Number of observers before calling deleteObserver(): 2\nObserver2\nObserver1\nNo. of observers after calling deleteObserver(): 0"
},
{
"code": null,
"e": 57046,
"s": 57021,
"text": "Ref: Observables in Java"
},
{
"code": null,
"e": 57347,
"s": 57046,
"text": "This article is contributed by Dipak Chouhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 57472,
"s": 57347,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 57492,
"s": 57472,
"text": "Java - util package"
},
{
"code": null,
"e": 57497,
"s": 57492,
"text": "Java"
},
{
"code": null,
"e": 57502,
"s": 57497,
"text": "Java"
},
{
"code": null,
"e": 57600,
"s": 57502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57609,
"s": 57600,
"text": "Comments"
},
{
"code": null,
"e": 57622,
"s": 57609,
"text": "Old Comments"
},
{
"code": null,
"e": 57673,
"s": 57622,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 57703,
"s": 57673,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 57734,
"s": 57703,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 57753,
"s": 57734,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 57785,
"s": 57753,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 57803,
"s": 57785,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 57823,
"s": 57803,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 57855,
"s": 57823,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 57874,
"s": 57855,
"text": "LinkedList in Java"
}
] |
How to increase the size of points on a scatterplot if the points are drawn based on another sequence using ggplot2 in R?
|
When we draw a scatterplot using ggplot2 with points based on a sequence of values then the size of the points might be very small for the small values. As a result, it becomes a little difficult to view the points. Therefore, we might want to increase the size of those points. It can be done by using scale_size_continuous function in which we can set a range for the points size.
Consider the below data frame −
Live Demo
x<-rnorm(10,1)
y<-rnorm(10,2)
Pair<-1:10
df<-data.frame(x,y,Pair)
df
x y Pair
1 0.2722750 0.7855144 1
2 0.6708724 2.8385502 2
3 1.6939261 1.7415868 3
4 0.5773440 2.1596557 4
5 0.1965571 0.7356820 5
6 0.3368027 1.4774414 6
7 0.8248820 2.8211750 7
8 -0.3364834 2.5258274 8
9 -0.3229903 1.1579749 9
10 -1.1594988 1.0636472 10
Loading ggplot2 package and creating a scatterplot with points size based on Pair column −
library(ggplot2)
ggplot(df,aes(x,y,size=Pair))+geom_point()
Creating the scatterplot with a range of point size −
ggplot(df,aes(x,y,size=Pair))+geom_point()+scale_size_continuous(range = c(2,5))
|
[
{
"code": null,
"e": 1445,
"s": 1062,
"text": "When we draw a scatterplot using ggplot2 with points based on a sequence of values then the size of the points might be very small for the small values. As a result, it becomes a little difficult to view the points. Therefore, we might want to increase the size of those points. It can be done by using scale_size_continuous function in which we can set a range for the points size."
},
{
"code": null,
"e": 1477,
"s": 1445,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1488,
"s": 1477,
"text": " Live Demo"
},
{
"code": null,
"e": 1557,
"s": 1488,
"text": "x<-rnorm(10,1)\ny<-rnorm(10,2)\nPair<-1:10\ndf<-data.frame(x,y,Pair)\ndf"
},
{
"code": null,
"e": 1857,
"s": 1557,
"text": " x y Pair\n1 0.2722750 0.7855144 1\n2 0.6708724 2.8385502 2\n3 1.6939261 1.7415868 3\n4 0.5773440 2.1596557 4\n5 0.1965571 0.7356820 5\n6 0.3368027 1.4774414 6\n7 0.8248820 2.8211750 7\n8 -0.3364834 2.5258274 8\n9 -0.3229903 1.1579749 9\n10 -1.1594988 1.0636472 10"
},
{
"code": null,
"e": 1948,
"s": 1857,
"text": "Loading ggplot2 package and creating a scatterplot with points size based on Pair column −"
},
{
"code": null,
"e": 2008,
"s": 1948,
"text": "library(ggplot2)\nggplot(df,aes(x,y,size=Pair))+geom_point()"
},
{
"code": null,
"e": 2062,
"s": 2008,
"text": "Creating the scatterplot with a range of point size −"
},
{
"code": null,
"e": 2143,
"s": 2062,
"text": "ggplot(df,aes(x,y,size=Pair))+geom_point()+scale_size_continuous(range = c(2,5))"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.