title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Find value in a MongoDB Array with multiple criteria? | To find value in the array with multiple criteria, for example, you can use elemMatchalongwithgt and $lt. The syntax is as follows β
db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPo sitiveValue}}}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows β
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Larry","StudentMarks":[-150,150]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77daf6fc4e719b197a12f5")
}
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Mike","StudentMarks":[19]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77db09fc4e719b197a12f6")
}
Display all documents from a collection with the help of find() method. The query is as follows β
> db.findValueInArrayWithMultipleCriteriaDemo.find().pretty();
The following is the output β
{
"_id" : ObjectId("5c77daf6fc4e719b197a12f5"),
"StudentName" : "Larry",
"StudentMarks" : [
-150,
150
]
}
{
"_id" : ObjectId("5c77db09fc4e719b197a12f6"),
"StudentName" : "Mike",
"StudentMarks" : [
19
]
}
Here is the query to find value in the array with multiple criteria. For example, here we are considering marks greater than -20 and less than 20 β
> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();
The following is the output β
{
"_id" : ObjectId("5c77db09fc4e719b197a12f6"),
"StudentName" : "Mike",
"StudentMarks" : [
19
]
} | [
{
"code": null,
"e": 1195,
"s": 1062,
"text": "To find value in the array with multiple criteria, for example, you can use elemMatchalongwithgt and $lt. The syntax is as follows β"
},
{
"code": null,
"e": 1309,
"s": 1195,
"text": "db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPo sitiveValue}}}).pretty();"
},
{
"code": null,
"e": 1452,
"s": 1309,
"text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows β"
},
{
"code": null,
"e": 1831,
"s": 1452,
"text": "> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({\"StudentName\":\"Larry\",\"StudentMarks\":[-150,150]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77daf6fc4e719b197a12f5\")\n}\n> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({\"StudentName\":\"Mike\",\"StudentMarks\":[19]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77db09fc4e719b197a12f6\")\n}"
},
{
"code": null,
"e": 1929,
"s": 1831,
"text": "Display all documents from a collection with the help of find() method. The query is as follows β"
},
{
"code": null,
"e": 1992,
"s": 1929,
"text": "> db.findValueInArrayWithMultipleCriteriaDemo.find().pretty();"
},
{
"code": null,
"e": 2022,
"s": 1992,
"text": "The following is the output β"
},
{
"code": null,
"e": 2268,
"s": 2022,
"text": "{\n \"_id\" : ObjectId(\"5c77daf6fc4e719b197a12f5\"),\n \"StudentName\" : \"Larry\",\n \"StudentMarks\" : [\n -150,\n 150\n ]\n}\n{\n \"_id\" : ObjectId(\"5c77db09fc4e719b197a12f6\"),\n \"StudentName\" : \"Mike\",\n \"StudentMarks\" : [\n 19\n ]\n}"
},
{
"code": null,
"e": 2416,
"s": 2268,
"text": "Here is the query to find value in the array with multiple criteria. For example, here we are considering marks greater than -20 and less than 20 β"
},
{
"code": null,
"e": 2523,
"s": 2416,
"text": "> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();"
},
{
"code": null,
"e": 2553,
"s": 2523,
"text": "The following is the output β"
},
{
"code": null,
"e": 2669,
"s": 2553,
"text": "{\n \"_id\" : ObjectId(\"5c77db09fc4e719b197a12f6\"),\n \"StudentName\" : \"Mike\",\n \"StudentMarks\" : [\n 19\n ]\n}"
}
] |
How to add/append content to an existing file using Java? | In most scenarios, if you try to write content to a file, using the classes of the java.io package, the file will be overwritten i.e. data existing in the file is erased and the new data is added to it.
But, in certain scenarios like logging exceptions into a file (without using logger frameworks) you need to append data (message) in the next line of the file.
You can do this using the Files class of the java.nio package. This class provides a method named write() which accepts
An object of the class Path, representing a file.
An object of the class Path, representing a file.
A byte array holding the data to the file.
A byte array holding the data to the file.
A variable argument of the type OpenOption (interface) as a value to it you can pass one of the elements of StandardOpenOption enumeration which contains 10 options namely, APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE.
A variable argument of the type OpenOption (interface) as a value to it you can pass one of the elements of StandardOpenOption enumeration which contains 10 options namely, APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE.
You can invoke this method by passing the path of the file, byte array containing the data to be appended and, the option StandardOpenOption.APPEND.
Following Java program has an array storing 5 integer values, we are letting the user choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in a try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them, we are invoking the writeToFile() method.
This method accepts an exception object and appends it to a file using the write() method of the Files class.
public class LoggingToFile {
private static void writeToFile(Exception e) throws IOException {
//Retrieving the log file
Path logFile = Paths.get("ExceptionLog.txt");
//Preparing the data to be logged
byte bytes[] = ("\r\n"+LocalDateTime.now()+": "+e.toString()).getBytes();
//Appending the exception to your file
Files.write(logFile, bytes, StandardOpenOption.APPEND);
System.out.println("Exception logged to your file");
}
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
try {
int a = sc.nextInt();
int b = sc.nextInt();
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You have chosen a position which is not in the array");
writeLogToFile(ex);
}
catch(ArithmeticException ex) {
System.out.println("Warning: You cannot divide an number with 0");
writeLogToFile(ex);
}
catch(InputMismatchException ex) {
System.out.println("Warning: You have entered invalid input");
writeLogToFile(ex);
}
}
}
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
2
4
Warning: You cannot divide an number with 0
Exception logged to your file
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
5
12
Warning: You have chosen a position which is not in the array
Exception logged to your file
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
hello
Warning: You have entered invalid input
Exception logged to your file
2019-07-19T17:57:09.735: java.lang.ArithmeticException: / by zero
2019-07-19T17:57:39.025: java.lang.ArrayIndexOutOfBoundsException: 12
2019-07-19T18:00:23.374: java.util.InputMismatchException | [
{
"code": null,
"e": 1265,
"s": 1062,
"text": "In most scenarios, if you try to write content to a file, using the classes of the java.io package, the file will be overwritten i.e. data existing in the file is erased and the new data is added to it."
},
{
"code": null,
"e": 1425,
"s": 1265,
"text": "But, in certain scenarios like logging exceptions into a file (without using logger frameworks) you need to append data (message) in the next line of the file."
},
{
"code": null,
"e": 1545,
"s": 1425,
"text": "You can do this using the Files class of the java.nio package. This class provides a method named write() which accepts"
},
{
"code": null,
"e": 1595,
"s": 1545,
"text": "An object of the class Path, representing a file."
},
{
"code": null,
"e": 1645,
"s": 1595,
"text": "An object of the class Path, representing a file."
},
{
"code": null,
"e": 1688,
"s": 1645,
"text": "A byte array holding the data to the file."
},
{
"code": null,
"e": 1731,
"s": 1688,
"text": "A byte array holding the data to the file."
},
{
"code": null,
"e": 2002,
"s": 1731,
"text": "A variable argument of the type OpenOption (interface) as a value to it you can pass one of the elements of StandardOpenOption enumeration which contains 10 options namely, APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE."
},
{
"code": null,
"e": 2273,
"s": 2002,
"text": "A variable argument of the type OpenOption (interface) as a value to it you can pass one of the elements of StandardOpenOption enumeration which contains 10 options namely, APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE."
},
{
"code": null,
"e": 2422,
"s": 2273,
"text": "You can invoke this method by passing the path of the file, byte array containing the data to be appended and, the option StandardOpenOption.APPEND."
},
{
"code": null,
"e": 2821,
"s": 2422,
"text": "Following Java program has an array storing 5 integer values, we are letting the user choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in a try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them, we are invoking the writeToFile() method."
},
{
"code": null,
"e": 2931,
"s": 2821,
"text": "This method accepts an exception object and appends it to a file using the write() method of the Files class."
},
{
"code": null,
"e": 4405,
"s": 2931,
"text": "public class LoggingToFile {\n private static void writeToFile(Exception e) throws IOException {\n //Retrieving the log file\n Path logFile = Paths.get(\"ExceptionLog.txt\");\n //Preparing the data to be logged\n byte bytes[] = (\"\\r\\n\"+LocalDateTime.now()+\": \"+e.toString()).getBytes();\n //Appending the exception to your file\n Files.write(logFile, bytes, StandardOpenOption.APPEND);\n System.out.println(\"Exception logged to your file\");\n }\n public static void main(String [] args) throws IOException {\n Scanner sc = new Scanner(System.in);\n int[] arr = {10, 20, 30, 2, 0, 8};\n System.out.println(\"Array: \"+Arrays.toString(arr));\n System.out.println(\"Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)\");\n try {\n int a = sc.nextInt();\n int b = sc.nextInt();\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }\n catch(ArrayIndexOutOfBoundsException ex) {\n System.out.println(\"Warning: You have chosen a position which is not in the array\");\n writeLogToFile(ex);\n }\n catch(ArithmeticException ex) {\n System.out.println(\"Warning: You cannot divide an number with 0\");\n writeLogToFile(ex);\n }\n catch(InputMismatchException ex) {\n System.out.println(\"Warning: You have entered invalid input\");\n writeLogToFile(ex);\n }\n }\n}"
},
{
"code": null,
"e": 4628,
"s": 4405,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n2\n4\nWarning: You cannot divide an number with 0\nException logged to your file"
},
{
"code": null,
"e": 4870,
"s": 4628,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n5\n12\nWarning: You have chosen a position which is not in the array\nException logged to your file"
},
{
"code": null,
"e": 5091,
"s": 4870,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\nhello\nWarning: You have entered invalid input\nException logged to your file"
},
{
"code": null,
"e": 5285,
"s": 5091,
"text": "2019-07-19T17:57:09.735: java.lang.ArithmeticException: / by zero\n2019-07-19T17:57:39.025: java.lang.ArrayIndexOutOfBoundsException: 12\n2019-07-19T18:00:23.374: java.util.InputMismatchException"
}
] |
Difference between "." and "#" selector in CSS - GeeksforGeeks | 30 Jun, 2021
The dot(.) and hash(#) both of them are used as a CSS selector. Both selectors are used to select the content to set the style. CSS selectors select HTML elements according to its id, class, type, attribute, etc.Id selector(β#β): The id selector selects the id attribute of an HTML element to select a specific element. An id is always unique within the page so it is chosen to select a single, unique element. It is written with the hash character (#), followed by the id of the element.
Syntax:
#element_id_name{
// CSS properties
}
Example: In this code we will use only id selector to set style to the HTML elements.
html
<!DOCTYPE html> <html> <head> <title>CSS Selector id(#)</title> <style> #container { width: 400px; height: 150px; border: 2px solid black; text-align: center; } #geeks { color: green; } #gfg { font-family: Courier New; } </style></head> <body> <div id="container"> <h1 id="geeks">GeeksforGeeks</h1> <h4 id="gfg">A Computer Science portal for Geeks</h4> <b class="selector">CSS Selector id(#)</b> </div></body> </html>
Output:
Class Selector(β.β): The class selector selects HTML elements with a specific class attribute. It is used with a period character β.β (full stop symbol) followed by the class name.
Syntax:
.element_class_name{
// CSS properties
}
Example: In this code we will use only class selector to set style to the HTML elements.
html
<!DOCTYPE html> <html> <head> <title>CSS class Selector</title> <style> .container { width: 400px; height: 150px; border: 2px solid black; text-align: center; } .geeks { color: green; } .selector { font-family: Courier New; } </style></head> <body> <div class="container"> <h1 class="geeks">GeeksforGeeks</h1> <h4 id="gfg">A Computer Science portal for Geeks</h4> <b class="selector">CSS Selector class(.)</b> </div></body> </html>
Output:
Difference between class (β.β) and id (β#β) Selectors:
Example: The Combine selector example, in this example we will use both the selectors β.β and β#β.
html
<!DOCTYPE html><html> <head> <style> /* #id selector */ #geeks { color:green; } /* .class selector */ .gfg { background-color: yellow; font-style:italic; color:green; } /* .class selector */ .options { background-color: yellow; color:purple; } </style> </head> <body style = "text-align:center"> <h1 id = "geeks"> GeeksforGeeks </h1> <h4>#id And .class Selector</h4> <div class = "gfg"> <p>A computer science portal for Geeks</p> </div> <div class="select"> <select name="slct" id="slct"> <option>Computer Science Subjects</option> <option class="options">Operating System</option> <option class="options">Computer Networks</option> <option class="options">Data Structure</option> <option class="options">Algorithm</option> <option class="options">C programming</option> <option class="options">JAVA</option> </select> </div> </body></html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
CSS-Misc
HTML-Misc
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25400,
"s": 25372,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25890,
"s": 25400,
"text": "The dot(.) and hash(#) both of them are used as a CSS selector. Both selectors are used to select the content to set the style. CSS selectors select HTML elements according to its id, class, type, attribute, etc.Id selector(β#β): The id selector selects the id attribute of an HTML element to select a specific element. An id is always unique within the page so it is chosen to select a single, unique element. It is written with the hash character (#), followed by the id of the element. "
},
{
"code": null,
"e": 25899,
"s": 25890,
"text": "Syntax: "
},
{
"code": null,
"e": 25939,
"s": 25899,
"text": "#element_id_name{\n // CSS properties\n}"
},
{
"code": null,
"e": 26026,
"s": 25939,
"text": "Example: In this code we will use only id selector to set style to the HTML elements. "
},
{
"code": null,
"e": 26031,
"s": 26026,
"text": "html"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS Selector id(#)</title> <style> #container { width: 400px; height: 150px; border: 2px solid black; text-align: center; } #geeks { color: green; } #gfg { font-family: Courier New; } </style></head> <body> <div id=\"container\"> <h1 id=\"geeks\">GeeksforGeeks</h1> <h4 id=\"gfg\">A Computer Science portal for Geeks</h4> <b class=\"selector\">CSS Selector id(#)</b> </div></body> </html>",
"e": 26611,
"s": 26031,
"text": null
},
{
"code": null,
"e": 26621,
"s": 26611,
"text": "Output: "
},
{
"code": null,
"e": 26803,
"s": 26621,
"text": "Class Selector(β.β): The class selector selects HTML elements with a specific class attribute. It is used with a period character β.β (full stop symbol) followed by the class name. "
},
{
"code": null,
"e": 26812,
"s": 26803,
"text": "Syntax: "
},
{
"code": null,
"e": 26855,
"s": 26812,
"text": ".element_class_name{\n // CSS properties\n}"
},
{
"code": null,
"e": 26945,
"s": 26855,
"text": "Example: In this code we will use only class selector to set style to the HTML elements. "
},
{
"code": null,
"e": 26950,
"s": 26945,
"text": "html"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS class Selector</title> <style> .container { width: 400px; height: 150px; border: 2px solid black; text-align: center; } .geeks { color: green; } .selector { font-family: Courier New; } </style></head> <body> <div class=\"container\"> <h1 class=\"geeks\">GeeksforGeeks</h1> <h4 id=\"gfg\">A Computer Science portal for Geeks</h4> <b class=\"selector\">CSS Selector class(.)</b> </div></body> </html>",
"e": 27544,
"s": 26950,
"text": null
},
{
"code": null,
"e": 27554,
"s": 27544,
"text": "Output: "
},
{
"code": null,
"e": 27613,
"s": 27556,
"text": "Difference between class (β.β) and id (β#β) Selectors: "
},
{
"code": null,
"e": 27714,
"s": 27613,
"text": "Example: The Combine selector example, in this example we will use both the selectors β.β and β#β. "
},
{
"code": null,
"e": 27719,
"s": 27714,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> /* #id selector */ #geeks { color:green; } /* .class selector */ .gfg { background-color: yellow; font-style:italic; color:green; } /* .class selector */ .options { background-color: yellow; color:purple; } </style> </head> <body style = \"text-align:center\"> <h1 id = \"geeks\"> GeeksforGeeks </h1> <h4>#id And .class Selector</h4> <div class = \"gfg\"> <p>A computer science portal for Geeks</p> </div> <div class=\"select\"> <select name=\"slct\" id=\"slct\"> <option>Computer Science Subjects</option> <option class=\"options\">Operating System</option> <option class=\"options\">Computer Networks</option> <option class=\"options\">Data Structure</option> <option class=\"options\">Algorithm</option> <option class=\"options\">C programming</option> <option class=\"options\">JAVA</option> </select> </div> </body></html> ",
"e": 29040,
"s": 27719,
"text": null
},
{
"code": null,
"e": 29050,
"s": 29040,
"text": "Output: "
},
{
"code": null,
"e": 29069,
"s": 29050,
"text": "Supported Browser:"
},
{
"code": null,
"e": 29083,
"s": 29069,
"text": "Google Chrome"
},
{
"code": null,
"e": 29101,
"s": 29083,
"text": "Internet Explorer"
},
{
"code": null,
"e": 29109,
"s": 29101,
"text": "Firefox"
},
{
"code": null,
"e": 29115,
"s": 29109,
"text": "Opera"
},
{
"code": null,
"e": 29122,
"s": 29115,
"text": "Safari"
},
{
"code": null,
"e": 29134,
"s": 29122,
"text": "ysachin2314"
},
{
"code": null,
"e": 29143,
"s": 29134,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29153,
"s": 29143,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29160,
"s": 29153,
"text": "Picked"
},
{
"code": null,
"e": 29164,
"s": 29160,
"text": "CSS"
},
{
"code": null,
"e": 29183,
"s": 29164,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29200,
"s": 29183,
"text": "Web Technologies"
},
{
"code": null,
"e": 29227,
"s": 29200,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29325,
"s": 29227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29362,
"s": 29325,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29391,
"s": 29362,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29430,
"s": 29391,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29472,
"s": 29430,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29519,
"s": 29472,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 29561,
"s": 29519,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29594,
"s": 29561,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29637,
"s": 29594,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29682,
"s": 29637,
"text": "Convert a string to an integer in JavaScript"
}
] |
DIY: Apache Spark & Docker. Set up a Spark cluster in Docker from... | by Shane De Silva | Towards Data Science | Two technologies that have risen in popularity over the last few years are Apache Spark and Docker.
Apache Spark provides users with a way of performing CPU intensive tasks in a distributed manner. Itβs adoption has been steadily increasing in the last few years due to its speed when compared to other distributed technologies such as Hadoop. In 2014 Spark won the Gray Sort Benchmark test in which they sorted 100TB of data 3x faster using 10x fewer machines then a Hadoop cluster previously did.
Docker on the other hand has seen widespread adoption in a variety of situations. Docker provides users the ability to define minimal specifications of environments meaning you can easily develop, ship, and scale applications. Furthermore, due to its use of linux containers users are able to develop Docker containers that can run be run simultaneously on a single server whilst remaining isolated from each other. Finally, Docker provides an abstraction layer called the Docker Engine that guarantees compatibility between machines that can run Docker solving the age-old headache of βit works on my machine, I donβt know why it doesnβt on yoursβ.
With the rise of Big Data these two technologies are a matched made in heaven. Apache Spark providing the analytics engine to crunch the numbers and Docker providing fast, scalable deployment coupled with a consistent environment.
I assume knowledge of Docker commands and terms as well as Apache Spark concepts. Therefore, I do not recommend this article if either of these two technologies are new to you. With considerations of brevity in mind this article will intentionally leave out much of the detail of what is happening. For a full drawn out description of the architecture and a more sequential walk through of the process I direct the reader to my github repo.
I also assume that you have at least basic experience with a cloud provider and as such are able to set up a computing instance on your preferred platform.
The rest of this article is going to be a fairly straight shot at going through varying levels of architectural complexity:
Docker container networking β local machineDocker container networking β multiple machinesApache Spark cluster β local machineDocker & Spark β local machineDocker & Spark β multiple machinesBONUS: Docker Stack & Spark
Docker container networking β local machine
Docker container networking β multiple machines
Apache Spark cluster β local machine
Docker & Spark β local machine
Docker & Spark β multiple machines
BONUS: Docker Stack & Spark
Letβs get to it!
First we need to get to grips with some basic Docker networking. We will do this with the containers running on the same machine in the first instance.
The first thing to do is to either build the docker images using the Dockerfiles from my repo or more conveniently just pull the docker images using the following commands
The first thing to do is to either build the docker images using the Dockerfiles from my repo or more conveniently just pull the docker images using the following commands
docker pull sdesilva26/spark_master:0.0.2docker pull sdesilva26/spark_worker:0.0.2
NOTE: For the purpose of this section any images will do.
2. Create a bridge network by running
docker network create --driver bridge spark-net-bridge
3. Run two containers on this user-defined bridge network by running
docker run -dit --name spark-master --network spark-net-bridge --entrypoint /bin/bash sdesilva26/spark_master:0.0.2docker run -dit --name spark-worker1 --network spark-net-bridge --entrypoint /bin/bash sdesilva26/spark_worker:0.0.2
4. Inspect the network and find the IP addresses of the two containers
docker network inspect spark-net-bridge
The output of the above should look like the image below
5. Attach to the spark-master container and test itβs communication to the spark-worker container using both itβs IP address and then using its container name
ping -c 2 172.24.0.3ping -c 2 spark-worker
Because the containers have been deployed into the same Docker bridge network they are able to resolve the IP address of other containers using the containerβs name. This is called automatic service discovery and will be a great help to us later.
With the above commands we have created the following architecture.
Go ahead and setup 2 instances on your favourite cloud providerWhen configuring the instanceβs network make sure to deploy them into the same subnetOpen up the following ports for the containers to communicate with each other and for overlay network traffic (inbound and outbound);
Go ahead and setup 2 instances on your favourite cloud provider
When configuring the instanceβs network make sure to deploy them into the same subnet
Open up the following ports for the containers to communicate with each other and for overlay network traffic (inbound and outbound);
Protocol | Port(s) | SourceTCP | 2377 | <your-security-group-or-subnet-name>TCP | 7946 | <your-security-group-or-subnet-name>UDP | 7946 | <your-security-group-or-subnet-name>UDP | 4789 | <your-security-group-or-subnet-name>
4. Open up the following ports for the instance to communicate with docker hub (inbound and outbound);
Protocol | Port(s) | SourceHTTPS | 443 | 0.0.0/0, ::/0
For example, on AWS, my security group which my two instances are deployed in have the following security group settings
where βsg-0140fc8be109d6ecf (docker-spark-tutorial)β is the name of the security group itself, so only traffic from within the network can communicate using ports 2377, 7946, and 4789.
5. Install docker.
sudo yum install docker -ysudo service docker startsudo usermod -a -G docker ec2-user # This avoids you having to use sudo everytime you use a docker command (log out and then in to your instance for this to take affect)
6. On instance 1, pull a docker image of your choice.
docker pull sdesilva26/spark_master:0.0.2
7. Pull another image onto instance 2.
docker pull sdesilva26/spark_worker:0.0.2
8. Initialise a docker swarm and make instance 1 the swarm manager by running
docker swarm init
on instance 1.
9. Copy the output of the command above from instance 1 and run it on instance 2 to join the swarm as a worker node
10. On instance 1 (the swarm manager) create an overlay network
docker network create -d overlay --attachable spark-net
11. On instance 1, run a container
docker run -it --name spark-master --network spark-net --entrypoint /bin/bash sdesilva26/spark_master:0.0.2
12. On instance 2, run a container within the overlay network created by the swarm manager
docker run -it --name spark-worker --network spark-net --entrypoint /bin/bash sdesilva26/spark_worker:0.0.2
13. From inside the container on instance 2 check the container communication by pinging the container running on instance 1
ping -c 2 spark-master
14. Similarly, check the backwards connection from the container in instance 1 to the container in instance 2
ping -c 2 spark-worker
As before, the containers are able to resolve each otherβs IP address using only the container name since they are within the same overlay network.
After following the instructions above, you have created an architecture similar to the one below.
Now that we have a handle on how to get two different docker hosts to communicate, we will get started on creating a Spark cluster on our local machine.
Install Spark from their websiteFrom the command line navigate to the bin directory of your Spark installationSetup a Spark master node
Install Spark from their website
From the command line navigate to the bin directory of your Spark installation
Setup a Spark master node
./spark-class org.apache.spark.deploy.master.Master
4. Check your master node has successfully been deploy by navigating to http://localhost:8080. You should see the following
5. Attach a worker node to the cluster
./spark-class org.apache.spark.deploy.worker.Worker -c 1 -m 3G spark://localhost:7077
where the two flags define the amount of cores and memory you wish this worker to have. The last input is the address and port of the master node prefixed with βspark://β because we are using sparkβs standalone cluster manager
6. Check that the worker was successfully registered with the master node by going back to http://localhost:8080. You should now see the worker node as a resource of the cluster. (You can also check the UI of the worker by going to http://localhost:8081)
7. Test the cluster by opening a scala shell from the bin directory of your spark installation
./spark-shell --master spark://localhost:7077
and running
val NUM_SAMPLES=10000var count = sc.parallelize(1 to NUM_SAMPLES).filter { _ => val x = math.random val y = math.random x*x + y*y < 1}.count() * 4/(NUM_SAMPLES.toFloat)
This will return an estimate of the value of pi.
8. Check the UI of the application by going to http://localhost:4040. You should see something similar to
You now have a fully functioning spark cluster!
Now itβs time to start tying the two together. We will now learn to walk before running by setting up a Spark cluster running inside Docker containers on your local machine
Create a user defined bridge network (if you havenβt done so already)
Create a user defined bridge network (if you havenβt done so already)
docker create network -d bridge spark-net
2. Create a Spark master node inside of the bridge network
docker run -it --name spark-master --network spark-net -p 8080:8080 sdesilva26/spark_master:0.0.2 bash
3. Check the container successfully started a Spark master node by navigating to http://localhost:8080. I have set the sdesilva26/spark_master:0.0.2 image to by default set up a master node. See the dockerfile.
4. Create a Spark worker node inside of the bridge network
docker run -dit --name spark-worker1 --network spark-net -p 8081:8081 -e MEMORY=2G -e CORES=1 sdesilva26/spark_worker:0.0.2 bash
By default the sdesilva26/spark_worker:0.0.2 image, when run, will try to join a Spark cluster with the master node located at spark://spark-master:7077.
If you change the name of the container running the Spark master node (step 2) then you will need to pass this container name to the above command, e.g. -e <MASTER_CONTAINER_NAME>. See the dockerfile here.
5. Again, verify the worker has successfully registered with the master node by navigating to http://localhost:8080 and http://localhost:8081.
6. Attach a second spark worker to the cluster
docker run -dit --name spark-worker2 --network spark-net -p 8082:8081 -e MEMORY=2G -e CORES=1 sdesilva26/spark_worker:0.0.2 bash
The only change we had to make from the command in step 4 was that we had to give the container a unique name and also we had to map port 8081 of the container to port 8082 of the local machine since the spark-worker1 container is already using your local machines port 8081.
7. Spin up a Spark submit node
docker run -it --name spark-submit --network spark-net -p 4040:4040 sdesilva26/spark_submit bash
You should now be inside of the spark-submit container.
8. Open a scala shell and connect to the Spark cluster
$SPARK_HOME/bin/spark-shell --conf spark.executor.memory=2G --conf spark.executor.cores=1 --master spark://spark-master:7077
As before, if you have a different name than spark-master for the container running your Spark master node then you would change the above command with β master spark://<YOUR_MASTER_CONTAINER>:7077.
The above command also asks that on your cluster, you want each executor to contain 2G of memory and 1 core. The Spark master node will allocate these executors, provided there is enough resource available on each worker to allow this. For an explanation of executors and workers see the following article.
9. Run an example job in the interactive scala shell
val myRange = spark.range(10000).toDF("number")val divisBy2 = myRange.where("number % 2 = 0")divisBy2.count()
10. Check the application UI by navigating to http://localhost:4040. You should see the following
You have just run a Spark job inside of Docker containers. Spocker is born!
What we have done in the above is created a network within Docker in which we can deploy containers and they can freely communicate with each other.
The white arrows in the diagram below represents open communication between containers. Ports on the containers are shown in green and the ports of your local machine are shown in yellow.
You can see that all the container are deployed within the bridge network. If we now deploy a container outside of this network, it would not be able to resolve the IP addresses of the other containers just by using their container names.
Now letβs wrap everything together to form a fully distributed Spark cluster running inside of Docker containers.
NOTE: For this part you will need to use the 3 images that I have created.
docker pull sdesilva26/spark_master:0.0.2docker pull sdesilva26/spark_worker:0.0.2docker pull sdesilva26/spark_submit:0.0.2
You can also build them yourself by downloading the Dockerfiles
Start up an instance on a cloud provider of your choice and make it a docker swarm manager
Start up an instance on a cloud provider of your choice and make it a docker swarm manager
docker swarm init
2. Copy and paste the output of the above command to at least 2 other instances. I have done this on 4 other instances β 3 will act as Spark workers and 1 will be my Spark submit node
3. On instance 1, create an overlay network as we did before
docker network create -d overlay --attachable spark-net
4. Run the spark_master image to create a container that will be the Spark master node
docker run -it --name spark-master --network spark-net -p 8080:8080 sdesilva26/spark_master:0.0.2
5. Open up ports 8080β8090 and 4040 by adding the following to your security groupβs inbound rules
Protocol | Port(s) | SourceCustom TCP | 8080-8090 | 0.0.0/0Custom TCP | 4040 | 0.0.0/0, ::/0
NOTE: In AWS security groups are stateful, so the return traffic from the instance to users is allowed automatically, so you donβt need to modify the security groupβs outbound rules. On other cloud providers you may have to add a similar rule to your outbound rules.
My inbound security group rules now look like this
6. Check the Spark master node UI at http://<PUBLIC_IPv4_ADDRESS_OF_INSTANCE>:8080. You should see the same UI that we saw earlier.
7. Now on another one of your instances run the following to attach a Spark worker node to the cluster
docker run -it --name spark-worker1 --network spark-net -p 8081:8081 -e MEMORY=6G -e CORES=3 sdesilva26/spark_worker:0.0.2
NOTE: As a general rule of thumb start your Spark worker node with memory = memory of instance-1GB, and cores = cores of instance - 1. This leaves 1 core and 1GB for the instanceβs OS to be able to carry out background tasks.
8. Again, check the master nodeβs web UI to make sure the worker was added successfully.
9. Rinse and repeat step 7 to add as many Spark workers as you please. Make sure to increment the name of the container though from spark-worker1 to spark-worker2, and so on.
I have connected 3 workers and my master nodeβs web UI looks like this
10. In another instance, fire up a Spark submit node
docker run -it --name spark-submit --network spark-net -p 4040:4040 sdesilva26/spark_submit:0.0.2 bash
11. Launch a pyspark interactive shell and connect to the cluster
$SPARK_HOME/bin/pyspark --conf spark.executor.memory=5G --conf spark.executor.cores=3 --master spark://spark-master:7077
NOTE: You specify the resources you would like each executor to have when connecting an application to the cluster by using the β conf flag. The topic of Spark tuning is a whole post in itself so I will not go into any detail here. This two part Cloudera blog post I found to be a good resource for understanding resource allocation: part 1 & part 2. Also a blog post by Anthony Shipman from C2FO.io I found very useful and also includes a handy excel sheet to work out settings for memory, cores, and parallelization.
12. Check the submit node has successfully connected to the cluster by checking both the Spark master nodeβs UI and the Spark submit nodeβs UI. They should look like the images below.
13. Run a sample job from the pyspark shell
from random import randomdef inside(p): x, y = random(), random() return x*x + y*y < 1NUM_SAMPLES = 100000count = sc.parallelize(range(0, NUM_SAMPLES)).filter(inside).count()print("Pi is roughly {:0.4f}".format(4.0 * count / NUM_SAMPLES))
The more common way to submit jobs to a Spark cluster is by using the spark-submit script which is included with your spark installation. Letβs also do this.
14. Exit out of pyspark and submit a program to executor on the cluster
$SPARK_HOME/bin/spark-submit --conf spark.executor.cores=3 --conf spark.executor.memory=5G --master spark://spark-master:7077 $SPARK_HOME/examples/src/main/python/pi.py 20
Itβs pretty much the same syntax as before except we are calling the spark-submit script and we are passing it a .py file along with any other configurations for the file to execute.
Happy days! We have now created a fully distributed Spark cluster running inside of Docker containers and submitted an application to the cluster.
The architecture we have just created looks like the following
Each Spark worker node and the master node is running inside a Docker container located on its own computing instance. The Spark driver node (spark submit node) is also located within its own container running on a separate instance. All the Docker daemons are connected by means of an overlay network with the Spark master node being the Docker swarm manager in this case.
Within the overlay network, containers can easily resolve each otherβs addresses by referencing container names which utilises automatic service discovery.
More Spark worker nodes can be fired up on additional instances if needed.
Welcome to the finish line!
In this tutorial we have managed to sequentially step through the varying levels of complexity in setting up a Spark cluster running inside of Docker containers.
We first started off with some simple Docker networking principles both on our local machine, in which we used a bridge network, and then on distributed machines using an overlay network with a docker swarm.
Next we set up a Spark cluster running on our local machine to get to grips with adding workers to a cluster.
Then we introduced Docker back in to the mix and set up a Spark cluster running inside of Docker containers on our local machine.
Finally, we brought everything together to construct a fully distributed Spark cluster running in Docker containers.
Hopefully youβve gained a clear understanding of how these two technologies link together and could provide benefit to your specific problem or project.
Now is the time for you to start experimenting and see what you can learn using this architecture.
Enjoy!
The above steps of manually creating a cluster was more informative than practical as it required a lot of manual typing and repeated commands.
For small(ish) problems where you only need the resources of maybe 4 or 5 computing instances this amount of effort is probably below your pain threshold.
However, as the data becomes truly large and the computing power needed starts to increase, following the above steps will turn you into a full-time cluster creator.
A much more practical and elegant way of setting up a cluster is by taking advantage of Docker compose
For those of you new to Docker compose, it allows you to launch what are called βservicesβ.
A service is made up of a single Docker image, but you may want multiple containers of this image to be running. For example, running multiple Spark worker containers from the docker image sdesilva26/spark_worker:0.0.2 would constitute a single service.
To launch a set of services you create a docker-compose.yml file which specifies everything about the various services you would like to run.
However, Docker compose is used to create services running on a single host. It does not support deploying containers across hosts.
Enter Docker stack.
The Docker stack is a simple extension to the idea of Docker compose. Instead of running your services on a single host, you can now run your services on multiple hosts which are connected as a Docker swarm.
Best of all, if you have a Docker compose file very little modifications need to be made in order for it to work with the Docker stack commands.
Letβs see how to create our distributed Spark cluster running inside of Docker containers using a compose file and docker stack.
The first step is to label the nodes in your Docker swarm. From the Docker swarm manager list the nodes in the swarm.
The first step is to label the nodes in your Docker swarm. From the Docker swarm manager list the nodes in the swarm.
docker node ls
You should get a similar output to the image below.
2. For any instances you wish to be Spark workers, add a label to them
docker node update --label-add role=worker x5kmfd8akvvtnsfvmxybcjb8w
3. Now label the instance you wish to run the Spark master node with the role of master
docker node update --label-add role=master
4. Create a docker-compose.yml file or pull the one I have created.
In this compose file I have defined two services β spark-master and spark-worker.
The first service deploys a single container onto any node in the swarm that has the label βrole=masterβ.
The second service will deploy 3 containers of the sdesilva26/spark_worker:0.0.2 image onto nodes with the label βrole=workerβ. If 3 suitable nodes in the swarm arenβt found it will deploy as many as is possible.
Finally, all these containers will be deployed into an overlay network called spark-net which will be created for us.
5. Copy the docker-compose.yml into the instance which is the swarm manager.
scp -i <YOUR_KEY>.pem /path/to/docker-compose.yml ec2-user@<PUBLIC_IP_ADDRESS_OF_INSTANCE>:/home/ec2-user/docker-compose.yml
[see here for alternative ways of doing this]
6. Finally, run your docker stack from the swarm manager and give it a name.
docker stack deploy --compose-file docker-compose.yml sparkdemo
NOTE: the name of your stack will be prepended to all service names. So the service βspark-masterβ becomes βsparkdemo_spark-masterβ. You can check the services that are running by using
docker service ls
7. Check that the spark_worker image is running on the instances you labelled as βworkerβ and that the spark_master image is running on the node labelled as βmasterβ.
Congratulations, we have just simplified all of the work from this article into a few commands from the Docker swarm manager.
The best thing about Docker services is that it is very easy to scale up. For example, if later on we added another instance to the Docker swarm and we then wished to scale up the βsparkdemo_spark-workerβ service, we can simply run
docker service scale sparkdemo_spark-worker=4
and you now have 4 Spark workers in your cluster! | [
{
"code": null,
"e": 146,
"s": 46,
"text": "Two technologies that have risen in popularity over the last few years are Apache Spark and Docker."
},
{
"code": null,
"e": 545,
"s": 146,
"text": "Apache Spark provides users with a way of performing CPU intensive tasks in a distributed manner. Itβs adoption has been steadily increasing in the last few years due to its speed when compared to other distributed technologies such as Hadoop. In 2014 Spark won the Gray Sort Benchmark test in which they sorted 100TB of data 3x faster using 10x fewer machines then a Hadoop cluster previously did."
},
{
"code": null,
"e": 1195,
"s": 545,
"text": "Docker on the other hand has seen widespread adoption in a variety of situations. Docker provides users the ability to define minimal specifications of environments meaning you can easily develop, ship, and scale applications. Furthermore, due to its use of linux containers users are able to develop Docker containers that can run be run simultaneously on a single server whilst remaining isolated from each other. Finally, Docker provides an abstraction layer called the Docker Engine that guarantees compatibility between machines that can run Docker solving the age-old headache of βit works on my machine, I donβt know why it doesnβt on yoursβ."
},
{
"code": null,
"e": 1426,
"s": 1195,
"text": "With the rise of Big Data these two technologies are a matched made in heaven. Apache Spark providing the analytics engine to crunch the numbers and Docker providing fast, scalable deployment coupled with a consistent environment."
},
{
"code": null,
"e": 1867,
"s": 1426,
"text": "I assume knowledge of Docker commands and terms as well as Apache Spark concepts. Therefore, I do not recommend this article if either of these two technologies are new to you. With considerations of brevity in mind this article will intentionally leave out much of the detail of what is happening. For a full drawn out description of the architecture and a more sequential walk through of the process I direct the reader to my github repo."
},
{
"code": null,
"e": 2023,
"s": 1867,
"text": "I also assume that you have at least basic experience with a cloud provider and as such are able to set up a computing instance on your preferred platform."
},
{
"code": null,
"e": 2147,
"s": 2023,
"text": "The rest of this article is going to be a fairly straight shot at going through varying levels of architectural complexity:"
},
{
"code": null,
"e": 2365,
"s": 2147,
"text": "Docker container networking β local machineDocker container networking β multiple machinesApache Spark cluster β local machineDocker & Spark β local machineDocker & Spark β multiple machinesBONUS: Docker Stack & Spark"
},
{
"code": null,
"e": 2409,
"s": 2365,
"text": "Docker container networking β local machine"
},
{
"code": null,
"e": 2457,
"s": 2409,
"text": "Docker container networking β multiple machines"
},
{
"code": null,
"e": 2494,
"s": 2457,
"text": "Apache Spark cluster β local machine"
},
{
"code": null,
"e": 2525,
"s": 2494,
"text": "Docker & Spark β local machine"
},
{
"code": null,
"e": 2560,
"s": 2525,
"text": "Docker & Spark β multiple machines"
},
{
"code": null,
"e": 2588,
"s": 2560,
"text": "BONUS: Docker Stack & Spark"
},
{
"code": null,
"e": 2605,
"s": 2588,
"text": "Letβs get to it!"
},
{
"code": null,
"e": 2757,
"s": 2605,
"text": "First we need to get to grips with some basic Docker networking. We will do this with the containers running on the same machine in the first instance."
},
{
"code": null,
"e": 2929,
"s": 2757,
"text": "The first thing to do is to either build the docker images using the Dockerfiles from my repo or more conveniently just pull the docker images using the following commands"
},
{
"code": null,
"e": 3101,
"s": 2929,
"text": "The first thing to do is to either build the docker images using the Dockerfiles from my repo or more conveniently just pull the docker images using the following commands"
},
{
"code": null,
"e": 3184,
"s": 3101,
"text": "docker pull sdesilva26/spark_master:0.0.2docker pull sdesilva26/spark_worker:0.0.2"
},
{
"code": null,
"e": 3242,
"s": 3184,
"text": "NOTE: For the purpose of this section any images will do."
},
{
"code": null,
"e": 3280,
"s": 3242,
"text": "2. Create a bridge network by running"
},
{
"code": null,
"e": 3336,
"s": 3280,
"text": "docker network create --driver bridge spark-net-bridge "
},
{
"code": null,
"e": 3405,
"s": 3336,
"text": "3. Run two containers on this user-defined bridge network by running"
},
{
"code": null,
"e": 3638,
"s": 3405,
"text": "docker run -dit --name spark-master --network spark-net-bridge --entrypoint /bin/bash sdesilva26/spark_master:0.0.2docker run -dit --name spark-worker1 --network spark-net-bridge --entrypoint /bin/bash sdesilva26/spark_worker:0.0.2 "
},
{
"code": null,
"e": 3709,
"s": 3638,
"text": "4. Inspect the network and find the IP addresses of the two containers"
},
{
"code": null,
"e": 3749,
"s": 3709,
"text": "docker network inspect spark-net-bridge"
},
{
"code": null,
"e": 3806,
"s": 3749,
"text": "The output of the above should look like the image below"
},
{
"code": null,
"e": 3965,
"s": 3806,
"text": "5. Attach to the spark-master container and test itβs communication to the spark-worker container using both itβs IP address and then using its container name"
},
{
"code": null,
"e": 4008,
"s": 3965,
"text": "ping -c 2 172.24.0.3ping -c 2 spark-worker"
},
{
"code": null,
"e": 4255,
"s": 4008,
"text": "Because the containers have been deployed into the same Docker bridge network they are able to resolve the IP address of other containers using the containerβs name. This is called automatic service discovery and will be a great help to us later."
},
{
"code": null,
"e": 4323,
"s": 4255,
"text": "With the above commands we have created the following architecture."
},
{
"code": null,
"e": 4605,
"s": 4323,
"text": "Go ahead and setup 2 instances on your favourite cloud providerWhen configuring the instanceβs network make sure to deploy them into the same subnetOpen up the following ports for the containers to communicate with each other and for overlay network traffic (inbound and outbound);"
},
{
"code": null,
"e": 4669,
"s": 4605,
"text": "Go ahead and setup 2 instances on your favourite cloud provider"
},
{
"code": null,
"e": 4755,
"s": 4669,
"text": "When configuring the instanceβs network make sure to deploy them into the same subnet"
},
{
"code": null,
"e": 4889,
"s": 4755,
"text": "Open up the following ports for the containers to communicate with each other and for overlay network traffic (inbound and outbound);"
},
{
"code": null,
"e": 5160,
"s": 4889,
"text": "Protocol | Port(s) | SourceTCP | 2377 | <your-security-group-or-subnet-name>TCP | 7946 | <your-security-group-or-subnet-name>UDP | 7946 | <your-security-group-or-subnet-name>UDP | 4789 | <your-security-group-or-subnet-name>"
},
{
"code": null,
"e": 5263,
"s": 5160,
"text": "4. Open up the following ports for the instance to communicate with docker hub (inbound and outbound);"
},
{
"code": null,
"e": 5331,
"s": 5263,
"text": "Protocol | Port(s) | SourceHTTPS | 443 | 0.0.0/0, ::/0"
},
{
"code": null,
"e": 5452,
"s": 5331,
"text": "For example, on AWS, my security group which my two instances are deployed in have the following security group settings"
},
{
"code": null,
"e": 5637,
"s": 5452,
"text": "where βsg-0140fc8be109d6ecf (docker-spark-tutorial)β is the name of the security group itself, so only traffic from within the network can communicate using ports 2377, 7946, and 4789."
},
{
"code": null,
"e": 5656,
"s": 5637,
"text": "5. Install docker."
},
{
"code": null,
"e": 5877,
"s": 5656,
"text": "sudo yum install docker -ysudo service docker startsudo usermod -a -G docker ec2-user # This avoids you having to use sudo everytime you use a docker command (log out and then in to your instance for this to take affect)"
},
{
"code": null,
"e": 5931,
"s": 5877,
"text": "6. On instance 1, pull a docker image of your choice."
},
{
"code": null,
"e": 5973,
"s": 5931,
"text": "docker pull sdesilva26/spark_master:0.0.2"
},
{
"code": null,
"e": 6012,
"s": 5973,
"text": "7. Pull another image onto instance 2."
},
{
"code": null,
"e": 6054,
"s": 6012,
"text": "docker pull sdesilva26/spark_worker:0.0.2"
},
{
"code": null,
"e": 6132,
"s": 6054,
"text": "8. Initialise a docker swarm and make instance 1 the swarm manager by running"
},
{
"code": null,
"e": 6150,
"s": 6132,
"text": "docker swarm init"
},
{
"code": null,
"e": 6165,
"s": 6150,
"text": "on instance 1."
},
{
"code": null,
"e": 6281,
"s": 6165,
"text": "9. Copy the output of the command above from instance 1 and run it on instance 2 to join the swarm as a worker node"
},
{
"code": null,
"e": 6345,
"s": 6281,
"text": "10. On instance 1 (the swarm manager) create an overlay network"
},
{
"code": null,
"e": 6401,
"s": 6345,
"text": "docker network create -d overlay --attachable spark-net"
},
{
"code": null,
"e": 6436,
"s": 6401,
"text": "11. On instance 1, run a container"
},
{
"code": null,
"e": 6544,
"s": 6436,
"text": "docker run -it --name spark-master --network spark-net --entrypoint /bin/bash sdesilva26/spark_master:0.0.2"
},
{
"code": null,
"e": 6635,
"s": 6544,
"text": "12. On instance 2, run a container within the overlay network created by the swarm manager"
},
{
"code": null,
"e": 6743,
"s": 6635,
"text": "docker run -it --name spark-worker --network spark-net --entrypoint /bin/bash sdesilva26/spark_worker:0.0.2"
},
{
"code": null,
"e": 6868,
"s": 6743,
"text": "13. From inside the container on instance 2 check the container communication by pinging the container running on instance 1"
},
{
"code": null,
"e": 6891,
"s": 6868,
"text": "ping -c 2 spark-master"
},
{
"code": null,
"e": 7001,
"s": 6891,
"text": "14. Similarly, check the backwards connection from the container in instance 1 to the container in instance 2"
},
{
"code": null,
"e": 7024,
"s": 7001,
"text": "ping -c 2 spark-worker"
},
{
"code": null,
"e": 7172,
"s": 7024,
"text": "As before, the containers are able to resolve each otherβs IP address using only the container name since they are within the same overlay network."
},
{
"code": null,
"e": 7271,
"s": 7172,
"text": "After following the instructions above, you have created an architecture similar to the one below."
},
{
"code": null,
"e": 7424,
"s": 7271,
"text": "Now that we have a handle on how to get two different docker hosts to communicate, we will get started on creating a Spark cluster on our local machine."
},
{
"code": null,
"e": 7560,
"s": 7424,
"text": "Install Spark from their websiteFrom the command line navigate to the bin directory of your Spark installationSetup a Spark master node"
},
{
"code": null,
"e": 7593,
"s": 7560,
"text": "Install Spark from their website"
},
{
"code": null,
"e": 7672,
"s": 7593,
"text": "From the command line navigate to the bin directory of your Spark installation"
},
{
"code": null,
"e": 7698,
"s": 7672,
"text": "Setup a Spark master node"
},
{
"code": null,
"e": 7750,
"s": 7698,
"text": "./spark-class org.apache.spark.deploy.master.Master"
},
{
"code": null,
"e": 7874,
"s": 7750,
"text": "4. Check your master node has successfully been deploy by navigating to http://localhost:8080. You should see the following"
},
{
"code": null,
"e": 7913,
"s": 7874,
"text": "5. Attach a worker node to the cluster"
},
{
"code": null,
"e": 7999,
"s": 7913,
"text": "./spark-class org.apache.spark.deploy.worker.Worker -c 1 -m 3G spark://localhost:7077"
},
{
"code": null,
"e": 8226,
"s": 7999,
"text": "where the two flags define the amount of cores and memory you wish this worker to have. The last input is the address and port of the master node prefixed with βspark://β because we are using sparkβs standalone cluster manager"
},
{
"code": null,
"e": 8481,
"s": 8226,
"text": "6. Check that the worker was successfully registered with the master node by going back to http://localhost:8080. You should now see the worker node as a resource of the cluster. (You can also check the UI of the worker by going to http://localhost:8081)"
},
{
"code": null,
"e": 8576,
"s": 8481,
"text": "7. Test the cluster by opening a scala shell from the bin directory of your spark installation"
},
{
"code": null,
"e": 8622,
"s": 8576,
"text": "./spark-shell --master spark://localhost:7077"
},
{
"code": null,
"e": 8634,
"s": 8622,
"text": "and running"
},
{
"code": null,
"e": 8806,
"s": 8634,
"text": "val NUM_SAMPLES=10000var count = sc.parallelize(1 to NUM_SAMPLES).filter { _ => val x = math.random val y = math.random x*x + y*y < 1}.count() * 4/(NUM_SAMPLES.toFloat)"
},
{
"code": null,
"e": 8855,
"s": 8806,
"text": "This will return an estimate of the value of pi."
},
{
"code": null,
"e": 8961,
"s": 8855,
"text": "8. Check the UI of the application by going to http://localhost:4040. You should see something similar to"
},
{
"code": null,
"e": 9009,
"s": 8961,
"text": "You now have a fully functioning spark cluster!"
},
{
"code": null,
"e": 9182,
"s": 9009,
"text": "Now itβs time to start tying the two together. We will now learn to walk before running by setting up a Spark cluster running inside Docker containers on your local machine"
},
{
"code": null,
"e": 9252,
"s": 9182,
"text": "Create a user defined bridge network (if you havenβt done so already)"
},
{
"code": null,
"e": 9322,
"s": 9252,
"text": "Create a user defined bridge network (if you havenβt done so already)"
},
{
"code": null,
"e": 9364,
"s": 9322,
"text": "docker create network -d bridge spark-net"
},
{
"code": null,
"e": 9423,
"s": 9364,
"text": "2. Create a Spark master node inside of the bridge network"
},
{
"code": null,
"e": 9526,
"s": 9423,
"text": "docker run -it --name spark-master --network spark-net -p 8080:8080 sdesilva26/spark_master:0.0.2 bash"
},
{
"code": null,
"e": 9737,
"s": 9526,
"text": "3. Check the container successfully started a Spark master node by navigating to http://localhost:8080. I have set the sdesilva26/spark_master:0.0.2 image to by default set up a master node. See the dockerfile."
},
{
"code": null,
"e": 9796,
"s": 9737,
"text": "4. Create a Spark worker node inside of the bridge network"
},
{
"code": null,
"e": 9926,
"s": 9796,
"text": "docker run -dit --name spark-worker1 --network spark-net -p 8081:8081 -e MEMORY=2G -e CORES=1 sdesilva26/spark_worker:0.0.2 bash"
},
{
"code": null,
"e": 10080,
"s": 9926,
"text": "By default the sdesilva26/spark_worker:0.0.2 image, when run, will try to join a Spark cluster with the master node located at spark://spark-master:7077."
},
{
"code": null,
"e": 10286,
"s": 10080,
"text": "If you change the name of the container running the Spark master node (step 2) then you will need to pass this container name to the above command, e.g. -e <MASTER_CONTAINER_NAME>. See the dockerfile here."
},
{
"code": null,
"e": 10429,
"s": 10286,
"text": "5. Again, verify the worker has successfully registered with the master node by navigating to http://localhost:8080 and http://localhost:8081."
},
{
"code": null,
"e": 10476,
"s": 10429,
"text": "6. Attach a second spark worker to the cluster"
},
{
"code": null,
"e": 10606,
"s": 10476,
"text": "docker run -dit --name spark-worker2 --network spark-net -p 8082:8081 -e MEMORY=2G -e CORES=1 sdesilva26/spark_worker:0.0.2 bash"
},
{
"code": null,
"e": 10882,
"s": 10606,
"text": "The only change we had to make from the command in step 4 was that we had to give the container a unique name and also we had to map port 8081 of the container to port 8082 of the local machine since the spark-worker1 container is already using your local machines port 8081."
},
{
"code": null,
"e": 10913,
"s": 10882,
"text": "7. Spin up a Spark submit node"
},
{
"code": null,
"e": 11010,
"s": 10913,
"text": "docker run -it --name spark-submit --network spark-net -p 4040:4040 sdesilva26/spark_submit bash"
},
{
"code": null,
"e": 11066,
"s": 11010,
"text": "You should now be inside of the spark-submit container."
},
{
"code": null,
"e": 11121,
"s": 11066,
"text": "8. Open a scala shell and connect to the Spark cluster"
},
{
"code": null,
"e": 11246,
"s": 11121,
"text": "$SPARK_HOME/bin/spark-shell --conf spark.executor.memory=2G --conf spark.executor.cores=1 --master spark://spark-master:7077"
},
{
"code": null,
"e": 11445,
"s": 11246,
"text": "As before, if you have a different name than spark-master for the container running your Spark master node then you would change the above command with β master spark://<YOUR_MASTER_CONTAINER>:7077."
},
{
"code": null,
"e": 11752,
"s": 11445,
"text": "The above command also asks that on your cluster, you want each executor to contain 2G of memory and 1 core. The Spark master node will allocate these executors, provided there is enough resource available on each worker to allow this. For an explanation of executors and workers see the following article."
},
{
"code": null,
"e": 11805,
"s": 11752,
"text": "9. Run an example job in the interactive scala shell"
},
{
"code": null,
"e": 11915,
"s": 11805,
"text": "val myRange = spark.range(10000).toDF(\"number\")val divisBy2 = myRange.where(\"number % 2 = 0\")divisBy2.count()"
},
{
"code": null,
"e": 12013,
"s": 11915,
"text": "10. Check the application UI by navigating to http://localhost:4040. You should see the following"
},
{
"code": null,
"e": 12089,
"s": 12013,
"text": "You have just run a Spark job inside of Docker containers. Spocker is born!"
},
{
"code": null,
"e": 12238,
"s": 12089,
"text": "What we have done in the above is created a network within Docker in which we can deploy containers and they can freely communicate with each other."
},
{
"code": null,
"e": 12426,
"s": 12238,
"text": "The white arrows in the diagram below represents open communication between containers. Ports on the containers are shown in green and the ports of your local machine are shown in yellow."
},
{
"code": null,
"e": 12665,
"s": 12426,
"text": "You can see that all the container are deployed within the bridge network. If we now deploy a container outside of this network, it would not be able to resolve the IP addresses of the other containers just by using their container names."
},
{
"code": null,
"e": 12779,
"s": 12665,
"text": "Now letβs wrap everything together to form a fully distributed Spark cluster running inside of Docker containers."
},
{
"code": null,
"e": 12854,
"s": 12779,
"text": "NOTE: For this part you will need to use the 3 images that I have created."
},
{
"code": null,
"e": 12978,
"s": 12854,
"text": "docker pull sdesilva26/spark_master:0.0.2docker pull sdesilva26/spark_worker:0.0.2docker pull sdesilva26/spark_submit:0.0.2"
},
{
"code": null,
"e": 13042,
"s": 12978,
"text": "You can also build them yourself by downloading the Dockerfiles"
},
{
"code": null,
"e": 13133,
"s": 13042,
"text": "Start up an instance on a cloud provider of your choice and make it a docker swarm manager"
},
{
"code": null,
"e": 13224,
"s": 13133,
"text": "Start up an instance on a cloud provider of your choice and make it a docker swarm manager"
},
{
"code": null,
"e": 13242,
"s": 13224,
"text": "docker swarm init"
},
{
"code": null,
"e": 13426,
"s": 13242,
"text": "2. Copy and paste the output of the above command to at least 2 other instances. I have done this on 4 other instances β 3 will act as Spark workers and 1 will be my Spark submit node"
},
{
"code": null,
"e": 13487,
"s": 13426,
"text": "3. On instance 1, create an overlay network as we did before"
},
{
"code": null,
"e": 13543,
"s": 13487,
"text": "docker network create -d overlay --attachable spark-net"
},
{
"code": null,
"e": 13630,
"s": 13543,
"text": "4. Run the spark_master image to create a container that will be the Spark master node"
},
{
"code": null,
"e": 13728,
"s": 13630,
"text": "docker run -it --name spark-master --network spark-net -p 8080:8080 sdesilva26/spark_master:0.0.2"
},
{
"code": null,
"e": 13827,
"s": 13728,
"text": "5. Open up ports 8080β8090 and 4040 by adding the following to your security groupβs inbound rules"
},
{
"code": null,
"e": 13935,
"s": 13827,
"text": "Protocol | Port(s) | SourceCustom TCP | 8080-8090 | 0.0.0/0Custom TCP | 4040 | 0.0.0/0, ::/0"
},
{
"code": null,
"e": 14202,
"s": 13935,
"text": "NOTE: In AWS security groups are stateful, so the return traffic from the instance to users is allowed automatically, so you donβt need to modify the security groupβs outbound rules. On other cloud providers you may have to add a similar rule to your outbound rules."
},
{
"code": null,
"e": 14253,
"s": 14202,
"text": "My inbound security group rules now look like this"
},
{
"code": null,
"e": 14385,
"s": 14253,
"text": "6. Check the Spark master node UI at http://<PUBLIC_IPv4_ADDRESS_OF_INSTANCE>:8080. You should see the same UI that we saw earlier."
},
{
"code": null,
"e": 14488,
"s": 14385,
"text": "7. Now on another one of your instances run the following to attach a Spark worker node to the cluster"
},
{
"code": null,
"e": 14611,
"s": 14488,
"text": "docker run -it --name spark-worker1 --network spark-net -p 8081:8081 -e MEMORY=6G -e CORES=3 sdesilva26/spark_worker:0.0.2"
},
{
"code": null,
"e": 14837,
"s": 14611,
"text": "NOTE: As a general rule of thumb start your Spark worker node with memory = memory of instance-1GB, and cores = cores of instance - 1. This leaves 1 core and 1GB for the instanceβs OS to be able to carry out background tasks."
},
{
"code": null,
"e": 14926,
"s": 14837,
"text": "8. Again, check the master nodeβs web UI to make sure the worker was added successfully."
},
{
"code": null,
"e": 15101,
"s": 14926,
"text": "9. Rinse and repeat step 7 to add as many Spark workers as you please. Make sure to increment the name of the container though from spark-worker1 to spark-worker2, and so on."
},
{
"code": null,
"e": 15172,
"s": 15101,
"text": "I have connected 3 workers and my master nodeβs web UI looks like this"
},
{
"code": null,
"e": 15225,
"s": 15172,
"text": "10. In another instance, fire up a Spark submit node"
},
{
"code": null,
"e": 15328,
"s": 15225,
"text": "docker run -it --name spark-submit --network spark-net -p 4040:4040 sdesilva26/spark_submit:0.0.2 bash"
},
{
"code": null,
"e": 15394,
"s": 15328,
"text": "11. Launch a pyspark interactive shell and connect to the cluster"
},
{
"code": null,
"e": 15515,
"s": 15394,
"text": "$SPARK_HOME/bin/pyspark --conf spark.executor.memory=5G --conf spark.executor.cores=3 --master spark://spark-master:7077"
},
{
"code": null,
"e": 16034,
"s": 15515,
"text": "NOTE: You specify the resources you would like each executor to have when connecting an application to the cluster by using the β conf flag. The topic of Spark tuning is a whole post in itself so I will not go into any detail here. This two part Cloudera blog post I found to be a good resource for understanding resource allocation: part 1 & part 2. Also a blog post by Anthony Shipman from C2FO.io I found very useful and also includes a handy excel sheet to work out settings for memory, cores, and parallelization."
},
{
"code": null,
"e": 16218,
"s": 16034,
"text": "12. Check the submit node has successfully connected to the cluster by checking both the Spark master nodeβs UI and the Spark submit nodeβs UI. They should look like the images below."
},
{
"code": null,
"e": 16262,
"s": 16218,
"text": "13. Run a sample job from the pyspark shell"
},
{
"code": null,
"e": 16507,
"s": 16262,
"text": "from random import randomdef inside(p): x, y = random(), random() return x*x + y*y < 1NUM_SAMPLES = 100000count = sc.parallelize(range(0, NUM_SAMPLES)).filter(inside).count()print(\"Pi is roughly {:0.4f}\".format(4.0 * count / NUM_SAMPLES))"
},
{
"code": null,
"e": 16665,
"s": 16507,
"text": "The more common way to submit jobs to a Spark cluster is by using the spark-submit script which is included with your spark installation. Letβs also do this."
},
{
"code": null,
"e": 16737,
"s": 16665,
"text": "14. Exit out of pyspark and submit a program to executor on the cluster"
},
{
"code": null,
"e": 16909,
"s": 16737,
"text": "$SPARK_HOME/bin/spark-submit --conf spark.executor.cores=3 --conf spark.executor.memory=5G --master spark://spark-master:7077 $SPARK_HOME/examples/src/main/python/pi.py 20"
},
{
"code": null,
"e": 17092,
"s": 16909,
"text": "Itβs pretty much the same syntax as before except we are calling the spark-submit script and we are passing it a .py file along with any other configurations for the file to execute."
},
{
"code": null,
"e": 17239,
"s": 17092,
"text": "Happy days! We have now created a fully distributed Spark cluster running inside of Docker containers and submitted an application to the cluster."
},
{
"code": null,
"e": 17302,
"s": 17239,
"text": "The architecture we have just created looks like the following"
},
{
"code": null,
"e": 17676,
"s": 17302,
"text": "Each Spark worker node and the master node is running inside a Docker container located on its own computing instance. The Spark driver node (spark submit node) is also located within its own container running on a separate instance. All the Docker daemons are connected by means of an overlay network with the Spark master node being the Docker swarm manager in this case."
},
{
"code": null,
"e": 17832,
"s": 17676,
"text": "Within the overlay network, containers can easily resolve each otherβs addresses by referencing container names which utilises automatic service discovery."
},
{
"code": null,
"e": 17907,
"s": 17832,
"text": "More Spark worker nodes can be fired up on additional instances if needed."
},
{
"code": null,
"e": 17935,
"s": 17907,
"text": "Welcome to the finish line!"
},
{
"code": null,
"e": 18097,
"s": 17935,
"text": "In this tutorial we have managed to sequentially step through the varying levels of complexity in setting up a Spark cluster running inside of Docker containers."
},
{
"code": null,
"e": 18305,
"s": 18097,
"text": "We first started off with some simple Docker networking principles both on our local machine, in which we used a bridge network, and then on distributed machines using an overlay network with a docker swarm."
},
{
"code": null,
"e": 18415,
"s": 18305,
"text": "Next we set up a Spark cluster running on our local machine to get to grips with adding workers to a cluster."
},
{
"code": null,
"e": 18545,
"s": 18415,
"text": "Then we introduced Docker back in to the mix and set up a Spark cluster running inside of Docker containers on our local machine."
},
{
"code": null,
"e": 18662,
"s": 18545,
"text": "Finally, we brought everything together to construct a fully distributed Spark cluster running in Docker containers."
},
{
"code": null,
"e": 18815,
"s": 18662,
"text": "Hopefully youβve gained a clear understanding of how these two technologies link together and could provide benefit to your specific problem or project."
},
{
"code": null,
"e": 18914,
"s": 18815,
"text": "Now is the time for you to start experimenting and see what you can learn using this architecture."
},
{
"code": null,
"e": 18921,
"s": 18914,
"text": "Enjoy!"
},
{
"code": null,
"e": 19065,
"s": 18921,
"text": "The above steps of manually creating a cluster was more informative than practical as it required a lot of manual typing and repeated commands."
},
{
"code": null,
"e": 19220,
"s": 19065,
"text": "For small(ish) problems where you only need the resources of maybe 4 or 5 computing instances this amount of effort is probably below your pain threshold."
},
{
"code": null,
"e": 19386,
"s": 19220,
"text": "However, as the data becomes truly large and the computing power needed starts to increase, following the above steps will turn you into a full-time cluster creator."
},
{
"code": null,
"e": 19489,
"s": 19386,
"text": "A much more practical and elegant way of setting up a cluster is by taking advantage of Docker compose"
},
{
"code": null,
"e": 19581,
"s": 19489,
"text": "For those of you new to Docker compose, it allows you to launch what are called βservicesβ."
},
{
"code": null,
"e": 19835,
"s": 19581,
"text": "A service is made up of a single Docker image, but you may want multiple containers of this image to be running. For example, running multiple Spark worker containers from the docker image sdesilva26/spark_worker:0.0.2 would constitute a single service."
},
{
"code": null,
"e": 19977,
"s": 19835,
"text": "To launch a set of services you create a docker-compose.yml file which specifies everything about the various services you would like to run."
},
{
"code": null,
"e": 20109,
"s": 19977,
"text": "However, Docker compose is used to create services running on a single host. It does not support deploying containers across hosts."
},
{
"code": null,
"e": 20129,
"s": 20109,
"text": "Enter Docker stack."
},
{
"code": null,
"e": 20337,
"s": 20129,
"text": "The Docker stack is a simple extension to the idea of Docker compose. Instead of running your services on a single host, you can now run your services on multiple hosts which are connected as a Docker swarm."
},
{
"code": null,
"e": 20482,
"s": 20337,
"text": "Best of all, if you have a Docker compose file very little modifications need to be made in order for it to work with the Docker stack commands."
},
{
"code": null,
"e": 20611,
"s": 20482,
"text": "Letβs see how to create our distributed Spark cluster running inside of Docker containers using a compose file and docker stack."
},
{
"code": null,
"e": 20729,
"s": 20611,
"text": "The first step is to label the nodes in your Docker swarm. From the Docker swarm manager list the nodes in the swarm."
},
{
"code": null,
"e": 20847,
"s": 20729,
"text": "The first step is to label the nodes in your Docker swarm. From the Docker swarm manager list the nodes in the swarm."
},
{
"code": null,
"e": 20862,
"s": 20847,
"text": "docker node ls"
},
{
"code": null,
"e": 20914,
"s": 20862,
"text": "You should get a similar output to the image below."
},
{
"code": null,
"e": 20985,
"s": 20914,
"text": "2. For any instances you wish to be Spark workers, add a label to them"
},
{
"code": null,
"e": 21054,
"s": 20985,
"text": "docker node update --label-add role=worker x5kmfd8akvvtnsfvmxybcjb8w"
},
{
"code": null,
"e": 21142,
"s": 21054,
"text": "3. Now label the instance you wish to run the Spark master node with the role of master"
},
{
"code": null,
"e": 21186,
"s": 21142,
"text": "docker node update --label-add role=master "
},
{
"code": null,
"e": 21254,
"s": 21186,
"text": "4. Create a docker-compose.yml file or pull the one I have created."
},
{
"code": null,
"e": 21336,
"s": 21254,
"text": "In this compose file I have defined two services β spark-master and spark-worker."
},
{
"code": null,
"e": 21442,
"s": 21336,
"text": "The first service deploys a single container onto any node in the swarm that has the label βrole=masterβ."
},
{
"code": null,
"e": 21655,
"s": 21442,
"text": "The second service will deploy 3 containers of the sdesilva26/spark_worker:0.0.2 image onto nodes with the label βrole=workerβ. If 3 suitable nodes in the swarm arenβt found it will deploy as many as is possible."
},
{
"code": null,
"e": 21773,
"s": 21655,
"text": "Finally, all these containers will be deployed into an overlay network called spark-net which will be created for us."
},
{
"code": null,
"e": 21850,
"s": 21773,
"text": "5. Copy the docker-compose.yml into the instance which is the swarm manager."
},
{
"code": null,
"e": 21975,
"s": 21850,
"text": "scp -i <YOUR_KEY>.pem /path/to/docker-compose.yml ec2-user@<PUBLIC_IP_ADDRESS_OF_INSTANCE>:/home/ec2-user/docker-compose.yml"
},
{
"code": null,
"e": 22021,
"s": 21975,
"text": "[see here for alternative ways of doing this]"
},
{
"code": null,
"e": 22098,
"s": 22021,
"text": "6. Finally, run your docker stack from the swarm manager and give it a name."
},
{
"code": null,
"e": 22162,
"s": 22098,
"text": "docker stack deploy --compose-file docker-compose.yml sparkdemo"
},
{
"code": null,
"e": 22348,
"s": 22162,
"text": "NOTE: the name of your stack will be prepended to all service names. So the service βspark-masterβ becomes βsparkdemo_spark-masterβ. You can check the services that are running by using"
},
{
"code": null,
"e": 22366,
"s": 22348,
"text": "docker service ls"
},
{
"code": null,
"e": 22533,
"s": 22366,
"text": "7. Check that the spark_worker image is running on the instances you labelled as βworkerβ and that the spark_master image is running on the node labelled as βmasterβ."
},
{
"code": null,
"e": 22659,
"s": 22533,
"text": "Congratulations, we have just simplified all of the work from this article into a few commands from the Docker swarm manager."
},
{
"code": null,
"e": 22891,
"s": 22659,
"text": "The best thing about Docker services is that it is very easy to scale up. For example, if later on we added another instance to the Docker swarm and we then wished to scale up the βsparkdemo_spark-workerβ service, we can simply run"
},
{
"code": null,
"e": 22937,
"s": 22891,
"text": "docker service scale sparkdemo_spark-worker=4"
}
] |
Understanding NLP and Topic Modeling Part 1 | by Tony Yiu | Towards Data Science | Natural language processing (NLP) is one of the trendier areas of data science. Its end applications are many β chatbots, recommender systems, search, virtual assistants, etc.
So it would be beneficial for budding data scientists to at least understand the basics of NLP even if their career takes them in a completely different direction. And who knows, some topics extracted through NLP might just give your next model that extra analytical boost. Today, in this post, we seek to understand why topic modeling is important and how it helps us as data scientists.
Topic modeling, just as it sounds, is using an algorithm to discover the topic or set of topics that best describes a given text document. You can think of each topic as a word or a set of words.
The first time I worked with NLP, I wondered to myself:
βIs NLP just another form of EDA (exploratory data analysis)?β
Thatβs because up until then, I had been mainly building models with a clear objective in mind β use X to forecast or explain Y. NLP was much less structured and clear. Even when I finally successfully ran my topic modeling algorithm, the topics that fell out produced more questions than answers. Here, take a look at some of the topics that came out of my NLP analysis of Reddit:
Topic 10:book read reading history series love author first people novel world finishedTopic 11:like feel something people look seem seems stuff actually right always questionTopic 12:story writing write character main novel chapter short plot first scene adviceTopic 13:think wait bit better people bad true might worth thinking put sellTopic 14:need financial house information relevant situation invest question money making ask considerTopic 15:car insurance loan vehicle damage accident hit month payment driver title pay
Some of the topics make sense, some of them do not. And what exactly should I be doing with these topics anyways?
Such is life as a data scientist β often the real work begins only after you finally get your data cleaned and your code debugged. Then, at long last, itβs time to find those annoyingly elusive insights. And thatβs precisely the point of NLP and topic modeling. It might not be an end unto itself, but extracting topics via NLP gets us that much closer to generating something useful in much the same way that dimensionality reduction techniques help us on the numerical side of the data science world.
Topic modeling allows us to cut through the noise (deal with the high dimensionality of text data) and identify the signal (the main topics) of our text data.
And with this distilled signal, we can start the real work of generating insights. Letβs go through this step by step.
High dimensional data is regarded as a curse in many data science applications. If you want to understand why in more detail, here is a previous post I wrote on The Curse of Dimensionality. But for those short on time hereβs the TLDR:
If we have more features than observations than we run the risk of massively overfitting our model β this would generally result in terrible out of sample performance.When we have too many features, observations become harder to cluster β believe it or not, too many dimensions causes every observation in your dataset to appear equidistant from all the others. And because clustering uses a distance measure such as Euclidean distance to quantify the similarity between observations, this is a big problem. If the distances are all approximately equal, then all the observations appear equally alike (as well as equally different), and no meaningful clusters can be formed.
If we have more features than observations than we run the risk of massively overfitting our model β this would generally result in terrible out of sample performance.
When we have too many features, observations become harder to cluster β believe it or not, too many dimensions causes every observation in your dataset to appear equidistant from all the others. And because clustering uses a distance measure such as Euclidean distance to quantify the similarity between observations, this is a big problem. If the distances are all approximately equal, then all the observations appear equally alike (as well as equally different), and no meaningful clusters can be formed.
When are we most likely to run into high dimensional data (a.k.a. too many features)? Text data. To see why, imagine how we would encode the data for the following sentence so that an algorithm can do something with it:
βThe man was wearing a jacket with a gold star.β
A natural way is whatβs called the bag of words approach β bag of words represents a given document as a list of distinct words and their frequencies. So the sentence above would look like this:
So in order to capture a given document, we need a feature for each unique word in it. And for a given document, the value for each feature is the number of times the word appears in the document (so for our earlier example, every word appears once besides βaβ, which appears twice).
Now imagine that our document is not an isolated one but rather part of a much larger corpus. Letβs first get the lingo out of the way:
Document is whatever you define a single observation (a.k.a. a single bag of words) to be. It can range from a single sentence to a whole article or even an entire book β how you define it will be determined by the objective of your analysis.
Corpus is the totality of all your text data β or in other words, all the documents in your dataset.
If your corpus is large, then you will probably have at least tens of thousands of unique words in it (more if your corpus includes a lot of names). Just attempting to picturing that bag of words makes my head hurt. And attempting to run algorithms on it would be both extremely slow and probably unhelpful β itβs highly likely that you will have more features (distinct words) than observations (documents).
Now letβs use a practical example to see how NLP helps sift through the dimensionality to reveal signal. Imagine that we want to recommend a few books to a friend. How would we go about doing that?
One way would be to ask:
βHey, name a few books that you read recently that you really liked.β
And then based on the reply, recommend a few of our favorite books that are most similar to the ones that he or she listed. We just described a simple recommender system.
In order to do what we just described algorithmically, we need to be able to figure out how to measure whether two books are similar or not. We could represent both books as bags of words and try comparing them using a distance measure like euclidean distance, but is that actually helpful? The answer is no for several reasons:
The first reason is stop words (really common words like βtheβ, βaβ, βitβ, βandβ, etc.) β these words occur very frequently in pretty much all documents and they would inject a lot of meaningless noise into our similarity score (knowing that both books contain many instances of the word βtheβ would not be helpful at all).
And even if we removed all the stop words, the Curse of Dimensionality still affects us. There are so many distinct words in a book and many of them have zero correlation to the actual topic of the book. Thus, itβs highly likely for our similarity measure to latch onto one of these noise words β this is basically the text version of spurious correlation. For example, we could have a book about fire fighters and a book about salmon fishing, but rank them as highly similar because our algorithm noticed that the words βpoleβ and βengineβ occur frequently in both. This is an accidental and meaningless similarity and it would be problematic if we acted upon it.
This is where topic modeling comes in. Topic modeling is the practice of using a quantitative algorithm to tease out the key topics that a body of text is about. It bears a lot of similarities with something like PCA, which identifies the key quantitative trends (that explain the most variance) within your features. The outputs of PCA are a way of summarizing our features β for example, it allows us to go from something like 500 features to 10 summary features. These 10 summary feature are basically topics.
In NLP, it works almost exactly the same way. We want to distill our total corpus of books and its 100,000 features (distinct words) into 7 topics (I decided on 7 topics arbitrarily). And once we know the topics along with what they consist of, we can transform each book in our corpus from a noisy bag of words to a clean portfolio of topic loadings:
Now weβre in business. Similarity scores calculated using each bookβs topic loadings are a lot more useful than ones calculated using the raw bag of words because spurious similarities are now much less likely.
Even the descriptive statistics of a book are more meaningful in βtopics spaceβ than in βbag of words spaceβ β we can now say a book loads heavily on the data science topic instead of puzzling over why the two most frequent words in our bag of words are βforestβ and βrandomβ.
In our previous example, we decided to express our book as loadings on 7 topics. But we could have gone with any number of topics (picking the number of topics is more art than science and depends heavily on your data β thus knowing your data well is critical). 10 works too, so does 100. But think about what happens as we keep increasing the number of topics and each topic becomes increasingly granular β the algorithm begins to lose the ability to see the big picture.
For example, letβs say we have three books β Book 1 is a French travel guide, Book 2 is a Chinese travel guide, and Book 3 is an economic history of the urbanization of China. With our 7 topics NLP model, we would classify Books 1 and 2 as travel books (and score them as similar to each other) and Book 3 as a business book (and score it as not similar to the others).
With 5,000 topics, we might classify Book 1 as βCycling Rural Franceβ, Book 2 as βTraveling Urban Chinaβ, and Book 3 as βHistory Urban Chinaβ. Now it is much less clear how we would score them β the algorithm might just throw up its hands and rate all 3 books as equally similar/different. Thatβs not necessarily wrong (depending on the application) but it does show how high dimensional data (which 5,000 topics definitely is) can inject noise that distorts our analysis in unintended ways.
A general rule of thumb when topic modeling, is to be only as specific as your end application requires you to be, never more.
I realize that so far Iβve been suitably vague on how we actually come up with our topics. Thatβs because I wanted to fully explore why NLP is important. Next time, I will cover (with Python code) two topic modeling algorithms β LDA (latent Dirichlet allocation) and NMF (non-negative matrix factorization).
Until then, thanks for reading and cheers!
More Data Science and Analytics Related Posts By Me:
The Curse of Dimensionality
Understanding PCA
Business Strategy For Data Scientists
Business Simulations With Python
Understanding Bayesβ Theorem
Understanding The Naive Bayes Classifier
The Binomial Distribution | [
{
"code": null,
"e": 347,
"s": 171,
"text": "Natural language processing (NLP) is one of the trendier areas of data science. Its end applications are many β chatbots, recommender systems, search, virtual assistants, etc."
},
{
"code": null,
"e": 736,
"s": 347,
"text": "So it would be beneficial for budding data scientists to at least understand the basics of NLP even if their career takes them in a completely different direction. And who knows, some topics extracted through NLP might just give your next model that extra analytical boost. Today, in this post, we seek to understand why topic modeling is important and how it helps us as data scientists."
},
{
"code": null,
"e": 932,
"s": 736,
"text": "Topic modeling, just as it sounds, is using an algorithm to discover the topic or set of topics that best describes a given text document. You can think of each topic as a word or a set of words."
},
{
"code": null,
"e": 988,
"s": 932,
"text": "The first time I worked with NLP, I wondered to myself:"
},
{
"code": null,
"e": 1051,
"s": 988,
"text": "βIs NLP just another form of EDA (exploratory data analysis)?β"
},
{
"code": null,
"e": 1433,
"s": 1051,
"text": "Thatβs because up until then, I had been mainly building models with a clear objective in mind β use X to forecast or explain Y. NLP was much less structured and clear. Even when I finally successfully ran my topic modeling algorithm, the topics that fell out produced more questions than answers. Here, take a look at some of the topics that came out of my NLP analysis of Reddit:"
},
{
"code": null,
"e": 1960,
"s": 1433,
"text": "Topic 10:book read reading history series love author first people novel world finishedTopic 11:like feel something people look seem seems stuff actually right always questionTopic 12:story writing write character main novel chapter short plot first scene adviceTopic 13:think wait bit better people bad true might worth thinking put sellTopic 14:need financial house information relevant situation invest question money making ask considerTopic 15:car insurance loan vehicle damage accident hit month payment driver title pay"
},
{
"code": null,
"e": 2074,
"s": 1960,
"text": "Some of the topics make sense, some of them do not. And what exactly should I be doing with these topics anyways?"
},
{
"code": null,
"e": 2577,
"s": 2074,
"text": "Such is life as a data scientist β often the real work begins only after you finally get your data cleaned and your code debugged. Then, at long last, itβs time to find those annoyingly elusive insights. And thatβs precisely the point of NLP and topic modeling. It might not be an end unto itself, but extracting topics via NLP gets us that much closer to generating something useful in much the same way that dimensionality reduction techniques help us on the numerical side of the data science world."
},
{
"code": null,
"e": 2736,
"s": 2577,
"text": "Topic modeling allows us to cut through the noise (deal with the high dimensionality of text data) and identify the signal (the main topics) of our text data."
},
{
"code": null,
"e": 2855,
"s": 2736,
"text": "And with this distilled signal, we can start the real work of generating insights. Letβs go through this step by step."
},
{
"code": null,
"e": 3090,
"s": 2855,
"text": "High dimensional data is regarded as a curse in many data science applications. If you want to understand why in more detail, here is a previous post I wrote on The Curse of Dimensionality. But for those short on time hereβs the TLDR:"
},
{
"code": null,
"e": 3765,
"s": 3090,
"text": "If we have more features than observations than we run the risk of massively overfitting our model β this would generally result in terrible out of sample performance.When we have too many features, observations become harder to cluster β believe it or not, too many dimensions causes every observation in your dataset to appear equidistant from all the others. And because clustering uses a distance measure such as Euclidean distance to quantify the similarity between observations, this is a big problem. If the distances are all approximately equal, then all the observations appear equally alike (as well as equally different), and no meaningful clusters can be formed."
},
{
"code": null,
"e": 3933,
"s": 3765,
"text": "If we have more features than observations than we run the risk of massively overfitting our model β this would generally result in terrible out of sample performance."
},
{
"code": null,
"e": 4441,
"s": 3933,
"text": "When we have too many features, observations become harder to cluster β believe it or not, too many dimensions causes every observation in your dataset to appear equidistant from all the others. And because clustering uses a distance measure such as Euclidean distance to quantify the similarity between observations, this is a big problem. If the distances are all approximately equal, then all the observations appear equally alike (as well as equally different), and no meaningful clusters can be formed."
},
{
"code": null,
"e": 4661,
"s": 4441,
"text": "When are we most likely to run into high dimensional data (a.k.a. too many features)? Text data. To see why, imagine how we would encode the data for the following sentence so that an algorithm can do something with it:"
},
{
"code": null,
"e": 4710,
"s": 4661,
"text": "βThe man was wearing a jacket with a gold star.β"
},
{
"code": null,
"e": 4905,
"s": 4710,
"text": "A natural way is whatβs called the bag of words approach β bag of words represents a given document as a list of distinct words and their frequencies. So the sentence above would look like this:"
},
{
"code": null,
"e": 5189,
"s": 4905,
"text": "So in order to capture a given document, we need a feature for each unique word in it. And for a given document, the value for each feature is the number of times the word appears in the document (so for our earlier example, every word appears once besides βaβ, which appears twice)."
},
{
"code": null,
"e": 5325,
"s": 5189,
"text": "Now imagine that our document is not an isolated one but rather part of a much larger corpus. Letβs first get the lingo out of the way:"
},
{
"code": null,
"e": 5568,
"s": 5325,
"text": "Document is whatever you define a single observation (a.k.a. a single bag of words) to be. It can range from a single sentence to a whole article or even an entire book β how you define it will be determined by the objective of your analysis."
},
{
"code": null,
"e": 5669,
"s": 5568,
"text": "Corpus is the totality of all your text data β or in other words, all the documents in your dataset."
},
{
"code": null,
"e": 6078,
"s": 5669,
"text": "If your corpus is large, then you will probably have at least tens of thousands of unique words in it (more if your corpus includes a lot of names). Just attempting to picturing that bag of words makes my head hurt. And attempting to run algorithms on it would be both extremely slow and probably unhelpful β itβs highly likely that you will have more features (distinct words) than observations (documents)."
},
{
"code": null,
"e": 6276,
"s": 6078,
"text": "Now letβs use a practical example to see how NLP helps sift through the dimensionality to reveal signal. Imagine that we want to recommend a few books to a friend. How would we go about doing that?"
},
{
"code": null,
"e": 6301,
"s": 6276,
"text": "One way would be to ask:"
},
{
"code": null,
"e": 6371,
"s": 6301,
"text": "βHey, name a few books that you read recently that you really liked.β"
},
{
"code": null,
"e": 6542,
"s": 6371,
"text": "And then based on the reply, recommend a few of our favorite books that are most similar to the ones that he or she listed. We just described a simple recommender system."
},
{
"code": null,
"e": 6871,
"s": 6542,
"text": "In order to do what we just described algorithmically, we need to be able to figure out how to measure whether two books are similar or not. We could represent both books as bags of words and try comparing them using a distance measure like euclidean distance, but is that actually helpful? The answer is no for several reasons:"
},
{
"code": null,
"e": 7195,
"s": 6871,
"text": "The first reason is stop words (really common words like βtheβ, βaβ, βitβ, βandβ, etc.) β these words occur very frequently in pretty much all documents and they would inject a lot of meaningless noise into our similarity score (knowing that both books contain many instances of the word βtheβ would not be helpful at all)."
},
{
"code": null,
"e": 7860,
"s": 7195,
"text": "And even if we removed all the stop words, the Curse of Dimensionality still affects us. There are so many distinct words in a book and many of them have zero correlation to the actual topic of the book. Thus, itβs highly likely for our similarity measure to latch onto one of these noise words β this is basically the text version of spurious correlation. For example, we could have a book about fire fighters and a book about salmon fishing, but rank them as highly similar because our algorithm noticed that the words βpoleβ and βengineβ occur frequently in both. This is an accidental and meaningless similarity and it would be problematic if we acted upon it."
},
{
"code": null,
"e": 8373,
"s": 7860,
"text": "This is where topic modeling comes in. Topic modeling is the practice of using a quantitative algorithm to tease out the key topics that a body of text is about. It bears a lot of similarities with something like PCA, which identifies the key quantitative trends (that explain the most variance) within your features. The outputs of PCA are a way of summarizing our features β for example, it allows us to go from something like 500 features to 10 summary features. These 10 summary feature are basically topics."
},
{
"code": null,
"e": 8725,
"s": 8373,
"text": "In NLP, it works almost exactly the same way. We want to distill our total corpus of books and its 100,000 features (distinct words) into 7 topics (I decided on 7 topics arbitrarily). And once we know the topics along with what they consist of, we can transform each book in our corpus from a noisy bag of words to a clean portfolio of topic loadings:"
},
{
"code": null,
"e": 8936,
"s": 8725,
"text": "Now weβre in business. Similarity scores calculated using each bookβs topic loadings are a lot more useful than ones calculated using the raw bag of words because spurious similarities are now much less likely."
},
{
"code": null,
"e": 9213,
"s": 8936,
"text": "Even the descriptive statistics of a book are more meaningful in βtopics spaceβ than in βbag of words spaceβ β we can now say a book loads heavily on the data science topic instead of puzzling over why the two most frequent words in our bag of words are βforestβ and βrandomβ."
},
{
"code": null,
"e": 9686,
"s": 9213,
"text": "In our previous example, we decided to express our book as loadings on 7 topics. But we could have gone with any number of topics (picking the number of topics is more art than science and depends heavily on your data β thus knowing your data well is critical). 10 works too, so does 100. But think about what happens as we keep increasing the number of topics and each topic becomes increasingly granular β the algorithm begins to lose the ability to see the big picture."
},
{
"code": null,
"e": 10056,
"s": 9686,
"text": "For example, letβs say we have three books β Book 1 is a French travel guide, Book 2 is a Chinese travel guide, and Book 3 is an economic history of the urbanization of China. With our 7 topics NLP model, we would classify Books 1 and 2 as travel books (and score them as similar to each other) and Book 3 as a business book (and score it as not similar to the others)."
},
{
"code": null,
"e": 10548,
"s": 10056,
"text": "With 5,000 topics, we might classify Book 1 as βCycling Rural Franceβ, Book 2 as βTraveling Urban Chinaβ, and Book 3 as βHistory Urban Chinaβ. Now it is much less clear how we would score them β the algorithm might just throw up its hands and rate all 3 books as equally similar/different. Thatβs not necessarily wrong (depending on the application) but it does show how high dimensional data (which 5,000 topics definitely is) can inject noise that distorts our analysis in unintended ways."
},
{
"code": null,
"e": 10675,
"s": 10548,
"text": "A general rule of thumb when topic modeling, is to be only as specific as your end application requires you to be, never more."
},
{
"code": null,
"e": 10983,
"s": 10675,
"text": "I realize that so far Iβve been suitably vague on how we actually come up with our topics. Thatβs because I wanted to fully explore why NLP is important. Next time, I will cover (with Python code) two topic modeling algorithms β LDA (latent Dirichlet allocation) and NMF (non-negative matrix factorization)."
},
{
"code": null,
"e": 11026,
"s": 10983,
"text": "Until then, thanks for reading and cheers!"
},
{
"code": null,
"e": 11079,
"s": 11026,
"text": "More Data Science and Analytics Related Posts By Me:"
},
{
"code": null,
"e": 11107,
"s": 11079,
"text": "The Curse of Dimensionality"
},
{
"code": null,
"e": 11125,
"s": 11107,
"text": "Understanding PCA"
},
{
"code": null,
"e": 11163,
"s": 11125,
"text": "Business Strategy For Data Scientists"
},
{
"code": null,
"e": 11196,
"s": 11163,
"text": "Business Simulations With Python"
},
{
"code": null,
"e": 11225,
"s": 11196,
"text": "Understanding Bayesβ Theorem"
},
{
"code": null,
"e": 11266,
"s": 11225,
"text": "Understanding The Naive Bayes Classifier"
}
] |
Who is a Potential Customer?. Online purchasing intention prediction... | by Pei Guo | Towards Data Science | Every day online shopping sites receive a huge number of visits. However, only a small portion of the visits turned into purchases.
What if the shopping sites know which customer groups are more likely to make purchases?
They will be able to launch target promotions that benefit both the websites and the customers. Today we will explore this problem using the power of machine learning. The dataset is from the research of C. Okan Sakar. We will use different methodologies from the research in this project. If you would like to reproduce this project, you can find all the resources in my Github.
The dataset consists of 12,330 sessions(rows) of online shopping visits to a website. The data is within a 1 year period to avoid any tendency. 18 features are used to describe each session, divided into numeric and categorical features. Feature βRevenueβ is the label of our binary classification problem. Our goal is to use all the other 17 features below to predict the label βRevenueβ, that is to see whether a visit session will end up with a transaction or not.
Here are the descriptions of the features, referenced to the paper.
Itβs worth note that Google Analytics metrics are used in numeric features: bounce rate measures whether a customer leaves a page without further visiting another one; exit rate tells you how often a page is the last page of a session; page value shows which page contributed more to the siteβs revenue.
We will follow the workflow above to find the best model for customer purchase intension prediction.
We need to make a lot of decisions on model selections and feature selections in this project. The decisions are made based on these metrics: Accuracy, Recall, Precision, and F1. Let me explain them using our business case.
In our dataset, there is a customer behind each online visit session. If we predict βRevenueβ is 1, it means this customer who initiated the session is more likely to make a purchase. However, our prediction is not always correct. The table below shows the different scenarios.
Assumptions: 1. $100 revenue for each order placed and $5 cost for each coupon sent. 2. A likely customer with a coupon will make a purchase and an unlikely customer with a coupon will NOT make a purchase.
As seen from the above table, we want more βtrue positive(TP)β to happen and to avoid βfalse negative(FN)β as much as possible. How do we apply this to a machine learning model? The classification metrics:
Recall score: TP/(TP+FN)
Of all the likely customers, how many of them the model can identify correctly. A high recall requires both high TP and low FN. It can identify a large portion of likely customers to reduce lost sales. Meanwhile more unlikely customers(FP) will also receive the coupons. This is fine when the lost sales cost is greater than the coupon cost.
Precision score: TP/(TP+ FP)
Of all the βlikelyβ customers our model predicted, how many of them are actually correct, not false positive. A high precision score requires both high TP and low FP. It can make sure a larger portion of predicted likely customers are correct. More coupons are used, fewer wasted coupons. However more other likely customers will be ignored to cause lost sales.
F1 score: 2*recall*precisoin/(recall+precision)
A value that balances recall and precision scores with consideration of both.
Accuracy score: (TP+TN)/(TP +TN+FN+FP)
The percentage of the predicted results are correct. This metric only works when the classes are balanced. We donβt use it for unbalanced data.
As a result of the above, in this project, we will use the Recall score as our main metric when making decisions on model selections. When recall scores are similar, we will also consider F1 scores.
First, letβs clean the data:
Usually only a small portion of the visits ended up into transactions, we suspect the data is imbalanced. After testing it below, we found the transaction conversion rate is only 18.3%. This means later we need to make a balance adjustment on the data for modeling.
The categorical data need to be converted into numeric for further analysis.
The data set is highly imbalanced. All the models tend to fit towards the majority class, so in order to improve the model performance, we need to balance the data first. I used the SMOTE oversizing technique, the result is that both classes have the same number of samples.
Now we can use Accuracy as a metric for a balanced dataset. I chose 7 classifiers as model candidates. I split the dataset into 80% train and 20% test. Then the train set is fitted into each model without tuning. Here we get a baseline accuracy ranking. I will choose the top 4 models as my baseline models: Random forest, EXTRA trees, ADAboost and logistic regression. We now prioritize on accuracy to recall, because we need unbiased models. Then later select high recall models within the high accuracy models.
Feature engineering and model tuning will be performed later on the 4 models. For code details please refer to my Github page.
My goal is to reduce the number of features and increase the metric values at the same time. With fewer features, the cost of data collection is reduced, as well as the computing time and cost. Three feature selection techniques were used to give a comprehensive decision: information values, sklearnβs SelectFromModel(), and the correlation values.
Which features can give us more information in prediction than other features? Letβs try sklearnβs SelectFromModel() to filter the importance weights of the features. This gives us three features as important features. We will keep them and continue exploring the other two methods for feature selection.
'ProductRelated_Duration', 'ExitRates', 'PageValues'
The heatmap on the left shows the correlations among all the features. The darker the color, the higher the correlation. What we want to see is that the features are very correlated with the label βRevenueβ but not correlated with one another. But some features are highly correlated with another feature. This means only one of the correlated features can be kept. How do we know which one to keep? The information values (IV) will help us.
Now, we will use information values to rank all the features and find the ones that have medium to strong prediction power.
The function below will calculate the information value of each feature.
With all the calculations above, now we have the results below:
The tables above show the 8 features kept for further modeling:
Administrative_Duration, Informational, ProductRelated_Duration, ExitRates, Special day, Month, VisitorType, PageValues
How did I make the decisions?
The flowchart on the left is my thought process.
A feature with IV below 0.1 is removed.For the rest, if a feature is selected by the sklearn filter, we keep it.Then the rest is removed if it is highly correlated with the kept features.Then last portion if a feature is not correlated with another, we keep it. If it is, the one with higher information value is kept.
A feature with IV below 0.1 is removed.
For the rest, if a feature is selected by the sklearn filter, we keep it.
Then the rest is removed if it is highly correlated with the kept features.
Then last portion if a feature is not correlated with another, we keep it. If it is, the one with higher information value is kept.
Now we have fewer features, letβs see if they can help improve our models:
We have great results! All the recall values are improved greatly after feature selection and the other metrics look good as well.
We have 7 categorical features. Even though they are converted to numeric values earlier, all the values of a categorical feature are in one column. What if we make each value its own feature? Letβs dummy the categorical feature variable! After processing the data, now we have 29 features and 1 label.
Why we donβt use the dummy variables in the 1st round feature selection? Because it is not effective to dummy the low information value features and make too many new features. That will lower the modelsβ performance.
Now we will use the same techniques in the 1st round feature selection process to select the new features. For details, please refer to my Github.
Administrative_Duration, Informational_bins_page_1_plus, ProductRelated_Duration, ExitRates, Month 11, VisitorType_bins_return, PageValues_bins_above_0
Now the heat map above shows the 7 features + 1 label after a new round of feature selection. Note that no two features are correlated (this is great), and the Pagevalues_bins_above_0 feature is very relevant to Revenue
Now letβs see the performance of these new features on the models.
We can see that EXTRA trees and AdaBoost have improved recall scores while the other two models donβt perform as well as before. EXTRA trees model has a lower recall than AdaBoost but a higher F1. So we will keep both models for now for the next step, model tuning.
Now we have narrowed down to two models: EXTRA trees and AdaBoost. By tuning their hyper-parameters, we could potentially increase the recall score even further. For model tuning techniques, I will use RandomizedSearchCV first. It will randomly run the model through a list of hyper-parameters we defined. Once we have the best performance through RandomizedSearch, we will use GridSearch to further improve the model by running through a narrower list of hyper-parameters. For details, please check my Github.
The picture above shows that both models were improved by using a randomized search, then grid search. The final recall scores only have 0.002 difference. We then look at F1 and accuracy scores. EXTRA trees model has much higher scores in both metrics. As a result, it is our final model.
In this project, we built a binary classification machine learning model to predict the purchase intension of customers on an online shopping site. After several rounds of feature selections and model selections, we determine the best model for our data is EXTRA trees and the features to fit in the model are as below.
EXTRA trees model we built in this project can capture 83% of the likely customers. This means if the marketing team send the coupons to all the likely customers predicted by this model, the coupons will cover 83% of all the actual likely customer in the market. This model can definitely help the marketing team make effective marketing strategies!
Thank you for your time in reading this article. I hope it gives you some inspirations in your own project. If you like my article, please give it a clap. Connect with me on Linkedin is always welcomed! Happy learning! | [
{
"code": null,
"e": 304,
"s": 172,
"text": "Every day online shopping sites receive a huge number of visits. However, only a small portion of the visits turned into purchases."
},
{
"code": null,
"e": 393,
"s": 304,
"text": "What if the shopping sites know which customer groups are more likely to make purchases?"
},
{
"code": null,
"e": 773,
"s": 393,
"text": "They will be able to launch target promotions that benefit both the websites and the customers. Today we will explore this problem using the power of machine learning. The dataset is from the research of C. Okan Sakar. We will use different methodologies from the research in this project. If you would like to reproduce this project, you can find all the resources in my Github."
},
{
"code": null,
"e": 1241,
"s": 773,
"text": "The dataset consists of 12,330 sessions(rows) of online shopping visits to a website. The data is within a 1 year period to avoid any tendency. 18 features are used to describe each session, divided into numeric and categorical features. Feature βRevenueβ is the label of our binary classification problem. Our goal is to use all the other 17 features below to predict the label βRevenueβ, that is to see whether a visit session will end up with a transaction or not."
},
{
"code": null,
"e": 1309,
"s": 1241,
"text": "Here are the descriptions of the features, referenced to the paper."
},
{
"code": null,
"e": 1613,
"s": 1309,
"text": "Itβs worth note that Google Analytics metrics are used in numeric features: bounce rate measures whether a customer leaves a page without further visiting another one; exit rate tells you how often a page is the last page of a session; page value shows which page contributed more to the siteβs revenue."
},
{
"code": null,
"e": 1714,
"s": 1613,
"text": "We will follow the workflow above to find the best model for customer purchase intension prediction."
},
{
"code": null,
"e": 1938,
"s": 1714,
"text": "We need to make a lot of decisions on model selections and feature selections in this project. The decisions are made based on these metrics: Accuracy, Recall, Precision, and F1. Let me explain them using our business case."
},
{
"code": null,
"e": 2216,
"s": 1938,
"text": "In our dataset, there is a customer behind each online visit session. If we predict βRevenueβ is 1, it means this customer who initiated the session is more likely to make a purchase. However, our prediction is not always correct. The table below shows the different scenarios."
},
{
"code": null,
"e": 2422,
"s": 2216,
"text": "Assumptions: 1. $100 revenue for each order placed and $5 cost for each coupon sent. 2. A likely customer with a coupon will make a purchase and an unlikely customer with a coupon will NOT make a purchase."
},
{
"code": null,
"e": 2628,
"s": 2422,
"text": "As seen from the above table, we want more βtrue positive(TP)β to happen and to avoid βfalse negative(FN)β as much as possible. How do we apply this to a machine learning model? The classification metrics:"
},
{
"code": null,
"e": 2653,
"s": 2628,
"text": "Recall score: TP/(TP+FN)"
},
{
"code": null,
"e": 2995,
"s": 2653,
"text": "Of all the likely customers, how many of them the model can identify correctly. A high recall requires both high TP and low FN. It can identify a large portion of likely customers to reduce lost sales. Meanwhile more unlikely customers(FP) will also receive the coupons. This is fine when the lost sales cost is greater than the coupon cost."
},
{
"code": null,
"e": 3024,
"s": 2995,
"text": "Precision score: TP/(TP+ FP)"
},
{
"code": null,
"e": 3386,
"s": 3024,
"text": "Of all the βlikelyβ customers our model predicted, how many of them are actually correct, not false positive. A high precision score requires both high TP and low FP. It can make sure a larger portion of predicted likely customers are correct. More coupons are used, fewer wasted coupons. However more other likely customers will be ignored to cause lost sales."
},
{
"code": null,
"e": 3434,
"s": 3386,
"text": "F1 score: 2*recall*precisoin/(recall+precision)"
},
{
"code": null,
"e": 3512,
"s": 3434,
"text": "A value that balances recall and precision scores with consideration of both."
},
{
"code": null,
"e": 3551,
"s": 3512,
"text": "Accuracy score: (TP+TN)/(TP +TN+FN+FP)"
},
{
"code": null,
"e": 3695,
"s": 3551,
"text": "The percentage of the predicted results are correct. This metric only works when the classes are balanced. We donβt use it for unbalanced data."
},
{
"code": null,
"e": 3894,
"s": 3695,
"text": "As a result of the above, in this project, we will use the Recall score as our main metric when making decisions on model selections. When recall scores are similar, we will also consider F1 scores."
},
{
"code": null,
"e": 3923,
"s": 3894,
"text": "First, letβs clean the data:"
},
{
"code": null,
"e": 4189,
"s": 3923,
"text": "Usually only a small portion of the visits ended up into transactions, we suspect the data is imbalanced. After testing it below, we found the transaction conversion rate is only 18.3%. This means later we need to make a balance adjustment on the data for modeling."
},
{
"code": null,
"e": 4266,
"s": 4189,
"text": "The categorical data need to be converted into numeric for further analysis."
},
{
"code": null,
"e": 4541,
"s": 4266,
"text": "The data set is highly imbalanced. All the models tend to fit towards the majority class, so in order to improve the model performance, we need to balance the data first. I used the SMOTE oversizing technique, the result is that both classes have the same number of samples."
},
{
"code": null,
"e": 5055,
"s": 4541,
"text": "Now we can use Accuracy as a metric for a balanced dataset. I chose 7 classifiers as model candidates. I split the dataset into 80% train and 20% test. Then the train set is fitted into each model without tuning. Here we get a baseline accuracy ranking. I will choose the top 4 models as my baseline models: Random forest, EXTRA trees, ADAboost and logistic regression. We now prioritize on accuracy to recall, because we need unbiased models. Then later select high recall models within the high accuracy models."
},
{
"code": null,
"e": 5182,
"s": 5055,
"text": "Feature engineering and model tuning will be performed later on the 4 models. For code details please refer to my Github page."
},
{
"code": null,
"e": 5532,
"s": 5182,
"text": "My goal is to reduce the number of features and increase the metric values at the same time. With fewer features, the cost of data collection is reduced, as well as the computing time and cost. Three feature selection techniques were used to give a comprehensive decision: information values, sklearnβs SelectFromModel(), and the correlation values."
},
{
"code": null,
"e": 5837,
"s": 5532,
"text": "Which features can give us more information in prediction than other features? Letβs try sklearnβs SelectFromModel() to filter the importance weights of the features. This gives us three features as important features. We will keep them and continue exploring the other two methods for feature selection."
},
{
"code": null,
"e": 5890,
"s": 5837,
"text": "'ProductRelated_Duration', 'ExitRates', 'PageValues'"
},
{
"code": null,
"e": 6332,
"s": 5890,
"text": "The heatmap on the left shows the correlations among all the features. The darker the color, the higher the correlation. What we want to see is that the features are very correlated with the label βRevenueβ but not correlated with one another. But some features are highly correlated with another feature. This means only one of the correlated features can be kept. How do we know which one to keep? The information values (IV) will help us."
},
{
"code": null,
"e": 6456,
"s": 6332,
"text": "Now, we will use information values to rank all the features and find the ones that have medium to strong prediction power."
},
{
"code": null,
"e": 6529,
"s": 6456,
"text": "The function below will calculate the information value of each feature."
},
{
"code": null,
"e": 6593,
"s": 6529,
"text": "With all the calculations above, now we have the results below:"
},
{
"code": null,
"e": 6657,
"s": 6593,
"text": "The tables above show the 8 features kept for further modeling:"
},
{
"code": null,
"e": 6777,
"s": 6657,
"text": "Administrative_Duration, Informational, ProductRelated_Duration, ExitRates, Special day, Month, VisitorType, PageValues"
},
{
"code": null,
"e": 6807,
"s": 6777,
"text": "How did I make the decisions?"
},
{
"code": null,
"e": 6856,
"s": 6807,
"text": "The flowchart on the left is my thought process."
},
{
"code": null,
"e": 7175,
"s": 6856,
"text": "A feature with IV below 0.1 is removed.For the rest, if a feature is selected by the sklearn filter, we keep it.Then the rest is removed if it is highly correlated with the kept features.Then last portion if a feature is not correlated with another, we keep it. If it is, the one with higher information value is kept."
},
{
"code": null,
"e": 7215,
"s": 7175,
"text": "A feature with IV below 0.1 is removed."
},
{
"code": null,
"e": 7289,
"s": 7215,
"text": "For the rest, if a feature is selected by the sklearn filter, we keep it."
},
{
"code": null,
"e": 7365,
"s": 7289,
"text": "Then the rest is removed if it is highly correlated with the kept features."
},
{
"code": null,
"e": 7497,
"s": 7365,
"text": "Then last portion if a feature is not correlated with another, we keep it. If it is, the one with higher information value is kept."
},
{
"code": null,
"e": 7572,
"s": 7497,
"text": "Now we have fewer features, letβs see if they can help improve our models:"
},
{
"code": null,
"e": 7703,
"s": 7572,
"text": "We have great results! All the recall values are improved greatly after feature selection and the other metrics look good as well."
},
{
"code": null,
"e": 8006,
"s": 7703,
"text": "We have 7 categorical features. Even though they are converted to numeric values earlier, all the values of a categorical feature are in one column. What if we make each value its own feature? Letβs dummy the categorical feature variable! After processing the data, now we have 29 features and 1 label."
},
{
"code": null,
"e": 8224,
"s": 8006,
"text": "Why we donβt use the dummy variables in the 1st round feature selection? Because it is not effective to dummy the low information value features and make too many new features. That will lower the modelsβ performance."
},
{
"code": null,
"e": 8371,
"s": 8224,
"text": "Now we will use the same techniques in the 1st round feature selection process to select the new features. For details, please refer to my Github."
},
{
"code": null,
"e": 8523,
"s": 8371,
"text": "Administrative_Duration, Informational_bins_page_1_plus, ProductRelated_Duration, ExitRates, Month 11, VisitorType_bins_return, PageValues_bins_above_0"
},
{
"code": null,
"e": 8743,
"s": 8523,
"text": "Now the heat map above shows the 7 features + 1 label after a new round of feature selection. Note that no two features are correlated (this is great), and the Pagevalues_bins_above_0 feature is very relevant to Revenue"
},
{
"code": null,
"e": 8810,
"s": 8743,
"text": "Now letβs see the performance of these new features on the models."
},
{
"code": null,
"e": 9076,
"s": 8810,
"text": "We can see that EXTRA trees and AdaBoost have improved recall scores while the other two models donβt perform as well as before. EXTRA trees model has a lower recall than AdaBoost but a higher F1. So we will keep both models for now for the next step, model tuning."
},
{
"code": null,
"e": 9587,
"s": 9076,
"text": "Now we have narrowed down to two models: EXTRA trees and AdaBoost. By tuning their hyper-parameters, we could potentially increase the recall score even further. For model tuning techniques, I will use RandomizedSearchCV first. It will randomly run the model through a list of hyper-parameters we defined. Once we have the best performance through RandomizedSearch, we will use GridSearch to further improve the model by running through a narrower list of hyper-parameters. For details, please check my Github."
},
{
"code": null,
"e": 9876,
"s": 9587,
"text": "The picture above shows that both models were improved by using a randomized search, then grid search. The final recall scores only have 0.002 difference. We then look at F1 and accuracy scores. EXTRA trees model has much higher scores in both metrics. As a result, it is our final model."
},
{
"code": null,
"e": 10196,
"s": 9876,
"text": "In this project, we built a binary classification machine learning model to predict the purchase intension of customers on an online shopping site. After several rounds of feature selections and model selections, we determine the best model for our data is EXTRA trees and the features to fit in the model are as below."
},
{
"code": null,
"e": 10546,
"s": 10196,
"text": "EXTRA trees model we built in this project can capture 83% of the likely customers. This means if the marketing team send the coupons to all the likely customers predicted by this model, the coupons will cover 83% of all the actual likely customer in the market. This model can definitely help the marketing team make effective marketing strategies!"
}
] |
Create many JavaScript objects as the same type? | It is very easy to create a single object than to create multiple objects of the same type. To breach this hurdle, javascript has provided object constructor function. Using this function, initially, we have to create the type of the object and later on, we need to declare the properties of the object.
In the following example, initially, we have declared the type of object that contains the "name", "property", "age", and "designation". Later on, using that type we have created two objects and the corresponding properties were displayed in the output based on our requirement.
Live Demo
<html>
<body>
<p id = "prop"></p>
<script>
function Business(name, property, age, designation) {
this.Name = name;
this.prop = property;
this.age = age;
this.designation = designation;
}
var person1 = new Business("Trump", "$28.8b", "73", "President");
var person2 = new Business("Jackma", "$35.6b", "54", "entrepeneur");
document.write(
"My inpiration is " + person1.Name + " and i want to be an " + person2.designation + ".");
</script>
</body>
</html>
My inpiration is Trump and i want to be an entrepeneur. | [
{
"code": null,
"e": 1366,
"s": 1062,
"text": "It is very easy to create a single object than to create multiple objects of the same type. To breach this hurdle, javascript has provided object constructor function. Using this function, initially, we have to create the type of the object and later on, we need to declare the properties of the object."
},
{
"code": null,
"e": 1645,
"s": 1366,
"text": "In the following example, initially, we have declared the type of object that contains the \"name\", \"property\", \"age\", and \"designation\". Later on, using that type we have created two objects and the corresponding properties were displayed in the output based on our requirement."
},
{
"code": null,
"e": 1655,
"s": 1645,
"text": "Live Demo"
},
{
"code": null,
"e": 2155,
"s": 1655,
"text": "<html>\n<body>\n<p id = \"prop\"></p>\n<script>\n function Business(name, property, age, designation) {\n this.Name = name;\n this.prop = property;\n this.age = age;\n this.designation = designation;\n }\n var person1 = new Business(\"Trump\", \"$28.8b\", \"73\", \"President\");\n var person2 = new Business(\"Jackma\", \"$35.6b\", \"54\", \"entrepeneur\");\n document.write(\n \"My inpiration is \" + person1.Name + \" and i want to be an \" + person2.designation + \".\");\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2211,
"s": 2155,
"text": "My inpiration is Trump and i want to be an entrepeneur."
}
] |
Sorting string in reverse order in JavaScript | We are required to write a JavaScript function that takes in a lowercase string and sorts it in the reverse order i.e., b should come before a, c before b and so on.
For example: If the input string is β
const str = "hello";
Then the output should be β
const output = "ollhe";
Following is the code β
const string = 'hello';
const sorter = (a, b) => {
const legend = [-1, 0, 1];
return legend[+(a < b)];
}
const reverseSort = str => {
const strArr = str.split("");
return strArr
.sort(sorter)
.join("");
};
console.log(reverseSort(string));
Following is the output in the console β
ollhe | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a lowercase string and sorts it in the reverse order i.e., b should come before a, c before b and so on."
},
{
"code": null,
"e": 1266,
"s": 1228,
"text": "For example: If the input string is β"
},
{
"code": null,
"e": 1287,
"s": 1266,
"text": "const str = \"hello\";"
},
{
"code": null,
"e": 1315,
"s": 1287,
"text": "Then the output should be β"
},
{
"code": null,
"e": 1339,
"s": 1315,
"text": "const output = \"ollhe\";"
},
{
"code": null,
"e": 1363,
"s": 1339,
"text": "Following is the code β"
},
{
"code": null,
"e": 1621,
"s": 1363,
"text": "const string = 'hello';\nconst sorter = (a, b) => {\n const legend = [-1, 0, 1];\n return legend[+(a < b)];\n}\nconst reverseSort = str => {\n const strArr = str.split(\"\");\n return strArr\n .sort(sorter)\n .join(\"\");\n};\nconsole.log(reverseSort(string));"
},
{
"code": null,
"e": 1662,
"s": 1621,
"text": "Following is the output in the console β"
},
{
"code": null,
"e": 1668,
"s": 1662,
"text": "ollhe"
}
] |
How to get selected text from a drop-down list using jQuery? - GeeksforGeeks | 03 Aug, 2021
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery.
By using val() method :The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
Syntax :
$(selector).val(parameter)
Parameter : parameter is optional.
Example :
<html><head> <title>jQuery Selector</title><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#submit").click(function() { alert($("#myselection").val()); }); }); </script> <style> div { width: 50%; height: 200px; padding: 10px; border: 2px solid green; } </style></head> <body> <div> <p>The selected value:</p> <select id="myselection"> <option value="1">First</option> <option value="2">Second</option> </select> <br> <br> <button id="submit">Submit</button> </div></body></html>
Output :Before click on the button.After click on the button.
By using option:selected :The option:selected method is a way in jQuery which is used to return the selected element from a list of the element.
Syntax :
$("#selector option:selected");
Parameter : No parameter required.
Example :
<html><head> <title>jQuery Selector</title><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#submit").click(function() { var value = $("#myselection option:selected"); alert(value.text()); }); }); </script> <style> div { width: 50%; height: 200px; padding: 10px; border: 2px solid green; } </style></head> <body> <div> <p>The selected value:</p> <select id="myselection"> <option value="1">First</option> <option value="2">Second</option> </select> <br> <br> <button id="submit">Submit</button> </div></body></html>
Output :Before click on the button.After click on the button.
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with itβs philosophy of βWrite less, do moreβ.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
jQuery | children() with Examples
How to prevent Body from scrolling when a modal is opened using jQuery ?
How to change the background color of the active nav-item?
jQuery | ajax() Method
How to add `style=display:βblockβ` to an element using jQuery?
Top 10 Front End Developer Skills That You Need 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": 24864,
"s": 24836,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25014,
"s": 24864,
"text": "We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery."
},
{
"code": null,
"e": 25167,
"s": 25014,
"text": "By using val() method :The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements."
},
{
"code": null,
"e": 25176,
"s": 25167,
"text": "Syntax :"
},
{
"code": null,
"e": 25204,
"s": 25176,
"text": "$(selector).val(parameter)\n"
},
{
"code": null,
"e": 25239,
"s": 25204,
"text": "Parameter : parameter is optional."
},
{
"code": null,
"e": 25249,
"s": 25239,
"text": "Example :"
},
{
"code": "<html><head> <title>jQuery Selector</title><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"#submit\").click(function() { alert($(\"#myselection\").val()); }); }); </script> <style> div { width: 50%; height: 200px; padding: 10px; border: 2px solid green; } </style></head> <body> <div> <p>The selected value:</p> <select id=\"myselection\"> <option value=\"1\">First</option> <option value=\"2\">Second</option> </select> <br> <br> <button id=\"submit\">Submit</button> </div></body></html>",
"e": 26011,
"s": 25249,
"text": null
},
{
"code": null,
"e": 26073,
"s": 26011,
"text": "Output :Before click on the button.After click on the button."
},
{
"code": null,
"e": 26218,
"s": 26073,
"text": "By using option:selected :The option:selected method is a way in jQuery which is used to return the selected element from a list of the element."
},
{
"code": null,
"e": 26227,
"s": 26218,
"text": "Syntax :"
},
{
"code": null,
"e": 26261,
"s": 26227,
"text": " $(\"#selector option:selected\");\n"
},
{
"code": null,
"e": 26296,
"s": 26261,
"text": "Parameter : No parameter required."
},
{
"code": null,
"e": 26306,
"s": 26296,
"text": "Example :"
},
{
"code": "<html><head> <title>jQuery Selector</title><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"#submit\").click(function() { var value = $(\"#myselection option:selected\"); alert(value.text()); }); }); </script> <style> div { width: 50%; height: 200px; padding: 10px; border: 2px solid green; } </style></head> <body> <div> <p>The selected value:</p> <select id=\"myselection\"> <option value=\"1\">First</option> <option value=\"2\">Second</option> </select> <br> <br> <button id=\"submit\">Submit</button> </div></body></html>",
"e": 27121,
"s": 26306,
"text": null
},
{
"code": null,
"e": 27183,
"s": 27121,
"text": "Output :Before click on the button.After click on the button."
},
{
"code": null,
"e": 27451,
"s": 27183,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with itβs philosophy of βWrite less, do moreβ.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 27463,
"s": 27451,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 27470,
"s": 27463,
"text": "Picked"
},
{
"code": null,
"e": 27477,
"s": 27470,
"text": "JQuery"
},
{
"code": null,
"e": 27494,
"s": 27477,
"text": "Web Technologies"
},
{
"code": null,
"e": 27592,
"s": 27494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27601,
"s": 27592,
"text": "Comments"
},
{
"code": null,
"e": 27614,
"s": 27601,
"text": "Old Comments"
},
{
"code": null,
"e": 27648,
"s": 27614,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 27721,
"s": 27648,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 27780,
"s": 27721,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 27803,
"s": 27780,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 27866,
"s": 27803,
"text": "How to add `style=display:βblockβ` to an element using jQuery?"
},
{
"code": null,
"e": 27922,
"s": 27866,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27955,
"s": 27922,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28017,
"s": 27955,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28060,
"s": 28017,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Artefact Correction with ICA. Illustrated with an example from the... | by Thomas A Dorfer | Towards Data Science | Time-series data is often contaminated with unwanted signal artefacts that have the potential to considerably distort any further analysis. Independent component analysis, or ICA, is a powerful method to get around this very problem. Here, I will give a brief introduction to ICA followed by a demonstration of how to implement it to remove signal artefacts. Throughout this article, I will be using time-series data obtained through electroencephalography (EEG)β a technique from the neurosciences that measures electrical activity of the cerebral cortex of the brain.
Note: I only present crucial code snippets here. The full code, written in Python 3, can be found on my GitHub in form of a Jupyter Notebook.
ICA is a signal processing method capable of separating a multivariate signal into its additive subcomponents, or sources. It is based on the assumptions that the sources are statistically independent and that the values in each source underlie non-Gaussian distributions [1]. A classic example of source separation is the cocktail party problem, where multiple people in a room are talking simultaneously and their voices are recorded by microphones positioned at different spatial locations. ICA can then be applied to separate the mixed source data into various information sources representing maximally temporally independent signals. In other words, the individual voices of each person in the room can be restored with a fairly high degree of accuracy, as illustrated below.
In the context of EEG, ICA can identify components that include artefacts such as eye blinks or eye movements. These components can then be removed before the data is transformed back from source space (individual sources as computed by ICA) to sensor space (original EEG data). An illustration of the placement of these sensors, or electrodes, is shown below.
Eye blinks and eye movements can usually be detected fairly easily by inspecting the time-series data. They are picked up particularly by frontal channels sitting either right above or in close proximity to the eyes. Examples of each are shown below.
The scientific community has been using various ICA algorithms, such as Infomax, JADE, and FastICA [3, 4], with the latter being arguably the most popular one. Additionally, scikit-learn provides the FastICA algorithm in its decomposition module, which further prompted me to use it for this demonstration.
The data used here was acquired from an approximately 8min resting-state EEG session. Before we start, letβs take a look at a slice of the EEG time-series.
The sampling rate here was 500 Hz, so the above figure shows 4 seconds of data. An eye blink can be seen between samples 1250 and 1500. Eye blinks are typically most pronounced in channels Fp1 and Fp2, so letβs plot them individually.
Looking at Fp1, a slight box shape can be detected just before the start of the eye blink. This represents horizontal eye movement and should ideally be removed as well. Now, letβs run scikit-learnβs FastICA and plot all 63 ICA components to see if we can identify the sources of any artefacts.
## Computing ICA componentsfrom sklearn.decomposition import FastICAica = FastICA(n_components=63, random_state=0, tol=0.05)comps = ica.fit_transform(eeg)# eeg --> raw data, shape: (224930, 63)# comps --> ICA components, shape: (224930, 63)
For the sake of simplicity, I have only plotted the components over 400 samples, from 1200 to 1600, hoping to spot that eye blink visible in Fp1 and Fp2. Upon close inspection, it appears as though component 29 contains horizontal eye movements and component 42 contains eye blink artefacts. To confirm this, I had a look at longer slices of data (not shown here) and found that the artefacts in these components in fact co-occur with the eye blink and eye movement artefacts in various frontal channels.
Note: ICA separates signals into their subcomponents based on statistical measures, meaning that there is no specific component order. If you donβt specify random_state, you will find that the components containing the artefacts can vary.
Letβs now remove components 29 and 42 and transform our source data back into the original sensor space, using the inverse transform.
## Set artefact components to zero before inverse transformcomps[:,[29,42]] = 0 restored = ica.inverse_transform(comps)
It worked! The restored signals (Fp1_post and Fp2_post, darker colors) no longer contain the eye blink and eye movement artefacts present in the raw signals (Fp1_pre and Fp2_pre, faint colors).
Cautionary note: ICA has been shown to work really well with stereotyped artefacts such as eye blinks and eye movements. However, non-stereotyped artefacts that produce noise in various spatial locations, i.e. when subjects are scratching their head, defy the workings of ICA and should be treated with caution.
[1] HyvaΜrinen, A., 2016. Independent component analysis: recent advances. Philos Trans A Math Phys Eng Sci. 371(1984):20110534. [PubMed]
[2] Tharwat, A., 2018. Independent component analysis: An introduction. Appl. Comput. Inform. https://doi.org/10.1016/j.aci.2018.08.006 [PDF]
[3] HyvaΜrinen, A., 1999. Fast and robust fixed-point algorithms for independent component analysis. IEEE Transactions on Neural Networks. 10(3): 626β634. [PDF]
[4] HyvaΜrinen, A.; Oja, E., 2000. Independent component analysis: Algorithms and applications. Neural Networks. 13(4β5): 411β430. [PDF] | [
{
"code": null,
"e": 741,
"s": 171,
"text": "Time-series data is often contaminated with unwanted signal artefacts that have the potential to considerably distort any further analysis. Independent component analysis, or ICA, is a powerful method to get around this very problem. Here, I will give a brief introduction to ICA followed by a demonstration of how to implement it to remove signal artefacts. Throughout this article, I will be using time-series data obtained through electroencephalography (EEG)β a technique from the neurosciences that measures electrical activity of the cerebral cortex of the brain."
},
{
"code": null,
"e": 883,
"s": 741,
"text": "Note: I only present crucial code snippets here. The full code, written in Python 3, can be found on my GitHub in form of a Jupyter Notebook."
},
{
"code": null,
"e": 1665,
"s": 883,
"text": "ICA is a signal processing method capable of separating a multivariate signal into its additive subcomponents, or sources. It is based on the assumptions that the sources are statistically independent and that the values in each source underlie non-Gaussian distributions [1]. A classic example of source separation is the cocktail party problem, where multiple people in a room are talking simultaneously and their voices are recorded by microphones positioned at different spatial locations. ICA can then be applied to separate the mixed source data into various information sources representing maximally temporally independent signals. In other words, the individual voices of each person in the room can be restored with a fairly high degree of accuracy, as illustrated below."
},
{
"code": null,
"e": 2026,
"s": 1665,
"text": "In the context of EEG, ICA can identify components that include artefacts such as eye blinks or eye movements. These components can then be removed before the data is transformed back from source space (individual sources as computed by ICA) to sensor space (original EEG data). An illustration of the placement of these sensors, or electrodes, is shown below."
},
{
"code": null,
"e": 2277,
"s": 2026,
"text": "Eye blinks and eye movements can usually be detected fairly easily by inspecting the time-series data. They are picked up particularly by frontal channels sitting either right above or in close proximity to the eyes. Examples of each are shown below."
},
{
"code": null,
"e": 2584,
"s": 2277,
"text": "The scientific community has been using various ICA algorithms, such as Infomax, JADE, and FastICA [3, 4], with the latter being arguably the most popular one. Additionally, scikit-learn provides the FastICA algorithm in its decomposition module, which further prompted me to use it for this demonstration."
},
{
"code": null,
"e": 2740,
"s": 2584,
"text": "The data used here was acquired from an approximately 8min resting-state EEG session. Before we start, letβs take a look at a slice of the EEG time-series."
},
{
"code": null,
"e": 2975,
"s": 2740,
"text": "The sampling rate here was 500 Hz, so the above figure shows 4 seconds of data. An eye blink can be seen between samples 1250 and 1500. Eye blinks are typically most pronounced in channels Fp1 and Fp2, so letβs plot them individually."
},
{
"code": null,
"e": 3270,
"s": 2975,
"text": "Looking at Fp1, a slight box shape can be detected just before the start of the eye blink. This represents horizontal eye movement and should ideally be removed as well. Now, letβs run scikit-learnβs FastICA and plot all 63 ICA components to see if we can identify the sources of any artefacts."
},
{
"code": null,
"e": 3511,
"s": 3270,
"text": "## Computing ICA componentsfrom sklearn.decomposition import FastICAica = FastICA(n_components=63, random_state=0, tol=0.05)comps = ica.fit_transform(eeg)# eeg --> raw data, shape: (224930, 63)# comps --> ICA components, shape: (224930, 63)"
},
{
"code": null,
"e": 4016,
"s": 3511,
"text": "For the sake of simplicity, I have only plotted the components over 400 samples, from 1200 to 1600, hoping to spot that eye blink visible in Fp1 and Fp2. Upon close inspection, it appears as though component 29 contains horizontal eye movements and component 42 contains eye blink artefacts. To confirm this, I had a look at longer slices of data (not shown here) and found that the artefacts in these components in fact co-occur with the eye blink and eye movement artefacts in various frontal channels."
},
{
"code": null,
"e": 4255,
"s": 4016,
"text": "Note: ICA separates signals into their subcomponents based on statistical measures, meaning that there is no specific component order. If you donβt specify random_state, you will find that the components containing the artefacts can vary."
},
{
"code": null,
"e": 4389,
"s": 4255,
"text": "Letβs now remove components 29 and 42 and transform our source data back into the original sensor space, using the inverse transform."
},
{
"code": null,
"e": 4509,
"s": 4389,
"text": "## Set artefact components to zero before inverse transformcomps[:,[29,42]] = 0 restored = ica.inverse_transform(comps)"
},
{
"code": null,
"e": 4703,
"s": 4509,
"text": "It worked! The restored signals (Fp1_post and Fp2_post, darker colors) no longer contain the eye blink and eye movement artefacts present in the raw signals (Fp1_pre and Fp2_pre, faint colors)."
},
{
"code": null,
"e": 5015,
"s": 4703,
"text": "Cautionary note: ICA has been shown to work really well with stereotyped artefacts such as eye blinks and eye movements. However, non-stereotyped artefacts that produce noise in various spatial locations, i.e. when subjects are scratching their head, defy the workings of ICA and should be treated with caution."
},
{
"code": null,
"e": 5153,
"s": 5015,
"text": "[1] HyvaΜrinen, A., 2016. Independent component analysis: recent advances. Philos Trans A Math Phys Eng Sci. 371(1984):20110534. [PubMed]"
},
{
"code": null,
"e": 5295,
"s": 5153,
"text": "[2] Tharwat, A., 2018. Independent component analysis: An introduction. Appl. Comput. Inform. https://doi.org/10.1016/j.aci.2018.08.006 [PDF]"
},
{
"code": null,
"e": 5456,
"s": 5295,
"text": "[3] HyvaΜrinen, A., 1999. Fast and robust fixed-point algorithms for independent component analysis. IEEE Transactions on Neural Networks. 10(3): 626β634. [PDF]"
}
] |
Apache Commons IO - Quick Guide | Apache Commons IO library provides various utility classes for common operations for File IO covering wide range of use cases. It helps avoid writing boilerplate code. Apache Commons IO library provides classes for following categories:
Utility classes β These classes under org.apache.commons.io package provides file and string comparison. Following are some of the examples.
IOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.
FilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way.
FileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
IOCase β Provides method for string manipulation and comparison.
FileSystemUtils β Provides method to get the free space on a disk drive.
LineIterator β Provides a flexible way to work with a line-based file.
Utility classes β These classes under org.apache.commons.io package provides file and string comparison. Following are some of the examples.
IOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.
IOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.
FilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way.
FilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way.
FileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
FileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
IOCase β Provides method for string manipulation and comparison.
IOCase β Provides method for string manipulation and comparison.
FileSystemUtils β Provides method to get the free space on a disk drive.
FileSystemUtils β Provides method to get the free space on a disk drive.
LineIterator β Provides a flexible way to work with a line-based file.
LineIterator β Provides a flexible way to work with a line-based file.
Filter classes β Filter classes under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias instead of string based tedious comparisons. Following are some of the examples.
NameFileFilter β Filters file-names for a name.
WildcardFileFilter β Filters files using the supplied wildcards.
SuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type.
PrefixFileFilter β Filters files based on prefix.
OrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false.
AndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.
Filter classes β Filter classes under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias instead of string based tedious comparisons. Following are some of the examples.
NameFileFilter β Filters file-names for a name.
NameFileFilter β Filters file-names for a name.
WildcardFileFilter β Filters files using the supplied wildcards.
WildcardFileFilter β Filters files using the supplied wildcards.
SuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type.
SuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type.
PrefixFileFilter β Filters files based on prefix.
PrefixFileFilter β Filters files based on prefix.
OrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false.
OrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false.
AndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.
AndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.
File Monitor classes β File monitor classes under org.apache.commons.io.monitor package provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples.
File Monitor classes β File monitor classes under org.apache.commons.io.monitor package provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples.
FileEntry β Provides the state of a file or directory, File attributes at a point in time.
FileEntry β Provides the state of a file or directory, File attributes at a point in time.
FileAlterationObserver β Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events.
FileAlterationObserver β Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events.
FileAlterationMonitor β Represent a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.
FileAlterationMonitor β Represent a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.
Comparator classes β File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily.
NameFileComparator β Compare the names of two files.
SizeFileComparator β Compare the size of two files.
LastModifiedFileComparator β Compare the last modified dates of two files.
Comparator classes β File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily.
NameFileComparator β Compare the names of two files.
NameFileComparator β Compare the names of two files.
SizeFileComparator β Compare the size of two files.
SizeFileComparator β Compare the size of two files.
LastModifiedFileComparator β Compare the last modified dates of two files.
LastModifiedFileComparator β Compare the last modified dates of two files.
Stream classes β There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package to do useful tasks on streams. Following are some of the examples.
NullOutputStream β absorbs all data sent with any error.
TeeOutputStream β sends output to two streams.
ByteArrayOutputStream β faster version of JDK class.
CountingOutputStream β Counts the number of bytes passed through the stream.
CountingOutputStream β Counts the number of bytes passed through the stream.
ProxyOutputStream β Changes the calls to proxied stream.
LockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling.
Stream classes β There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package to do useful tasks on streams. Following are some of the examples.
NullOutputStream β absorbs all data sent with any error.
NullOutputStream β absorbs all data sent with any error.
TeeOutputStream β sends output to two streams.
TeeOutputStream β sends output to two streams.
ByteArrayOutputStream β faster version of JDK class.
ByteArrayOutputStream β faster version of JDK class.
CountingOutputStream β Counts the number of bytes passed through the stream.
CountingOutputStream β Counts the number of bytes passed through the stream.
CountingOutputStream β Counts the number of bytes passed through the stream.
CountingOutputStream β Counts the number of bytes passed through the stream.
ProxyOutputStream β Changes the calls to proxied stream.
ProxyOutputStream β Changes the calls to proxied stream.
LockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling.
LockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling.
In this chapter, we will learn about the local environment setup of Apache Commons IO and how to set up the path of Commons IO for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons IO archive.
First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.
If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.
Open command console and type β
\>java -version
java version "11.0.11" 2021-04-20 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)
Open command terminal and type β
$java -version
java version "11.0.11" 2021-04-20 LTS
Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)
Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)
We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.
We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.
In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.
In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.
Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,
Windows
Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11
Linux
Export JAVA_HOME = /usr/local/java-current
Append the full path of Java compiler location to the System Path.
Windows
Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH.
Linux
Export PATH = $PATH:$JAVA_HOME/bin/
Execute the command java -version from the command prompt as explained above.
To write your Java programs, you need a text editor. There are many sophisticated integrated development environment (IDEs) available in the market. But for now, you can consider one of the following β
Notepad β On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Notepad β On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans β It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Netbeans β It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Eclipse β It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Eclipse β It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Download the latest version of Apache Common IO jar file from commons-io-2.11.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-io-2.11.0-bin.zip and copied it into C:\>Apache folder.
Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows.
Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows.
Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.
Following is the declaration for org.apache.commons.io.IOUtils Class -
public class IOUtils
extends Object
Provides static utility methods for input/output operations.
Provides static utility methods for input/output operations.
toXXX() - reads data from a stream.
toXXX() - reads data from a stream.
write() - write data to a stream.
write() - write data to a stream.
copy() - copy all data to a stream to another stream.
copy() - copy all data to a stream to another stream.
contentEquals - compare the contents of two streams.
contentEquals - compare the contents of two streams.
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
public class IOTester {
public static void main(String[] args) {
try{
//Using BufferedReader
readUsingTraditionalWay();
//Using IOUtils
readUsingIOUtils();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
//reading a file using buffered reader line by line
public static void readUsingTraditionalWay() throws IOException{
try (BufferedReader bufferReader
= new BufferedReader(
new InputStreamReader(
new FileInputStream("input.txt") ) )) {
String line;
while ( ( line = bufferReader.readLine() ) != null ) {
System.out.println( line );
}
}
}
//reading a file using IOUtils in one go
public static void readUsingIOUtils() throws IOException {
try(InputStream in = new FileInputStream("input.txt")){
System.out.println( IOUtils.toString( in , "UTF-8") );
}
}
}
It will print the following result.
Welcome to TutorialsPoint. Simply Easy Learning.
Welcome to TutorialsPoint. Simply Easy Learning.
Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
Following is the declaration for org.apache.commons.io.FileUtils Class -
public class FileUtils
extends Object
Methods to write to a file.
Methods to write to a file.
Methods to read from a file.
Methods to read from a file.
Methods to make a directory including parent directories.
Methods to make a directory including parent directories.
Methods to copy files and directories.
Methods to copy files and directories.
Methods to delete files and directories.
Methods to delete files and directories.
Methods to convert to and from a URL.
Methods to convert to and from a URL.
Methods to list files and directories by filter and extension.
Methods to list files and directories by filter and extension.
Methods to compare file content.
Methods to compare file content.
Methods to file last changed date.
Methods to file last changed date.
Methods to calculating a checksum.
Methods to calculating a checksum.
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class IOTester {
public static void main(String[] args) {
try{
//Using FileUtils
usingFileUtils();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingFileUtils() throws IOException {
//get the file object
File file = FileUtils.getFile("input.txt");
//get the temp directory
File tmpDir = FileUtils.getTempDirectory();
System.out.println(tmpDir.getName());
//copy file to temp directory
FileUtils.copyFileToDirectory(file, tmpDir);
//create a new file
File newTempFile = FileUtils.getFile(tmpDir, file.getName());
//get the content
String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
//print the content
System.out.println(data);
}
}
It will print the following result.
Temp
Welcome to TutorialsPoint. Simply Easy Learning.
Provides method to work with file names without using File Object. It works on different operating systems in similar way. This class solves problems when moving from a Windows based development machine to a Unix based production machine.
Following is the declaration for org.apache.commons.io.FilenameUtils Class -
public class FilenameUtils
extends Object
This class defines six components within a filename. Consider an example location as C:\dev\project\file.txt. Then the components are
Prefix - C:\
Prefix - C:\
Relative Path - dev\project\
Relative Path - dev\project\
Absolute path - C:\dev\project\
Absolute path - C:\dev\project\
Name - file.txt
Name - file.txt
Base name - file
Base name - file
Extension - txt
Extension - txt
To identify a directory, add a separator to file name.
IOTester.java
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class IOTester {
public static void main(String[] args) {
try{
//Using FilenameUtils
usingFilenameUtils();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingFilenameUtils() throws IOException {
String path = "C:\\dev\\project\\file.txt";
System.out.println("Full Path: " +FilenameUtils.getFullPath(path));
System.out.println("Relative Path: " +FilenameUtils.getPath(path));
System.out.println("Prefix: " +FilenameUtils.getPrefix(path));
System.out.println("Extension: " + FilenameUtils.getExtension(path));
System.out.println("Base: " + FilenameUtils.getBaseName(path));
System.out.println("Name: " + FilenameUtils.getName(path));
String filename = "C:/commons/io/../lang/project.xml";
System.out.println("Normalized Path: " + FilenameUtils.normalize(filename));
}
}
It will print the following result.
Full Path: C:\dev\project\
Relative Path: dev\project\
Prefix: C:\
Extension: txt
Base: file
Name: file.txt
Normalized Path: C:\commons\lang\project.xml
Provides method to get the free space on a disk drive.
Following is the declaration for org.apache.commons.io.FileSystemUtils Class -
public class FileSystemUtils
extends Object
IOTester.java
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
public class IOTester {
public static void main(String[] args) {
try{
System.out.println("Free Space " + FileSystemUtils.freeSpaceKb("C:/") + " Bytes");
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
It will print the following result.
Free Space 61355640 kb
Enumeration of IO case sensitivity. Different Operating systems have different rules for case-sensitivity for file names. For example Windows is case-insensitive for file naming while Unix is case-sensitive. IOCase captures that difference, provides an enumeration to control how filename comparisons should be performed. It also provides methods to use the enumeration to perform comparisons.
Following is the declaration for org.apache.commons.io.IOCase Enum -
public enum IOCase
extends Enum<IOCase>
implements Serializable
IOTester.java
import java.io.IOException;
import org.apache.commons.io.IOCase;
public class IOTester {
public static void main(String[] args) {
try{
usingIOCase();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingIOCase() throws IOException {
String text = "Welcome to TutorialsPoint. Simply Easy Learning.";
String text1 = "WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.";
System.out.println("Ends with Learning (case sensitive): " +
IOCase.SENSITIVE.checkEndsWith(text1, "Learning."));
System.out.println("Ends with Learning (case insensitive): " +
IOCase.INSENSITIVE.checkEndsWith(text1, "Learning."));
System.out.println("Equality Check (case sensitive): " +
IOCase.SENSITIVE.checkEquals(text, text1));
System.out.println("Equality Check (case insensitive): " +
IOCase.INSENSITIVE.checkEquals(text, text1));
}
}
It will print the following result.
Ends with Learning (case sensitive): false
Ends with Learning (case insensitive): true
Equality Check (case sensitive): false
Equality Check (case insensitive): true
Provides a flexible way to work with a line-based file.
Following is the declaration for org.apache.commons.io.LineIterator Class -
public class LineIterator
extends Object
implements Iterator<String>, Closeable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class IOTester {
public static void main(String[] args) {
try{
usingLineIterator();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingLineIterator() throws IOException {
//get the file object
File file = FileUtils.getFile("input.txt");
try(LineIterator lineIterator = FileUtils.lineIterator(file)){
System.out.println("Contents of input.txt");
while (lineIterator.hasNext()) {
System.out.println(lineIterator.next());
}
}
}
}
It will print the following result.
Contents of input.txt
Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.
Filters file-names for a name.
Following is the declaration for org.apache.commons.io.filefilter.NameFileFilter Class -
public class NameFileFilter
extends AbstractFileFilter
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file whose name is Input.txt.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingNameFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingNameFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile with name input.txt\n");
String[] acceptedNames = {"input", "input.txt"};
String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.INSENSITIVE) );
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File with name input.txt
input.txt
Filters files using the supplied wildcards.
Following is the declaration for org.apache.commons.io.filefilter.WildcardFileFilter Class -
public class WildcardFileFilter
extends AbstractFileFilter
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file whose name ends with t.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingWildcardFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingWildcardFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile name ending with t.\n");
String[] filesNames = currentDirectory.list( new WildcardFileFilter("*t") );
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File name ending with t
.project
input.txt
Filters files based on suffix. This is used in retrieving all the files of a particular type.
Following is the declaration for org.apache.commons.io.filefilter.SuffixFileFilter Class -
public class SuffixFileFilter
extends AbstractFileFilter
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file with extension txt.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.SuffixFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingSuffixFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingSuffixFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile with extenstion txt\n");
String[] filesNames = currentDirectory.list( new SuffixFileFilter("txt") );
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File with extenstion txt
input.txt
Filters files based on prefix.
Following is the declaration for org.apache.commons.io.filefilter.PrefixFileFilter Class -
public class PrefixFileFilter
extends AbstractFileFilter
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file with name starting with input.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.PrefixFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingPrefixFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingPrefixFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile starting with input\n");
String[] filesNames = currentDirectory.list( new PrefixFileFilter("input") );
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File with extenstion txt
input.txt
Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false.
Following is the declaration for org.apache.commons.io.filefilter.OrFileFilter Class -
public class OrFileFilter
extends AbstractFileFilter
implements ConditionalFileFilter, Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file with name starting with . or ends with t.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingOrFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingOrFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile starting with . or ends with t\n");
String[] filesNames = currentDirectory.list(
new OrFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")));
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File starting with . or ends with t
.classpath
.project
.settings
input.txt
Provides conditional And logic across a list of file filters. Returns true if all filters in the list return true. Otherwise, it returns false.
Following is the declaration for org.apache.commons.io.filefilter.AndFileFilter Class -
public class AndFileFilter
extends AbstractFileFilter
implements ConditionalFileFilter, Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
Let's print all files and directories in the current directory and then filter a file with name starting with . and ends with t.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingAndFileFilter();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingAndFileFilter() throws IOException {
//get the current directory
File currentDirectory = new File(".");
//get names of all files and directory in current directory
String[] files = currentDirectory.list();
System.out.println("All files and Folders.\n");
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
System.out.println("\nFile starting with . and ends with t\n");
String[] filesNames = currentDirectory.list(
new AndFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")));
for ( int i = 0; i < filesNames.length; i++ ) {
System.out.println(filesNames[i]);
}
}
}
It will print the following result.
All files and Folders.
.classpath
.project
.settings
bin
input.txt
src
File starting with . or ends with t
.project
Provides the state of a file or directory, File attributes at a point in time.
Following is the declaration for org.apache.commons.io.monitor.FileEntry Class -
public class FileEntry
extends Object
implements Serializable
FileEntry class object provides following file attributes at a point in time.
getName() - file name.
getName() - file name.
exists() - checks if file exists or not.
exists() - checks if file exists or not.
isDirectory() - checks if file is a directory.
isDirectory() - checks if file is a directory.
lastModified() - gives last modified date time.
lastModified() - gives last modified date time.
listFiles() - gives content of directory.
listFiles() - gives content of directory.
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileEntry;
public class IOTester {
public static void main(String[] args) {
try{
usingFileEntry();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingFileEntry() throws IOException {
//get the file object
File file = FileUtils.getFile("input.txt");
FileEntry fileEntry = new FileEntry(file);
System.out.println("Monitored File: " + fileEntry.getFile());
System.out.println("File name: " + fileEntry.getName());
System.out.println("Is Directory: " + fileEntry.isDirectory());
}
}
It will print the following result.
Monitored File: input.txt
File name: input.txt
Is Directory: false
Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events.
Following is the declaration for org.apache.commons.io.monitor.FileAlterationObserver Class -
public class FileAlterationObserver
extends Object
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class IOTester {
public static void main(String[] args) {
try{
usingFileAlterationObserver();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingFileAlterationObserver() throws IOException {
//get the file object
File inputFile = FileUtils.getFile("input.txt");
String absolutePath = inputFile.getAbsolutePath();
String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
File parentDirectory = FileUtils.getFile(parent);
FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);
observer.addListener(new FileAlterationListenerAdaptor(){
@Override
public void onDirectoryCreate(File file) {
System.out.println("Folder created: " + file.getName());
}
@Override
public void onDirectoryDelete(File file) {
System.out.println("Folder deleted: " + file.getName());
}
@Override
public void onFileCreate(File file) {
System.out.println("File created: " + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("File deleted: " + file.getName());
}
});
//create a monitor to check changes after every 500 ms
FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
try{
monitor.start();
//create a new directory
File newFolder = new File("test");
File newFile = new File("test1");
newFolder.mkdirs();
Thread.sleep(1000);
newFile.createNewFile();
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFolder);
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFile);
Thread.sleep(1000);
monitor.stop(10000);
}catch(IOException e){
System.out.println(e.getMessage());
} catch(InterruptedException e){
System.out.println(e.getMessage());
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
It will print the following result.
Folder created: test
File created: test1
Folder deleted: test
File deleted: test1
Representa a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.
Following is the declaration for org.apache.commons.io.monitor.FileAlterationMonitor Class -
public final class FileAlterationMonitor
extends Object
implements Runnable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class IOTester {
public static void main(String[] args) {
try{
usingFileAlterationMonitor();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingFileAlterationMonitor() throws IOException {
//get the file object
File inputFile = FileUtils.getFile("input.txt");
String absolutePath = inputFile.getAbsolutePath();
String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
File parentDirectory = FileUtils.getFile(parent);
FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);
observer.addListener(new FileAlterationListenerAdaptor(){
@Override
public void onDirectoryCreate(File file) {
System.out.println("Folder created: " + file.getName());
}
@Override
public void onDirectoryDelete(File file) {
System.out.println("Folder deleted: " + file.getName());
}
@Override
public void onFileCreate(File file) {
System.out.println("File created: " + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("File deleted: " + file.getName());
}
});
//create a monitor to check changes after every 500 ms
FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
try{
monitor.start();
//create a new directory
File newFolder = new File("test");
File newFile = new File("test1");
newFolder.mkdirs();
Thread.sleep(1000);
newFile.createNewFile();
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFolder);
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newFile);
Thread.sleep(1000);
monitor.stop(10000);
}catch(IOException e){
System.out.println(e.getMessage());
} catch(InterruptedException e){
System.out.println(e.getMessage());
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
It will print the following result.
Folder created: test
File created: test1
Folder deleted: test
File deleted: test1
Compare the names of two files. NameFileComparator can be used to sort lists or arrays of files using their name either in a case-sensitive, case-insensitive or system dependent case sensitive way.
Following is the declaration for org.apache.commons.io.comparator.NameFileComparator Class -
public class NameFileComparator
extends Object
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingNameFileComparator();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingNameFileComparator() throws IOException {
//get the current directory
File currentDirectory = new File(".");
NameFileComparator comparator = new NameFileComparator(IOCase.INSENSITIVE);
File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
System.out.println("Sorted By Name: ");
for(File file:sortedFiles){
System.out.println(file.getName());
}
}
}
It will print the following result.
Sorted By Name:
.classpath
.project
input.txt
Compare the sizes of two files/directory. SizeFileComparator can be used to sort lists or arrays of files using their size or directories based on their no. of children.
Following is the declaration for org.apache.commons.io.comparator.SizeFileComparator Class -
public class SizeFileComparator
extends Object
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingSizeFileComparator();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingSizeFileComparator() throws IOException {
//get the current directory
File currentDirectory = new File(".");
SizeFileComparator comparator = new SizeFileComparator();
File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
System.out.println("Sorted By Size: ");
for(File file:sortedFiles){
System.out.println(file.getName() + ", size(kb) :" + file.length());
}
}
}
It will print the following result.
Sorted By Size:
input.txt, size:124
.project, size:382
.classpath, size:441
Compare the last modified dates of two files/directory. LastModifiedFileComparator can be used to sort lists or arrays of files/directories using their last modified dates.
Following is the declaration for org.apache.commons.io.comparator.LastModifiedFileComparator Class -
public class LastModifiedFileComparator
extends Object
implements Serializable
Here is the input file we need to parse β
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;
public class IOTester {
public static void main(String[] args) {
try{
usingLastModifiedFileComparator();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingLastModifiedFileComparator() throws IOException {
//get the current directory
File currentDirectory = new File(".");
LastModifiedFileComparator comparator = new LastModifiedFileComparator();
File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
System.out.println("Sorted By Last Modified date: ");
for(File file:sortedFiles){
System.out.println(file.getName() + ", Modified on: " + new Date(file.lastModified()));
}
}
}
It will print the following result.
Sorted By Last Modified date:
.project, Modified on: Thu Oct 12 19:06:45 IST 2017
.classpath, Modified on: Mon Nov 20 13:09:55 IST 2017
input.txt, Modified on: Mon Nov 20 19:27:55 IST 2017
It is an InputStream proxy that transparently writes a copy of all bytes read from the proxied stream to a given OutputStream. The proxied input stream is closed when the close() method on this proxy is called. It can be used to operate two streams collectively at a time.
Following is the declaration for org.apache.commons.io.input.TeeInputStream Class -
public class TeeInputStream
extends ProxyInputStream
In this example, closing a TeeInputStream closes the TeeInputStream as well as TeeOutputStream objects.
IOTester.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
public class IOTester {
private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";
public static void main(String[] args) {
try{
usingTeeInputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingTeeInputStream() throws IOException {
TeeInputStream teeInputStream = null;
TeeOutputStream teeOutputStream = null;
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);
teeInputStream.read(new byte[SAMPLE.length()]);
System.out.println("Output stream 1: " + outputStream1.toString());
System.out.println("Output stream 2: " + outputStream2.toString());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
//teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
try {
teeInputStream.close();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
It will print the following result.
Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.
TeeOutputStream splits OutputStream. It is named after the unix 'tee' command. It allows a stream to be branched to two streams.
Following is the declaration for org.apache.commons.io.output.TeeOutputStream Class -
public class TeeOutputStream
extends ProxyOutputStream
In this example, TeeOutputStream accepts two output streams as parameter and passing data to TeeOutputStream set data to both output streams.
IOTester.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
public class IOTester {
private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";
public static void main(String[] args) {
try{
usingTeeInputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void usingTeeInputStream() throws IOException {
TeeInputStream teeInputStream = null;
TeeOutputStream teeOutputStream = null;
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);
teeInputStream.read(new byte[SAMPLE.length()]);
System.out.println("Output stream 1: " + outputStream1.toString());
System.out.println("Output stream 2: " + outputStream2.toString());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
//teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
try {
teeInputStream.close();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
It will print the following result.
Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2641,
"s": 2404,
"text": "Apache Commons IO library provides various utility classes for common operations for File IO covering wide range of use cases. It helps avoid writing boilerplate code. Apache Commons IO library provides classes for following categories:"
},
{
"code": null,
"e": 3420,
"s": 2641,
"text": "Utility classes β These classes under org.apache.commons.io package provides file and string comparison. Following are some of the examples.\n\nIOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.\nFilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way.\nFileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.\nIOCase β Provides method for string manipulation and comparison.\nFileSystemUtils β Provides method to get the free space on a disk drive.\nLineIterator β Provides a flexible way to work with a line-based file.\n\n"
},
{
"code": null,
"e": 3561,
"s": 3420,
"text": "Utility classes β These classes under org.apache.commons.io package provides file and string comparison. Following are some of the examples."
},
{
"code": null,
"e": 3705,
"s": 3561,
"text": "IOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer."
},
{
"code": null,
"e": 3849,
"s": 3705,
"text": "IOUtils β Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer."
},
{
"code": null,
"e": 3988,
"s": 3849,
"text": "FilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way."
},
{
"code": null,
"e": 4127,
"s": 3988,
"text": "FilenameUtils β Provides method to work with file names without using File Object. It works on different operating systems in similar way."
},
{
"code": null,
"e": 4270,
"s": 4127,
"text": "FileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object."
},
{
"code": null,
"e": 4413,
"s": 4270,
"text": "FileUtils β Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object."
},
{
"code": null,
"e": 4478,
"s": 4413,
"text": "IOCase β Provides method for string manipulation and comparison."
},
{
"code": null,
"e": 4543,
"s": 4478,
"text": "IOCase β Provides method for string manipulation and comparison."
},
{
"code": null,
"e": 4616,
"s": 4543,
"text": "FileSystemUtils β Provides method to get the free space on a disk drive."
},
{
"code": null,
"e": 4689,
"s": 4616,
"text": "FileSystemUtils β Provides method to get the free space on a disk drive."
},
{
"code": null,
"e": 4760,
"s": 4689,
"text": "LineIterator β Provides a flexible way to work with a line-based file."
},
{
"code": null,
"e": 4831,
"s": 4760,
"text": "LineIterator β Provides a flexible way to work with a line-based file."
},
{
"code": null,
"e": 5650,
"s": 4831,
"text": "Filter classes β Filter classes under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias instead of string based tedious comparisons. Following are some of the examples.\n\nNameFileFilter β Filters file-names for a name.\nWildcardFileFilter β Filters files using the supplied wildcards.\nSuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type.\nPrefixFileFilter β Filters files based on prefix.\nOrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false. \nAndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.\n\n"
},
{
"code": null,
"e": 5870,
"s": 5650,
"text": "Filter classes β Filter classes under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias instead of string based tedious comparisons. Following are some of the examples."
},
{
"code": null,
"e": 5918,
"s": 5870,
"text": "NameFileFilter β Filters file-names for a name."
},
{
"code": null,
"e": 5966,
"s": 5918,
"text": "NameFileFilter β Filters file-names for a name."
},
{
"code": null,
"e": 6031,
"s": 5966,
"text": "WildcardFileFilter β Filters files using the supplied wildcards."
},
{
"code": null,
"e": 6096,
"s": 6031,
"text": "WildcardFileFilter β Filters files using the supplied wildcards."
},
{
"code": null,
"e": 6209,
"s": 6096,
"text": "SuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type."
},
{
"code": null,
"e": 6322,
"s": 6209,
"text": "SuffixFileFilter β Filters files based on suffix. This is used in retrieving all the files of a particular type."
},
{
"code": null,
"e": 6372,
"s": 6322,
"text": "PrefixFileFilter β Filters files based on prefix."
},
{
"code": null,
"e": 6422,
"s": 6372,
"text": "PrefixFileFilter β Filters files based on prefix."
},
{
"code": null,
"e": 6581,
"s": 6422,
"text": "OrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false. "
},
{
"code": null,
"e": 6740,
"s": 6581,
"text": "OrFileFilter β Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false. "
},
{
"code": null,
"e": 6901,
"s": 6740,
"text": "AndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true."
},
{
"code": null,
"e": 7062,
"s": 6901,
"text": "AndFileFilter β Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true."
},
{
"code": null,
"e": 7301,
"s": 7062,
"text": "File Monitor classes β File monitor classes under org.apache.commons.io.monitor package provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples."
},
{
"code": null,
"e": 7540,
"s": 7301,
"text": "File Monitor classes β File monitor classes under org.apache.commons.io.monitor package provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples."
},
{
"code": null,
"e": 7631,
"s": 7540,
"text": "FileEntry β Provides the state of a file or directory, File attributes at a point in time."
},
{
"code": null,
"e": 7722,
"s": 7631,
"text": "FileEntry β Provides the state of a file or directory, File attributes at a point in time."
},
{
"code": null,
"e": 7882,
"s": 7722,
"text": "FileAlterationObserver β Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events."
},
{
"code": null,
"e": 8042,
"s": 7882,
"text": "FileAlterationObserver β Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events."
},
{
"code": null,
"e": 8191,
"s": 8042,
"text": "FileAlterationMonitor β Represent a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval."
},
{
"code": null,
"e": 8340,
"s": 8191,
"text": "FileAlterationMonitor β Represent a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval."
},
{
"code": null,
"e": 8668,
"s": 8340,
"text": "Comparator classes β File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily.\n\nNameFileComparator β Compare the names of two files.\nSizeFileComparator β Compare the size of two files.\nLastModifiedFileComparator β Compare the last modified dates of two files.\n\n"
},
{
"code": null,
"e": 8814,
"s": 8668,
"text": "Comparator classes β File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily.\n"
},
{
"code": null,
"e": 8867,
"s": 8814,
"text": "NameFileComparator β Compare the names of two files."
},
{
"code": null,
"e": 8920,
"s": 8867,
"text": "NameFileComparator β Compare the names of two files."
},
{
"code": null,
"e": 8972,
"s": 8920,
"text": "SizeFileComparator β Compare the size of two files."
},
{
"code": null,
"e": 9024,
"s": 8972,
"text": "SizeFileComparator β Compare the size of two files."
},
{
"code": null,
"e": 9099,
"s": 9024,
"text": "LastModifiedFileComparator β Compare the last modified dates of two files."
},
{
"code": null,
"e": 9174,
"s": 9099,
"text": "LastModifiedFileComparator β Compare the last modified dates of two files."
},
{
"code": null,
"e": 9888,
"s": 9174,
"text": "Stream classes β There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package to do useful tasks on streams. Following are some of the examples.\n\nNullOutputStream β absorbs all data sent with any error.\nTeeOutputStream β sends output to two streams.\nByteArrayOutputStream β faster version of JDK class.\nCountingOutputStream β Counts the number of bytes passed through the stream.\nCountingOutputStream β Counts the number of bytes passed through the stream.\nProxyOutputStream β Changes the calls to proxied stream.\nLockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling.\n\n"
},
{
"code": null,
"e": 10126,
"s": 9888,
"text": "Stream classes β There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package to do useful tasks on streams. Following are some of the examples."
},
{
"code": null,
"e": 10183,
"s": 10126,
"text": "NullOutputStream β absorbs all data sent with any error."
},
{
"code": null,
"e": 10240,
"s": 10183,
"text": "NullOutputStream β absorbs all data sent with any error."
},
{
"code": null,
"e": 10287,
"s": 10240,
"text": "TeeOutputStream β sends output to two streams."
},
{
"code": null,
"e": 10334,
"s": 10287,
"text": "TeeOutputStream β sends output to two streams."
},
{
"code": null,
"e": 10387,
"s": 10334,
"text": "ByteArrayOutputStream β faster version of JDK class."
},
{
"code": null,
"e": 10440,
"s": 10387,
"text": "ByteArrayOutputStream β faster version of JDK class."
},
{
"code": null,
"e": 10517,
"s": 10440,
"text": "CountingOutputStream β Counts the number of bytes passed through the stream."
},
{
"code": null,
"e": 10594,
"s": 10517,
"text": "CountingOutputStream β Counts the number of bytes passed through the stream."
},
{
"code": null,
"e": 10671,
"s": 10594,
"text": "CountingOutputStream β Counts the number of bytes passed through the stream."
},
{
"code": null,
"e": 10748,
"s": 10671,
"text": "CountingOutputStream β Counts the number of bytes passed through the stream."
},
{
"code": null,
"e": 10805,
"s": 10748,
"text": "ProxyOutputStream β Changes the calls to proxied stream."
},
{
"code": null,
"e": 10862,
"s": 10805,
"text": "ProxyOutputStream β Changes the calls to proxied stream."
},
{
"code": null,
"e": 10967,
"s": 10862,
"text": "LockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling."
},
{
"code": null,
"e": 11072,
"s": 10967,
"text": "LockableFileWriter β A FileWriter to create lock files and allow simple cross thread file lock handling."
},
{
"code": null,
"e": 11338,
"s": 11072,
"text": "In this chapter, we will learn about the local environment setup of Apache Commons IO and how to set up the path of Commons IO for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons IO archive."
},
{
"code": null,
"e": 11525,
"s": 11338,
"text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on."
},
{
"code": null,
"e": 11709,
"s": 11525,
"text": "If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table."
},
{
"code": null,
"e": 11741,
"s": 11709,
"text": "Open command console and type β"
},
{
"code": null,
"e": 11757,
"s": 11741,
"text": "\\>java -version"
},
{
"code": null,
"e": 11795,
"s": 11757,
"text": "java version \"11.0.11\" 2021-04-20 LTS"
},
{
"code": null,
"e": 11858,
"s": 11795,
"text": "Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)"
},
{
"code": null,
"e": 11935,
"s": 11858,
"text": "Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)"
},
{
"code": null,
"e": 11968,
"s": 11935,
"text": "Open command terminal and type β"
},
{
"code": null,
"e": 11983,
"s": 11968,
"text": "$java -version"
},
{
"code": null,
"e": 12021,
"s": 11983,
"text": "java version \"11.0.11\" 2021-04-20 LTS"
},
{
"code": null,
"e": 12081,
"s": 12021,
"text": "Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)"
},
{
"code": null,
"e": 12145,
"s": 12081,
"text": "Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)"
},
{
"code": null,
"e": 12241,
"s": 12145,
"text": "We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system."
},
{
"code": null,
"e": 12337,
"s": 12241,
"text": "We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system."
},
{
"code": null,
"e": 12489,
"s": 12337,
"text": "In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.\n"
},
{
"code": null,
"e": 12640,
"s": 12489,
"text": "In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed."
},
{
"code": null,
"e": 12773,
"s": 12640,
"text": "Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,"
},
{
"code": null,
"e": 12781,
"s": 12773,
"text": "Windows"
},
{
"code": null,
"e": 12830,
"s": 12781,
"text": "Set JAVA_HOME to C:\\ProgramFiles\\java\\jdk11.0.11"
},
{
"code": null,
"e": 12836,
"s": 12830,
"text": "Linux"
},
{
"code": null,
"e": 12879,
"s": 12836,
"text": "Export JAVA_HOME = /usr/local/java-current"
},
{
"code": null,
"e": 12946,
"s": 12879,
"text": "Append the full path of Java compiler location to the System Path."
},
{
"code": null,
"e": 12954,
"s": 12946,
"text": "Windows"
},
{
"code": null,
"e": 13051,
"s": 12954,
"text": "Append the String \"C:\\Program Files\\Java\\jdk11.0.11\\bin\" to the end of the system variable PATH."
},
{
"code": null,
"e": 13057,
"s": 13051,
"text": "Linux"
},
{
"code": null,
"e": 13093,
"s": 13057,
"text": "Export PATH = $PATH:$JAVA_HOME/bin/"
},
{
"code": null,
"e": 13171,
"s": 13093,
"text": "Execute the command java -version from the command prompt as explained above."
},
{
"code": null,
"e": 13373,
"s": 13171,
"text": "To write your Java programs, you need a text editor. There are many sophisticated integrated development environment (IDEs) available in the market. But for now, you can consider one of the following β"
},
{
"code": null,
"e": 13492,
"s": 13373,
"text": "Notepad β On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 13611,
"s": 13492,
"text": "Notepad β On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 13726,
"s": 13611,
"text": "Netbeans β It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 13841,
"s": 13726,
"text": "Netbeans β It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 13964,
"s": 13841,
"text": "Eclipse β It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 14087,
"s": 13964,
"text": "Eclipse β It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 14297,
"s": 14087,
"text": "Download the latest version of Apache Common IO jar file from commons-io-2.11.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-io-2.11.0-bin.zip and copied it into C:\\>Apache folder."
},
{
"code": null,
"e": 14532,
"s": 14297,
"text": "Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows."
},
{
"code": null,
"e": 14721,
"s": 14532,
"text": "Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows."
},
{
"code": null,
"e": 14855,
"s": 14721,
"text": "Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer."
},
{
"code": null,
"e": 14926,
"s": 14855,
"text": "Following is the declaration for org.apache.commons.io.IOUtils Class -"
},
{
"code": null,
"e": 14965,
"s": 14926,
"text": "public class IOUtils\n extends Object"
},
{
"code": null,
"e": 15026,
"s": 14965,
"text": "Provides static utility methods for input/output operations."
},
{
"code": null,
"e": 15087,
"s": 15026,
"text": "Provides static utility methods for input/output operations."
},
{
"code": null,
"e": 15123,
"s": 15087,
"text": "toXXX() - reads data from a stream."
},
{
"code": null,
"e": 15159,
"s": 15123,
"text": "toXXX() - reads data from a stream."
},
{
"code": null,
"e": 15193,
"s": 15159,
"text": "write() - write data to a stream."
},
{
"code": null,
"e": 15227,
"s": 15193,
"text": "write() - write data to a stream."
},
{
"code": null,
"e": 15281,
"s": 15227,
"text": "copy() - copy all data to a stream to another stream."
},
{
"code": null,
"e": 15335,
"s": 15281,
"text": "copy() - copy all data to a stream to another stream."
},
{
"code": null,
"e": 15388,
"s": 15335,
"text": "contentEquals - compare the contents of two streams."
},
{
"code": null,
"e": 15441,
"s": 15388,
"text": "contentEquals - compare the contents of two streams."
},
{
"code": null,
"e": 15483,
"s": 15441,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 15532,
"s": 15483,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 15546,
"s": 15532,
"text": "IOTester.java"
},
{
"code": null,
"e": 16714,
"s": 15546,
"text": "import java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\nimport org.apache.commons.io.IOUtils;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n //Using BufferedReader\n readUsingTraditionalWay();\n\n //Using IOUtils\n readUsingIOUtils();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n //reading a file using buffered reader line by line\n public static void readUsingTraditionalWay() throws IOException{\n try (BufferedReader bufferReader \n = new BufferedReader( \n new InputStreamReader( \n new FileInputStream(\"input.txt\") ) )) {\n String line;\n while ( ( line = bufferReader.readLine() ) != null ) {\n System.out.println( line );\n }\n }\n }\n\n //reading a file using IOUtils in one go\n public static void readUsingIOUtils() throws IOException {\n try(InputStream in = new FileInputStream(\"input.txt\")){\n System.out.println( IOUtils.toString( in , \"UTF-8\") );\n }\n }\n}"
},
{
"code": null,
"e": 16750,
"s": 16714,
"text": "It will print the following result."
},
{
"code": null,
"e": 16849,
"s": 16750,
"text": "Welcome to TutorialsPoint. Simply Easy Learning.\nWelcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 16980,
"s": 16849,
"text": "Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object."
},
{
"code": null,
"e": 17053,
"s": 16980,
"text": "Following is the declaration for org.apache.commons.io.FileUtils Class -"
},
{
"code": null,
"e": 17094,
"s": 17053,
"text": "public class FileUtils\n extends Object"
},
{
"code": null,
"e": 17122,
"s": 17094,
"text": "Methods to write to a file."
},
{
"code": null,
"e": 17150,
"s": 17122,
"text": "Methods to write to a file."
},
{
"code": null,
"e": 17179,
"s": 17150,
"text": "Methods to read from a file."
},
{
"code": null,
"e": 17208,
"s": 17179,
"text": "Methods to read from a file."
},
{
"code": null,
"e": 17266,
"s": 17208,
"text": "Methods to make a directory including parent directories."
},
{
"code": null,
"e": 17324,
"s": 17266,
"text": "Methods to make a directory including parent directories."
},
{
"code": null,
"e": 17363,
"s": 17324,
"text": "Methods to copy files and directories."
},
{
"code": null,
"e": 17402,
"s": 17363,
"text": "Methods to copy files and directories."
},
{
"code": null,
"e": 17443,
"s": 17402,
"text": "Methods to delete files and directories."
},
{
"code": null,
"e": 17484,
"s": 17443,
"text": "Methods to delete files and directories."
},
{
"code": null,
"e": 17522,
"s": 17484,
"text": "Methods to convert to and from a URL."
},
{
"code": null,
"e": 17560,
"s": 17522,
"text": "Methods to convert to and from a URL."
},
{
"code": null,
"e": 17623,
"s": 17560,
"text": "Methods to list files and directories by filter and extension."
},
{
"code": null,
"e": 17686,
"s": 17623,
"text": "Methods to list files and directories by filter and extension."
},
{
"code": null,
"e": 17719,
"s": 17686,
"text": "Methods to compare file content."
},
{
"code": null,
"e": 17752,
"s": 17719,
"text": "Methods to compare file content."
},
{
"code": null,
"e": 17787,
"s": 17752,
"text": "Methods to file last changed date."
},
{
"code": null,
"e": 17822,
"s": 17787,
"text": "Methods to file last changed date."
},
{
"code": null,
"e": 17857,
"s": 17822,
"text": "Methods to calculating a checksum."
},
{
"code": null,
"e": 17892,
"s": 17857,
"text": "Methods to calculating a checksum."
},
{
"code": null,
"e": 17934,
"s": 17892,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 17983,
"s": 17934,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 17997,
"s": 17983,
"text": "IOTester.java"
},
{
"code": null,
"e": 18968,
"s": 17997,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\n\nimport org.apache.commons.io.FileUtils;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n //Using FileUtils\n usingFileUtils();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFileUtils() throws IOException {\n //get the file object\n File file = FileUtils.getFile(\"input.txt\");\n\n //get the temp directory\n File tmpDir = FileUtils.getTempDirectory();\n\n System.out.println(tmpDir.getName());\n\n //copy file to temp directory\n FileUtils.copyFileToDirectory(file, tmpDir);\n\n //create a new file\n File newTempFile = FileUtils.getFile(tmpDir, file.getName());\n\n //get the content\n String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());\n\n //print the content\n System.out.println(data);\n }\n}"
},
{
"code": null,
"e": 19004,
"s": 18968,
"text": "It will print the following result."
},
{
"code": null,
"e": 19059,
"s": 19004,
"text": "Temp\nWelcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 19298,
"s": 19059,
"text": "Provides method to work with file names without using File Object. It works on different operating systems in similar way. This class solves problems when moving from a Windows based development machine to a Unix based production machine."
},
{
"code": null,
"e": 19375,
"s": 19298,
"text": "Following is the declaration for org.apache.commons.io.FilenameUtils Class -"
},
{
"code": null,
"e": 19420,
"s": 19375,
"text": "public class FilenameUtils\n extends Object"
},
{
"code": null,
"e": 19554,
"s": 19420,
"text": "This class defines six components within a filename. Consider an example location as C:\\dev\\project\\file.txt. Then the components are"
},
{
"code": null,
"e": 19567,
"s": 19554,
"text": "Prefix - C:\\"
},
{
"code": null,
"e": 19580,
"s": 19567,
"text": "Prefix - C:\\"
},
{
"code": null,
"e": 19609,
"s": 19580,
"text": "Relative Path - dev\\project\\"
},
{
"code": null,
"e": 19638,
"s": 19609,
"text": "Relative Path - dev\\project\\"
},
{
"code": null,
"e": 19670,
"s": 19638,
"text": "Absolute path - C:\\dev\\project\\"
},
{
"code": null,
"e": 19702,
"s": 19670,
"text": "Absolute path - C:\\dev\\project\\"
},
{
"code": null,
"e": 19718,
"s": 19702,
"text": "Name - file.txt"
},
{
"code": null,
"e": 19734,
"s": 19718,
"text": "Name - file.txt"
},
{
"code": null,
"e": 19751,
"s": 19734,
"text": "Base name - file"
},
{
"code": null,
"e": 19768,
"s": 19751,
"text": "Base name - file"
},
{
"code": null,
"e": 19784,
"s": 19768,
"text": "Extension - txt"
},
{
"code": null,
"e": 19800,
"s": 19784,
"text": "Extension - txt"
},
{
"code": null,
"e": 19855,
"s": 19800,
"text": "To identify a directory, add a separator to file name."
},
{
"code": null,
"e": 19869,
"s": 19855,
"text": "IOTester.java"
},
{
"code": null,
"e": 20866,
"s": 19869,
"text": "import java.io.IOException;\nimport org.apache.commons.io.FilenameUtils;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n //Using FilenameUtils\n usingFilenameUtils();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFilenameUtils() throws IOException {\n String path = \"C:\\\\dev\\\\project\\\\file.txt\";\n System.out.println(\"Full Path: \" +FilenameUtils.getFullPath(path));\n System.out.println(\"Relative Path: \" +FilenameUtils.getPath(path));\n System.out.println(\"Prefix: \" +FilenameUtils.getPrefix(path));\n System.out.println(\"Extension: \" + FilenameUtils.getExtension(path));\n System.out.println(\"Base: \" + FilenameUtils.getBaseName(path));\n System.out.println(\"Name: \" + FilenameUtils.getName(path));\n\n String filename = \"C:/commons/io/../lang/project.xml\";\n System.out.println(\"Normalized Path: \" + FilenameUtils.normalize(filename));\n }\n}"
},
{
"code": null,
"e": 20902,
"s": 20866,
"text": "It will print the following result."
},
{
"code": null,
"e": 21056,
"s": 20902,
"text": "Full Path: C:\\dev\\project\\\nRelative Path: dev\\project\\\nPrefix: C:\\\nExtension: txt\nBase: file\nName: file.txt\nNormalized Path: C:\\commons\\lang\\project.xml\n"
},
{
"code": null,
"e": 21111,
"s": 21056,
"text": "Provides method to get the free space on a disk drive."
},
{
"code": null,
"e": 21190,
"s": 21111,
"text": "Following is the declaration for org.apache.commons.io.FileSystemUtils Class -"
},
{
"code": null,
"e": 21237,
"s": 21190,
"text": "public class FileSystemUtils\n extends Object"
},
{
"code": null,
"e": 21251,
"s": 21237,
"text": "IOTester.java"
},
{
"code": null,
"e": 21587,
"s": 21251,
"text": "import java.io.IOException;\n\nimport org.apache.commons.io.FileSystemUtils;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n System.out.println(\"Free Space \" + FileSystemUtils.freeSpaceKb(\"C:/\") + \" Bytes\");\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n}"
},
{
"code": null,
"e": 21623,
"s": 21587,
"text": "It will print the following result."
},
{
"code": null,
"e": 21647,
"s": 21623,
"text": "Free Space 61355640 kb\n"
},
{
"code": null,
"e": 22041,
"s": 21647,
"text": "Enumeration of IO case sensitivity. Different Operating systems have different rules for case-sensitivity for file names. For example Windows is case-insensitive for file naming while Unix is case-sensitive. IOCase captures that difference, provides an enumeration to control how filename comparisons should be performed. It also provides methods to use the enumeration to perform comparisons."
},
{
"code": null,
"e": 22110,
"s": 22041,
"text": "Following is the declaration for org.apache.commons.io.IOCase Enum -"
},
{
"code": null,
"e": 22183,
"s": 22110,
"text": "public enum IOCase\n extends Enum<IOCase>\n implements Serializable"
},
{
"code": null,
"e": 22197,
"s": 22183,
"text": "IOTester.java"
},
{
"code": null,
"e": 23155,
"s": 22197,
"text": "import java.io.IOException;\nimport org.apache.commons.io.IOCase;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingIOCase();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingIOCase() throws IOException {\n String text = \"Welcome to TutorialsPoint. Simply Easy Learning.\";\n String text1 = \"WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.\";\n\n System.out.println(\"Ends with Learning (case sensitive): \" +\n IOCase.SENSITIVE.checkEndsWith(text1, \"Learning.\"));\n\n System.out.println(\"Ends with Learning (case insensitive): \" +\n IOCase.INSENSITIVE.checkEndsWith(text1, \"Learning.\"));\n\n System.out.println(\"Equality Check (case sensitive): \" +\n IOCase.SENSITIVE.checkEquals(text, text1));\n\n System.out.println(\"Equality Check (case insensitive): \" +\n IOCase.INSENSITIVE.checkEquals(text, text1));\n }\n}"
},
{
"code": null,
"e": 23191,
"s": 23155,
"text": "It will print the following result."
},
{
"code": null,
"e": 23360,
"s": 23191,
"text": "Ends with Learning (case sensitive): false\nEnds with Learning (case insensitive): true\nEquality Check (case sensitive): false\nEquality Check (case insensitive): true\n"
},
{
"code": null,
"e": 23416,
"s": 23360,
"text": "Provides a flexible way to work with a line-based file."
},
{
"code": null,
"e": 23492,
"s": 23416,
"text": "Following is the declaration for org.apache.commons.io.LineIterator Class -"
},
{
"code": null,
"e": 23581,
"s": 23492,
"text": "public class LineIterator\n extends Object\n implements Iterator<String>, Closeable"
},
{
"code": null,
"e": 23623,
"s": 23581,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 23742,
"s": 23623,
"text": "Welcome to TutorialsPoint. Simply Easy Learning.\nLearn web technologies,\nprepare exams,\ncode online,\nall at one place."
},
{
"code": null,
"e": 23756,
"s": 23742,
"text": "IOTester.java"
},
{
"code": null,
"e": 24473,
"s": 23756,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.LineIterator;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingLineIterator();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingLineIterator() throws IOException {\n //get the file object\n File file = FileUtils.getFile(\"input.txt\");\n\n try(LineIterator lineIterator = FileUtils.lineIterator(file)){\n System.out.println(\"Contents of input.txt\");\n while (lineIterator.hasNext()) {\n System.out.println(lineIterator.next());\n }\n }\n }\n}"
},
{
"code": null,
"e": 24509,
"s": 24473,
"text": "It will print the following result."
},
{
"code": null,
"e": 24651,
"s": 24509,
"text": "Contents of input.txt\nWelcome to TutorialsPoint. Simply Easy Learning.\nLearn web technologies,\nprepare exams,\ncode online,\nall at one place.\n"
},
{
"code": null,
"e": 24682,
"s": 24651,
"text": "Filters file-names for a name."
},
{
"code": null,
"e": 24771,
"s": 24682,
"text": "Following is the declaration for org.apache.commons.io.filefilter.NameFileFilter Class -"
},
{
"code": null,
"e": 24859,
"s": 24771,
"text": "public class NameFileFilter\n extends AbstractFileFilter\n implements Serializable"
},
{
"code": null,
"e": 24901,
"s": 24859,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 24950,
"s": 24901,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 25061,
"s": 24950,
"text": "Let's print all files and directories in the current directory and then filter a file whose name is Input.txt."
},
{
"code": null,
"e": 25075,
"s": 25061,
"text": "IOTester.java"
},
{
"code": null,
"e": 26160,
"s": 25075,
"text": "import java.io.File;\nimport java.io.IOException;\nimport org.apache.commons.io.IOCase;\nimport org.apache.commons.io.filefilter.NameFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingNameFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingNameFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile with name input.txt\\n\");\n String[] acceptedNames = {\"input\", \"input.txt\"};\n String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.INSENSITIVE) );\n\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 26196,
"s": 26160,
"text": "It will print the following result."
},
{
"code": null,
"e": 26306,
"s": 26196,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile with name input.txt\n\ninput.txt\n"
},
{
"code": null,
"e": 26350,
"s": 26306,
"text": "Filters files using the supplied wildcards."
},
{
"code": null,
"e": 26443,
"s": 26350,
"text": "Following is the declaration for org.apache.commons.io.filefilter.WildcardFileFilter Class -"
},
{
"code": null,
"e": 26535,
"s": 26443,
"text": "public class WildcardFileFilter\n extends AbstractFileFilter\n implements Serializable"
},
{
"code": null,
"e": 26577,
"s": 26535,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 26626,
"s": 26577,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 26736,
"s": 26626,
"text": "Let's print all files and directories in the current directory and then filter a file whose name ends with t."
},
{
"code": null,
"e": 26750,
"s": 26736,
"text": "IOTester.java"
},
{
"code": null,
"e": 27729,
"s": 26750,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.filefilter.WildcardFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingWildcardFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n public static void usingWildcardFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile name ending with t.\\n\");\n String[] filesNames = currentDirectory.list( new WildcardFileFilter(\"*t\") );\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 27765,
"s": 27729,
"text": "It will print the following result."
},
{
"code": null,
"e": 27883,
"s": 27765,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile name ending with t\n\n.project\ninput.txt\n"
},
{
"code": null,
"e": 27977,
"s": 27883,
"text": "Filters files based on suffix. This is used in retrieving all the files of a particular type."
},
{
"code": null,
"e": 28068,
"s": 27977,
"text": "Following is the declaration for org.apache.commons.io.filefilter.SuffixFileFilter Class -"
},
{
"code": null,
"e": 28158,
"s": 28068,
"text": "public class SuffixFileFilter\n extends AbstractFileFilter\n implements Serializable"
},
{
"code": null,
"e": 28200,
"s": 28158,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 28249,
"s": 28200,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 28355,
"s": 28249,
"text": "Let's print all files and directories in the current directory and then filter a file with extension txt."
},
{
"code": null,
"e": 28369,
"s": 28355,
"text": "IOTester.java"
},
{
"code": null,
"e": 29342,
"s": 28369,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.filefilter.SuffixFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingSuffixFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingSuffixFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile with extenstion txt\\n\");\n String[] filesNames = currentDirectory.list( new SuffixFileFilter(\"txt\") );\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 29378,
"s": 29342,
"text": "It will print the following result."
},
{
"code": null,
"e": 29488,
"s": 29378,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile with extenstion txt\n\ninput.txt\n"
},
{
"code": null,
"e": 29519,
"s": 29488,
"text": "Filters files based on prefix."
},
{
"code": null,
"e": 29610,
"s": 29519,
"text": "Following is the declaration for org.apache.commons.io.filefilter.PrefixFileFilter Class -"
},
{
"code": null,
"e": 29700,
"s": 29610,
"text": "public class PrefixFileFilter\n extends AbstractFileFilter\n implements Serializable"
},
{
"code": null,
"e": 29742,
"s": 29700,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 29791,
"s": 29742,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 29908,
"s": 29791,
"text": "Let's print all files and directories in the current directory and then filter a file with name starting with input."
},
{
"code": null,
"e": 29922,
"s": 29908,
"text": "IOTester.java"
},
{
"code": null,
"e": 30897,
"s": 29922,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.filefilter.PrefixFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingPrefixFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingPrefixFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile starting with input\\n\");\n String[] filesNames = currentDirectory.list( new PrefixFileFilter(\"input\") );\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 30933,
"s": 30897,
"text": "It will print the following result."
},
{
"code": null,
"e": 31043,
"s": 30933,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile with extenstion txt\n\ninput.txt\n"
},
{
"code": null,
"e": 31186,
"s": 31043,
"text": "Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false."
},
{
"code": null,
"e": 31273,
"s": 31186,
"text": "Following is the declaration for org.apache.commons.io.filefilter.OrFileFilter Class -"
},
{
"code": null,
"e": 31382,
"s": 31273,
"text": "public class OrFileFilter\n extends AbstractFileFilter\n implements ConditionalFileFilter, Serializable"
},
{
"code": null,
"e": 31424,
"s": 31382,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 31473,
"s": 31424,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 31601,
"s": 31473,
"text": "Let's print all files and directories in the current directory and then filter a file with name starting with . or ends with t."
},
{
"code": null,
"e": 31615,
"s": 31601,
"text": "IOTester.java"
},
{
"code": null,
"e": 32759,
"s": 31615,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.filefilter.OrFileFilter;\nimport org.apache.commons.io.filefilter.PrefixFileFilter;\nimport org.apache.commons.io.filefilter.WildcardFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingOrFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingOrFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile starting with . or ends with t\\n\");\n String[] filesNames = currentDirectory.list(\n new OrFileFilter(new PrefixFileFilter(\".\"), new WildcardFileFilter(\"*t\")));\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 32795,
"s": 32759,
"text": "It will print the following result."
},
{
"code": null,
"e": 32946,
"s": 32795,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile starting with . or ends with t\n\n.classpath\n.project\n.settings\ninput.txt\n"
},
{
"code": null,
"e": 33090,
"s": 32946,
"text": "Provides conditional And logic across a list of file filters. Returns true if all filters in the list return true. Otherwise, it returns false."
},
{
"code": null,
"e": 33178,
"s": 33090,
"text": "Following is the declaration for org.apache.commons.io.filefilter.AndFileFilter Class -"
},
{
"code": null,
"e": 33288,
"s": 33178,
"text": "public class AndFileFilter\n extends AbstractFileFilter\n implements ConditionalFileFilter, Serializable"
},
{
"code": null,
"e": 33330,
"s": 33288,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 33380,
"s": 33330,
"text": "Welcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 33509,
"s": 33380,
"text": "Let's print all files and directories in the current directory and then filter a file with name starting with . and ends with t."
},
{
"code": null,
"e": 33523,
"s": 33509,
"text": "IOTester.java"
},
{
"code": null,
"e": 34671,
"s": 33523,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.filefilter.AndFileFilter;\nimport org.apache.commons.io.filefilter.PrefixFileFilter;\nimport org.apache.commons.io.filefilter.WildcardFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingAndFileFilter();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n public static void usingAndFileFilter() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n //get names of all files and directory in current directory\n String[] files = currentDirectory.list();\n System.out.println(\"All files and Folders.\\n\");\n for ( int i = 0; i < files.length; i++ ) {\n System.out.println(files[i]);\n }\n System.out.println(\"\\nFile starting with . and ends with t\\n\");\n String[] filesNames = currentDirectory.list(\n new AndFileFilter(new PrefixFileFilter(\".\"), new WildcardFileFilter(\"*t\")));\n for ( int i = 0; i < filesNames.length; i++ ) {\n System.out.println(filesNames[i]);\n }\n }\n}"
},
{
"code": null,
"e": 34707,
"s": 34671,
"text": "It will print the following result."
},
{
"code": null,
"e": 34827,
"s": 34707,
"text": "All files and Folders.\n\n.classpath\n.project\n.settings\nbin\ninput.txt\nsrc\n\nFile starting with . or ends with t\n\n.project\n"
},
{
"code": null,
"e": 34906,
"s": 34827,
"text": "Provides the state of a file or directory, File attributes at a point in time."
},
{
"code": null,
"e": 34987,
"s": 34906,
"text": "Following is the declaration for org.apache.commons.io.monitor.FileEntry Class -"
},
{
"code": null,
"e": 35058,
"s": 34987,
"text": "public class FileEntry\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 35136,
"s": 35058,
"text": "FileEntry class object provides following file attributes at a point in time."
},
{
"code": null,
"e": 35159,
"s": 35136,
"text": "getName() - file name."
},
{
"code": null,
"e": 35182,
"s": 35159,
"text": "getName() - file name."
},
{
"code": null,
"e": 35223,
"s": 35182,
"text": "exists() - checks if file exists or not."
},
{
"code": null,
"e": 35264,
"s": 35223,
"text": "exists() - checks if file exists or not."
},
{
"code": null,
"e": 35311,
"s": 35264,
"text": "isDirectory() - checks if file is a directory."
},
{
"code": null,
"e": 35358,
"s": 35311,
"text": "isDirectory() - checks if file is a directory."
},
{
"code": null,
"e": 35406,
"s": 35358,
"text": "lastModified() - gives last modified date time."
},
{
"code": null,
"e": 35454,
"s": 35406,
"text": "lastModified() - gives last modified date time."
},
{
"code": null,
"e": 35496,
"s": 35454,
"text": "listFiles() - gives content of directory."
},
{
"code": null,
"e": 35538,
"s": 35496,
"text": "listFiles() - gives content of directory."
},
{
"code": null,
"e": 35580,
"s": 35538,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 35629,
"s": 35580,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 35643,
"s": 35629,
"text": "IOTester.java"
},
{
"code": null,
"e": 36373,
"s": 35643,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.monitor.FileEntry;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingFileEntry();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFileEntry() throws IOException {\n //get the file object\n File file = FileUtils.getFile(\"input.txt\");\n\n FileEntry fileEntry = new FileEntry(file);\n\n System.out.println(\"Monitored File: \" + fileEntry.getFile());\n System.out.println(\"File name: \" + fileEntry.getName());\n System.out.println(\"Is Directory: \" + fileEntry.isDirectory());\n }\n}"
},
{
"code": null,
"e": 36409,
"s": 36373,
"text": "It will print the following result."
},
{
"code": null,
"e": 36477,
"s": 36409,
"text": "Monitored File: input.txt\nFile name: input.txt\nIs Directory: false\n"
},
{
"code": null,
"e": 36612,
"s": 36477,
"text": "Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events."
},
{
"code": null,
"e": 36706,
"s": 36612,
"text": "Following is the declaration for org.apache.commons.io.monitor.FileAlterationObserver Class -"
},
{
"code": null,
"e": 36790,
"s": 36706,
"text": "public class FileAlterationObserver\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 36832,
"s": 36790,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 36881,
"s": 36832,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 36895,
"s": 36881,
"text": "IOTester.java"
},
{
"code": null,
"e": 39411,
"s": 36895,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileDeleteStrategy;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.monitor.FileAlterationListenerAdaptor;\nimport org.apache.commons.io.monitor.FileAlterationMonitor;\nimport org.apache.commons.io.monitor.FileAlterationObserver;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingFileAlterationObserver();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFileAlterationObserver() throws IOException {\n //get the file object\n File inputFile = FileUtils.getFile(\"input.txt\");\n String absolutePath = inputFile.getAbsolutePath();\n String parent = absolutePath.substring(0,absolutePath.indexOf(\"input.txt\")); \n File parentDirectory = FileUtils.getFile(parent);\n\n FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);\n\n observer.addListener(new FileAlterationListenerAdaptor(){\n\n @Override\n public void onDirectoryCreate(File file) {\n System.out.println(\"Folder created: \" + file.getName());\n }\n\n @Override\n public void onDirectoryDelete(File file) {\n System.out.println(\"Folder deleted: \" + file.getName());\n } \n\n @Override\n public void onFileCreate(File file) {\n System.out.println(\"File created: \" + file.getName());\n }\n\n @Override\n public void onFileDelete(File file) {\n System.out.println(\"File deleted: \" + file.getName());\n } \n });\n\n //create a monitor to check changes after every 500 ms\n FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);\n\n try{\n monitor.start();\n\n //create a new directory\n File newFolder = new File(\"test\");\n File newFile = new File(\"test1\");\n\n newFolder.mkdirs();\n Thread.sleep(1000);\n newFile.createNewFile();\n Thread.sleep(1000);\n FileDeleteStrategy.NORMAL.delete(newFolder);\n Thread.sleep(1000);\n FileDeleteStrategy.NORMAL.delete(newFile);\n Thread.sleep(1000);\n\n monitor.stop(10000);\n\n }catch(IOException e){\n System.out.println(e.getMessage());\n } catch(InterruptedException e){\n System.out.println(e.getMessage());\n }catch (Exception e) {\n System.out.println(e.getMessage());\n }\n }\n}"
},
{
"code": null,
"e": 39447,
"s": 39411,
"text": "It will print the following result."
},
{
"code": null,
"e": 39530,
"s": 39447,
"text": "Folder created: test\nFile created: test1\nFolder deleted: test\nFile deleted: test1\n"
},
{
"code": null,
"e": 39656,
"s": 39530,
"text": "Representa a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval."
},
{
"code": null,
"e": 39749,
"s": 39656,
"text": "Following is the declaration for org.apache.commons.io.monitor.FileAlterationMonitor Class -"
},
{
"code": null,
"e": 39835,
"s": 39749,
"text": "public final class FileAlterationMonitor\n extends Object\n implements Runnable\n"
},
{
"code": null,
"e": 39877,
"s": 39835,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 39927,
"s": 39877,
"text": "Welcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 39941,
"s": 39927,
"text": "IOTester.java"
},
{
"code": null,
"e": 42455,
"s": 39941,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileDeleteStrategy;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.monitor.FileAlterationListenerAdaptor;\nimport org.apache.commons.io.monitor.FileAlterationMonitor;\nimport org.apache.commons.io.monitor.FileAlterationObserver;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingFileAlterationMonitor();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFileAlterationMonitor() throws IOException {\n //get the file object\n File inputFile = FileUtils.getFile(\"input.txt\");\n String absolutePath = inputFile.getAbsolutePath();\n String parent = absolutePath.substring(0,absolutePath.indexOf(\"input.txt\")); \n File parentDirectory = FileUtils.getFile(parent);\n\n FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);\n\n observer.addListener(new FileAlterationListenerAdaptor(){\n\n @Override\n public void onDirectoryCreate(File file) {\n System.out.println(\"Folder created: \" + file.getName());\n }\n\n @Override\n public void onDirectoryDelete(File file) {\n System.out.println(\"Folder deleted: \" + file.getName());\n } \n\n @Override\n public void onFileCreate(File file) {\n System.out.println(\"File created: \" + file.getName());\n }\n\n @Override\n public void onFileDelete(File file) {\n System.out.println(\"File deleted: \" + file.getName());\n } \n });\n\n //create a monitor to check changes after every 500 ms\n FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);\n\n try{\n monitor.start();\n\n //create a new directory\n File newFolder = new File(\"test\");\n File newFile = new File(\"test1\");\n\n newFolder.mkdirs();\n Thread.sleep(1000);\n newFile.createNewFile();\n Thread.sleep(1000);\n FileDeleteStrategy.NORMAL.delete(newFolder);\n Thread.sleep(1000);\n FileDeleteStrategy.NORMAL.delete(newFile);\n Thread.sleep(1000);\n\n monitor.stop(10000);\n\n }catch(IOException e){\n System.out.println(e.getMessage());\n } catch(InterruptedException e){\n System.out.println(e.getMessage());\n }catch (Exception e) {\n System.out.println(e.getMessage());\n }\n }\n}"
},
{
"code": null,
"e": 42491,
"s": 42455,
"text": "It will print the following result."
},
{
"code": null,
"e": 42574,
"s": 42491,
"text": "Folder created: test\nFile created: test1\nFolder deleted: test\nFile deleted: test1\n"
},
{
"code": null,
"e": 42772,
"s": 42574,
"text": "Compare the names of two files. NameFileComparator can be used to sort lists or arrays of files using their name either in a case-sensitive, case-insensitive or system dependent case sensitive way."
},
{
"code": null,
"e": 42865,
"s": 42772,
"text": "Following is the declaration for org.apache.commons.io.comparator.NameFileComparator Class -"
},
{
"code": null,
"e": 42945,
"s": 42865,
"text": "public class NameFileComparator\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 42987,
"s": 42945,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 43036,
"s": 42987,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 43050,
"s": 43036,
"text": "IOTester.java"
},
{
"code": null,
"e": 43968,
"s": 43050,
"text": "import java.io.File;\nimport java.io.FileFilter;\nimport java.io.IOException;\n\nimport org.apache.commons.io.IOCase;\nimport org.apache.commons.io.comparator.NameFileComparator;\nimport org.apache.commons.io.filefilter.FileFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingNameFileComparator();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingNameFileComparator() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n\n NameFileComparator comparator = new NameFileComparator(IOCase.INSENSITIVE);\n\n File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));\n\n System.out.println(\"Sorted By Name: \");\n for(File file:sortedFiles){ \n System.out.println(file.getName());\n }\n }\n}"
},
{
"code": null,
"e": 44004,
"s": 43968,
"text": "It will print the following result."
},
{
"code": null,
"e": 44052,
"s": 44004,
"text": "Sorted By Name: \n.classpath\n.project\ninput.txt\n"
},
{
"code": null,
"e": 44222,
"s": 44052,
"text": "Compare the sizes of two files/directory. SizeFileComparator can be used to sort lists or arrays of files using their size or directories based on their no. of children."
},
{
"code": null,
"e": 44315,
"s": 44222,
"text": "Following is the declaration for org.apache.commons.io.comparator.SizeFileComparator Class -"
},
{
"code": null,
"e": 44395,
"s": 44315,
"text": "public class SizeFileComparator\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 44437,
"s": 44395,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 44486,
"s": 44437,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 44500,
"s": 44486,
"text": "IOTester.java"
},
{
"code": null,
"e": 45396,
"s": 44500,
"text": "import java.io.File;\nimport java.io.FileFilter;\nimport java.io.IOException;\n\nimport org.apache.commons.io.comparator.SizeFileComparator;\nimport org.apache.commons.io.filefilter.FileFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingSizeFileComparator();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingSizeFileComparator() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n\n SizeFileComparator comparator = new SizeFileComparator();\n\n File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));\n\n System.out.println(\"Sorted By Size: \");\n for(File file:sortedFiles){ \n System.out.println(file.getName() + \", size(kb) :\" + file.length());\n }\n }\n}"
},
{
"code": null,
"e": 45432,
"s": 45396,
"text": "It will print the following result."
},
{
"code": null,
"e": 45510,
"s": 45432,
"text": "Sorted By Size: \ninput.txt, size:124\n.project, size:382\n.classpath, size:441\n"
},
{
"code": null,
"e": 45683,
"s": 45510,
"text": "Compare the last modified dates of two files/directory. LastModifiedFileComparator can be used to sort lists or arrays of files/directories using their last modified dates."
},
{
"code": null,
"e": 45784,
"s": 45683,
"text": "Following is the declaration for org.apache.commons.io.comparator.LastModifiedFileComparator Class -"
},
{
"code": null,
"e": 45872,
"s": 45784,
"text": "public class LastModifiedFileComparator\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 45914,
"s": 45872,
"text": "Here is the input file we need to parse β"
},
{
"code": null,
"e": 45963,
"s": 45914,
"text": "Welcome to TutorialsPoint. Simply Easy Learning."
},
{
"code": null,
"e": 45977,
"s": 45963,
"text": "IOTester.java"
},
{
"code": null,
"e": 46969,
"s": 45977,
"text": "import java.io.File;\nimport java.io.FileFilter;\nimport java.io.IOException;\nimport java.util.Date;\n\nimport org.apache.commons.io.comparator.LastModifiedFileComparator;\nimport org.apache.commons.io.filefilter.FileFileFilter;\n\npublic class IOTester {\n public static void main(String[] args) {\n try{\n usingLastModifiedFileComparator();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingLastModifiedFileComparator() throws IOException {\n //get the current directory\n File currentDirectory = new File(\".\");\n\n LastModifiedFileComparator comparator = new LastModifiedFileComparator();\n\n File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));\n\n System.out.println(\"Sorted By Last Modified date: \");\n for(File file:sortedFiles){ \n System.out.println(file.getName() + \", Modified on: \" + new Date(file.lastModified()));\n }\n }\n}"
},
{
"code": null,
"e": 47005,
"s": 46969,
"text": "It will print the following result."
},
{
"code": null,
"e": 47196,
"s": 47005,
"text": "Sorted By Last Modified date: \n.project, Modified on: Thu Oct 12 19:06:45 IST 2017\n.classpath, Modified on: Mon Nov 20 13:09:55 IST 2017\ninput.txt, Modified on: Mon Nov 20 19:27:55 IST 2017\n"
},
{
"code": null,
"e": 47469,
"s": 47196,
"text": "It is an InputStream proxy that transparently writes a copy of all bytes read from the proxied stream to a given OutputStream. The proxied input stream is closed when the close() method on this proxy is called. It can be used to operate two streams collectively at a time."
},
{
"code": null,
"e": 47553,
"s": 47469,
"text": "Following is the declaration for org.apache.commons.io.input.TeeInputStream Class -"
},
{
"code": null,
"e": 47610,
"s": 47553,
"text": "public class TeeInputStream\n extends ProxyInputStream\n"
},
{
"code": null,
"e": 47714,
"s": 47610,
"text": "In this example, closing a TeeInputStream closes the TeeInputStream as well as TeeOutputStream objects."
},
{
"code": null,
"e": 47728,
"s": 47714,
"text": "IOTester.java"
},
{
"code": null,
"e": 49383,
"s": 47728,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\n\nimport org.apache.commons.io.input.TeeInputStream;\nimport org.apache.commons.io.output.TeeOutputStream;\n\npublic class IOTester {\n private static final String SAMPLE = \"Welcome to TutorialsPoint. Simply Easy Learning.\";\n\n public static void main(String[] args) {\n try{\n usingTeeInputStream();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n public static void usingTeeInputStream() throws IOException {\n TeeInputStream teeInputStream = null;\n TeeOutputStream teeOutputStream = null;\n try {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes(\"US-ASCII\"));\n ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();\n ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();\n\n teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);\n teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);\n teeInputStream.read(new byte[SAMPLE.length()]);\n\n System.out.println(\"Output stream 1: \" + outputStream1.toString());\n System.out.println(\"Output stream 2: \" + outputStream2.toString());\n\n } catch (IOException e) {\n System.out.println(e.getMessage());\n } finally {\n //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2. \n try { \n teeInputStream.close(); \n }\n catch (IOException e) { \n System.out.println(e.getMessage());\n }\n }\n }\n}"
},
{
"code": null,
"e": 49419,
"s": 49383,
"text": "It will print the following result."
},
{
"code": null,
"e": 49552,
"s": 49419,
"text": "Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.\nOutput stream 2: Welcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 49681,
"s": 49552,
"text": "TeeOutputStream splits OutputStream. It is named after the unix 'tee' command. It allows a stream to be branched to two streams."
},
{
"code": null,
"e": 49767,
"s": 49681,
"text": "Following is the declaration for org.apache.commons.io.output.TeeOutputStream Class -"
},
{
"code": null,
"e": 49825,
"s": 49767,
"text": "public class TeeOutputStream\n extends ProxyOutputStream"
},
{
"code": null,
"e": 49967,
"s": 49825,
"text": "In this example, TeeOutputStream accepts two output streams as parameter and passing data to TeeOutputStream set data to both output streams."
},
{
"code": null,
"e": 49981,
"s": 49967,
"text": "IOTester.java"
},
{
"code": null,
"e": 51635,
"s": 49981,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\n\nimport org.apache.commons.io.input.TeeInputStream;\nimport org.apache.commons.io.output.TeeOutputStream;\n\npublic class IOTester {\n private static final String SAMPLE = \"Welcome to TutorialsPoint. Simply Easy Learning.\";\n public static void main(String[] args) {\n try{\n usingTeeInputStream();\n }catch(IOException e){\n System.out.println(e.getMessage());\n }\n }\n public static void usingTeeInputStream() throws IOException {\n TeeInputStream teeInputStream = null;\n TeeOutputStream teeOutputStream = null;\n try {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes(\"US-ASCII\"));\n ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();\n ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();\n\n teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);\n teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);\n teeInputStream.read(new byte[SAMPLE.length()]);\n\n System.out.println(\"Output stream 1: \" + outputStream1.toString());\n System.out.println(\"Output stream 2: \" + outputStream2.toString());\n\n } catch (IOException e) {\n System.out.println(e.getMessage());\n } finally {\n //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2. \n try { \n teeInputStream.close(); \n }\n catch (IOException e) { \n System.out.println(e.getMessage());\n }\n }\n }\n}"
},
{
"code": null,
"e": 51671,
"s": 51635,
"text": "It will print the following result."
},
{
"code": null,
"e": 51804,
"s": 51671,
"text": "Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.\nOutput stream 2: Welcome to TutorialsPoint. Simply Easy Learning.\n"
},
{
"code": null,
"e": 51811,
"s": 51804,
"text": " Print"
},
{
"code": null,
"e": 51822,
"s": 51811,
"text": " Add Notes"
}
] |
Material Design Buttons in Android with Example - GeeksforGeeks | 02 Sep, 2020
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Buttons. A Button is a user interface that is used to perform some action when clicked or tapped. Under the Button category, there are mainly 4 types of buttons in Google material design components:
Contained ButtonOutlined ButtonText ButtonToggle Button
Contained Button
Outlined Button
Text Button
Toggle Button
Below is a demo for all types of Buttons that we are going to create in this project.
Before going to implement all types of Button letβs understand why choosing these material components over ordinary inbuilt components in android? Please refer to the following points to understand this.
Choosing these material components saves time and these make the app look more like materially designed, and makes the way for user interactions hassle-free for developers.If we take the buttons as an example we need to create a ripple as root element in custom_button.xml inside the drawable and then we need to set the background of the button as custom_button.xml, then only it will create the ripple effect for the ordinary button. But in Google MDCs there is no need of creating the manual ripple layout for the buttons.And the main thing about the Google Material Design Components is that these are open source and free. If you wish to contribute to the Google MDCs Click Here.One more thing great about the Google Material Design Components is that they support for cross-platform that includes Android, IOS, Flutter, Web applications.If the user wants to switch their system theme to Dark Theme, then the Google MDCs will automatically adapt and change their color and background to match the Dark Theme. But in the case of ordinary widgets, they wonβt get adapt to the system theme change. The differences between the normal button and the Google MDC button when the dark theme is enabled is shown below:
Choosing these material components saves time and these make the app look more like materially designed, and makes the way for user interactions hassle-free for developers.
If we take the buttons as an example we need to create a ripple as root element in custom_button.xml inside the drawable and then we need to set the background of the button as custom_button.xml, then only it will create the ripple effect for the ordinary button. But in Google MDCs there is no need of creating the manual ripple layout for the buttons.
And the main thing about the Google Material Design Components is that these are open source and free. If you wish to contribute to the Google MDCs Click Here.
One more thing great about the Google Material Design Components is that they support for cross-platform that includes Android, IOS, Flutter, Web applications.
If the user wants to switch their system theme to Dark Theme, then the Google MDCs will automatically adapt and change their color and background to match the Dark Theme. But in the case of ordinary widgets, they wonβt get adapt to the system theme change. The differences between the normal button and the Google MDC button when the dark theme is enabled is shown below:
Normal Contained Button behavior under dark theme.
Google MDC button behavior under dark theme.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Include google material design components dependency in the build.gradle file. After adding the dependencies donβt forget to click on the βSync Nowβ button present at the top right corner.
implementation βcom.google.android.material:material:1.3.0-alpha02β
Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.
Go to app -> src -> main -> res -> values -> styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles.
Why the theme needs to be changed:
Letβs discuss why we need to change the action bar theme to the material theme of the app to invoke all the Google MDC widgets in our android application:
Because all the Google material design components are built and packaged inside the MaterialTheme for Android.If you are invoking the AppCompat action bar theme you will not end up with the error, but the application crashes immediately after launching it. Below is the code for the styles.xml file.
Because all the Google material design components are built and packaged inside the MaterialTheme for Android.
If you are invoking the AppCompat action bar theme you will not end up with the error, but the application crashes immediately after launching it. Below is the code for the styles.xml file.
styles.xml
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Customize your theme here --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
If you are unable to get the things in the step mentioned above you may refer to this image.
One can change the color combination of the application and itβs an optional step. Go to app -> src -> main -> res -> colors.xml file and choose your color combination.
colors.xml
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0f9d58</color> <color name="colorPrimaryDark">#006d2d</color> <color name="colorAccent">#55cf86</color></resources>
If you are unable to get the things in the step mentioned above you may refer to this image.
Now in this file, we are going to design the material button as the user requirements. Note that for each of the Button styles the βstyleβ attribute is different.
A. Button Style 1: Contained Button
Contained buttons are high-emphasis, distinguished by their use of elevation and fill. They contain actions that are primary to the app. Note that the contained button is the default style if the style is not set. Below is the XML code for the contained button.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="ExtraText"> <!-- Since this is the default type, you don't need to specify a style tag as long as you are using a Material Components Theme --> <Button android:id="+id/contained_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Contained Button" android:textAllCaps="false" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
B. Button Style 2: Outlined Button
Outlined buttons are medium-emphasis buttons. They contain actions that are important but arenβt the primary action in an app. These are used for more emphasis than text buttons due to the stroke. Below is the XML code for the Outlined button.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="ExtraText"> <!--style attribute below is to be invoked for outlined button--> <Button android:id="@+id/outlined_button" style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Outlined Button" android:textAllCaps="false" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
C. Button Style 3: Text Button
Text buttons are typically used for less-pronounced actions, including those located in dialogs and cards. In cards, text buttons help maintain an emphasis on card content. These are typically used for less important actions. Below is the XML code for the Text button.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="ExtraText"> <!--style attribute below is to be invoked for text button--> <Button android:id="@+id/text_button" style="@style/Widget.MaterialComponents.Button.TextButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text Button" android:textAllCaps="false" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
D. Button Style 4: Toggle Button
Toggle buttons group a set of actions using layout and spacing. Theyβre used less often than other button types. There are 2 types of Toggle Buttons in Google Material Design Components.
Toggle Button
Toggle Button with icons
Before going to the design part do some pre-task to implement these two buttons. As now the styles and the attributes like padding and margin of the buttons in the toggle group needs to be changed so in the values folder open styles.xml and invoke the following code:
XML
<resources> <!-- Base application theme --> <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <!--these attributes and styles are only effected for the MaterialButtonToggleGroup widget--> <style name="Widget.App.Button.OutlinedButton.IconOnly" parent="Widget.MaterialComponents.Button.OutlinedButton"> <item name="iconPadding">0dp</item> <item name="android:insetTop">0dp</item> <item name="android:insetBottom">0dp</item> <item name="android:paddingLeft">12dp</item> <item name="android:paddingRight">12dp</item> <item name="android:minWidth">48dp</item> <item name="android:minHeight">48dp</item> </style> </resources>
Toggle Button:
To emphasize groups of related toggle buttons, a group should share a common container. Below is the XML code for the Toggle button.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="ExtraText"> <!--attribution of google MDC toggle button is little different from normal toggle button Instead of invoking ToggleButton you should invoke com.google.android.material.button.MaterialButtonToggleGroup as you can see below--> <com.google.android.material.button.MaterialButtonToggleGroup android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <Button android:id="@+id/button1" style="?attr/materialButtonOutlinedStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" /> <Button android:id="@+id/button2" style="?attr/materialButtonOutlinedStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 2" /> <Button android:id="@+id/button3" style="?attr/materialButtonOutlinedStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 3" /> </com.google.android.material.button.MaterialButtonToggleGroup> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Toggle Button with icons:
To implement the toggle button with icons only import the icons in the drawable folder. In this example, we have imported format_black, format_italic, format_underline icons. To import the icons right-click on the drawable folder, goto new, and select Vector Asset as shown below.
After clicking on Vector Asset select the icon you want to import to the drawable folder as shown below.
After importing the desired icons invoke the code in the activity_main.xml file. Below is the XML code for the Toggle button with icons.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="ExtraText"> <!--this implementation does not creates individual toggle button it groups them together--> <com.google.android.material.button.MaterialButtonToggleGroup android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <Button android:id="@+id/bold_button" style="@style/Widget.App.Button.OutlinedButton.IconOnly" android:layout_width="wrap_content" android:layout_height="wrap_content" app:icon="@drawable/ic_format_bold_black_24dp" /> <Button android:id="@+id/italic_button" style="@style/Widget.App.Button.OutlinedButton.IconOnly" android:layout_width="wrap_content" android:layout_height="wrap_content" app:icon="@drawable/ic_format_underlined_black_24dp" /> <Button android:id="@+id/underline_button" style="@style/Widget.App.Button.OutlinedButton.IconOnly" android:layout_width="wrap_content" android:layout_height="wrap_content" app:icon="@drawable/ic_format_italic_black_24dp" /> </com.google.android.material.button.MaterialButtonToggleGroup> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
For more information and more components like alert dialogue, SnackBars, etc., you may refer to the official documentation here. For more other resources and for more themes and customization you may visit and refer this.
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Navigation Drawer in Android
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to View and Locate SQLite Database in Android Studio?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example | [
{
"code": null,
"e": 25095,
"s": 25067,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 25872,
"s": 25095,
"text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Buttons. A Button is a user interface that is used to perform some action when clicked or tapped. Under the Button category, there are mainly 4 types of buttons in Google material design components:"
},
{
"code": null,
"e": 25928,
"s": 25872,
"text": "Contained ButtonOutlined ButtonText ButtonToggle Button"
},
{
"code": null,
"e": 25945,
"s": 25928,
"text": "Contained Button"
},
{
"code": null,
"e": 25961,
"s": 25945,
"text": "Outlined Button"
},
{
"code": null,
"e": 25973,
"s": 25961,
"text": "Text Button"
},
{
"code": null,
"e": 25987,
"s": 25973,
"text": "Toggle Button"
},
{
"code": null,
"e": 26073,
"s": 25987,
"text": "Below is a demo for all types of Buttons that we are going to create in this project."
},
{
"code": null,
"e": 26277,
"s": 26073,
"text": "Before going to implement all types of Button letβs understand why choosing these material components over ordinary inbuilt components in android? Please refer to the following points to understand this."
},
{
"code": null,
"e": 27492,
"s": 26277,
"text": "Choosing these material components saves time and these make the app look more like materially designed, and makes the way for user interactions hassle-free for developers.If we take the buttons as an example we need to create a ripple as root element in custom_button.xml inside the drawable and then we need to set the background of the button as custom_button.xml, then only it will create the ripple effect for the ordinary button. But in Google MDCs there is no need of creating the manual ripple layout for the buttons.And the main thing about the Google Material Design Components is that these are open source and free. If you wish to contribute to the Google MDCs Click Here.One more thing great about the Google Material Design Components is that they support for cross-platform that includes Android, IOS, Flutter, Web applications.If the user wants to switch their system theme to Dark Theme, then the Google MDCs will automatically adapt and change their color and background to match the Dark Theme. But in the case of ordinary widgets, they wonβt get adapt to the system theme change. The differences between the normal button and the Google MDC button when the dark theme is enabled is shown below:"
},
{
"code": null,
"e": 27665,
"s": 27492,
"text": "Choosing these material components saves time and these make the app look more like materially designed, and makes the way for user interactions hassle-free for developers."
},
{
"code": null,
"e": 28019,
"s": 27665,
"text": "If we take the buttons as an example we need to create a ripple as root element in custom_button.xml inside the drawable and then we need to set the background of the button as custom_button.xml, then only it will create the ripple effect for the ordinary button. But in Google MDCs there is no need of creating the manual ripple layout for the buttons."
},
{
"code": null,
"e": 28179,
"s": 28019,
"text": "And the main thing about the Google Material Design Components is that these are open source and free. If you wish to contribute to the Google MDCs Click Here."
},
{
"code": null,
"e": 28339,
"s": 28179,
"text": "One more thing great about the Google Material Design Components is that they support for cross-platform that includes Android, IOS, Flutter, Web applications."
},
{
"code": null,
"e": 28711,
"s": 28339,
"text": "If the user wants to switch their system theme to Dark Theme, then the Google MDCs will automatically adapt and change their color and background to match the Dark Theme. But in the case of ordinary widgets, they wonβt get adapt to the system theme change. The differences between the normal button and the Google MDC button when the dark theme is enabled is shown below:"
},
{
"code": null,
"e": 28762,
"s": 28711,
"text": "Normal Contained Button behavior under dark theme."
},
{
"code": null,
"e": 28808,
"s": 28762,
"text": "Google MDC button behavior under dark theme. "
},
{
"code": null,
"e": 28920,
"s": 28808,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. "
},
{
"code": null,
"e": 29111,
"s": 28920,
"text": "Include google material design components dependency in the build.gradle file. After adding the dependencies donβt forget to click on the βSync Nowβ button present at the top right corner. "
},
{
"code": null,
"e": 29179,
"s": 29111,
"text": "implementation βcom.google.android.material:material:1.3.0-alpha02β"
},
{
"code": null,
"e": 29350,
"s": 29179,
"text": "Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below."
},
{
"code": null,
"e": 29605,
"s": 29350,
"text": "Go to app -> src -> main -> res -> values -> styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles."
},
{
"code": null,
"e": 29640,
"s": 29605,
"text": "Why the theme needs to be changed:"
},
{
"code": null,
"e": 29795,
"s": 29640,
"text": "Letβs discuss why we need to change the action bar theme to the material theme of the app to invoke all the Google MDC widgets in our android application:"
},
{
"code": null,
"e": 30095,
"s": 29795,
"text": "Because all the Google material design components are built and packaged inside the MaterialTheme for Android.If you are invoking the AppCompat action bar theme you will not end up with the error, but the application crashes immediately after launching it. Below is the code for the styles.xml file."
},
{
"code": null,
"e": 30206,
"s": 30095,
"text": "Because all the Google material design components are built and packaged inside the MaterialTheme for Android."
},
{
"code": null,
"e": 30396,
"s": 30206,
"text": "If you are invoking the AppCompat action bar theme you will not end up with the error, but the application crashes immediately after launching it. Below is the code for the styles.xml file."
},
{
"code": null,
"e": 30407,
"s": 30396,
"text": "styles.xml"
},
{
"code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Customize your theme here --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> </resources>",
"e": 30795,
"s": 30407,
"text": null
},
{
"code": null,
"e": 30888,
"s": 30795,
"text": "If you are unable to get the things in the step mentioned above you may refer to this image."
},
{
"code": null,
"e": 31058,
"s": 30888,
"text": "One can change the color combination of the application and itβs an optional step. Go to app -> src -> main -> res -> colors.xml file and choose your color combination. "
},
{
"code": null,
"e": 31069,
"s": 31058,
"text": "colors.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0f9d58</color> <color name=\"colorPrimaryDark\">#006d2d</color> <color name=\"colorAccent\">#55cf86</color></resources>",
"e": 31272,
"s": 31069,
"text": null
},
{
"code": null,
"e": 31367,
"s": 31272,
"text": " If you are unable to get the things in the step mentioned above you may refer to this image. "
},
{
"code": null,
"e": 31530,
"s": 31367,
"text": "Now in this file, we are going to design the material button as the user requirements. Note that for each of the Button styles the βstyleβ attribute is different."
},
{
"code": null,
"e": 31566,
"s": 31530,
"text": "A. Button Style 1: Contained Button"
},
{
"code": null,
"e": 31828,
"s": 31566,
"text": "Contained buttons are high-emphasis, distinguished by their use of elevation and fill. They contain actions that are primary to the app. Note that the contained button is the default style if the style is not set. Below is the XML code for the contained button."
},
{
"code": null,
"e": 31832,
"s": 31828,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"ExtraText\"> <!-- Since this is the default type, you don't need to specify a style tag as long as you are using a Material Components Theme --> <Button android:id=\"+id/contained_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Contained Button\" android:textAllCaps=\"false\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 32862,
"s": 31832,
"text": null
},
{
"code": null,
"e": 32873,
"s": 32862,
"text": "Output UI:"
},
{
"code": null,
"e": 32908,
"s": 32873,
"text": "B. Button Style 2: Outlined Button"
},
{
"code": null,
"e": 33152,
"s": 32908,
"text": "Outlined buttons are medium-emphasis buttons. They contain actions that are important but arenβt the primary action in an app. These are used for more emphasis than text buttons due to the stroke. Below is the XML code for the Outlined button."
},
{
"code": null,
"e": 33156,
"s": 33152,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"ExtraText\"> <!--style attribute below is to be invoked for outlined button--> <Button android:id=\"@+id/outlined_button\" style=\"@style/Widget.MaterialComponents.Button.OutlinedButton.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Outlined Button\" android:textAllCaps=\"false\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 34175,
"s": 33156,
"text": null
},
{
"code": null,
"e": 34186,
"s": 34175,
"text": "Output UI:"
},
{
"code": null,
"e": 34217,
"s": 34186,
"text": "C. Button Style 3: Text Button"
},
{
"code": null,
"e": 34487,
"s": 34217,
"text": "Text buttons are typically used for less-pronounced actions, including those located in dialogs and cards. In cards, text buttons help maintain an emphasis on card content. These are typically used for less important actions. Below is the XML code for the Text button."
},
{
"code": null,
"e": 34491,
"s": 34487,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"ExtraText\"> <!--style attribute below is to be invoked for text button--> <Button android:id=\"@+id/text_button\" style=\"@style/Widget.MaterialComponents.Button.TextButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Text Button\" android:textAllCaps=\"false\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 35489,
"s": 34491,
"text": null
},
{
"code": null,
"e": 35500,
"s": 35489,
"text": "Output UI:"
},
{
"code": null,
"e": 35533,
"s": 35500,
"text": "D. Button Style 4: Toggle Button"
},
{
"code": null,
"e": 35721,
"s": 35533,
"text": "Toggle buttons group a set of actions using layout and spacing. Theyβre used less often than other button types. There are 2 types of Toggle Buttons in Google Material Design Components. "
},
{
"code": null,
"e": 35735,
"s": 35721,
"text": "Toggle Button"
},
{
"code": null,
"e": 35760,
"s": 35735,
"text": "Toggle Button with icons"
},
{
"code": null,
"e": 36028,
"s": 35760,
"text": "Before going to the design part do some pre-task to implement these two buttons. As now the styles and the attributes like padding and margin of the buttons in the toggle group needs to be changed so in the values folder open styles.xml and invoke the following code:"
},
{
"code": null,
"e": 36032,
"s": 36028,
"text": "XML"
},
{
"code": "<resources> <!-- Base application theme --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> <!--these attributes and styles are only effected for the MaterialButtonToggleGroup widget--> <style name=\"Widget.App.Button.OutlinedButton.IconOnly\" parent=\"Widget.MaterialComponents.Button.OutlinedButton\"> <item name=\"iconPadding\">0dp</item> <item name=\"android:insetTop\">0dp</item> <item name=\"android:insetBottom\">0dp</item> <item name=\"android:paddingLeft\">12dp</item> <item name=\"android:paddingRight\">12dp</item> <item name=\"android:minWidth\">48dp</item> <item name=\"android:minHeight\">48dp</item> </style> </resources>",
"e": 37013,
"s": 36032,
"text": null
},
{
"code": null,
"e": 37028,
"s": 37013,
"text": "Toggle Button:"
},
{
"code": null,
"e": 37162,
"s": 37028,
"text": "To emphasize groups of related toggle buttons, a group should share a common container. Below is the XML code for the Toggle button. "
},
{
"code": null,
"e": 37166,
"s": 37162,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"ExtraText\"> <!--attribution of google MDC toggle button is little different from normal toggle button Instead of invoking ToggleButton you should invoke com.google.android.material.button.MaterialButtonToggleGroup as you can see below--> <com.google.android.material.button.MaterialButtonToggleGroup android:id=\"@+id/toggleButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <Button android:id=\"@+id/button1\" style=\"?attr/materialButtonOutlinedStyle\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Button 1\" /> <Button android:id=\"@+id/button2\" style=\"?attr/materialButtonOutlinedStyle\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Button 2\" /> <Button android:id=\"@+id/button3\" style=\"?attr/materialButtonOutlinedStyle\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Button 3\" /> </com.google.android.material.button.MaterialButtonToggleGroup> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 39065,
"s": 37166,
"text": null
},
{
"code": null,
"e": 39076,
"s": 39065,
"text": "Output UI:"
},
{
"code": null,
"e": 39102,
"s": 39076,
"text": "Toggle Button with icons:"
},
{
"code": null,
"e": 39383,
"s": 39102,
"text": "To implement the toggle button with icons only import the icons in the drawable folder. In this example, we have imported format_black, format_italic, format_underline icons. To import the icons right-click on the drawable folder, goto new, and select Vector Asset as shown below."
},
{
"code": null,
"e": 39488,
"s": 39383,
"text": "After clicking on Vector Asset select the icon you want to import to the drawable folder as shown below."
},
{
"code": null,
"e": 39625,
"s": 39488,
"text": "After importing the desired icons invoke the code in the activity_main.xml file. Below is the XML code for the Toggle button with icons."
},
{
"code": null,
"e": 39629,
"s": 39625,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"ExtraText\"> <!--this implementation does not creates individual toggle button it groups them together--> <com.google.android.material.button.MaterialButtonToggleGroup android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <Button android:id=\"@+id/bold_button\" style=\"@style/Widget.App.Button.OutlinedButton.IconOnly\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:icon=\"@drawable/ic_format_bold_black_24dp\" /> <Button android:id=\"@+id/italic_button\" style=\"@style/Widget.App.Button.OutlinedButton.IconOnly\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:icon=\"@drawable/ic_format_underlined_black_24dp\" /> <Button android:id=\"@+id/underline_button\" style=\"@style/Widget.App.Button.OutlinedButton.IconOnly\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:icon=\"@drawable/ic_format_italic_black_24dp\" /> </com.google.android.material.button.MaterialButtonToggleGroup> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 41476,
"s": 39629,
"text": null
},
{
"code": null,
"e": 41487,
"s": 41476,
"text": "Output UI:"
},
{
"code": null,
"e": 41709,
"s": 41487,
"text": "For more information and more components like alert dialogue, SnackBars, etc., you may refer to the official documentation here. For more other resources and for more themes and customization you may visit and refer this."
},
{
"code": null,
"e": 41717,
"s": 41709,
"text": "android"
},
{
"code": null,
"e": 41725,
"s": 41717,
"text": "Android"
},
{
"code": null,
"e": 41733,
"s": 41725,
"text": "Android"
},
{
"code": null,
"e": 41831,
"s": 41733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41840,
"s": 41831,
"text": "Comments"
},
{
"code": null,
"e": 41853,
"s": 41840,
"text": "Old Comments"
},
{
"code": null,
"e": 41911,
"s": 41853,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 41954,
"s": 41911,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 41985,
"s": 41954,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 42027,
"s": 41985,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 42056,
"s": 42027,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 42095,
"s": 42056,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 42145,
"s": 42095,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 42203,
"s": 42145,
"text": "How to View and Locate SQLite Database in Android Studio?"
},
{
"code": null,
"e": 42254,
"s": 42203,
"text": "How to Post Data to API using Retrofit in Android?"
}
] |
This Is How Twitter Sees The World : Sentiment Analysis Part One | by Ronald Wahome | Towards Data Science | Twitter is an online social network with over 330 million active monthly users as of February 2018. Users on twitter create short messages called tweets to be shared with other twitter users who interact by retweeting and responding. Twitter employs a message size restriction of 280 characters or less which forces the users to stay focused on the message they wish to disseminate. This very characteristic makes messages on twitter very good candidates for the Machine Learning (ML) task of sentiment analysis. Sentiment Analysis falls under Natural Language Processing (NLP) which is a branch of ML that deals with how computers process and analyze human language.
The training data was obtained from Sentiment140 and is made up of about 1.6 million random tweets with corresponding binary labels. 0 for Negative sentiment and 1 for Positive sentiment. In this blog post, weβll use a Naive Bayes Classifier to learn the correct labels from this training set and do a binary classification. In a nut shell, the Naive Bayes theorem calculates the probability of a certain event happening based on the joint probabilistic distributions of certain other events. I downloaded the test dataset using twitterβs API and will be use to test the modelβs real world performance. Full documentation and terms of the API are available at developer.twitter.com/en/docs.
In the first section of this blog post weβll go through standard preprocessing steps performed on text data for a sentiment analysis ML task. The second section is covered in a subsequent blog post where we combine the preprocessing into one step within a ML pipeline. This first post goes through the trouble of explaining what is happening under the hood when we use a pipeline to handle preprocessing.
Weβll use Jupyter Notebook with Python for our workflow.
Import the python libraries used in this project.
Import the data to a pandas dataframe and do some exploratory data analysis.
# you can see the full list of imports on GitHub!# Machine Learning importsimport nltkfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_scorefrom sklearn.naive_bayes import MultinomialNBfrom sklearn.model_selection import KFold, cross_val_scorefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.model_selection import GridSearchCVfrom sklearn.externals import joblibfrom nltk.corpus import stopwordsfrom nltk.tokenize import TweetTokenizerfrom nltk.stem.wordnet import WordNetLemmatizerLoad training dataset to Pandas and preview the top rows.
# load train datadata = pd.read_csv('Sentiment Analysis Dataset.csv', error_bad_lines=False)data.columns = ['id','label','source','text']data.head(2)# get text and matching label columnsdata = data.drop(['id','source'],axis=1)data.head(10)
We can observe that the data is indeed from tweet messages posted on twitter.
The labels and the text do not seem to be in any listed order. This can be a problem if data is not randomly distributed as it can introduce biases to a learning model. In any case, we are going to use the Scikit Learn library which has a function to split our training and testing data and shuffle the data at the same time.
Shuffling data reduces variance and makes sure our model can generalize better on the data and do less overfitting. We want to make sure the train and test dataset are representative of the overall distribution of the data.
To that note, we also want to check the label frequency distribution in the data which is done below.
Another observation we can make is that the text contains varying formats. Some words contain mixed case letters which need to be normalized to their base word. e.g.: βCRyβ changed to βcryβ.
Leaving words with first letter capitalized can be experimented with as they may hold a different feature space like the name of a person or country etc.
Explore distribution of label types.
# check the number of positive vs. negative tagged sentencespositives = data['label'][data.label == 0]negatives = data['label'][data.label == 1]print('number of positve tagged sentences is: {}'.format(len(positives)))print('number of negative tagged sentences is: {}'.format(len(negatives)))print('total length of the data is: {}'.format(data.shape[0]))
Considering the size of the dataset, the labels seem to be βaboutβ evenly distributed at 788435 vs. 790177 for positive and negative respectively.
Next, we want to see the number of words contained in every sentence so I created a function to extract this information and appended it to a column next to the text column. Below is a sample output.
# get a word count per sentence columndef word_count(sentence): return len(sentence.split()) data['word count'] = data['text'].apply(word_count)data.head(3)
# plot word count distribution for both positive and negative sentimentsx = data['word count'][data.label == 1]y = data['word count'][data.label == 0]plt.figure(figsize=(12,6))plt.xlim(0,45)plt.xlabel('word count')plt.ylabel('frequency')g = plt.hist([x, y], color=['r','b'], alpha=0.5, label=['positive','negative'])plt.legend(loc='upper right')
From the graph above, most sentences fall between 5β10 words but itβs fair to say that majority of text on twitter falls between 1 and 25 words. This is no wonder considering that twitter has a limit of how many characters one can use in a message. 280 characters is the limit at the time of this writing.
In all, it looks like 1β20 words covers more than 80% of all sentences which makes this dataset set a good training candidate.
There are more positive sentences with 5 words or less than there are negative ones which does not seem like a big enough difference to cause any concern at the moment.
# get most common words in training datasetall_words = []for line in list(data['text']): words = line.split() for word in words: all_words.append(word.lower()) Counter(all_words).most_common(10)
Output below:
[('i', 741876), ('to', 556149), ('the', 516654), ('a', 374024), ('my', 309966), ('and', 294805), ('you', 236109), ('is', 229444), ('for', 212852), ('in', 209009)]
In the cell above we extracted the most common words in the dataset and listed the top ten.
Perhaps to no surprise we encounter words like i, and and is as they are very highly used in human expressions. These kind of words usually appear equally in both negative and positive oriented expressions and as such they bring very little information that can be incorporated in the model so we will have to get rid of them down the road.
In the text preprocessing steps later on we will learn how to deal with these common words that donβt add much to the feature space.
Below is a code to output a graph showing the frequency of the first 25 words.
# plot word frequency distribution of first few wordsplt.figure(figsize=(12,5))plt.title('Top 25 most common words')plt.xticks(fontsize=13, rotation=90)fd = nltk.FreqDist(all_words)fd.plot(25,cumulative=False)# log-log plotword_counts = sorted(Counter(all_words).values(), reverse=True)plt.figure(figsize=(12,5))plt.loglog(word_counts, linestyle='-', linewidth=1.5)plt.ylabel("Freq")plt.xlabel("Word Rank")plt.title('log-log plot of words frequency')
I also created a log-log plot for the words frequency which is similar to the previous frequency graph but includes all words and is plotted on a base 10 logarithmic scale which helps us visualize the rapidly diminishing frequency of words as their rank drops.
The word distribution present in this data dictionary is a very common phenomenon in large samples of words as shown by Zipfβs law where the most frequent word will occur about twice as often as the second most frequent word, three times as often as the third most frequent word, etc.
It would be interesting to see if this holds true after we remove words like i, and and is from the observation above.
After training the model we make sentiment predictions on the raw twitter data but before we can do that, we need to download and do some basic data cleaning. You download tweets off the twitter RESTful API by keyword and get a stream of historical tweets back along with the metadata. I used Tweepy which is a python wrapper library for the twitter API that gives you more control on how you query the API. You can see the code on GitHub.
The keyword used to download historical tweets was βPaul Ryanβ who is the speaker of the US House of Representative at the time of writing. My choice for this keyword is arbitrary but I feel is good enough to return some polarizing tweets. This is important because the tweets themselves can act as their own benchmark. One of the obstacles of NLP is evaluating a modelβs performance considering that language is relative and always changing.
Import and preview raw data.
# create column namescol_names=['date','user_loc','followers','friends','message','bbox_coords',\ 'full_name','country','country_code','place_type']# read csvdf_twtr = pd.read_csv('paul_ryan_twitter.csv', names=col_names)# check headdf_twtr.head()
Weβll keep the location data and use it later to map out our results on a geographic map.
We want to remove any unnecessary qualities in the data which would make the trained model a poor generalizer.
Text preprocessing involves many things like removing emojis, properly formatting the text to remove extra spaces or any other information in the text that we donβt believe would add information to our model. Weβll see some examples below.
We also have to make sure that the information we pass the model is in a format that computers can understand. Weβll also go through some of these steps below.
After this pre-processing step, our data should be ready to use for a machine learning classification task.
NOTE : Whatever text preprocessing we do on the train data must also be done on the test and our raw data.
This step is one that we could spend a lot of time on but the goal is always to find the best balance.
The bulk of the work in NLP is done on feature engineering. For now we will get rid of the links and emoji characters. It is important to mention that we can use them as features but for now weβre just building a basic model.
I created a function that uses regex to do bulk formatting for every tweet in the dataset. Sample output is included under the code.
# helper function to clean tweetsdef processTweet(tweet): # Remove HTML special entities (e.g. &) tweet = re.sub(r'\&\w*;', '', tweet) #Convert @username to AT_USER tweet = re.sub('@[^\s]+','',tweet) # Remove tickers tweet = re.sub(r'\$\w*', '', tweet) # To lowercase tweet = tweet.lower() # Remove hyperlinks tweet = re.sub(r'https?:\/\/.*\/\w*', '', tweet) # Remove hashtags tweet = re.sub(r'#\w*', '', tweet) # Remove Punctuation and split 's, 't, 've with a space for filter tweet = re.sub(r'[' + punctuation.replace('@', '') + ']+', ' ', tweet) # Remove words with 2 or fewer letters tweet = re.sub(r'\b\w{1,2}\b', '', tweet) # Remove whitespace (including new line characters) tweet = re.sub(r'\s\s+', ' ', tweet) # Remove single space remaining at the front of the tweet. tweet = tweet.lstrip(' ') # Remove characters beyond Basic Multilingual Plane (BMP) of Unicode: tweet = ''.join(c for c in tweet if c <= '\uFFFF') return tweet# ______________________________________________________________# clean dataframe's text columndf_paulry['message'] = df_paulry['message'].apply(processTweet)# preview some cleaned tweetsdf_paulry['message'].head()
Also note that you cannot have a perfect set of clean up steps as some cleanup steps will ultimately introduce some flaws in the data.
Below is a before and after example where βreβ has been removed from re-election which alters the meaning of the word and perhaps the userβs intended meaning. The word wonβt also changes to won which obviously has a totally different meaning.
We drop duplicate tweets as they bring no new information to the dataset and are also computationally inefficient. We also visualize the most common words in the corpus.
# most common words in twitter datasetall_words = []for line in list(df_paulry['message']): words = line.split() for word in words: all_words.append(word.lower())# plot word frequency distribution of first few wordsplt.figure(figsize=(12,5))plt.xticks(fontsize=13, rotation=90)fd = nltk.FreqDist(all_words)fd.plot(25,cumulative=False)# log-log of all words word_counts = sorted(Counter(all_words).values(), reverse=True)plt.figure(figsize=(12,5))plt.loglog(word_counts, linestyle='-', linewidth=1.5)plt.ylabel("Freq")plt.xlabel("Word Rank")
Our training data has now been transformed into a much leaner body of text that is much cleaner for feature extraction. As we mentioned before, we do have some words in the dataset that are common in natural human language but used in most sentence compositions that we would be better left off since they bring no useful features to our model.
These words are commonly known as stop-words in NLP and the NLTK library comes with a function that can filter out these words from the dataset. Below is the actual words contained in the stop_words list. We can also make our own special list of stop words to fit any unique case. For example if you are doing sentiment analysis on law documents, you would probably need a special set considering the law jargon contained is unique in nature.
# show stop words examples("i , me , my , myself , we , our , ours , ourselves , you , you're , you've , you'll , you'd , your , yours , yourself , yourselves , he , him , his , himself , she , her , hers , herself , it ")
After removing stop-words we split all the sentences in the dataset to get individual words (tokens) which is basically a list of words per sentence contained in the newly processed tweet. Now we can see that we have two new columns in the dataframe that contains these tokenized versions of a tweet.
A sample output is included below.
# tokenize helper functiondef text_process(raw_text): """ Takes in a string of text, then performs the following: 1. Remove all punctuation 2. Remove all stopwords 3. Returns a list of the cleaned text """ # Check characters to see if they are in punctuation nopunc = [char for char in list(raw_text) if char not in string.punctuation] # Join the characters again to form the string. nopunc = ''.join(nopunc) # Now just remove any stopwords return [word for word in nopunc.lower().split() if word.lower() not in stopwords.words('english')]def remove_words(word_list): remove = ['paul','ryan','...','β','β','β','...','ryanβ'] return [w for w in word_list if w not in remove]# -------------------------------------------# tokenize message column and create a column for tokensdf_paulry = df_paulry.copy()df_paulry['tokens'] = df_paulry['message'].apply(text_process) # tokenize style 1df_paulry['no_pauls'] = df_paulry['tokens'].apply(remove_words) #tokenize style 2df_paulry.head()
There are additional normalization techniques like stemming and lemmatizing that we can try on our data but twitter messages are short by design and the above methods may not work so well because they essentially shorten words to their base words. e.g.: running to run.
For now we will stick with the current normalized state of our message data which we can now convert into a vector that can be fed into the appropriate ML algorithim.
I have also created a word cloud depicting the most common words in the entire twitter dataset after normalization.
We can see our keywords β paul & ryan β are obviously very prominent but some domain knowledge would be helpful in making sense of why some of the other words are there. It is twitter after all so you can always expect a wide range of emotions. Some words in the dataset do use very strong language.The word cloud also excludes the words paul and ryan as they are disproportionately common in the dataset.
# split sentences to get individual wordsall_words = []for line in df_paulry['no_pauls']: # try 'tokens' all_words.extend(line) # create a word frequency dictionarywordfreq = Counter(all_words)# draw a Word Cloud with word frequencieswordcloud = WordCloud(width=900, height=500, max_words=500, max_font_size=100, relative_scaling=0.5, colormap='Blues', normalize_plurals=True).generate_from_frequencies(wordfreq)plt.figure(figsize=(17,14))plt.imshow(wordcloud, interpolation='bilinear')plt.axis("off")plt.show()
Weβll convert each message which is represented by a list of tokens into a vector that a machine learning model can understand.
To do this we use the Bag Of Words model which is a three step process.
1.Count how many times does a word occur in each message (Known as term frequency)
2.Weigh the counts, so that frequent tokens get lower weight (inverse document frequency)
3.Normalize the vectors to unit length, to abstract from the original text length (L2 norm)
Each vector will have as many dimensions as there are unique words in the tweeter corpus.
We will first use SciKit Learnβs CountVectorizer function which converts a collection of text documents to a matrix of token counts.
Imagine this as a 2-D matrix where 1-D is the entire vocabulary contained in the messages and the other dimension is one column per tweet.
Since there are so many messages, we can expect a lot of zero counts for the presence of every word in the data but SciKit Learn will output a Sparse Matrix. Below is an example β code and output β of a vectorized sentence.
# vectorizebow_transformer = CountVectorizer(analyzer=text_process).fit(df_paulry['message'])# print total number of vocab wordsprint(len(bow_transformer.vocabulary_))# output6865# example of vectorized textsample_tweet = df_paulry['message'][111]print(sample_tweet)print('\n')# vector representationbow_sample = bow_transformer.transform([sample_tweet])print(bow_sample)print('\n')
# transform the entire DataFrame of messagesmessages_bow = bow_transformer.transform(df_paulry['message'])# check out the bag-of-words counts for the entire corpus as a large sparse matrixprint('Shape of Sparse Matrix: ', messages_bow.shape)print('Amount of Non-Zero occurences: ', messages_bow.nnz)
TF-IDF stands for term frequency-inverse document frequency, and the tf-idf weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus.
The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus. Variations of the tf-idf weighting scheme are often used by search engines as a central tool in scoring and ranking a documentβs relevance given a user query.
One of the simplest ranking functions is computed by summing the tf-idf for each query term; many more sophisticated ranking functions are variants of this simple model.
Typically, the tf-idf weight is composed by two terms: the first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document; the second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears.
TF: Term Frequency, which measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka. the total number of terms in the document) as a way of normalization:
TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document).
IDF: Inverse Document Frequency, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as βisβ, βofβ, and βthatβ, may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following:
IDF(t) = log_e(Total number of documents / Number of documents with term t in it).
See below for a simple example.
Example: Consider a document containing 100 words wherein the word cat appears 3 times. The term frequency (i.e., tf) for cat is then (3 / 100) = 0.03. Now, assume we have 10 million documents and the word cat appears in one thousand of these. Then, the inverse document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12.
# from sklearn.feature_extraction.text import TfidfTransformertfidf_transformer = TfidfTransformer().fit(messages_bow)tfidf_sample = tfidf_transformer.transform(bow_sample)print(tfidf_sample)
Weβll go ahead and check what is the IDF (inverse document frequency) of the word βtrumpβ and of word βgopβ?
# some IDF (inverse document frequency) exampleprint(tfidf_transformer.idf_[bow_transformer.vocabulary_['trump']])print(tfidf_transformer.idf_[bow_transformer.vocabulary_['gop']])
To transform our entire twitter bag-of-words corpus into TF-IDF corpus at once weβll use the code below:
# to transform the entire bag-of-words corpusmessages_tfidf = tfidf_transformer.transform(messages_bow)print(messages_tfidf.shape)# Output(4164, 6865)
After preprocessing the data, we are now ready to pass it through a ML classification algorithim.
This ends the text preprocessing stages of our workflow but we will revisit these steps as one step in the pipeline in the next section continued here. | [
{
"code": null,
"e": 839,
"s": 171,
"text": "Twitter is an online social network with over 330 million active monthly users as of February 2018. Users on twitter create short messages called tweets to be shared with other twitter users who interact by retweeting and responding. Twitter employs a message size restriction of 280 characters or less which forces the users to stay focused on the message they wish to disseminate. This very characteristic makes messages on twitter very good candidates for the Machine Learning (ML) task of sentiment analysis. Sentiment Analysis falls under Natural Language Processing (NLP) which is a branch of ML that deals with how computers process and analyze human language."
},
{
"code": null,
"e": 1530,
"s": 839,
"text": "The training data was obtained from Sentiment140 and is made up of about 1.6 million random tweets with corresponding binary labels. 0 for Negative sentiment and 1 for Positive sentiment. In this blog post, weβll use a Naive Bayes Classifier to learn the correct labels from this training set and do a binary classification. In a nut shell, the Naive Bayes theorem calculates the probability of a certain event happening based on the joint probabilistic distributions of certain other events. I downloaded the test dataset using twitterβs API and will be use to test the modelβs real world performance. Full documentation and terms of the API are available at developer.twitter.com/en/docs."
},
{
"code": null,
"e": 1935,
"s": 1530,
"text": "In the first section of this blog post weβll go through standard preprocessing steps performed on text data for a sentiment analysis ML task. The second section is covered in a subsequent blog post where we combine the preprocessing into one step within a ML pipeline. This first post goes through the trouble of explaining what is happening under the hood when we use a pipeline to handle preprocessing."
},
{
"code": null,
"e": 1992,
"s": 1935,
"text": "Weβll use Jupyter Notebook with Python for our workflow."
},
{
"code": null,
"e": 2042,
"s": 1992,
"text": "Import the python libraries used in this project."
},
{
"code": null,
"e": 2119,
"s": 2042,
"text": "Import the data to a pandas dataframe and do some exploratory data analysis."
},
{
"code": null,
"e": 2912,
"s": 2119,
"text": "# you can see the full list of imports on GitHub!# Machine Learning importsimport nltkfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_scorefrom sklearn.naive_bayes import MultinomialNBfrom sklearn.model_selection import KFold, cross_val_scorefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.model_selection import GridSearchCVfrom sklearn.externals import joblibfrom nltk.corpus import stopwordsfrom nltk.tokenize import TweetTokenizerfrom nltk.stem.wordnet import WordNetLemmatizerLoad training dataset to Pandas and preview the top rows."
},
{
"code": null,
"e": 3170,
"s": 2912,
"text": "# load train datadata = pd.read_csv('Sentiment Analysis Dataset.csv', error_bad_lines=False)data.columns = ['id','label','source','text']data.head(2)# get text and matching label columnsdata = data.drop(['id','source'],axis=1)data.head(10)"
},
{
"code": null,
"e": 3248,
"s": 3170,
"text": "We can observe that the data is indeed from tweet messages posted on twitter."
},
{
"code": null,
"e": 3574,
"s": 3248,
"text": "The labels and the text do not seem to be in any listed order. This can be a problem if data is not randomly distributed as it can introduce biases to a learning model. In any case, we are going to use the Scikit Learn library which has a function to split our training and testing data and shuffle the data at the same time."
},
{
"code": null,
"e": 3798,
"s": 3574,
"text": "Shuffling data reduces variance and makes sure our model can generalize better on the data and do less overfitting. We want to make sure the train and test dataset are representative of the overall distribution of the data."
},
{
"code": null,
"e": 3900,
"s": 3798,
"text": "To that note, we also want to check the label frequency distribution in the data which is done below."
},
{
"code": null,
"e": 4091,
"s": 3900,
"text": "Another observation we can make is that the text contains varying formats. Some words contain mixed case letters which need to be normalized to their base word. e.g.: βCRyβ changed to βcryβ."
},
{
"code": null,
"e": 4245,
"s": 4091,
"text": "Leaving words with first letter capitalized can be experimented with as they may hold a different feature space like the name of a person or country etc."
},
{
"code": null,
"e": 4282,
"s": 4245,
"text": "Explore distribution of label types."
},
{
"code": null,
"e": 4648,
"s": 4282,
"text": "# check the number of positive vs. negative tagged sentencespositives = data['label'][data.label == 0]negatives = data['label'][data.label == 1]print('number of positve tagged sentences is: {}'.format(len(positives)))print('number of negative tagged sentences is: {}'.format(len(negatives)))print('total length of the data is: {}'.format(data.shape[0]))"
},
{
"code": null,
"e": 4795,
"s": 4648,
"text": "Considering the size of the dataset, the labels seem to be βaboutβ evenly distributed at 788435 vs. 790177 for positive and negative respectively."
},
{
"code": null,
"e": 4995,
"s": 4795,
"text": "Next, we want to see the number of words contained in every sentence so I created a function to extract this information and appended it to a column next to the text column. Below is a sample output."
},
{
"code": null,
"e": 5158,
"s": 4995,
"text": "# get a word count per sentence columndef word_count(sentence): return len(sentence.split()) data['word count'] = data['text'].apply(word_count)data.head(3)"
},
{
"code": null,
"e": 5504,
"s": 5158,
"text": "# plot word count distribution for both positive and negative sentimentsx = data['word count'][data.label == 1]y = data['word count'][data.label == 0]plt.figure(figsize=(12,6))plt.xlim(0,45)plt.xlabel('word count')plt.ylabel('frequency')g = plt.hist([x, y], color=['r','b'], alpha=0.5, label=['positive','negative'])plt.legend(loc='upper right')"
},
{
"code": null,
"e": 5810,
"s": 5504,
"text": "From the graph above, most sentences fall between 5β10 words but itβs fair to say that majority of text on twitter falls between 1 and 25 words. This is no wonder considering that twitter has a limit of how many characters one can use in a message. 280 characters is the limit at the time of this writing."
},
{
"code": null,
"e": 5937,
"s": 5810,
"text": "In all, it looks like 1β20 words covers more than 80% of all sentences which makes this dataset set a good training candidate."
},
{
"code": null,
"e": 6106,
"s": 5937,
"text": "There are more positive sentences with 5 words or less than there are negative ones which does not seem like a big enough difference to cause any concern at the moment."
},
{
"code": null,
"e": 6321,
"s": 6106,
"text": "# get most common words in training datasetall_words = []for line in list(data['text']): words = line.split() for word in words: all_words.append(word.lower()) Counter(all_words).most_common(10)"
},
{
"code": null,
"e": 6335,
"s": 6321,
"text": "Output below:"
},
{
"code": null,
"e": 6498,
"s": 6335,
"text": "[('i', 741876), ('to', 556149), ('the', 516654), ('a', 374024), ('my', 309966), ('and', 294805), ('you', 236109), ('is', 229444), ('for', 212852), ('in', 209009)]"
},
{
"code": null,
"e": 6590,
"s": 6498,
"text": "In the cell above we extracted the most common words in the dataset and listed the top ten."
},
{
"code": null,
"e": 6931,
"s": 6590,
"text": "Perhaps to no surprise we encounter words like i, and and is as they are very highly used in human expressions. These kind of words usually appear equally in both negative and positive oriented expressions and as such they bring very little information that can be incorporated in the model so we will have to get rid of them down the road."
},
{
"code": null,
"e": 7064,
"s": 6931,
"text": "In the text preprocessing steps later on we will learn how to deal with these common words that donβt add much to the feature space."
},
{
"code": null,
"e": 7143,
"s": 7064,
"text": "Below is a code to output a graph showing the frequency of the first 25 words."
},
{
"code": null,
"e": 7594,
"s": 7143,
"text": "# plot word frequency distribution of first few wordsplt.figure(figsize=(12,5))plt.title('Top 25 most common words')plt.xticks(fontsize=13, rotation=90)fd = nltk.FreqDist(all_words)fd.plot(25,cumulative=False)# log-log plotword_counts = sorted(Counter(all_words).values(), reverse=True)plt.figure(figsize=(12,5))plt.loglog(word_counts, linestyle='-', linewidth=1.5)plt.ylabel(\"Freq\")plt.xlabel(\"Word Rank\")plt.title('log-log plot of words frequency')"
},
{
"code": null,
"e": 7855,
"s": 7594,
"text": "I also created a log-log plot for the words frequency which is similar to the previous frequency graph but includes all words and is plotted on a base 10 logarithmic scale which helps us visualize the rapidly diminishing frequency of words as their rank drops."
},
{
"code": null,
"e": 8140,
"s": 7855,
"text": "The word distribution present in this data dictionary is a very common phenomenon in large samples of words as shown by Zipfβs law where the most frequent word will occur about twice as often as the second most frequent word, three times as often as the third most frequent word, etc."
},
{
"code": null,
"e": 8259,
"s": 8140,
"text": "It would be interesting to see if this holds true after we remove words like i, and and is from the observation above."
},
{
"code": null,
"e": 8699,
"s": 8259,
"text": "After training the model we make sentiment predictions on the raw twitter data but before we can do that, we need to download and do some basic data cleaning. You download tweets off the twitter RESTful API by keyword and get a stream of historical tweets back along with the metadata. I used Tweepy which is a python wrapper library for the twitter API that gives you more control on how you query the API. You can see the code on GitHub."
},
{
"code": null,
"e": 9142,
"s": 8699,
"text": "The keyword used to download historical tweets was βPaul Ryanβ who is the speaker of the US House of Representative at the time of writing. My choice for this keyword is arbitrary but I feel is good enough to return some polarizing tweets. This is important because the tweets themselves can act as their own benchmark. One of the obstacles of NLP is evaluating a modelβs performance considering that language is relative and always changing."
},
{
"code": null,
"e": 9171,
"s": 9142,
"text": "Import and preview raw data."
},
{
"code": null,
"e": 9429,
"s": 9171,
"text": "# create column namescol_names=['date','user_loc','followers','friends','message','bbox_coords',\\ 'full_name','country','country_code','place_type']# read csvdf_twtr = pd.read_csv('paul_ryan_twitter.csv', names=col_names)# check headdf_twtr.head()"
},
{
"code": null,
"e": 9519,
"s": 9429,
"text": "Weβll keep the location data and use it later to map out our results on a geographic map."
},
{
"code": null,
"e": 9630,
"s": 9519,
"text": "We want to remove any unnecessary qualities in the data which would make the trained model a poor generalizer."
},
{
"code": null,
"e": 9870,
"s": 9630,
"text": "Text preprocessing involves many things like removing emojis, properly formatting the text to remove extra spaces or any other information in the text that we donβt believe would add information to our model. Weβll see some examples below."
},
{
"code": null,
"e": 10030,
"s": 9870,
"text": "We also have to make sure that the information we pass the model is in a format that computers can understand. Weβll also go through some of these steps below."
},
{
"code": null,
"e": 10138,
"s": 10030,
"text": "After this pre-processing step, our data should be ready to use for a machine learning classification task."
},
{
"code": null,
"e": 10245,
"s": 10138,
"text": "NOTE : Whatever text preprocessing we do on the train data must also be done on the test and our raw data."
},
{
"code": null,
"e": 10348,
"s": 10245,
"text": "This step is one that we could spend a lot of time on but the goal is always to find the best balance."
},
{
"code": null,
"e": 10574,
"s": 10348,
"text": "The bulk of the work in NLP is done on feature engineering. For now we will get rid of the links and emoji characters. It is important to mention that we can use them as features but for now weβre just building a basic model."
},
{
"code": null,
"e": 10707,
"s": 10574,
"text": "I created a function that uses regex to do bulk formatting for every tweet in the dataset. Sample output is included under the code."
},
{
"code": null,
"e": 11935,
"s": 10707,
"text": "# helper function to clean tweetsdef processTweet(tweet): # Remove HTML special entities (e.g. &) tweet = re.sub(r'\\&\\w*;', '', tweet) #Convert @username to AT_USER tweet = re.sub('@[^\\s]+','',tweet) # Remove tickers tweet = re.sub(r'\\$\\w*', '', tweet) # To lowercase tweet = tweet.lower() # Remove hyperlinks tweet = re.sub(r'https?:\\/\\/.*\\/\\w*', '', tweet) # Remove hashtags tweet = re.sub(r'#\\w*', '', tweet) # Remove Punctuation and split 's, 't, 've with a space for filter tweet = re.sub(r'[' + punctuation.replace('@', '') + ']+', ' ', tweet) # Remove words with 2 or fewer letters tweet = re.sub(r'\\b\\w{1,2}\\b', '', tweet) # Remove whitespace (including new line characters) tweet = re.sub(r'\\s\\s+', ' ', tweet) # Remove single space remaining at the front of the tweet. tweet = tweet.lstrip(' ') # Remove characters beyond Basic Multilingual Plane (BMP) of Unicode: tweet = ''.join(c for c in tweet if c <= '\\uFFFF') return tweet# ______________________________________________________________# clean dataframe's text columndf_paulry['message'] = df_paulry['message'].apply(processTweet)# preview some cleaned tweetsdf_paulry['message'].head()"
},
{
"code": null,
"e": 12070,
"s": 11935,
"text": "Also note that you cannot have a perfect set of clean up steps as some cleanup steps will ultimately introduce some flaws in the data."
},
{
"code": null,
"e": 12313,
"s": 12070,
"text": "Below is a before and after example where βreβ has been removed from re-election which alters the meaning of the word and perhaps the userβs intended meaning. The word wonβt also changes to won which obviously has a totally different meaning."
},
{
"code": null,
"e": 12483,
"s": 12313,
"text": "We drop duplicate tweets as they bring no new information to the dataset and are also computationally inefficient. We also visualize the most common words in the corpus."
},
{
"code": null,
"e": 13037,
"s": 12483,
"text": "# most common words in twitter datasetall_words = []for line in list(df_paulry['message']): words = line.split() for word in words: all_words.append(word.lower())# plot word frequency distribution of first few wordsplt.figure(figsize=(12,5))plt.xticks(fontsize=13, rotation=90)fd = nltk.FreqDist(all_words)fd.plot(25,cumulative=False)# log-log of all words word_counts = sorted(Counter(all_words).values(), reverse=True)plt.figure(figsize=(12,5))plt.loglog(word_counts, linestyle='-', linewidth=1.5)plt.ylabel(\"Freq\")plt.xlabel(\"Word Rank\")"
},
{
"code": null,
"e": 13382,
"s": 13037,
"text": "Our training data has now been transformed into a much leaner body of text that is much cleaner for feature extraction. As we mentioned before, we do have some words in the dataset that are common in natural human language but used in most sentence compositions that we would be better left off since they bring no useful features to our model."
},
{
"code": null,
"e": 13825,
"s": 13382,
"text": "These words are commonly known as stop-words in NLP and the NLTK library comes with a function that can filter out these words from the dataset. Below is the actual words contained in the stop_words list. We can also make our own special list of stop words to fit any unique case. For example if you are doing sentiment analysis on law documents, you would probably need a special set considering the law jargon contained is unique in nature."
},
{
"code": null,
"e": 14048,
"s": 13825,
"text": "# show stop words examples(\"i , me , my , myself , we , our , ours , ourselves , you , you're , you've , you'll , you'd , your , yours , yourself , yourselves , he , him , his , himself , she , her , hers , herself , it \")"
},
{
"code": null,
"e": 14349,
"s": 14048,
"text": "After removing stop-words we split all the sentences in the dataset to get individual words (tokens) which is basically a list of words per sentence contained in the newly processed tweet. Now we can see that we have two new columns in the dataframe that contains these tokenized versions of a tweet."
},
{
"code": null,
"e": 14384,
"s": 14349,
"text": "A sample output is included below."
},
{
"code": null,
"e": 15411,
"s": 14384,
"text": "# tokenize helper functiondef text_process(raw_text): \"\"\" Takes in a string of text, then performs the following: 1. Remove all punctuation 2. Remove all stopwords 3. Returns a list of the cleaned text \"\"\" # Check characters to see if they are in punctuation nopunc = [char for char in list(raw_text) if char not in string.punctuation] # Join the characters again to form the string. nopunc = ''.join(nopunc) # Now just remove any stopwords return [word for word in nopunc.lower().split() if word.lower() not in stopwords.words('english')]def remove_words(word_list): remove = ['paul','ryan','...','β','β','β','...','ryanβ'] return [w for w in word_list if w not in remove]# -------------------------------------------# tokenize message column and create a column for tokensdf_paulry = df_paulry.copy()df_paulry['tokens'] = df_paulry['message'].apply(text_process) # tokenize style 1df_paulry['no_pauls'] = df_paulry['tokens'].apply(remove_words) #tokenize style 2df_paulry.head()"
},
{
"code": null,
"e": 15681,
"s": 15411,
"text": "There are additional normalization techniques like stemming and lemmatizing that we can try on our data but twitter messages are short by design and the above methods may not work so well because they essentially shorten words to their base words. e.g.: running to run."
},
{
"code": null,
"e": 15848,
"s": 15681,
"text": "For now we will stick with the current normalized state of our message data which we can now convert into a vector that can be fed into the appropriate ML algorithim."
},
{
"code": null,
"e": 15964,
"s": 15848,
"text": "I have also created a word cloud depicting the most common words in the entire twitter dataset after normalization."
},
{
"code": null,
"e": 16370,
"s": 15964,
"text": "We can see our keywords β paul & ryan β are obviously very prominent but some domain knowledge would be helpful in making sense of why some of the other words are there. It is twitter after all so you can always expect a wide range of emotions. Some words in the dataset do use very strong language.The word cloud also excludes the words paul and ryan as they are disproportionately common in the dataset."
},
{
"code": null,
"e": 17014,
"s": 16370,
"text": "# split sentences to get individual wordsall_words = []for line in df_paulry['no_pauls']: # try 'tokens' all_words.extend(line) # create a word frequency dictionarywordfreq = Counter(all_words)# draw a Word Cloud with word frequencieswordcloud = WordCloud(width=900, height=500, max_words=500, max_font_size=100, relative_scaling=0.5, colormap='Blues', normalize_plurals=True).generate_from_frequencies(wordfreq)plt.figure(figsize=(17,14))plt.imshow(wordcloud, interpolation='bilinear')plt.axis(\"off\")plt.show()"
},
{
"code": null,
"e": 17142,
"s": 17014,
"text": "Weβll convert each message which is represented by a list of tokens into a vector that a machine learning model can understand."
},
{
"code": null,
"e": 17214,
"s": 17142,
"text": "To do this we use the Bag Of Words model which is a three step process."
},
{
"code": null,
"e": 17297,
"s": 17214,
"text": "1.Count how many times does a word occur in each message (Known as term frequency)"
},
{
"code": null,
"e": 17387,
"s": 17297,
"text": "2.Weigh the counts, so that frequent tokens get lower weight (inverse document frequency)"
},
{
"code": null,
"e": 17479,
"s": 17387,
"text": "3.Normalize the vectors to unit length, to abstract from the original text length (L2 norm)"
},
{
"code": null,
"e": 17569,
"s": 17479,
"text": "Each vector will have as many dimensions as there are unique words in the tweeter corpus."
},
{
"code": null,
"e": 17702,
"s": 17569,
"text": "We will first use SciKit Learnβs CountVectorizer function which converts a collection of text documents to a matrix of token counts."
},
{
"code": null,
"e": 17841,
"s": 17702,
"text": "Imagine this as a 2-D matrix where 1-D is the entire vocabulary contained in the messages and the other dimension is one column per tweet."
},
{
"code": null,
"e": 18065,
"s": 17841,
"text": "Since there are so many messages, we can expect a lot of zero counts for the presence of every word in the data but SciKit Learn will output a Sparse Matrix. Below is an example β code and output β of a vectorized sentence."
},
{
"code": null,
"e": 18448,
"s": 18065,
"text": "# vectorizebow_transformer = CountVectorizer(analyzer=text_process).fit(df_paulry['message'])# print total number of vocab wordsprint(len(bow_transformer.vocabulary_))# output6865# example of vectorized textsample_tweet = df_paulry['message'][111]print(sample_tweet)print('\\n')# vector representationbow_sample = bow_transformer.transform([sample_tweet])print(bow_sample)print('\\n')"
},
{
"code": null,
"e": 18748,
"s": 18448,
"text": "# transform the entire DataFrame of messagesmessages_bow = bow_transformer.transform(df_paulry['message'])# check out the bag-of-words counts for the entire corpus as a large sparse matrixprint('Shape of Sparse Matrix: ', messages_bow.shape)print('Amount of Non-Zero occurences: ', messages_bow.nnz)"
},
{
"code": null,
"e": 19015,
"s": 18748,
"text": "TF-IDF stands for term frequency-inverse document frequency, and the tf-idf weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus."
},
{
"code": null,
"e": 19326,
"s": 19015,
"text": "The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus. Variations of the tf-idf weighting scheme are often used by search engines as a central tool in scoring and ranking a documentβs relevance given a user query."
},
{
"code": null,
"e": 19496,
"s": 19326,
"text": "One of the simplest ranking functions is computed by summing the tf-idf for each query term; many more sophisticated ranking functions are variants of this simple model."
},
{
"code": null,
"e": 19912,
"s": 19496,
"text": "Typically, the tf-idf weight is composed by two terms: the first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document; the second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears."
},
{
"code": null,
"e": 20270,
"s": 19912,
"text": "TF: Term Frequency, which measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka. the total number of terms in the document) as a way of normalization:"
},
{
"code": null,
"e": 20368,
"s": 20270,
"text": "TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document)."
},
{
"code": null,
"e": 20735,
"s": 20368,
"text": "IDF: Inverse Document Frequency, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as βisβ, βofβ, and βthatβ, may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following:"
},
{
"code": null,
"e": 20818,
"s": 20735,
"text": "IDF(t) = log_e(Total number of documents / Number of documents with term t in it)."
},
{
"code": null,
"e": 20850,
"s": 20818,
"text": "See below for a simple example."
},
{
"code": null,
"e": 21266,
"s": 20850,
"text": "Example: Consider a document containing 100 words wherein the word cat appears 3 times. The term frequency (i.e., tf) for cat is then (3 / 100) = 0.03. Now, assume we have 10 million documents and the word cat appears in one thousand of these. Then, the inverse document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12."
},
{
"code": null,
"e": 21458,
"s": 21266,
"text": "# from sklearn.feature_extraction.text import TfidfTransformertfidf_transformer = TfidfTransformer().fit(messages_bow)tfidf_sample = tfidf_transformer.transform(bow_sample)print(tfidf_sample)"
},
{
"code": null,
"e": 21567,
"s": 21458,
"text": "Weβll go ahead and check what is the IDF (inverse document frequency) of the word βtrumpβ and of word βgopβ?"
},
{
"code": null,
"e": 21747,
"s": 21567,
"text": "# some IDF (inverse document frequency) exampleprint(tfidf_transformer.idf_[bow_transformer.vocabulary_['trump']])print(tfidf_transformer.idf_[bow_transformer.vocabulary_['gop']])"
},
{
"code": null,
"e": 21852,
"s": 21747,
"text": "To transform our entire twitter bag-of-words corpus into TF-IDF corpus at once weβll use the code below:"
},
{
"code": null,
"e": 22003,
"s": 21852,
"text": "# to transform the entire bag-of-words corpusmessages_tfidf = tfidf_transformer.transform(messages_bow)print(messages_tfidf.shape)# Output(4164, 6865)"
},
{
"code": null,
"e": 22101,
"s": 22003,
"text": "After preprocessing the data, we are now ready to pass it through a ML classification algorithim."
}
] |
Difference Between ordinal() and compareTo() in Java Enum - GeeksforGeeks | 02 Feb, 2021
Enumerations serve the purpose of representing a group of named constants in a programming language. If we want to represent a group named constant then we should go for Enum. Every enum constant is static. Hence, we can access it by using enum Name.
Example:
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
The java.lang.Enum.ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.
ordinal() method is a non-static method, it means that it is accessible with the class object only and if we try to access the object of another class it will give the error. It is a final method, cannot be overridden.
The ordinal() method returns the ordinal of the enum constant. (its position in its enum declaration, where the first constant is assigned an ordinal of zero).
Syntax:
public final int ordinal();
Return Value:
This method returns the ordinal of this enumeration constant.
Example:
Day d1 = Day.TUESDAY;
System.out.println("the ordinal value is :" + d1.ordinal());
Output:
the ordinal value is : 2
Java
// Java program to show the usage of // ordinal() method of java enumeration enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} class Main{ public static void main(String args[]) { Day days[] = Day.values(); for(Day d : days) System.out.print(d.ordinal() + " " ); }}
0 1 2 3 4 5 6
The compareTo() method of Enum class compares this enum object with the defined object for order. Enum constants can only be compared to other enum constants of the same type.
Returns:
A negative integer, if this enum is less than the defined object.zero, if this enum is equal to the defined object.a positive integer, if this enum is greater than the defined object.
A negative integer, if this enum is less than the defined object.
zero, if this enum is equal to the defined object.
a positive integer, if this enum is greater than the defined object.
Syntax:
int compareTo(Object obj)
Example:
Day day1 = Day.SUNDAY;
Day day2 = Day.MONDAY;
System.out.println(day1.compareTo(day2));
Since the ordinal value of day1 is less than day2 so it will return a negative value.
Java
// Java program to show the usage of // compareTo() method of java enumeration enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} class GFG{ public static void main(String args[]) { Day d1 = Day.SUNDAY; Day d2 = Day.MONDAY; Day d3 = Day.TUESDAY; // will return negative value since d1 < d2 System.out.println(d1.compareTo(d2) ); // will return positive value since d2 > d1 System.out.println(d2.compareTo(d1) ); // will return 0 since d3 == d3 System.out.println(d3.compareTo(d3) ); }}
-1
1
0
Ordinal() Method
CompareTo() Method
Returns A negative integer, if this enum is less than the defined object.
Returns zero, if this enum is equal to the defined object.
Returns a positive integer, if this enum is greater than the defined object.
Example:
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
Day d = Day.SUNDAY;
d.ordinal() // 0
Example:
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
Day d1 = Day.SUNDAY;
Day d2 = Day.MONDAY;
d1.compareTo(d2) // since d1 < d2 output will be -ve
Java-Enumeration
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 24778,
"s": 24750,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 25029,
"s": 24778,
"text": "Enumerations serve the purpose of representing a group of named constants in a programming language. If we want to represent a group named constant then we should go for Enum. Every enum constant is static. Hence, we can access it by using enum Name."
},
{
"code": null,
"e": 25038,
"s": 25029,
"text": "Example:"
},
{
"code": null,
"e": 25116,
"s": 25038,
"text": "enum Day{\n SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;\n}"
},
{
"code": null,
"e": 25304,
"s": 25116,
"text": "The java.lang.Enum.ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum."
},
{
"code": null,
"e": 25523,
"s": 25304,
"text": "ordinal() method is a non-static method, it means that it is accessible with the class object only and if we try to access the object of another class it will give the error. It is a final method, cannot be overridden."
},
{
"code": null,
"e": 25683,
"s": 25523,
"text": "The ordinal() method returns the ordinal of the enum constant. (its position in its enum declaration, where the first constant is assigned an ordinal of zero)."
},
{
"code": null,
"e": 25692,
"s": 25683,
"text": "Syntax: "
},
{
"code": null,
"e": 25720,
"s": 25692,
"text": "public final int ordinal();"
},
{
"code": null,
"e": 25734,
"s": 25720,
"text": "Return Value:"
},
{
"code": null,
"e": 25796,
"s": 25734,
"text": "This method returns the ordinal of this enumeration constant."
},
{
"code": null,
"e": 25805,
"s": 25796,
"text": "Example:"
},
{
"code": null,
"e": 25922,
"s": 25805,
"text": "Day d1 = Day.TUESDAY;\nSystem.out.println(\"the ordinal value is :\" + d1.ordinal());\n\nOutput:\nthe ordinal value is : 2"
},
{
"code": null,
"e": 25927,
"s": 25922,
"text": "Java"
},
{
"code": "// Java program to show the usage of // ordinal() method of java enumeration enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} class Main{ public static void main(String args[]) { Day days[] = Day.values(); for(Day d : days) System.out.print(d.ordinal() + \" \" ); }}",
"e": 26257,
"s": 25927,
"text": null
},
{
"code": null,
"e": 26272,
"s": 26257,
"text": "0 1 2 3 4 5 6 "
},
{
"code": null,
"e": 26448,
"s": 26272,
"text": "The compareTo() method of Enum class compares this enum object with the defined object for order. Enum constants can only be compared to other enum constants of the same type."
},
{
"code": null,
"e": 26457,
"s": 26448,
"text": "Returns:"
},
{
"code": null,
"e": 26641,
"s": 26457,
"text": "A negative integer, if this enum is less than the defined object.zero, if this enum is equal to the defined object.a positive integer, if this enum is greater than the defined object."
},
{
"code": null,
"e": 26707,
"s": 26641,
"text": "A negative integer, if this enum is less than the defined object."
},
{
"code": null,
"e": 26758,
"s": 26707,
"text": "zero, if this enum is equal to the defined object."
},
{
"code": null,
"e": 26827,
"s": 26758,
"text": "a positive integer, if this enum is greater than the defined object."
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "Syntax:"
},
{
"code": null,
"e": 26861,
"s": 26835,
"text": "int compareTo(Object obj)"
},
{
"code": null,
"e": 26870,
"s": 26861,
"text": "Example:"
},
{
"code": null,
"e": 26893,
"s": 26870,
"text": "Day day1 = Day.SUNDAY;"
},
{
"code": null,
"e": 26916,
"s": 26893,
"text": "Day day2 = Day.MONDAY;"
},
{
"code": null,
"e": 26958,
"s": 26916,
"text": "System.out.println(day1.compareTo(day2));"
},
{
"code": null,
"e": 27044,
"s": 26958,
"text": "Since the ordinal value of day1 is less than day2 so it will return a negative value."
},
{
"code": null,
"e": 27049,
"s": 27044,
"text": "Java"
},
{
"code": "// Java program to show the usage of // compareTo() method of java enumeration enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} class GFG{ public static void main(String args[]) { Day d1 = Day.SUNDAY; Day d2 = Day.MONDAY; Day d3 = Day.TUESDAY; // will return negative value since d1 < d2 System.out.println(d1.compareTo(d2) ); // will return positive value since d2 > d1 System.out.println(d2.compareTo(d1) ); // will return 0 since d3 == d3 System.out.println(d3.compareTo(d3) ); }}",
"e": 27686,
"s": 27049,
"text": null
},
{
"code": null,
"e": 27693,
"s": 27686,
"text": "-1\n1\n0"
},
{
"code": null,
"e": 27710,
"s": 27693,
"text": "Ordinal() Method"
},
{
"code": null,
"e": 27729,
"s": 27710,
"text": "CompareTo() Method"
},
{
"code": null,
"e": 27803,
"s": 27729,
"text": "Returns A negative integer, if this enum is less than the defined object."
},
{
"code": null,
"e": 27862,
"s": 27803,
"text": "Returns zero, if this enum is equal to the defined object."
},
{
"code": null,
"e": 27939,
"s": 27862,
"text": "Returns a positive integer, if this enum is greater than the defined object."
},
{
"code": null,
"e": 27949,
"s": 27939,
"text": "Example: "
},
{
"code": null,
"e": 27959,
"s": 27949,
"text": "enum Day{"
},
{
"code": null,
"e": 28023,
"s": 27959,
"text": "SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;"
},
{
"code": null,
"e": 28025,
"s": 28023,
"text": "}"
},
{
"code": null,
"e": 28045,
"s": 28025,
"text": "Day d = Day.SUNDAY;"
},
{
"code": null,
"e": 28062,
"s": 28045,
"text": "d.ordinal() // 0"
},
{
"code": null,
"e": 28074,
"s": 28065,
"text": "Example:"
},
{
"code": null,
"e": 28084,
"s": 28074,
"text": "enum Day{"
},
{
"code": null,
"e": 28148,
"s": 28084,
"text": "SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;"
},
{
"code": null,
"e": 28150,
"s": 28148,
"text": "}"
},
{
"code": null,
"e": 28171,
"s": 28150,
"text": "Day d1 = Day.SUNDAY;"
},
{
"code": null,
"e": 28192,
"s": 28171,
"text": "Day d2 = Day.MONDAY;"
},
{
"code": null,
"e": 28245,
"s": 28192,
"text": "d1.compareTo(d2) // since d1 < d2 output will be -ve"
},
{
"code": null,
"e": 28262,
"s": 28245,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 28269,
"s": 28262,
"text": "Picked"
},
{
"code": null,
"e": 28288,
"s": 28269,
"text": "Difference Between"
},
{
"code": null,
"e": 28293,
"s": 28288,
"text": "Java"
},
{
"code": null,
"e": 28298,
"s": 28293,
"text": "Java"
},
{
"code": null,
"e": 28396,
"s": 28298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28405,
"s": 28396,
"text": "Comments"
},
{
"code": null,
"e": 28418,
"s": 28405,
"text": "Old Comments"
},
{
"code": null,
"e": 28479,
"s": 28418,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28547,
"s": 28479,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28602,
"s": 28547,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 28660,
"s": 28602,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 28734,
"s": 28660,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 28749,
"s": 28734,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28793,
"s": 28749,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28815,
"s": 28793,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28840,
"s": 28815,
"text": "Reverse a string in Java"
}
] |
Spreadsheets to Python : Monitoring Covid Made Easy, Using Code | by Clive Siviour | Towards Data Science | The massive availability of data on the internet gives us an unprecedented opportunity to explore the underlying numbers behind different phenomena and events. Often these data are updated as time goes on, and we want to take advantage of this by updating our analysis. For me, one of the most important reasons to move from spreadsheets to code is that this process becomes so much easier.
A few months ago, I wrote a blog post examining the start of the βthird waveβ of Covid in the UK. For the post I wrote code to read in data from the UK government website [1]. Iβm now interested in how the now dominant Omicron variant is affecting case numbers; the good news is that it is really easy to reuse the code that I produced in order to find out.
Iβm writing this blog in Filament, a cloud-based Python platform, which allows me to re-run the code easily from my phone or computer whenever I am interested. At this point I should say that I am CSO of Filament. Of course, the same code will work on other Python platforms.
There has been a big increase recently in the number of Covid cases in the UK; letβs see how it compares to previous waves. To do this, Iβm going to use two libraries, Pandas for storing the data and Matplotlib for plotting them, so first I import the libraries that I need. To avoid breaking up the text, in this post all of the code is presented at the end. I encourage readers to copy and run this code themselves; alternatively, users of Filament can launch a workspace containing code from a range of blog-posts, including the ones in this series.
I then import a csv file containing the number of cases per day. Iβve chosen to use a csv organised by the date the specimen was taken, because I think this will be more accurate for my later calculations. This means that the data for the last few days are incomplete. The other option would be to download a file organised by the date the result was reported. This is more up-to-date, but might affect calculations of hospitalisation rates.
Once the file is imported, itβs simple to produce a plot showing the number of cases per day. We can see the big uptick in cases over the past few weeks!
For the next graph, I have downloaded the number of hospital admissions per day. We expect these to lag cases a bit (weβll explore this a bit more later), but even so, we can see a big increase at the end.
And, finally, deaths. There are a number of different measures of deaths; this graph shows deaths within 28 days of a positive test; the death was not necessarily from Covid. Itβs easy to change the code to read one of the other measures instead.
These data are interesting in themselves, but what is more important is that it is now really easy to re-run the code and update the graphs whenever I want to: I just have to hit run again! This would be a lot more difficult if I manually downloaded the spreadsheets each day.
Letβs now do some simple calculations with these data. The first thing I am going to do is look at the ratio of cases to hospital admissions and see how this has changed over time. I am going to miss out the first Covid wave, in spring 2020, because the testing was limited and it is likely that a lot of cases were missed. Instead, I will start on the 1st September 2020. Before calculating a ratio, the first thing I need to do is align the two sets of data: it turns out that the peak in hospitalisations is 8 days after the peak in cases. This implies that, on average, people who go to hospital do so 8 days after their positive test. I account for this by shifting the hospital admissions by 8 days. To make things easier to view, I have smoothed the data with a 7-day rolling average.
Now letβs have a look at the ratio of cases to admissions. The graph below shows this (on the right-hand axis). In late 2020, about one in 15 people who caught Covid-19 in the UK went to hospital; in mid-2021, presumably as vaccination took effect, this improved to about one in 40. The ratio seems to be improving again now; however, itβs too early to be sure and the data may have been affected by reporting delays over Christmas. Iβll keep checking back to see how things evolve.
Finally, lets take a look at death rates, for the graph below I have shifted these by 15 days to overlap with the cases; I also scaled them by multiplying by 50 so that cases and deaths can be viewed on the same axis. Around a year ago, there was one death for every 50 cases, this improved rapidly before settling at around one for every 250 cases or so, the very high ratio around July 2021 is probably a result of the Euro 2020 football tournament, during which I expect a large number of cases were among young people who were less likely to be seriously ill. It appears as though the recent rise in cases has not been associated with a rise in deaths, which will be good news if it continues, but may also be an artifact of the shifting: more data are needed before firm conclusions can be drawn.
We have seen how Python can be used to visualise and analyse data obtained from an internet source. Unfortunately, a bit more time is required before these data can be used to draw reliable conclusions about the Omicron variant of Covid: the new wave of cases is too recent and the available data are probably not yet up-to-date because of disruption over Christmas and the New Year.
The great thing about using code, however, is that I can now rerun the analysis every few days simply by, quite literally, pressing a single βrunβ button. This is a huge advantage of performing this analysis in Python. The analysis is also adaptable, I can change the amount of averaging, the shifts between different sets of data, or even the data set used just by changing one or two lines and running the code again.
One of the main assumptions in the analysis above is that the time delay between cases and hospital admissions (or deaths) is the same in the current (fourth) wave as it was in the second. This is a difficult assumption to justify β most people are not vaccinated, and Omicron appears to be a very different virus. If cases stabilise, this wonβt matter; whilst they are rising quickly, small mis-alignments might make a large difference to the calculated ratios. This is something to continue tweaking in the future, again made easier by code.
I hope this simple example has again shown the value of performing data analyses and visualisation in Python.
The text, code and images for this post were created using Filament, the all-in-one workspace for data, analysis and reporting. To find out more please visit our website. Filament is currently running a closed Beta program; the first 100 people to request access using referral code TDSFILAMENT can skip the waitlist and get early access. All code for this and other blogs is available to all Filament users.
Follow me on Medium for more stories like this
Connect on LinkedIn
[1] See Fair Use Policy here: https://coronavirus.data.gov.uk/details/download
#%% Code to import and plot UK Covid Dataimport matplotlib.pyplot as pltimport matplotlib.ticker as tkrfrom matplotlib.dates import DateFormatterimport pandas as pd#%% Read case data into a DataFramecovid_cases=pd.read_csv('https://coronavirus.data.gov.uk/api/v1/data?filters=areaType=overview&structure=%7B%22areaType%22:%22areaType%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22date%22:%22date%22,%22newCasesBySpecimenDate%22:%22newCasesBySpecimenDate%22,%22cumCasesBySpecimenDate%22:%22cumCasesBySpecimenDate%22%7D&format=csv')# Change date formats in the DataFrame, and reorder so that the most recent data are lastcovid_cases['date']=pd.to_datetime(covid_cases['date'])covid_cases=covid_cases[::-1]covid_cases.reset_index(drop=True, inplace=True)#%% Plotfig, ax1 = plt.subplots(figsize = [4,3], dpi=200)ax1.plot(covid_cases['date'], covid_cases['newCasesBySpecimenDate'], label='Full data', color='b' )# Format the axesax1.tick_params(axis='both', which='major', labelsize=8)ax1.set_xlabel('Date', fontsize=10)ax1.set_ylabel('UK Cases per day', fontsize=10)ax1.set_xticks(ax1.get_xticks())ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='center')# this code adds a comma at the thousand separator on the y-axisax1.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ',')))# these two lines are used to set the date format to MMM-YYdate_form = DateFormatter("%b-%y") ax1.xaxis.set_major_formatter(date_form) #%% Read hospital admission data into a new DataFramecovid_hospital=pd.read_csv('https://coronavirus.data.gov.uk/api/v1/data?filters=areaType=overview&structure=%7B%22areaType%22:%22areaType%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22date%22:%22date%22,%22newAdmissions%22:%22newAdmissions%22,%22cumAdmissions%22:%22cumAdmissions%22%7D&format=csv')covid_hospital['date']=pd.to_datetime(covid_hospital['date'])covid_hospital=covid_hospital[::-1]covid_hospital.reset_index(drop=True, inplace=True)#%% Plotfig, ax2 = plt.subplots(figsize=[4,3] ,dpi=200)ax2.plot(covid_hospital['date'], covid_hospital['newAdmissions'], label='Full data', color='r' )# Format the axesax2.tick_params(axis='both', which='major', labelsize=8)ax2.set_xlabel('Date', fontsize=10)ax2.set_ylabel('UK Hospital admissions per day', fontsize=10)ax2.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax2.xaxis.set_major_formatter(date_form)#%% Read death data into a new DataFramecovid_deaths=pd.read_csv('https://coronavirus.data.gov.uk/api/v1/data?filters=areaType=overview&structure=%7B%22areaType%22:%22areaType%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22date%22:%22date%22,%22newDeaths28DaysByDeathDate%22:%22newDeaths28DaysByDeathDate%22,%22cumDeaths28DaysByDeathDate%22:%22cumDeaths28DaysByDeathDate%22%7D&format=csv') covid_deaths['date']=pd.to_datetime(covid_deaths['date'])covid_deaths=covid_deaths[::-1]covid_deaths.reset_index(drop=True, inplace=True)#%% Plotfig, ax3 = plt.subplots(figsize=[4,3] ,dpi=200)ax3.plot(covid_deaths['date'], covid_deaths['newDeaths28DaysByDeathDate'], label='Full data', color='g' )# Format the axesax3.tick_params(axis='both', which='major', labelsize=8)ax3.set_xlabel('Date', fontsize=10)ax3.set_ylabel('UK Deaths per day', fontsize=10)ax3.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax3.xaxis.set_major_formatter(date_form)#%% Compare cases and hospital admissions, align admissions# Choose shift and averaging periodshift_1 = 8 # number of days to shift admissions data to compare to case dataav_period = 7 # days over which to average# In order to align the two datasets, I find the index of the date I want to start plotting fromstart_1=covid_cases[covid_cases['date']=='2020-09-01'].index[0]start_2=covid_hospital[covid_hospital['date']=='2020-09-01'].index[0] # Create figure and axesfig, ax4 = plt.subplots(figsize=[4,3] ,dpi=200)ax4_2=ax4.twinx() # allows me to plot the data using two y-axes# Now draw the plotsax4.plot(covid_cases['date'][start_1:-shift_1], covid_cases['newCasesBySpecimenDate'][start_1:-shift_1].rolling(av_period).mean(), label='Cases', color='b' )ax4_2.plot(covid_hospital['date'][start_2:], covid_hospital['newAdmissions'][start_2:].rolling(av_period).mean(), label='Hospital Admissions ', color=(1,0,0,0.5) )ax4_2.plot(covid_hospital['date'][start_2:-shift_1], covid_hospital['newAdmissions'][start_2+shift_1:].rolling(av_period).mean(), label='Hospital Admissions \nShifted', color='r' )# Format the axesax4.legend(fontsize=6, frameon=False, loc='upper left' )ax4_2.legend(fontsize=6, frameon=False, loc='upper right' )#ax4_2.legend(fontsize=6, facecolor='white', edgecolor='white',framealpha=1, loc='upper right')ax4.tick_params(axis='both', which='major', labelsize=8)ax4_2.tick_params(axis='both', which='major', labelsize=8)ax4.set_xlabel('Date', fontsize=10)ax4.set_ylabel('Cases per day', fontsize=10)ax4_2.set_ylabel('Hospital admissions per day', fontsize=10) ax4.set_ylim([0,65000])ax4_2.set_ylim([0,4500])ax4.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax4_2.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax4.set_xticks(ax4.get_xticks())ax4.set_xticklabels(ax4.get_xticklabels(), rotation=45, ha='center')ax4.xaxis.set_major_formatter(date_form)#%% Plot hospitalisation ratios# create a DataFrame with the required datahospitalisation_rate=pd.DataFrame({'Date':covid_cases['date'][start_1:]})hospitalisation_rate['Cases']=covid_cases['newCasesBySpecimenDate'][start_1:]hospitalisation_rate.reset_index(drop=True, inplace=True)temp=pd.DataFrame({'Admissions': covid_hospital['newAdmissions'][start_2:]})temp.reset_index(drop=True, inplace=True)hospitalisation_rate['Admissions']=temptemp=pd.DataFrame({'Admissions_shifted': covid_hospital['newAdmissions'][start_2+shift_1:]})temp.reset_index(drop=True, inplace=True)hospitalisation_rate['Admissions_shifted']=tempdel temphospitalisation_rate['Ratio']=hospitalisation_rate['Cases'].rolling(7).mean()/hospitalisation_rate['Admissions_shifted'].rolling(7).mean()#%% Plotfig, ax5 = plt.subplots(figsize=[4,3] ,dpi=200)ax5.plot(hospitalisation_rate['Date'], hospitalisation_rate['Cases'].rolling(7).mean(), label='Cases', color='b' )ax5.plot(hospitalisation_rate['Date'], hospitalisation_rate['Admissions'].rolling(7).mean(), label='Hospital Admissions', color=(1,0,0,0.5) )ax5.plot(hospitalisation_rate['Date'], hospitalisation_rate['Admissions_shifted'].rolling(7).mean(), label='Hospital Admissions \nShifted', color='r' )ax5_2 = ax5.twinx()ax5_2.plot(hospitalisation_rate['Date'], hospitalisation_rate['Ratio'], label='Ratio ', color='k' )ax5.legend(fontsize=6, frameon=False, loc='upper left' )ax5_2.legend(fontsize=6, frameon=False, loc='upper right')ax5.tick_params(axis='both', which='major', labelsize=8)ax5_2.tick_params(axis='both', which='major', labelsize=8)ax5.set_xlabel('Date', fontsize=10)ax5.set_ylabel('Cases / Admission per day', fontsize=10)ax5_2.set_ylabel('Ratio', fontsize=10) ax5.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax5_2.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax5.set_xticks(ax5.get_xticks())ax5.set_xticklabels(ax5.get_xticklabels(), rotation=45, ha='center')ax5.xaxis.set_major_formatter(date_form)ax5.set_ylim(bottom=0)ax5_2.set_ylim(bottom=0)#%% Plot death ratios# create a DataFrame with the required datastart_3=covid_deaths[covid_deaths['date']=='2020-09-01'].index[0]shift_2=15temp=pd.DataFrame({'Deaths_shifted': covid_deaths['newDeaths28DaysByDeathDate'][start_3+shift_2:]})temp.reset_index(drop=True, inplace=True)hospitalisation_rate['Deaths_shifted']=tempdel temphospitalisation_rate['Deaths_Ratio']=hospitalisation_rate['Cases'].rolling(7).mean()/hospitalisation_rate['Deaths_shifted'].rolling(7).mean()#%% Plotfig, ax6 = plt.subplots(figsize=[4,3] ,dpi=200)ax6.plot(hospitalisation_rate['Date'], hospitalisation_rate['Cases'].rolling(7).mean(), label='Cases', color='b' )ax6.plot(hospitalisation_rate['Date'], hospitalisation_rate['Deaths_shifted'].rolling(7).mean()*50, label='Deaths Shifted x 50', color='lightgreen' )ax6_2 = ax6.twinx()ax6_2.plot(hospitalisation_rate['Date'], hospitalisation_rate['Deaths_Ratio'], label='Ratio ', color='k' )ax6.legend(fontsize=6, frameon=False, loc='upper left' )ax6_2.legend(fontsize=6, frameon=False, loc='upper right')ax6.tick_params(axis='both', which='major', labelsize=8)ax6_2.tick_params(axis='both', which='major', labelsize=8)ax6.set_xlabel('Date', fontsize=10)ax6.set_ylabel('Cases / Deaths per day', fontsize=10)ax6_2.set_ylabel('Ratio', fontsize=10) ax6.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax6_2.get_yaxis().set_major_formatter( tkr.FuncFormatter(lambda x, p: format(int(x), ','))) ax6.set_xticks(ax6.get_xticks())ax6.set_xticklabels(ax6.get_xticklabels(), rotation=45, ha='center')ax6.xaxis.set_major_formatter(date_form)ax6.set_ylim(bottom=0) | [
{
"code": null,
"e": 556,
"s": 165,
"text": "The massive availability of data on the internet gives us an unprecedented opportunity to explore the underlying numbers behind different phenomena and events. Often these data are updated as time goes on, and we want to take advantage of this by updating our analysis. For me, one of the most important reasons to move from spreadsheets to code is that this process becomes so much easier."
},
{
"code": null,
"e": 914,
"s": 556,
"text": "A few months ago, I wrote a blog post examining the start of the βthird waveβ of Covid in the UK. For the post I wrote code to read in data from the UK government website [1]. Iβm now interested in how the now dominant Omicron variant is affecting case numbers; the good news is that it is really easy to reuse the code that I produced in order to find out."
},
{
"code": null,
"e": 1190,
"s": 914,
"text": "Iβm writing this blog in Filament, a cloud-based Python platform, which allows me to re-run the code easily from my phone or computer whenever I am interested. At this point I should say that I am CSO of Filament. Of course, the same code will work on other Python platforms."
},
{
"code": null,
"e": 1743,
"s": 1190,
"text": "There has been a big increase recently in the number of Covid cases in the UK; letβs see how it compares to previous waves. To do this, Iβm going to use two libraries, Pandas for storing the data and Matplotlib for plotting them, so first I import the libraries that I need. To avoid breaking up the text, in this post all of the code is presented at the end. I encourage readers to copy and run this code themselves; alternatively, users of Filament can launch a workspace containing code from a range of blog-posts, including the ones in this series."
},
{
"code": null,
"e": 2185,
"s": 1743,
"text": "I then import a csv file containing the number of cases per day. Iβve chosen to use a csv organised by the date the specimen was taken, because I think this will be more accurate for my later calculations. This means that the data for the last few days are incomplete. The other option would be to download a file organised by the date the result was reported. This is more up-to-date, but might affect calculations of hospitalisation rates."
},
{
"code": null,
"e": 2339,
"s": 2185,
"text": "Once the file is imported, itβs simple to produce a plot showing the number of cases per day. We can see the big uptick in cases over the past few weeks!"
},
{
"code": null,
"e": 2545,
"s": 2339,
"text": "For the next graph, I have downloaded the number of hospital admissions per day. We expect these to lag cases a bit (weβll explore this a bit more later), but even so, we can see a big increase at the end."
},
{
"code": null,
"e": 2792,
"s": 2545,
"text": "And, finally, deaths. There are a number of different measures of deaths; this graph shows deaths within 28 days of a positive test; the death was not necessarily from Covid. Itβs easy to change the code to read one of the other measures instead."
},
{
"code": null,
"e": 3069,
"s": 2792,
"text": "These data are interesting in themselves, but what is more important is that it is now really easy to re-run the code and update the graphs whenever I want to: I just have to hit run again! This would be a lot more difficult if I manually downloaded the spreadsheets each day."
},
{
"code": null,
"e": 3861,
"s": 3069,
"text": "Letβs now do some simple calculations with these data. The first thing I am going to do is look at the ratio of cases to hospital admissions and see how this has changed over time. I am going to miss out the first Covid wave, in spring 2020, because the testing was limited and it is likely that a lot of cases were missed. Instead, I will start on the 1st September 2020. Before calculating a ratio, the first thing I need to do is align the two sets of data: it turns out that the peak in hospitalisations is 8 days after the peak in cases. This implies that, on average, people who go to hospital do so 8 days after their positive test. I account for this by shifting the hospital admissions by 8 days. To make things easier to view, I have smoothed the data with a 7-day rolling average."
},
{
"code": null,
"e": 4344,
"s": 3861,
"text": "Now letβs have a look at the ratio of cases to admissions. The graph below shows this (on the right-hand axis). In late 2020, about one in 15 people who caught Covid-19 in the UK went to hospital; in mid-2021, presumably as vaccination took effect, this improved to about one in 40. The ratio seems to be improving again now; however, itβs too early to be sure and the data may have been affected by reporting delays over Christmas. Iβll keep checking back to see how things evolve."
},
{
"code": null,
"e": 5146,
"s": 4344,
"text": "Finally, lets take a look at death rates, for the graph below I have shifted these by 15 days to overlap with the cases; I also scaled them by multiplying by 50 so that cases and deaths can be viewed on the same axis. Around a year ago, there was one death for every 50 cases, this improved rapidly before settling at around one for every 250 cases or so, the very high ratio around July 2021 is probably a result of the Euro 2020 football tournament, during which I expect a large number of cases were among young people who were less likely to be seriously ill. It appears as though the recent rise in cases has not been associated with a rise in deaths, which will be good news if it continues, but may also be an artifact of the shifting: more data are needed before firm conclusions can be drawn."
},
{
"code": null,
"e": 5530,
"s": 5146,
"text": "We have seen how Python can be used to visualise and analyse data obtained from an internet source. Unfortunately, a bit more time is required before these data can be used to draw reliable conclusions about the Omicron variant of Covid: the new wave of cases is too recent and the available data are probably not yet up-to-date because of disruption over Christmas and the New Year."
},
{
"code": null,
"e": 5950,
"s": 5530,
"text": "The great thing about using code, however, is that I can now rerun the analysis every few days simply by, quite literally, pressing a single βrunβ button. This is a huge advantage of performing this analysis in Python. The analysis is also adaptable, I can change the amount of averaging, the shifts between different sets of data, or even the data set used just by changing one or two lines and running the code again."
},
{
"code": null,
"e": 6494,
"s": 5950,
"text": "One of the main assumptions in the analysis above is that the time delay between cases and hospital admissions (or deaths) is the same in the current (fourth) wave as it was in the second. This is a difficult assumption to justify β most people are not vaccinated, and Omicron appears to be a very different virus. If cases stabilise, this wonβt matter; whilst they are rising quickly, small mis-alignments might make a large difference to the calculated ratios. This is something to continue tweaking in the future, again made easier by code."
},
{
"code": null,
"e": 6604,
"s": 6494,
"text": "I hope this simple example has again shown the value of performing data analyses and visualisation in Python."
},
{
"code": null,
"e": 7013,
"s": 6604,
"text": "The text, code and images for this post were created using Filament, the all-in-one workspace for data, analysis and reporting. To find out more please visit our website. Filament is currently running a closed Beta program; the first 100 people to request access using referral code TDSFILAMENT can skip the waitlist and get early access. All code for this and other blogs is available to all Filament users."
},
{
"code": null,
"e": 7060,
"s": 7013,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 7080,
"s": 7060,
"text": "Connect on LinkedIn"
},
{
"code": null,
"e": 7159,
"s": 7080,
"text": "[1] See Fair Use Policy here: https://coronavirus.data.gov.uk/details/download"
}
] |
C# Enum GetName Method | The GetName() method returns the names of the constants in the Enumeration.
Here is the enum.
enum Stock { Appliance, Clothing, Footwear };
Now, get the names using the Enum.GetName() method. Just set the constant and retrieve the individual name.
Enum.GetName(typeof(Stock), 1
Let us see the example now.
Live Demo
using System;
class Demo {
enum Stock { Appliance, Clothing, Footwear };
static void Main() {
Console.WriteLine("The value of second stock category = {0}",Enum.GetName(typeof(Stock), 1));
Console.WriteLine("The value of third stock category = {0}",Enum.GetName(typeof(Stock), 2));
}
}
The value of second stock category = Clothing
The value of third stock category = Footwear | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "The GetName() method returns the names of the constants in the Enumeration."
},
{
"code": null,
"e": 1156,
"s": 1138,
"text": "Here is the enum."
},
{
"code": null,
"e": 1202,
"s": 1156,
"text": "enum Stock { Appliance, Clothing, Footwear };"
},
{
"code": null,
"e": 1310,
"s": 1202,
"text": "Now, get the names using the Enum.GetName() method. Just set the constant and retrieve the individual name."
},
{
"code": null,
"e": 1340,
"s": 1310,
"text": "Enum.GetName(typeof(Stock), 1"
},
{
"code": null,
"e": 1368,
"s": 1340,
"text": "Let us see the example now."
},
{
"code": null,
"e": 1379,
"s": 1368,
"text": " Live Demo"
},
{
"code": null,
"e": 1685,
"s": 1379,
"text": "using System;\nclass Demo {\n enum Stock { Appliance, Clothing, Footwear };\n static void Main() {\n Console.WriteLine(\"The value of second stock category = {0}\",Enum.GetName(typeof(Stock), 1));\n Console.WriteLine(\"The value of third stock category = {0}\",Enum.GetName(typeof(Stock), 2));\n }\n}"
},
{
"code": null,
"e": 1776,
"s": 1685,
"text": "The value of second stock category = Clothing\nThe value of third stock category = Footwear"
}
] |
Batch Script - SYSTEMINFO | This batch command shows configuration of a computer and its operating system.
systeminfo
@echo off
systeminfo
The above command will show the system information on the current system. Following is a subset of the output.
Host Name: WIN-50GP30FGO75
OS Name: Microsoft Windows Server 2012 R2 Standard
OS Version: 6.3.9600 N/A Build 9600
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Server
OS Build Type: Multiprocessor Free
Registered Owner: Windows User
Registered Organization:
Product ID: 00252-70000-00000-AA535
Original Install Date: 12/13/2015, 12:10:16 AM
System Boot Time: 12/28/2015, 4:43:04 PM
System Manufacturer: LENOVO
System Model: 20287
System Type: x64-based PC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2248,
"s": 2169,
"text": "This batch command shows configuration of a computer and its operating system."
},
{
"code": null,
"e": 2260,
"s": 2248,
"text": "systeminfo\n"
},
{
"code": null,
"e": 2281,
"s": 2260,
"text": "@echo off\nsysteminfo"
},
{
"code": null,
"e": 2392,
"s": 2281,
"text": "The above command will show the system information on the current system. Following is a subset of the output."
},
{
"code": null,
"e": 3021,
"s": 2392,
"text": "Host Name: WIN-50GP30FGO75 \nOS Name: Microsoft Windows Server 2012 R2 Standard \nOS Version: 6.3.9600 N/A Build 9600\nOS Manufacturer: Microsoft Corporation \nOS Configuration: Standalone Server \nOS Build Type: Multiprocessor Free \nRegistered Owner: Windows User \nRegistered Organization: \nProduct ID: 00252-70000-00000-AA535 \nOriginal Install Date: 12/13/2015, 12:10:16 AM \nSystem Boot Time: 12/28/2015, 4:43:04 PM \nSystem Manufacturer: LENOVO \nSystem Model: 20287 \nSystem Type: x64-based PC\n"
},
{
"code": null,
"e": 3028,
"s": 3021,
"text": " Print"
},
{
"code": null,
"e": 3039,
"s": 3028,
"text": " Add Notes"
}
] |
How to Verify Tooltip using Selenium WebDriver? | We can verify the tooltip of an element using Selenium webdriver using the getAttribute method. A tooltip text is the one which gets displayed while we hover on that element.
It disappears once we move the mouse away from the element. A tooltip text generally displays the title attribute value of an element. First, we identify the element then apply the getAttribute method on it. The parameter to be passed to this method is title.
Let us investigate the html code of an element - Tools having a tooltip text.
Here, the tooltip text displayed from Tools menu is Tools - Online Development and Testing Tools which is the value set for the title attribute in the html.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class TooltipVerfy{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/index.htm");
//identify element
WebElement n = driver.findElement(By.linkText("Tools"));
//obtain title attribute
String s = n.getAttribute("title");
//verify tooltip text
if(s.equals("Tools - Online Development and Testing Tools")) {
System.out.println("Tooltip text matched");
}else{
System.out.println("Tooltip text not matched");
}
driver.quit();
}
} | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "We can verify the tooltip of an element using Selenium webdriver using the getAttribute method. A tooltip text is the one which gets displayed while we hover on that element."
},
{
"code": null,
"e": 1497,
"s": 1237,
"text": "It disappears once we move the mouse away from the element. A tooltip text generally displays the title attribute value of an element. First, we identify the element then apply the getAttribute method on it. The parameter to be passed to this method is title."
},
{
"code": null,
"e": 1575,
"s": 1497,
"text": "Let us investigate the html code of an element - Tools having a tooltip text."
},
{
"code": null,
"e": 1732,
"s": 1575,
"text": "Here, the tooltip text displayed from Tools menu is Tools - Online Development and Testing Tools which is the value set for the title attribute in the html."
},
{
"code": null,
"e": 2752,
"s": 1732,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class TooltipVerfy{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //identify element\n WebElement n = driver.findElement(By.linkText(\"Tools\"));\n\n //obtain title attribute\n String s = n.getAttribute(\"title\");\n //verify tooltip text\n\n if(s.equals(\"Tools - Online Development and Testing Tools\")) {\n System.out.println(\"Tooltip text matched\");\n }else{\n System.out.println(\"Tooltip text not matched\");\n }\n driver.quit();\n }\n}"
}
] |
C++ Program to Implement Segmented Sieve to Generate Prime Numbers Between Given Range | This is C++ program to implement Segmented Sieve to Generate Prime Numbers Between Given Range. Segmented Sieve first uses Simple Sieve to find primes smaller than or equal to β(n). The idea of this algorithm is to divide the range [0 ... n-1] in different segments and compute primes in all segments one by one.
Begin
Create function to find all primes smaller than limit
using simple sieve of eratosthenes.
Finds all prime numbers in given range using
segmented sieve
A) Compute all primes smaller or equal to square root of high using simple sieve
B) Count of elements in given range
C) Declaring boolean only for [low, high]
D) Find the minimum number in [low ... high] that is a multiple of prime[i] (divisible by prime[i])
E) Mark multiples of prime[i] in [low ... high]
F) Numbers which are not marked in range, are prime
End
#include <bits/stdc++.h>
using namespace std;
void simpleSieve(int lmt, vector<int>& prime) {
bool mark[lmt + 1];
memset(mark, false, sizeof(mark));
for (int i = 2; i <= lmt; ++i) {
if (mark[i] == false) {
prime.push_back(i);
for (int j = i; j <= lmt; j += i)
mark[j] = true;
}
}
}
void PrimeInRange(int low, int high) {
int lmt = floor(sqrt(high)) + 1;
vector<int> prime;
simpleSieve(lmt, prime);
int n = high - low + 1;
bool mark[n + 1];
memset(mark, false, sizeof(mark));
for (int i = 0; i < prime.size(); i++) {
int lowLim = floor(low / prime[i]) * prime[i];
if (lowLim < low)
lowLim += prime[i];
for (int j = lowLim; j <= high; j += prime[i])
mark[j - low] = true;
}
for (int i = low; i <= high; i++)
if (!mark[i - low])
cout << i << " ";
}
int main() {
int low = 10, high = 50;
PrimeInRange(low, high);
return 0;
}
11 13 17 19 23 29 31 37 41 43 47 | [
{
"code": null,
"e": 1375,
"s": 1062,
"text": "This is C++ program to implement Segmented Sieve to Generate Prime Numbers Between Given Range. Segmented Sieve first uses Simple Sieve to find primes smaller than or equal to β(n). The idea of this algorithm is to divide the range [0 ... n-1] in different segments and compute primes in all segments one by one."
},
{
"code": null,
"e": 1925,
"s": 1375,
"text": "Begin\n Create function to find all primes smaller than limit\n using simple sieve of eratosthenes.\n Finds all prime numbers in given range using\n segmented sieve\n A) Compute all primes smaller or equal to square root of high using simple sieve\n B) Count of elements in given range\n C) Declaring boolean only for [low, high]\n D) Find the minimum number in [low ... high] that is a multiple of prime[i] (divisible by prime[i])\n E) Mark multiples of prime[i] in [low ... high]\n F) Numbers which are not marked in range, are prime\nEnd"
},
{
"code": null,
"e": 2887,
"s": 1925,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid simpleSieve(int lmt, vector<int>& prime) {\n bool mark[lmt + 1];\n memset(mark, false, sizeof(mark));\n for (int i = 2; i <= lmt; ++i) {\n if (mark[i] == false) {\n prime.push_back(i);\n for (int j = i; j <= lmt; j += i)\n mark[j] = true;\n }\n }\n}\nvoid PrimeInRange(int low, int high) {\n int lmt = floor(sqrt(high)) + 1;\n vector<int> prime;\n simpleSieve(lmt, prime);\n int n = high - low + 1;\n bool mark[n + 1];\n memset(mark, false, sizeof(mark));\n for (int i = 0; i < prime.size(); i++) {\n int lowLim = floor(low / prime[i]) * prime[i];\n if (lowLim < low)\n lowLim += prime[i];\n for (int j = lowLim; j <= high; j += prime[i])\n mark[j - low] = true;\n }\n for (int i = low; i <= high; i++)\n if (!mark[i - low])\n cout << i << \" \";\n}\nint main() {\n int low = 10, high = 50;\n PrimeInRange(low, high);\n return 0;\n}"
},
{
"code": null,
"e": 2920,
"s": 2887,
"text": "11 13 17 19 23 29 31 37 41 43 47"
}
] |
Similarity Measures β Scoring Textual Articles | by Saif Ali Kheraj | Towards Data Science | Many real-world applications make use of similarity measures to see how two objects are related together. We can use these measures in the applications involving Computer vision and Natural Language Processing, for example, to find and map similar documents. One important use case here for the business would be to match resumes with the Job Description saving a considerable amount of time for the recruiter. Another important use case would be to segment different customers for marketing campaigns using the K Means Clustering algorithm which also uses similarity measures.
Similarities are usually positive ranging between 0 (No Similarity) and 1 (Complete Similarity). We will specifically discuss two important similarity metric namely euclidean and cosine along with the coding example to deal with Wikipedia articles.
Do you remember Pythagoras Theorem?? Pythagoras Theorem is used to calculate the distance between two points as indicated in the figure below.
In the figure, we have two data points (x1,y1) and (x2,y2) and we are interested in calculating the distance or closeness between these two points. To find the distance, we need to first go horizontally from x1 to x2 and then go vertically up from y1 to y2. This makes up a right-angled triangle. We are interested in calculating hypotenuse d which we can calculate easily using the Pythagoras theorem.
where b is the base of the right-angled triangle and p is the perpendicular of the right-angled triangle.
This completes our euclidean distance formula for two points in two-dimensional space.
This defines the euclidean distance between two points in one, two, three or higher-dimensional space where n is the number of dimensions and x_k and y_k are components of x and y respectively.
Python Function to define euclidean distance
def euclidean_distance(x, y): return np.sqrt(np.sum((x - y) ** 2))
Here x and y are the two vectors.
You can also use sklearn library to calculate the euclidean distance. This function is computationally more efficient.
from sklearn.metrics.pairwise import euclidean_distances
Greater the distance, lower the similarity between the two objects; Lower the distance, higher the similarity between the two objects. To convert this distance metric into the similarity metric, we can divide the distances of objects with the max distance, and then subtract it by 1 to score the similarity between 0 and 1. We will look at the example after discussing the cosine metric.
This is another metric to find the similarity specifically for the documents. This metric is a measure of the angle between x and y as indicated in the diagram and is used when the magnitude of the vector does not matter.
If the angle between v and w is 0 degree, then the cosine similarity =1 (Complete Similarity).
Cosine Formula for dot Product:
ββ
β denotes vector length
ΞΈ: Angle between v and w. Here we are interested in measuring the similarity between v and w.
If you want to know how to derive the equation for cosine formula for dot product, please refer to this page: https://proofwiki.org/wiki/Cosine_Formula_for_Dot_Product. This dot product formula is derived from the same Law of Cosine which you have studied in your schools.
Letβs use the notation x and y instead of v and w.
Example:
These two vectors have low similarity explained by the value of 0.11. This value is close to 0 which means that the angle between x and y is close to 90 degrees. If the value would have been close to 1, then this would be very similar objects with an angle close to 0 degrees.
Dividing x and y by their lengths normalizes its length to 1 making it what is known as Unit Vector. This tells that cosine similarity does not take into account the magnitude of x and y. When we need to take into account the magnitude, euclidean might be a better option.
If we already have vectors with a length of 1, cosine similarity can be easily calculated using simple dot product. It is therefore recommended to normalize vectors first to have a unit length to reduce the computation time.
Python Function to define Cosine Similarity
def cosine_similarity(x, y): return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))
The diagram summarizes both the Euclidean and Cosine Metric.
Cosine looks at the angle between the two vectors ignoring magnitude while the Euclidean focuses on the straight line distance taking into account the magnitude of the vector.
Text mining is one of those areas where we can make use of cosine similarity to map similar documents. We can also use it to rank documents with respect to the given vector of words, CV shortlisting is one of those use cases where we can make use of Cosine similarity.
Letβs take the problem where we need to match similar documents, we first create the Document Term Matrix that contains the frequency of terms occurring in a collection of documents. We usually have documents of uneven lengths as in the case of Wikipedia articles. Letβs say the word math appeared more in Document 1 than it does in document 2, cosine similarity, in this case, would be a perfect choice as we are not concerned about the length of the document but the content it contains. If we were to consider the length, then the Euclidean might be a perfect option.
import wikipediaarticles=['Data Mining','Machine Learning','Cricket','Swimming','Tennis']wiki_lst=[]for article in articles: print(article) wiki_lst.append(wikipedia.page(article).content)
Here we have just fetched contents from the 5 Wikipedia articles.
from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()X=cv.fit_transform(wiki_lst)
Count Vectorizer just converts the collection of documents into the matrix of word counts.
Lets now use the euclidean metric to find out which of our articles are similar. Here we have normalized these euclidean distances between 0 and 1 and then subtracted it by 1 to range it between 0 and 1. Hence, closer it is to 1, higher the similarity.
from sklearn.metrics.pairwise import euclidean_distancesprint("Data Mining and Machine Learning",1-euclidean_distances(X[0],X[1])/np.max((euclidean_distances(X))))print("Data Mining and Cricket",1-euclidean_distances(X[0],X[2])/np.max((euclidean_distances(X))))print("Data Mining and Swimming",1-euclidean_distances(X[0],X[3])/np.max((euclidean_distances(X))))print("Data Mining and Tennis",1-euclidean_distances(X[0],X[4])/np.max((euclidean_distances(X))))
How are these two articles(Data Mining Swimming) most similar? It does not make any sense. Lets now try Cosine Similarity.
from sklearn.metrics.pairwise import cosine_similarityprint("Data Mining and Machine Learning",cosine_similarity(X[0],X[1]))print("Data Mining and Cricket",cosine_similarity(X[0],X[2]))print("Data Mining and Swimming",cosine_similarity(X[0],X[3]))print("Data Mining and Tennis",cosine_similarity(X[0],X[4]))
This is what makes sense to us. Data Mining is very close to Machine Learning.
The Euclidean metric here seems to focus on length rather than the content while cosine concentrated on the content ignoring the magnitude. | [
{
"code": null,
"e": 750,
"s": 172,
"text": "Many real-world applications make use of similarity measures to see how two objects are related together. We can use these measures in the applications involving Computer vision and Natural Language Processing, for example, to find and map similar documents. One important use case here for the business would be to match resumes with the Job Description saving a considerable amount of time for the recruiter. Another important use case would be to segment different customers for marketing campaigns using the K Means Clustering algorithm which also uses similarity measures."
},
{
"code": null,
"e": 999,
"s": 750,
"text": "Similarities are usually positive ranging between 0 (No Similarity) and 1 (Complete Similarity). We will specifically discuss two important similarity metric namely euclidean and cosine along with the coding example to deal with Wikipedia articles."
},
{
"code": null,
"e": 1142,
"s": 999,
"text": "Do you remember Pythagoras Theorem?? Pythagoras Theorem is used to calculate the distance between two points as indicated in the figure below."
},
{
"code": null,
"e": 1545,
"s": 1142,
"text": "In the figure, we have two data points (x1,y1) and (x2,y2) and we are interested in calculating the distance or closeness between these two points. To find the distance, we need to first go horizontally from x1 to x2 and then go vertically up from y1 to y2. This makes up a right-angled triangle. We are interested in calculating hypotenuse d which we can calculate easily using the Pythagoras theorem."
},
{
"code": null,
"e": 1651,
"s": 1545,
"text": "where b is the base of the right-angled triangle and p is the perpendicular of the right-angled triangle."
},
{
"code": null,
"e": 1738,
"s": 1651,
"text": "This completes our euclidean distance formula for two points in two-dimensional space."
},
{
"code": null,
"e": 1932,
"s": 1738,
"text": "This defines the euclidean distance between two points in one, two, three or higher-dimensional space where n is the number of dimensions and x_k and y_k are components of x and y respectively."
},
{
"code": null,
"e": 1977,
"s": 1932,
"text": "Python Function to define euclidean distance"
},
{
"code": null,
"e": 2050,
"s": 1977,
"text": "def euclidean_distance(x, y): return np.sqrt(np.sum((x - y) ** 2))"
},
{
"code": null,
"e": 2084,
"s": 2050,
"text": "Here x and y are the two vectors."
},
{
"code": null,
"e": 2203,
"s": 2084,
"text": "You can also use sklearn library to calculate the euclidean distance. This function is computationally more efficient."
},
{
"code": null,
"e": 2260,
"s": 2203,
"text": "from sklearn.metrics.pairwise import euclidean_distances"
},
{
"code": null,
"e": 2648,
"s": 2260,
"text": "Greater the distance, lower the similarity between the two objects; Lower the distance, higher the similarity between the two objects. To convert this distance metric into the similarity metric, we can divide the distances of objects with the max distance, and then subtract it by 1 to score the similarity between 0 and 1. We will look at the example after discussing the cosine metric."
},
{
"code": null,
"e": 2870,
"s": 2648,
"text": "This is another metric to find the similarity specifically for the documents. This metric is a measure of the angle between x and y as indicated in the diagram and is used when the magnitude of the vector does not matter."
},
{
"code": null,
"e": 2965,
"s": 2870,
"text": "If the angle between v and w is 0 degree, then the cosine similarity =1 (Complete Similarity)."
},
{
"code": null,
"e": 2997,
"s": 2965,
"text": "Cosine Formula for dot Product:"
},
{
"code": null,
"e": 3023,
"s": 2997,
"text": "ββ
β denotes vector length"
},
{
"code": null,
"e": 3117,
"s": 3023,
"text": "ΞΈ: Angle between v and w. Here we are interested in measuring the similarity between v and w."
},
{
"code": null,
"e": 3390,
"s": 3117,
"text": "If you want to know how to derive the equation for cosine formula for dot product, please refer to this page: https://proofwiki.org/wiki/Cosine_Formula_for_Dot_Product. This dot product formula is derived from the same Law of Cosine which you have studied in your schools."
},
{
"code": null,
"e": 3441,
"s": 3390,
"text": "Letβs use the notation x and y instead of v and w."
},
{
"code": null,
"e": 3450,
"s": 3441,
"text": "Example:"
},
{
"code": null,
"e": 3727,
"s": 3450,
"text": "These two vectors have low similarity explained by the value of 0.11. This value is close to 0 which means that the angle between x and y is close to 90 degrees. If the value would have been close to 1, then this would be very similar objects with an angle close to 0 degrees."
},
{
"code": null,
"e": 4000,
"s": 3727,
"text": "Dividing x and y by their lengths normalizes its length to 1 making it what is known as Unit Vector. This tells that cosine similarity does not take into account the magnitude of x and y. When we need to take into account the magnitude, euclidean might be a better option."
},
{
"code": null,
"e": 4225,
"s": 4000,
"text": "If we already have vectors with a length of 1, cosine similarity can be easily calculated using simple dot product. It is therefore recommended to normalize vectors first to have a unit length to reduce the computation time."
},
{
"code": null,
"e": 4269,
"s": 4225,
"text": "Python Function to define Cosine Similarity"
},
{
"code": null,
"e": 4371,
"s": 4269,
"text": "def cosine_similarity(x, y): return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))"
},
{
"code": null,
"e": 4432,
"s": 4371,
"text": "The diagram summarizes both the Euclidean and Cosine Metric."
},
{
"code": null,
"e": 4608,
"s": 4432,
"text": "Cosine looks at the angle between the two vectors ignoring magnitude while the Euclidean focuses on the straight line distance taking into account the magnitude of the vector."
},
{
"code": null,
"e": 4877,
"s": 4608,
"text": "Text mining is one of those areas where we can make use of cosine similarity to map similar documents. We can also use it to rank documents with respect to the given vector of words, CV shortlisting is one of those use cases where we can make use of Cosine similarity."
},
{
"code": null,
"e": 5448,
"s": 4877,
"text": "Letβs take the problem where we need to match similar documents, we first create the Document Term Matrix that contains the frequency of terms occurring in a collection of documents. We usually have documents of uneven lengths as in the case of Wikipedia articles. Letβs say the word math appeared more in Document 1 than it does in document 2, cosine similarity, in this case, would be a perfect choice as we are not concerned about the length of the document but the content it contains. If we were to consider the length, then the Euclidean might be a perfect option."
},
{
"code": null,
"e": 5643,
"s": 5448,
"text": "import wikipediaarticles=['Data Mining','Machine Learning','Cricket','Swimming','Tennis']wiki_lst=[]for article in articles: print(article) wiki_lst.append(wikipedia.page(article).content)"
},
{
"code": null,
"e": 5709,
"s": 5643,
"text": "Here we have just fetched contents from the 5 Wikipedia articles."
},
{
"code": null,
"e": 5819,
"s": 5709,
"text": "from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()X=cv.fit_transform(wiki_lst)"
},
{
"code": null,
"e": 5910,
"s": 5819,
"text": "Count Vectorizer just converts the collection of documents into the matrix of word counts."
},
{
"code": null,
"e": 6163,
"s": 5910,
"text": "Lets now use the euclidean metric to find out which of our articles are similar. Here we have normalized these euclidean distances between 0 and 1 and then subtracted it by 1 to range it between 0 and 1. Hence, closer it is to 1, higher the similarity."
},
{
"code": null,
"e": 6621,
"s": 6163,
"text": "from sklearn.metrics.pairwise import euclidean_distancesprint(\"Data Mining and Machine Learning\",1-euclidean_distances(X[0],X[1])/np.max((euclidean_distances(X))))print(\"Data Mining and Cricket\",1-euclidean_distances(X[0],X[2])/np.max((euclidean_distances(X))))print(\"Data Mining and Swimming\",1-euclidean_distances(X[0],X[3])/np.max((euclidean_distances(X))))print(\"Data Mining and Tennis\",1-euclidean_distances(X[0],X[4])/np.max((euclidean_distances(X))))"
},
{
"code": null,
"e": 6744,
"s": 6621,
"text": "How are these two articles(Data Mining Swimming) most similar? It does not make any sense. Lets now try Cosine Similarity."
},
{
"code": null,
"e": 7052,
"s": 6744,
"text": "from sklearn.metrics.pairwise import cosine_similarityprint(\"Data Mining and Machine Learning\",cosine_similarity(X[0],X[1]))print(\"Data Mining and Cricket\",cosine_similarity(X[0],X[2]))print(\"Data Mining and Swimming\",cosine_similarity(X[0],X[3]))print(\"Data Mining and Tennis\",cosine_similarity(X[0],X[4]))"
},
{
"code": null,
"e": 7131,
"s": 7052,
"text": "This is what makes sense to us. Data Mining is very close to Machine Learning."
}
] |
MySQL Tryit Editor v1.0 | SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;
β
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 54,
"s": 0,
"text": "SELECT SUBSTR(\"SQL Tutorial\", 5, 3) AS ExtractString;"
},
{
"code": null,
"e": 56,
"s": 54,
"text": "β"
},
{
"code": null,
"e": 128,
"s": 65,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 188,
"s": 128,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 256,
"s": 188,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 294,
"s": 256,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 379,
"s": 294,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 553,
"s": 379,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 604,
"s": 553,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 672,
"s": 604,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 843,
"s": 672,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 943,
"s": 843,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 993,
"s": 943,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
The debugger statement in JavaScript | The debugger statement in JavaScript is used for setting a breakpoint in the code. The code
stops execution as soon as it encounters the debugger statement and calls the debugger function (if available).
Following is the code to implement debugger statement in JavaScript β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Debugger statement in JavaScript.</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the printTable() function</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
function printTable(num) {
for (let i = 1; i <= 10; i++) {
debugger;
resEle.innerHTML += i + " ";
}
}
BtnEle.addEventListener("click", () => {
printTable();
});
</script>
</body>
</html>
On clicking the βCLICK HEREβ button and opening the debugger β | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "The debugger statement in JavaScript is used for setting a breakpoint in the code. The code\nstops execution as soon as it encounters the debugger statement and calls the debugger function (if available)."
},
{
"code": null,
"e": 1336,
"s": 1266,
"text": "Following is the code to implement debugger statement in JavaScript β"
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": " Live Demo"
},
{
"code": null,
"e": 2243,
"s": 1347,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Debugger statement in JavaScript.</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to call the printTable() function</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function printTable(num) {\n for (let i = 1; i <= 10; i++) {\n debugger;\n resEle.innerHTML += i + \" \";\n }\n }\n BtnEle.addEventListener(\"click\", () => {\n printTable();\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2306,
"s": 2243,
"text": "On clicking the βCLICK HEREβ button and opening the debugger β"
}
] |
Arithmetic Operators in VBScript | Following table shows all the arithmetic operators supported by VBScript language. Assume variable A holds 5 and variable B holds 10, then β
Try the following example to understand all the arithmetic operators available in VBScript β
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 5
Dim b : b = 10
Dim c
c = a+b
Document.write ("Addition Result is " &c)
Document.write ("<br></br>") 'Inserting a Line Break for readability
c = a-b
Document.write ("Subtraction Result is " &c)
Document.write ("<br></br>") 'Inserting a Line Break for readability
c = a*b
Document.write ("Multiplication Result is " &c)
Document.write ("<br></br>")
c = b/a
Document.write ("Division Result is " &c)
Document.write ("<br></br>")
c = b MOD a
Document.write ("Modulus Result is " &c)
Document.write ("<br></br>")
c = b^a
Document.write ("Exponentiation Result is " &c)
Document.write ("<br></br>")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result β
Addition Result is 15
Subtraction Result is -5
Multiplication Result is 50
Division Result is 2
Modulus Result is 0
Exponentiation Result is 100000
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2221,
"s": 2080,
"text": "Following table shows all the arithmetic operators supported by VBScript language. Assume variable A holds 5 and variable B holds 10, then β"
},
{
"code": null,
"e": 2314,
"s": 2221,
"text": "Try the following example to understand all the arithmetic operators available in VBScript β"
},
{
"code": null,
"e": 3294,
"s": 2314,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim a : a = 5\n Dim b : b = 10\n Dim c\n\n c = a+b\n Document.write (\"Addition Result is \" &c)\n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n \n c = a-b\n Document.write (\"Subtraction Result is \" &c)\n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n \n c = a*b\n Document.write (\"Multiplication Result is \" &c)\n Document.write (\"<br></br>\")\n \n c = b/a\n Document.write (\"Division Result is \" &c)\n Document.write (\"<br></br>\")\n \n c = b MOD a\n Document.write (\"Modulus Result is \" &c)\n Document.write (\"<br></br>\")\n \n c = b^a\n Document.write (\"Exponentiation Result is \" &c)\n Document.write (\"<br></br>\")\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3415,
"s": 3294,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result β"
},
{
"code": null,
"e": 3569,
"s": 3415,
"text": "Addition Result is 15\n\nSubtraction Result is -5\n\nMultiplication Result is 50\n\nDivision Result is 2\n\nModulus Result is 0\n\nExponentiation Result is 100000\n"
},
{
"code": null,
"e": 3602,
"s": 3569,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3619,
"s": 3602,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3626,
"s": 3619,
"text": " Print"
},
{
"code": null,
"e": 3637,
"s": 3626,
"text": " Add Notes"
}
] |
Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) in C++ | In this problem, we are given a number n which defines the nth term of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n). Our task is to create a program to find the sum of the series.
Input
n = 3
Output
Explanation β sum = (2) + (2+4) + (2+4+6) = 2 + 6 + 12 = 20
A simple solution to the problem is to use a nested loop. The inner loop finds the ith element of the series and then add up all elements to the sum variable.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
int sum = 0;
for (int i = 1; i<=n; i++) {
int even = 2;
for (int j = 1; j<=i; j++) {
sum += even;
even += 2;
}
}
return sum;
}
int main() {
int n = 5;
cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n);
return 0;
}
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70
This is not the most effective way to solve the problem as the time complexity of the problem is of the order O(n2).
An effective solution to the problem is by using the mathematical formula for the sum of the series.
The series is 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)
The nth term of the series is
an = (2 + 4 + 6 + 8 + ... + 2n) = (n*n) + n
an is the sum of even numbers upto n.
The sum of the series is
sum = 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)
sum = β (n2 + n)
sum = β n2 + β n
sum = [ (n*(n+1)*(2n + 1))/6 ] + [ (n*(n+1))/2 ]
sum = 1β2 (n*(n+1)) [(2n + 1)/3 + 1]
sum = 1β2 (n*(n+1)) [(2n + 1 + 3)/3]
sum = 1β2 (n*(n+1)) [2(n+2)/3]
sum = 1β3 n*(n+1)(n+2)
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
return ((n)*(n+1)*(n+2)/3);
}
int main() {
int n = 5;
cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n);
return 0;
}
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70 | [
{
"code": null,
"e": 1265,
"s": 1062,
"text": "In this problem, we are given a number n which defines the nth term of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n). Our task is to create a program to find the sum of the series."
},
{
"code": null,
"e": 1272,
"s": 1265,
"text": "Input "
},
{
"code": null,
"e": 1278,
"s": 1272,
"text": "n = 3"
},
{
"code": null,
"e": 1285,
"s": 1278,
"text": "Output"
},
{
"code": null,
"e": 1345,
"s": 1285,
"text": "Explanation β sum = (2) + (2+4) + (2+4+6) = 2 + 6 + 12 = 20"
},
{
"code": null,
"e": 1504,
"s": 1345,
"text": "A simple solution to the problem is to use a nested loop. The inner loop finds the ith element of the series and then add up all elements to the sum variable."
},
{
"code": null,
"e": 1555,
"s": 1504,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 1566,
"s": 1555,
"text": " Live Demo"
},
{
"code": null,
"e": 1955,
"s": 1566,
"text": "#include <iostream>\nusing namespace std;\nint calcSeriesSum(int n) {\n int sum = 0;\n for (int i = 1; i<=n; i++) {\n int even = 2;\n for (int j = 1; j<=i; j++) {\n sum += even;\n even += 2;\n }\n }\n return sum;\n}\nint main() {\n int n = 5;\n cout<<\"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+\"<<(2*n)<<\") is \"<<calcSeriesSum(n);\n return 0;\n}"
},
{
"code": null,
"e": 2022,
"s": 1955,
"text": "Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70"
},
{
"code": null,
"e": 2139,
"s": 2022,
"text": "This is not the most effective way to solve the problem as the time complexity of the problem is of the order O(n2)."
},
{
"code": null,
"e": 2240,
"s": 2139,
"text": "An effective solution to the problem is by using the mathematical formula for the sum of the series."
},
{
"code": null,
"e": 2311,
"s": 2240,
"text": "The series is 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)"
},
{
"code": null,
"e": 2341,
"s": 2311,
"text": "The nth term of the series is"
},
{
"code": null,
"e": 2385,
"s": 2341,
"text": "an = (2 + 4 + 6 + 8 + ... + 2n) = (n*n) + n"
},
{
"code": null,
"e": 2423,
"s": 2385,
"text": "an is the sum of even numbers upto n."
},
{
"code": null,
"e": 2448,
"s": 2423,
"text": "The sum of the series is"
},
{
"code": null,
"e": 2722,
"s": 2448,
"text": "sum = 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)\nsum = β (n2 + n)\nsum = β n2 + β n\nsum = [ (n*(n+1)*(2n + 1))/6 ] + [ (n*(n+1))/2 ]\nsum = 1β2 (n*(n+1)) [(2n + 1)/3 + 1]\nsum = 1β2 (n*(n+1)) [(2n + 1 + 3)/3]\nsum = 1β2 (n*(n+1)) [2(n+2)/3]\nsum = 1β3 n*(n+1)(n+2)"
},
{
"code": null,
"e": 2773,
"s": 2722,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2784,
"s": 2773,
"text": " Live Demo"
},
{
"code": null,
"e": 3031,
"s": 2784,
"text": "#include <iostream>\nusing namespace std;\nint calcSeriesSum(int n) {\n return ((n)*(n+1)*(n+2)/3);\n}\nint main() {\n int n = 5;\n cout<<\"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+\"<<(2*n)<<\") is \"<<calcSeriesSum(n);\n return 0;\n}"
},
{
"code": null,
"e": 3098,
"s": 3031,
"text": "Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70"
}
] |
Database Testing - Quick Guide | Database testing includes performing data validity, data integrity testing, performance check related to database and testing of procedures, triggers and functions in the database.
Consider an application that captures the day-to-day transaction details for users and stores the details in the database. From database testing point of view, the following checks should be performed β
The transactional information from the application should be stored in the database and it should provide correct information to the user.
The transactional information from the application should be stored in the database and it should provide correct information to the user.
Information should not be lost when it is loaded to database.
Information should not be lost when it is loaded to database.
Only completed transactions should be stored and all incomplete operations should be aborted by the application.
Only completed transactions should be stored and all incomplete operations should be aborted by the application.
Access authorization to database should be maintained. No unapproved or unauthorized access to user information should be provided.
Access authorization to database should be maintained. No unapproved or unauthorized access to user information should be provided.
There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose.
Given below are some common reasons for Database testing β
To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures.
To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures.
These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels.
These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels.
Black-box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system.
Black-box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system.
In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly.
In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly.
Database testing is different from front-end UI testing. The following table highlights the key differences β
Database testing is known as data validation and integrity testing or back-end testing.
UI testing or front-end testing is also called Application testing or GUI testing.
Database testing involves testing of back-end components, which are not visible to users.
This includes database components and DBMS systems such as My SQL, Oracle.
UI testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc.
These components are created using front-end development tools like VB.net, C#, Delphi, etc.
Database testing involves checking stored procedures, views, schemas in database, tables, indexes, keys, triggers, data validations and data consistence check.
UI testing involves checking the functionality of application, buttons, forms and fields, calendar and images, navigation from one page to other, and the overall functionality of the application.
To perform DB testing, a tester needs a thorough knowledge of database concept β like procedures and functions, views, indexes, keys and good hands-on SQL.
To perform UI testing, a tester needs a good understanding of business requirements, application functional knowledge, coding, etc.
Data comes from multiple heterogeneous data sources over web applications, Intranet applications and various other applications.
Data is entered manually into applications. It involves functional testing of front-end applications.
Based on the function and structure of a database, DB testing can be categorized into three categories β
Structural Database Testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc.
Structural Database Testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc.
Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing.
Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing.
Nonfunctional Testing β It involves load-testing, risk testing in database, stress testing, minimum system requirements, and deals with the performance of the database.
Nonfunctional Testing β It involves load-testing, risk testing in database, stress testing, minimum system requirements, and deals with the performance of the database.
Structural database testing involves verifying those components of database, which are not exposed to end users. It involves all the components of repository, which are used to store the data and are not changed by the end users. Database administrators with good command over SQL stored procedures and other concepts normally perform this testing.
Discussed are the common components tested with respect to Structural Testing β
It involves validating the objects of front-end application with database object mapping.
In Schema Testing β
Sometimes it happens that the end user application objects are not correctly mapped or compatible with database objects. Therefore, checking the validation of the various schema formats associated with the databases is required.
Sometimes it happens that the end user application objects are not correctly mapped or compatible with database objects. Therefore, checking the validation of the various schema formats associated with the databases is required.
It is required to find the unmapped objects in database, like tables, views, columns etc. is required.
It is required to find the unmapped objects in database, like tables, views, columns etc. is required.
There are various tools in the market that can be used to perform object mapping in schemas.
Example β In Microsoft SQL Server, a tester can write simple queries to check and validate schemas in the database.
If the tester wants to make changes to a table structure, he/she should ensure that all the stored procedures having that table are compatible with this change.
In this testing, a tester ensures that the manual execution of stored procedures and views generate the required result.
The tester ensures β
If it enables the required triggers to be executed as expected.
If it enables the required triggers to be executed as expected.
If the development team has covered all the loops and conditions by passing input to applications in the procedures.
If the development team has covered all the loops and conditions by passing input to applications in the procedures.
If there are any unused stored procedures in the database.
If there are any unused stored procedures in the database.
TRIM operations are applied properly when the data is fetched from required tables in database.
TRIM operations are applied properly when the data is fetched from required tables in database.
Validation of the overall integration of the stored procedure modules as per as the requirements of the application under test.
Validation of the overall integration of the stored procedure modules as per as the requirements of the application under test.
Exception and error handling mechanisms are followed.
Exception and error handling mechanisms are followed.
The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc.
In trigger testing, a tester needs to ensure the following β
Whether the coding conventions are followed during the coding phase of the triggers.
Whether the coding conventions are followed during the coding phase of the triggers.
See the triggers executed meets the required conditions.
See the triggers executed meets the required conditions.
Whether the trigger updates the data correctly, once they have been executed.
Whether the trigger updates the data correctly, once they have been executed.
Validation of Update/Insert/Delete triggers functionality w.r.t application under test.
Validation of Update/Insert/Delete triggers functionality w.r.t application under test.
The key areas covered in this testing are β
Validating the data types in the database to field values in front-end application.
Validating the data types in the database to field values in front-end application.
Validating the length of data field in database to length of data types in the application.
Validating the length of data field in database to length of data types in the application.
Checking if there are any unmapped tables or columns in the database from application field objects.
Checking if there are any unmapped tables or columns in the database from application field objects.
Naming conventions of database tables and columns are verified, if they are in accordance with business requirement or not.
Naming conventions of database tables and columns are verified, if they are in accordance with business requirement or not.
Validating the Keys and Indexes in the database, i.e., primary and foreign keys in tables are defined as per requirement.
Validating the Keys and Indexes in the database, i.e., primary and foreign keys in tables are defined as per requirement.
Check if the primary keys and their corresponding foreign keys are same in two tables.
Check if the primary keys and their corresponding foreign keys are same in two tables.
Check Unique and NOT NULL characteristics of keys are maintained.
Check Unique and NOT NULL characteristics of keys are maintained.
Length and data type of keys and indexes are maintained as per requirement.
Length and data type of keys and indexes are maintained as per requirement.
Database Server check involves verifying β
If the database server can handle the expected number of transactions as per the business requirement.
If the database server can handle the expected number of transactions as per the business requirement.
If the configuration details of database servers meets the business requirement.
If the configuration details of database servers meets the business requirement.
If the user authorization is maintained as per requirement.
If the user authorization is maintained as per requirement.
Functional testing is performed keeping in mind an end-user point of view; whether the required transactions and operations run by the end-users meet the business specifications.
Black Box Testing involves verifying the integration of database to check the functionality. The test cases are simple and are used to verify incoming data and outgoing data from the function.
Various techniques such as cause-effect graphing technique, equivalence partitioning and boundary-value analysis are used to test the functionality of the database.
Its advantages are as follows β
It is fairly simple and is performed in the early stages of development.
Cost of developing test-cases is less as compared to white-box testing.
Its disadvantages are as follows β
A few errors cannot be detected
It is unknown how much program needs to be tested.
White Box Testing deals with the internal structure of the database and the specification details are hidden from the users. It involves the testing of database triggers and logical views, which are going to support database refactoring.
It performs module testing of database functions, triggers, views, SQL queries etc. This type of testing validates database tables, data models, database schema etc. It checks rules of Referential integrity. It selects default table values to check on database consistency.
The most common techniques used to perform white box testing are condition coverage, decision coverage, statement coverage, etc.
Coding errors can be detected in white-box testing, so internal bugs in the database can be eliminated. The limitation of white-box testing is that SQL statements are not covered.
Nonfunctional testing involves performing load testing, stress testing, checking minimum system requirements to meet business specification, risk finding and performance optimization of database.
The primary target of load testing is to check if most running transactions have performance impact on the database.
In Load testing, the tester checks β
The response time for executing the transactions for multiple remote users.
Time taken by the database to fetch specific records.
Examples of load testing in different testing types β
Running most used transaction repeatedly to see performance of database system.
Downloading a series of large files from the internet.
Running multiple applications on a computer or server simultaneously.
Stress testing is performed to identify the system breakpoint. In this testing, application is loaded in such a way that the system fails at one point. This point is called the breakpoint of database system.
Determining the state of database transactions involves a significant amount of effort. Proper planning is required to avoid any time and cost-based issues.
The most commonly used stress testing tools are LoadRunner and WinRunner.
Let us take an example of Stress Testing. A CRM application can take a maximum user load of 50000 concurrent users. Suppose you increase the load to 51000 and make some transactions such as updating records or adding an entry. As soon as you do the transaction, the application can sync with the database system. So the next test is to perform with a user load of 52000. Sometimes, Stress Testing is also called Fatigue Testing.
The process to perform database testing is similar to testing of other applications. DB testing can be described with key processes given below.
Set up the environment
Run a test
Check the test result
Validate according to the expected results
Report the findings to the respective stakeholders
Various SQL statements are used to develop the Test cases. The most common SQL statement, which is used to perform DB testing, is the Select statement. Apart from this, various DDL, DML, DCL statements can also be used.
Example β Create, Insert, Select, Update, etc.
DB testing is not a tedious process and includes various stages in database testing lifecycle in accordance with the test processes.
The key stages in database testing are β
Checking the initial state
Test run
Outcome validation as per expected result
Generating the results
First stage in DB Testing is to check the initial state of the database before starting the testing process. Then database behavior is tested for defined test cases. In accordance with the results obtained, test cases are customized.
For successful database testing, the workflow given below is executed by every single test.
Cleaning up the database β If there is testable data in the database, it should be emptied.
Cleaning up the database β If there is testable data in the database, it should be emptied.
Set up Fixture β This involves entering the data into the database and check the current state of the database.
Set up Fixture β This involves entering the data into the database and check the current state of the database.
Perform test, verify results and generate results β The Test is run and the output is verified. If the output is as per expected results, the next step is to generate the results as per requirement. Otherwise, testing is repeated to find the bugs in database.
Perform test, verify results and generate results β The Test is run and the output is verified. If the output is as per expected results, the next step is to generate the results as per requirement. Otherwise, testing is repeated to find the bugs in database.
This chapter explains the most common techniques that are used to perform Database Testing.
As mentioned earlier, it involves testing each object in the Schema.
Verifying the name of database
Verifying the data device, log device and dump device
Verifying if enough space allocated for each database
Verifying database option setting
Verify the items given below to find out the differences between actual and applied setting.
Name of all the tables in database
Name of all the tables in database
Column names for each table
Column names for each table
Column types for each table
Column types for each table
NULL value checked or not
NULL value checked or not
Whether a default is bound to correct table columns
Whether a default is bound to correct table columns
Rule definitions to correct table names and access privileges
Rule definitions to correct table names and access privileges
Verify the Key and indexes in each table β
Primary key for each table
Primary key for each table
Foreign keys for each table
Foreign keys for each table
Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique
Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique
It involves checking whether a stored procedure is defined and the output results are compared. In a Stored Procedure test, the following points are checked β
Stored procedure name
Stored procedure name
Parameter names, parameter types, etc.
Parameter names, parameter types, etc.
Output β Whether the output contains many records. Zero rows are effected or only a few records are extracted.
Output β Whether the output contains many records. Zero rows are effected or only a few records are extracted.
What is the function of Stored Procedure and what a stored procedure is not supposed to do?
What is the function of Stored Procedure and what a stored procedure is not supposed to do?
Passing sample input queries to check if a stored procedure extracts correct data.
Passing sample input queries to check if a stored procedure extracts correct data.
Stored Procedure Parameters β Call stored procedure with boundary data and with valid data. Make each parameter invalid once and run a procedure.
Stored Procedure Parameters β Call stored procedure with boundary data and with valid data. Make each parameter invalid once and run a procedure.
Return values β Check the values that are returned by stored procedure. In case of a failure, nonzero must be returned.
Return values β Check the values that are returned by stored procedure. In case of a failure, nonzero must be returned.
Error messages check β Make changes in such a way that the stored procedure fails and generate every error message at least once. Check any exception scenarios when there is no predefined error message.
Error messages check β Make changes in such a way that the stored procedure fails and generate every error message at least once. Check any exception scenarios when there is no predefined error message.
In a Trigger test, the tester must perform the following tasks β
Make sure the trigger name is correct.
Validate the trigger if it is generated for a specific table column.
Triggerβs update validation.
Update a record with a valid data.
Update a record with invalid data and cover every trigger error.
Update a record when it is still referenced by a row in other table.
Ensure rolling back transactions when a failure occurs.
Find out any cases in which a trigger is not supposed to roll back transactions.
Two types of tests should be performed β
Setting up the database from scratch, and
To set up an existing database.
Integration tests should be performed after you are through with component testing.
Stored procedures should be called intensively to select, insert, update, and delete records in different tables to find any conflicts and incompatibility.
Stored procedures should be called intensively to select, insert, update, and delete records in different tables to find any conflicts and incompatibility.
Any conflicts between schema and triggers.
Any conflicts between schema and triggers.
Any conflicts between stored procedures and schema.
Any conflicts between stored procedures and schema.
Any conflicts between stored procedures and triggers.
Any conflicts between stored procedures and triggers.
Functional testing can be performed by dividing the database into modules as per functionality. The functionalities are of the following two types β
Type 1 β In Type 1 testing, find out the features of the project. For each major feature, find out the schema, triggers, and stored procedures responsible to implement that function and put them into a functional group. Then test each group together.
Type 1 β In Type 1 testing, find out the features of the project. For each major feature, find out the schema, triggers, and stored procedures responsible to implement that function and put them into a functional group. Then test each group together.
Type 2 β In Type 2 testing, the border of functional groups in a back-end is not obvious. You can check the data flow and see where you can check the data. Start from the front-end.
Type 2 β In Type 2 testing, the border of functional groups in a back-end is not obvious. You can check the data flow and see where you can check the data. Start from the front-end.
The following process takes place β
When a service has a request or saves data, some stored procedures will get called.
When a service has a request or saves data, some stored procedures will get called.
The procedures will update some tables.
The procedures will update some tables.
Those stored procedures will be the place to start testing and those tables will be the place to check the test results.
Those stored procedures will be the place to start testing and those tables will be the place to check the test results.
Stress Testing involves getting a list of major database functions and corresponding stored procedures. Follow the steps given below for Stress Testing β
Write test scripts to try those functions and every function must be checked at least once in a full cycle.
Write test scripts to try those functions and every function must be checked at least once in a full cycle.
Perform the test scripts again and again for a specific time period.
Perform the test scripts again and again for a specific time period.
Verifying the log files to check any deadlocks, failure out of memory, data corruption, etc.
Verifying the log files to check any deadlocks, failure out of memory, data corruption, etc.
If your database does not have any data problems or bugs, system performance can be checked. A poor system performance can be found in benchmark testing by checking the parameters given below β
System level performance
Identify most-likely-used functions/features
Timing β maximum time, minimum time and average time to perform functions
Access volume
Back-end bugs can also be found sometimes by doing front-end testing. You can follow the simple steps given below to detect bugs by front-end testing.
Write queries from the front-end and issue the searches.
Write queries from the front-end and issue the searches.
Pick up an existing record, change the values in some fields, and save the record. (It involves the UPDATE statement or update stored procedures and update triggers.)
Pick up an existing record, change the values in some fields, and save the record. (It involves the UPDATE statement or update stored procedures and update triggers.)
Insert a new menu item in the front-end window. Fill in the information and save the record. (It involves the INSERT statements or insertion stored procedures and deletion triggers.)
Insert a new menu item in the front-end window. Fill in the information and save the record. (It involves the INSERT statements or insertion stored procedures and deletion triggers.)
Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves the DELETE statement or deletion stored procedures and deletion triggers.)
Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves the DELETE statement or deletion stored procedures and deletion triggers.)
Repeat these test-cases with invalid data and see how the database responds.
Repeat these test-cases with invalid data and see how the database responds.
In this chapter, we will see some common database test scenarios with respect to various testing methods.
Common database scenarios with respect to Structured Database Testing are given below β
Verifying the name of database, verifying the data device, log device and dump device, verifying if enough space allocated for each database and verifying database option setting.
Verifying the name of database, verifying the data device, log device and dump device, verifying if enough space allocated for each database and verifying database option setting.
Names of all the tables in database, column names for each table, column types for each table, null value check or not. Verify the Key and indexes in each table: Primary key for each table, foreign keys for each table.
Names of all the tables in database, column names for each table, column types for each table, null value check or not. Verify the Key and indexes in each table: Primary key for each table, foreign keys for each table.
Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique.
Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique.
Common Database Test scenarios with respect to Functional Database Testing are β
Finding out the schema, triggers and stored procedures responsible to implement that function and make them into a functional group and then each group can be tested together.
Finding out the schema, triggers and stored procedures responsible to implement that function and make them into a functional group and then each group can be tested together.
Check data flow and see where you can check the data. Start from the front-end.
Check data flow and see where you can check the data. Start from the front-end.
Common Database Test scenarios with respect to Non-Functional Database Testing are β
Write test scripts to try major functions and every function must be checked at least once in a full cycle.
Write test scripts to try major functions and every function must be checked at least once in a full cycle.
Perform the test scripts again and again for a specific time period.
Perform the test scripts again and again for a specific time period.
Verifying the log files to check any deadlock, failure out of memory, data corruption, etc.
Verifying the log files to check any deadlock, failure out of memory, data corruption, etc.
Write queries from a front end and issue the searches. Pick up an existing record, change values in some fields and save the record. (It involves UPDATE statement or update stored procedures, update triggers.)
Write queries from a front end and issue the searches. Pick up an existing record, change values in some fields and save the record. (It involves UPDATE statement or update stored procedures, update triggers.)
Insert a new menu item in a front-end window. Fill in information and save the record. (It involves INSERT statements or insertion stored procedures, deletion triggers.)
Insert a new menu item in a front-end window. Fill in information and save the record. (It involves INSERT statements or insertion stored procedures, deletion triggers.)
Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves DELETE statement or deletion stored procedures, deletion triggers.)
Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves DELETE statement or deletion stored procedures, deletion triggers.)
Repeat these test-cases with invalid data and see how the database responds.
Repeat these test-cases with invalid data and see how the database responds.
Schemas, tables, stored procedures, and Triggers are key objects of a database. We have already shared DB testing types and test scenarios for these data base objects.
A database schema defines the structure of a database system in a format supported by the database management system. A Schema refers to how a database is structured (composed of database tables in the case of Relational Databases).
The database schema is a set of formulas called integrity constraints imposed on a database. These integrity constraints ensure compatibility between parts of the schema.
In a relational database, the schema consists of tables, fields, views, indexes, packages, procedures, functions, triggers, types, materialized views, synonyms, database links, and other elements.
Schemas are generally stored in a data dictionary. Although a schema is defined in text database language, the term is often used to refer to a graphical depiction of the database structure. In other words, schema is the structure of the database that defines the objects in the database.
Common type of Schemas used in a data warehouse are β
Star Schema
Snowflakes Schema
Galaxy Schema
In a relational database, a table is used to organize the information into rows and columns.
Example β A Customer table contains information such as customer id, addresses, phone numbers, and so on as a series of columns.
Each single piece of data is a field in the table. A column consists of all the entries in a single field, such as the telephone numbers of all the customers. Fields are organized as records, which are complete sets of information (such as the set of information about a particular customer), each of which comprises a row.
A stored procedure is a series of SQL statements stored in the database in a compiled form and multiple programs can share it. The use of stored procedures can be helpful in maintaining data integrity, data control access and improving productivity.
A database trigger is code that is executed in response to certain events on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database.
Data Integrity is important in a database. It includes data validation before insertion, updates, and deletion. Triggers must be in place to validate reference table records.
For checking Data Integrity, you need to perform the following operations β
You need to check major columns in each table and verify if any incorrect data exists. (Characters in name field, negative percentage, etc.)
You need to check major columns in each table and verify if any incorrect data exists. (Characters in name field, negative percentage, etc.)
Find out inconsistent data and insert them into relevant tables and see if any failure occurs.
Find out inconsistent data and insert them into relevant tables and see if any failure occurs.
Insert a child data before inserting its parentβs data. Try to delete a record that is still referenced by the data in another table.
Insert a child data before inserting its parentβs data. Try to delete a record that is still referenced by the data in another table.
If a data in a table is updated, check whether the other relevant data is updated as well. You need to ensure that replicated servers or databases are in sync and contain consistent information.
If a data in a table is updated, check whether the other relevant data is updated as well. You need to ensure that replicated servers or databases are in sync and contain consistent information.
Data mapping in a database is one of the key concept that needs to be validated by every tester. Usually the testers have to verify the user interface front end field mapping with the corresponding back end database field.
This information is given in Software requirement specification or business requirement specification SRS/BRS document. If mapping is not provided, then you need to check the coding part.
When you take any action in the front end application, there is a corresponding CRUD action get invoked, and tester have to check the every invoked action is successful or not.
Given below are the key aspects of Data Mapping β
To check the fields in the UI/Front end forms and mapped consistently with the corresponding DB table. This mapping information is defined in the requirements documents as mentioned above.
To check the fields in the UI/Front end forms and mapped consistently with the corresponding DB table. This mapping information is defined in the requirements documents as mentioned above.
For any action performed in the front end of an application, a corresponding CRUD βCreate, Retrieve, Update and deleteβ action gets initiated at the back end.
For any action performed in the front end of an application, a corresponding CRUD βCreate, Retrieve, Update and deleteβ action gets initiated at the back end.
A tester will have to check if the right action is invoked and the invoked action in itself is successful or not.
A tester will have to check if the right action is invoked and the invoked action in itself is successful or not.
Given below are the steps followed for Data Mapping Testing β
Step 1 β First check for syntax error in each script.
Step 1 β First check for syntax error in each script.
Step 2 β Next is to check for table mapping, column mapping, and data type mapping.
Step 2 β Next is to check for table mapping, column mapping, and data type mapping.
Step 3 β Verify lookup data mapping.
Step 3 β Verify lookup data mapping.
Step 4 β Run each script when records do not exist in destination tables.
Step 4 β Run each script when records do not exist in destination tables.
Step 5 β Run each script when the records already exist in the destination tables.
Step 5 β Run each script when the records already exist in the destination tables.
An application with more response time and poor performance can lead to huge problems. Database Load Testing is used to find any performance issues before you deploy your database applications for end users.
Database Load Testing helps you design database application for performance, reliability and scalability. Load Testing of Database applications involves testing the performance and scalability of your Database application with varying user load.
Database Load testing involves simulating real-life user load for the target Database application. It helps you determine how your Database application behaves when multiple users hits it simultaneously.
The primary target of Load Testing is to check if most running transactions have performance impact on the database. In load testing, you need to check the following aspects β
The response time for executing the transactions for multiple remote users should be checked.
The response time for executing the transactions for multiple remote users should be checked.
With normal transactions, you should include one editable transaction to check the performance of the database for these type pf transactions.
With normal transactions, you should include one editable transaction to check the performance of the database for these type pf transactions.
With normal transactions, you should include one non-editing transaction to check performance of database for these type of transactions.
With normal transactions, you should include one non-editing transaction to check performance of database for these type of transactions.
Time taken by database to fetch specific records should be checked.
Time taken by database to fetch specific records should be checked.
Stress testing is performed to identify the system breakpoint. Here the application is loaded in such a way that the system fails at one point. This point is called the breakpoint of the database system. Stress testing is also known as Fatigue Testing.
Determining the state of database transactions involves a significant amount of effort. Proper planning is required to avoid any time- and cost-based issues.
The most common stress testing tools are LoadRunner and WinRunner.
There are various tools provided by vendors that can be used to generate Test data, to manage Test data and perform database testing like Load Testing and Regression Testing.
A few common tools that are used are given below.
Load Testing Tools
These tools are used to put high usage loads on your database, which enables to determine whether your system's landscape will stand up to your business needs.
Web Performance
Rad View
Mercury
Data Security Tools
These tools are used to implement compliance and standards as per the information security regulations.
IBM Optim Data Privacy
Test Data generator tools
A tester uses these tools to generate the test data for a database system. These are mostly required when you have huge amount of data and you need sample to perform DB Testing. It is commonly used for Load and Stress testing.
Data Factory
DTM Data Generator
Turbo Data
Test Data Management Tool
These tools are used to maintain version control for test data. You have to define the expected results and then you compare it with the actual outcomes of the tests.
IBM Optim Test Data Management
Tools to perform Unit Testing
These tools are used to perform regression testing on your database.
SQLUnit
TSQLUnit
DBFit
DBUnit
The most important part of an organizational growth is its data. In case of a system failure, there is a need to restore the data. Back up is an exact copy of the database, which helps you to restore your data in case of any data loss.
Consider a finance company which has data related to its customers such as A/C number, customer names, credit and debits, duration, etc. How would such an organization deal with the pressure of losing such important information in case of a data failure?
This is the reason you back up the data so that in case of any failure of a disk, disk controller, etc. you can rely on the backup to restore it into the database.
There are two types of backup that can be used β
Physical Backups β Physical backup includes taking back up using third-party backup tools like Veritas Net Back, IBM Tivoli Manager or user manager backups using OS utilities.
Physical Backups β Physical backup includes taking back up using third-party backup tools like Veritas Net Back, IBM Tivoli Manager or user manager backups using OS utilities.
Logical Backups β Logical backup of database includes taking backups of logical objects like tables, indexes, procedures, etc.
Logical Backups β Logical backup of database includes taking backups of logical objects like tables, indexes, procedures, etc.
Example β One of common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup.
RMAN consists of two components β
Target database for which backup is required.
Target database for which backup is required.
RMAN client is used to run commands to take data backup.
RMAN client is used to run commands to take data backup.
BACKUP VALIDATE is used to test if you are able to make a valid backup of database files. It ensures β
If backup is in place for physical or logical objects of database.
If regular backups are set up for invaluable data.
If the backup tool meets the backup requirements of an organization.
Database recovery testing is used to ensure that the database is recovered. Recovery testing allows you to find out whether the application is running properly and to check retrieving invaluable data that would have been lost if your recovery method is not properly setup.
You also check if several critical processes are running smooth to ensure that the data recovery will pass smoothly through the testing phase.
You can perform the following checks for database recovery β
Any errors or mistakes in the backup software and you need to resolve these issues at an earlier stage.
Any errors or mistakes in the backup software and you need to resolve these issues at an earlier stage.
You need to conduct the recovery testing so that you will know what to do in case of an emergency situation.
You need to conduct the recovery testing so that you will know what to do in case of an emergency situation.
You need to check recovery testing needs so that you can plan for an effective recovery strategy.
You need to check recovery testing needs so that you can plan for an effective recovery strategy.
You should also know how you can recover the documents.
You should also know how you can recover the documents.
You need to run the recovery tests in early phase of the project. This allows you to remove and throw away every type of errors from the system. Here is a list of some of important points, which should be considered at the time of testing β
Time span when changes or modifications occurs in database system.
Time span when changes or modifications occurs in database system.
The period by which you want your recovery plan conducted.
The period by which you want your recovery plan conducted.
The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software.
The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software.
In database recovery testing, you need to run the test in the actual environment to check if the system or the data can actually be recovered in case of any disasters and any other unforeseen events in the business environment.
Given below are the common actions performed in Database Recovery Testing β
Testing of database system
Testing of the SQL files
Testing of partial files
Testing of data backup
Testing of Backup tool
Testing log backups
Database security testing is done to find the loopholes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system.
The main target of database security testing is to find out vulnerabilities in a system and to determine whether its data and resources are protected from potential intruders. Security testing defines a way to identify potential vulnerabilities effectively, when performed regularly.
Given below are the primary objectives of performing database security testing β
Authentication
Authorization
Confidentiality
Availability
Integrity
Resilience
This is most common type of attack in a database system where malicious SQL statements are inserted in the database system and are executed to get critical information from the database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this, user inputs fields should be carefully handled.
In this attack, a user already has some access in the database system and he only tries to elevate this access higher level so that he/she can perform some unauthorized activities in database system.
In this type of attack, an attacker makes a database system or application resource unavailable to its legitimate users. Applications can also be attacked in ways that render the application, and sometimes the entire machine, unusable.
Another type of attack is gaining unauthorized access to data within an application or database system. Unauthorized access includes β
Unauthorized access to data via user based applications
Unauthorized access to by monitoring the access of others
Unauthorized access to reusable client authentication information
In Identity Spoofing, a hacker uses the credentials of a user or device to launch attacks against network hosts, steal data or bypass access controls to database system. Preventing this attack requires IT-infrastructure and network-level mitigations.
In a data manipulation attack, a hacker changes data to gain some advantage or to damage the image of database owners.
A penetration test is an attack on a computer system with the intention of finding security loopholes, potentially gaining access to it, its functionality and data.
Risk Finding is a process of assessing and deciding on the risk involved with the type of loss and the possibility of vulnerability occurrence. This is determined within the organization by various interviews, discussions and analysis.
It involves checking the user inputs in application fields. For example, entering a special character like β,β or β;β in any text box in a user application should not be allowed. When a database error occurs, it means that the user input is inserted in some query, which is then executed by the application. In such a case, the application is vulnerable to SQL injection.
These attacks are a big threat to data as the attackers can get access to important information from the server database. To check SQL injection entry points into your web application, find out code from your code base where direct MySQL queries are executed on the database by accepting some user inputs.
SQL Injection Testing can be performed for Brackets, Commas, and Quotation marks.
This is the most important check while performing database system testing. To access critical information, hackers can use a password-cracking tool or can guess a common username/password. These common passwords are easily available on internet and also password cracking tools exist freely.
Therefore, it is necessary to check at the time of testing if the password policy is maintained in the system. In case of any banking and finance applications, there is a need to set a strict password policy on all the critical information database systems.
A security audit is a process of evaluating companyβs security policies at a regular time interval to determine whether necessary standards are followed or not. Various security standards can be followed as per business requirement to define the security policy and then assessment of set policies against those standards can be done.
Example of most common security standards are ISO 27001, BS15999, etc.
There are various system testing tools available in market, which can be used to test OS and application check. Some of the most common tools are discussed below.
It is a penetration-testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. It is commonly used for Windows, Linux, Mac OS.
All HTTP and HTTPS data between server and client, including cookies and form fields, can be intercepted and modified using these scanners. It is used for Cross-platform, Java JRE/JDK 1.4.2 or above.
It is an open source tool and human elements are attacked rather than the system element. It enables you to send emails, java applets etc. containing the attack code. It is preferred for Linux, Apple Mac OS X and Microsoft Windows.
This tool is used to scan their sites for vulnerabilities. Reports generated by the tool are meant to serve as a foundation for professional web application security assessments. It is preferred for Linux, FreeBSD, MacOS X, and Windows.
It is an open source, multiplatform web security tool that is used to find instances of SQL injection, cross-site scripting (XSS), and other vulnerabilities in web applications. It is preferred for Java, Linux, and Windows.
Wapiti is an open source and web-based tool that scans the web pages of the web application and check for scripts and forms where it can inject data. It is built with Python and can detect File handling errors, Database, XSS, LDAP and CRLF injections, Command execution detection.
It is written in Java and is used for analyzing the applications that communicate through HTTP/HTTPS protocols. This tool is primarily designed for developers who can write code themselves. This tool is not OS dependent.
To perform database testing successfully, a tester should collect the requirements from all the sources, like technical and functional requirements. There is a possibility that a few requirements are at a high level, so there is a need to breakdown those requirements into the small parts. Testing database is a complex task and the testers face many challenges while performing this testing. Most common database testing challenges are β
A tester needs to identify the test items in database testing otherwise he may not have a clear understanding of what he would test and what he would not test. Therefore, if you are clear on the requirement, you may waste a lot of time testing uncritical objects in the database.
When you have a list of objects to test, next is to estimate the effort required to design the tests and execute the tests for each test item. Depending on their design and data size, some database tests may take a long time to execute.
As the database size is too large, it becomes a big challenge to find out the objects that have to be tested and those which are to be left out.
Normally testers are provided with a copy of the development database to test. That database only have little data, which is sufficient to run the application. So there is a need to test the development, staging and as well as production database system.
This is one of the common challenges in DB testing. Sometimes, it happens that you design or execute a test, and the database structure has been changed at that time. This is necessary that you should be aware of the changes made to the database during testing.
Once the database structure changes, you should analyze the impact of the changes and modify the tests. In addition, if multiple users use the test database, you would not be sure about the test results so you should ensure that the test database is used for testing purpose only.
Another challenge in DB testing is that you run multiple tests at the same time. You should run one test at a time at least for the performance tests. You do not want your database performing multiple tasks and under-reporting performance.
The database structure is normally complex and it has huge data, so there is a possibility that you are executing incomplete or same tests repeatedly. So there is a need to create a test plan and proceed accordingly and checking the progress regularly.
To test a database, you should have a good knowledge of SQL queries and the required database management tools.
Database testing includes performing the data validity, data Integrity testing, performance check related to database and testing of Procedures, triggers and functions in the database.
There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose.
Some of the common reasons why one needs to perform Database testing are as follows β
To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures.
To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures.
These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels.
These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels.
Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system.
Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system.
In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly.
In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly.
The steps that you need to follow while performing database testing are as follows β
The data that is being in the database must be verified.
Verify if the constraints are maintained.
The performance of the procedures and execution of triggers must be checked.
Roll back and commit of transaction must be checked.
On the basis of function and structure of a database, DB testing can be categorized into the following categories β
Structural Database testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc.
Structural Database testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc.
Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing.
Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing.
Nonfunctional Testing β It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database.
Nonfunctional Testing β It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database.
The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc.
Joins are used to connect two or more tables in some logical manner. Common types of joins include: Inner join, Non-equijoin, Outer join, Self-join, and Cross join.
You can join a single table to itself. In this case, you are using the same table twice.
Step 1 β Connect to the database
db_connect(query1 DRIVER {drivername};SERVER server_name;UID uidname;
PWD password;DBQ database_name );
Step 2 β Execute the query of the database β
db_excecute_query (write the required query that is to execute); Specify the appropriate condition
Step 3 β Disconnect the database connection by using
db_disconnect(query);
Using Output database checkpoints, SQL manual queries options must be selected. Here, the select query can be written.
First, check the requirement of the stored procedure. The next step is to check if indexes, joins, deletions, update are correct in comparison with tables mentioned in stored procedure.
Next, perform the following tasks β
Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters.
Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters.
Execute the procedure with TOAD or MySQL or Query Analyzer.
Execute the procedure with TOAD or MySQL or Query Analyzer.
Re-execute the available procedures by sending different parameters, and check the results against expected values.
Re-execute the available procedures by sending different parameters, and check the results against expected values.
Concluding to the process, automate the tests with WinRunner.
Concluding to the process, automate the tests with WinRunner.
The tester should call the stored procedure in the database using the EXEC command. If any parameters are required, they must be passed. Different values of parameters must be passed to confirm if the stored procedure is executed or not. On calling this command it must check and verify the nature and behavior of the database.
Example β If the stored procedure is written to populate some table, the table values must be checked.
We have three types of SQL statements β
Data Manipulation Language (DML)
Data Definition Language (DDL)
Data Control Language (DCL)
DDL statements are used to define the database structure or schema. Some examples β
CREATE β to create objects in the database
CREATE β to create objects in the database
ALTER β alters the structure of the database
ALTER β alters the structure of the database
DROP β delete objects from the database
DROP β delete objects from the database
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
Arithmetic Operators
Comparison/Relational Operators
Logical Operators
Set Operators
Operators used to negate conditions
Union is used to combine the results of two or more Select statements. However it will eliminate the duplicate rows. Union is a set operator.
Union is used to combine the results of two or more Select statements. However it will eliminate duplicate rows
Union All operation is similar to Union, but it also shows the duplicate rows.
Triggers are used to maintain the Integrity of database. To check Trigger is fired or not you can check in audit logs.
Triggers canβt be invoked on demand. They are invoked when an associated action (insert, delete & update) happens on the table on which they are defined. Triggers are used to apply business rules, auditing and also for the referential integrity checks.
First, get the functional requirement. Then, understand the table structure, Joins, Cursors and Triggers, Stored procedure used, and other parameters. Next, you can write a test-case with different values as input to these objects.
DB testing involves testing of back-end components which are not visible to users. It includes database components and DBMS systems such as MySQL and Oracle.
Front-end testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc. These components are created using front-end development tools like VB.net, C#, Delphi, etc.
The process to perform database testing is similar to testing of other applications. DB testing can be described with the following key processes β
Setting up the environment
Run a test
Check the test result
Validating according to the expected results
Report the findings to the respective stakeholders
Various SQL statements are used to develop the Test cases. Most common SQL statement which is used to perform DB testing is select statement. Apart from this various DDL, DML, DCL statements can also be used.
Example β Create, Insert, Select, Update, etc.
A view is a table that does not really exist in its own right but is instead derived from one or more base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the changes in the database. Hence accounts for logical data independence.
It specifies user views and their mappings to the conceptual schema.
It is a process of decomposing a table into multiple tables without losing any information. Normalization is done to achieve the following goals β
To minimize redundancy.
To minimize insertion, deletion and update anomalies.
Indexing is a technique for determining how quickly specific data can be found. It is used for query performance optimization. Indexing can be of the following types β
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
SQL is a Structured Query language that is designed specifically for data access operations on normalized relational database structures.
The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them.
Stored procedures are used to perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client.
PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors β implicit and explicit.
Cold Backup β Cold back is known as taking back up of database files, redo logs, and control file when the instance is shut down. This is a file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All the changes that are performed after the last backup is lost.
Hot Backup β Some databases canβt shut down while making a backup copy of the files, so cold backup is not an available option. For these types of database we use hot backup.
SQL subquery is a means of querying two or more tables at the same time. The subquery itself is an SQL SELECT statement contained within the WHERE clause of another SQL SELECT statement, and separated by being enclosed in parenthesis. Some subqueries have equivalent SQL join structures, but correlated subqueries cannot be duplicated by a join
In such a case, you need to test the following aspects β
Multivalued dependencies
Functional dependencies
Candidate keys
Primary keys
Foreign keys
You can go to the database and run a relevant SQL query. In WinRunner, you can use database checkpoint function. If the application provides view function, then you can verify the same from the front-end.
Data-driven testing is defined as an automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface.
Once you execute the test-cases and find the defects that has been already detected and fixed. Re-execution of the same test with different input values to confirm the original defect has been successfully removed is called Re-testing.
Retesting is also called Data Driven Testing with a small difference β
Retesting β It is a manual testing process whereas application testing done with entire new set of data.
Retesting β It is a manual testing process whereas application testing done with entire new set of data.
Data-driven Testing β It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface.
Data-driven Testing β It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface.
There are four types of data driven testing β
Dynamic test data submission through keyboard
Data Driven Tests via .txt, .doc flat files
Data Driven Tests via front-end objects
Data Driven Tests via excel sheet
Performance testing is a software testing technique to determine how a system performs in terms of speed, sensitivity and stability under a heavy workload.
The following key points are to be considered while performing database recovery testing β
Time span when changes or modifications occurs in database system.
Time span when changes or modifications occurs in database system.
The period by which you want your recovery plan conducted.
The period by which you want your recovery plan conducted.
The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software.
The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software.
The following tools are used to generate test data β
Data Factory
DTM Data Generator
Turbo Data
There are two types of backup that can be used β
Physical Backups β Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities.
Physical Backups β Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities.
Logical Backups β Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc.
Logical Backups β Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc.
A common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup.
The following actions are performed in database recovery testing β
Testing of database system
Testing of the SQL files
Testing of partial files
Testing of data backup
Testing of Backup tool
Testing log backups
Database security testing is performed to find the loop holes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system.
Database security testing is performed to check the following aspects β
Authentication
Authorization
Confidentiality
Availability
Integrity
Resilience
SQL Injection threat is the most common type of attack in a database system where malicious SQL statements are inserted in database system and executed to get critical information from database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this user inputs fields should be carefully handled.
The following tools can be used to perform database security testing: Zed Attack Proxy, Paros, Social Engineer Toolkit, Skipfish, Vega, Wapiti, and Web Scarab.
The common challenges that one faces while performing database testing are as follows β
Testing scope is too large
Scaled-down test database
Changes in database structure
Complex Test Plans
Good understanding of SQL
33 Lectures
7.5 hours
Syed Raza
31 Lectures
6 hours
Eduonix Learning Solutions
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
17 Lectures
1.5 hours
Pranjal Srivastava
19 Lectures
2 hours
Harshit Srivastava
19 Lectures
5 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2251,
"s": 2070,
"text": "Database testing includes performing data validity, data integrity testing, performance check related to database and testing of procedures, triggers and functions in the database."
},
{
"code": null,
"e": 2454,
"s": 2251,
"text": "Consider an application that captures the day-to-day transaction details for users and stores the details in the database. From database testing point of view, the following checks should be performed β"
},
{
"code": null,
"e": 2593,
"s": 2454,
"text": "The transactional information from the application should be stored in the database and it should provide correct information to the user."
},
{
"code": null,
"e": 2732,
"s": 2593,
"text": "The transactional information from the application should be stored in the database and it should provide correct information to the user."
},
{
"code": null,
"e": 2794,
"s": 2732,
"text": "Information should not be lost when it is loaded to database."
},
{
"code": null,
"e": 2856,
"s": 2794,
"text": "Information should not be lost when it is loaded to database."
},
{
"code": null,
"e": 2969,
"s": 2856,
"text": "Only completed transactions should be stored and all incomplete operations should be aborted by the application."
},
{
"code": null,
"e": 3082,
"s": 2969,
"text": "Only completed transactions should be stored and all incomplete operations should be aborted by the application."
},
{
"code": null,
"e": 3214,
"s": 3082,
"text": "Access authorization to database should be maintained. No unapproved or unauthorized access to user information should be provided."
},
{
"code": null,
"e": 3346,
"s": 3214,
"text": "Access authorization to database should be maintained. No unapproved or unauthorized access to user information should be provided."
},
{
"code": null,
"e": 3594,
"s": 3346,
"text": "There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose."
},
{
"code": null,
"e": 3653,
"s": 3594,
"text": "Given below are some common reasons for Database testing β"
},
{
"code": null,
"e": 3765,
"s": 3653,
"text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures."
},
{
"code": null,
"e": 3877,
"s": 3765,
"text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures."
},
{
"code": null,
"e": 4068,
"s": 3877,
"text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels."
},
{
"code": null,
"e": 4259,
"s": 4068,
"text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels."
},
{
"code": null,
"e": 4491,
"s": 4259,
"text": "Black-box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system."
},
{
"code": null,
"e": 4723,
"s": 4491,
"text": "Black-box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system."
},
{
"code": null,
"e": 5001,
"s": 4723,
"text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly."
},
{
"code": null,
"e": 5279,
"s": 5001,
"text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly."
},
{
"code": null,
"e": 5389,
"s": 5279,
"text": "Database testing is different from front-end UI testing. The following table highlights the key differences β"
},
{
"code": null,
"e": 5477,
"s": 5389,
"text": "Database testing is known as data validation and integrity testing or back-end testing."
},
{
"code": null,
"e": 5560,
"s": 5477,
"text": "UI testing or front-end testing is also called Application testing or GUI testing."
},
{
"code": null,
"e": 5650,
"s": 5560,
"text": "Database testing involves testing of back-end components, which are not visible to users."
},
{
"code": null,
"e": 5725,
"s": 5650,
"text": "This includes database components and DBMS systems such as My SQL, Oracle."
},
{
"code": null,
"e": 5848,
"s": 5725,
"text": "UI testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc."
},
{
"code": null,
"e": 5941,
"s": 5848,
"text": "These components are created using front-end development tools like VB.net, C#, Delphi, etc."
},
{
"code": null,
"e": 6101,
"s": 5941,
"text": "Database testing involves checking stored procedures, views, schemas in database, tables, indexes, keys, triggers, data validations and data consistence check."
},
{
"code": null,
"e": 6297,
"s": 6101,
"text": "UI testing involves checking the functionality of application, buttons, forms and fields, calendar and images, navigation from one page to other, and the overall functionality of the application."
},
{
"code": null,
"e": 6453,
"s": 6297,
"text": "To perform DB testing, a tester needs a thorough knowledge of database concept β like procedures and functions, views, indexes, keys and good hands-on SQL."
},
{
"code": null,
"e": 6585,
"s": 6453,
"text": "To perform UI testing, a tester needs a good understanding of business requirements, application functional knowledge, coding, etc."
},
{
"code": null,
"e": 6714,
"s": 6585,
"text": "Data comes from multiple heterogeneous data sources over web applications, Intranet applications and various other applications."
},
{
"code": null,
"e": 6816,
"s": 6714,
"text": "Data is entered manually into applications. It involves functional testing of front-end applications."
},
{
"code": null,
"e": 6921,
"s": 6816,
"text": "Based on the function and structure of a database, DB testing can be categorized into three categories β"
},
{
"code": null,
"e": 7068,
"s": 6921,
"text": "Structural Database Testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc."
},
{
"code": null,
"e": 7215,
"s": 7068,
"text": "Structural Database Testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc."
},
{
"code": null,
"e": 7384,
"s": 7215,
"text": "Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing."
},
{
"code": null,
"e": 7553,
"s": 7384,
"text": "Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing."
},
{
"code": null,
"e": 7722,
"s": 7553,
"text": "Nonfunctional Testing β It involves load-testing, risk testing in database, stress testing, minimum system requirements, and deals with the performance of the database."
},
{
"code": null,
"e": 7891,
"s": 7722,
"text": "Nonfunctional Testing β It involves load-testing, risk testing in database, stress testing, minimum system requirements, and deals with the performance of the database."
},
{
"code": null,
"e": 8240,
"s": 7891,
"text": "Structural database testing involves verifying those components of database, which are not exposed to end users. It involves all the components of repository, which are used to store the data and are not changed by the end users. Database administrators with good command over SQL stored procedures and other concepts normally perform this testing."
},
{
"code": null,
"e": 8320,
"s": 8240,
"text": "Discussed are the common components tested with respect to Structural Testing β"
},
{
"code": null,
"e": 8410,
"s": 8320,
"text": "It involves validating the objects of front-end application with database object mapping."
},
{
"code": null,
"e": 8430,
"s": 8410,
"text": "In Schema Testing β"
},
{
"code": null,
"e": 8659,
"s": 8430,
"text": "Sometimes it happens that the end user application objects are not correctly mapped or compatible with database objects. Therefore, checking the validation of the various schema formats associated with the databases is required."
},
{
"code": null,
"e": 8888,
"s": 8659,
"text": "Sometimes it happens that the end user application objects are not correctly mapped or compatible with database objects. Therefore, checking the validation of the various schema formats associated with the databases is required."
},
{
"code": null,
"e": 8991,
"s": 8888,
"text": "It is required to find the unmapped objects in database, like tables, views, columns etc. is required."
},
{
"code": null,
"e": 9094,
"s": 8991,
"text": "It is required to find the unmapped objects in database, like tables, views, columns etc. is required."
},
{
"code": null,
"e": 9187,
"s": 9094,
"text": "There are various tools in the market that can be used to perform object mapping in schemas."
},
{
"code": null,
"e": 9303,
"s": 9187,
"text": "Example β In Microsoft SQL Server, a tester can write simple queries to check and validate schemas in the database."
},
{
"code": null,
"e": 9464,
"s": 9303,
"text": "If the tester wants to make changes to a table structure, he/she should ensure that all the stored procedures having that table are compatible with this change."
},
{
"code": null,
"e": 9585,
"s": 9464,
"text": "In this testing, a tester ensures that the manual execution of stored procedures and views generate the required result."
},
{
"code": null,
"e": 9606,
"s": 9585,
"text": "The tester ensures β"
},
{
"code": null,
"e": 9670,
"s": 9606,
"text": "If it enables the required triggers to be executed as expected."
},
{
"code": null,
"e": 9734,
"s": 9670,
"text": "If it enables the required triggers to be executed as expected."
},
{
"code": null,
"e": 9851,
"s": 9734,
"text": "If the development team has covered all the loops and conditions by passing input to applications in the procedures."
},
{
"code": null,
"e": 9968,
"s": 9851,
"text": "If the development team has covered all the loops and conditions by passing input to applications in the procedures."
},
{
"code": null,
"e": 10027,
"s": 9968,
"text": "If there are any unused stored procedures in the database."
},
{
"code": null,
"e": 10086,
"s": 10027,
"text": "If there are any unused stored procedures in the database."
},
{
"code": null,
"e": 10182,
"s": 10086,
"text": "TRIM operations are applied properly when the data is fetched from required tables in database."
},
{
"code": null,
"e": 10278,
"s": 10182,
"text": "TRIM operations are applied properly when the data is fetched from required tables in database."
},
{
"code": null,
"e": 10406,
"s": 10278,
"text": "Validation of the overall integration of the stored procedure modules as per as the requirements of the application under test."
},
{
"code": null,
"e": 10534,
"s": 10406,
"text": "Validation of the overall integration of the stored procedure modules as per as the requirements of the application under test."
},
{
"code": null,
"e": 10588,
"s": 10534,
"text": "Exception and error handling mechanisms are followed."
},
{
"code": null,
"e": 10642,
"s": 10588,
"text": "Exception and error handling mechanisms are followed."
},
{
"code": null,
"e": 10744,
"s": 10642,
"text": "The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc."
},
{
"code": null,
"e": 10805,
"s": 10744,
"text": "In trigger testing, a tester needs to ensure the following β"
},
{
"code": null,
"e": 10890,
"s": 10805,
"text": "Whether the coding conventions are followed during the coding phase of the triggers."
},
{
"code": null,
"e": 10975,
"s": 10890,
"text": "Whether the coding conventions are followed during the coding phase of the triggers."
},
{
"code": null,
"e": 11032,
"s": 10975,
"text": "See the triggers executed meets the required conditions."
},
{
"code": null,
"e": 11089,
"s": 11032,
"text": "See the triggers executed meets the required conditions."
},
{
"code": null,
"e": 11167,
"s": 11089,
"text": "Whether the trigger updates the data correctly, once they have been executed."
},
{
"code": null,
"e": 11245,
"s": 11167,
"text": "Whether the trigger updates the data correctly, once they have been executed."
},
{
"code": null,
"e": 11333,
"s": 11245,
"text": "Validation of Update/Insert/Delete triggers functionality w.r.t application under test."
},
{
"code": null,
"e": 11421,
"s": 11333,
"text": "Validation of Update/Insert/Delete triggers functionality w.r.t application under test."
},
{
"code": null,
"e": 11465,
"s": 11421,
"text": "The key areas covered in this testing are β"
},
{
"code": null,
"e": 11549,
"s": 11465,
"text": "Validating the data types in the database to field values in front-end application."
},
{
"code": null,
"e": 11633,
"s": 11549,
"text": "Validating the data types in the database to field values in front-end application."
},
{
"code": null,
"e": 11725,
"s": 11633,
"text": "Validating the length of data field in database to length of data types in the application."
},
{
"code": null,
"e": 11817,
"s": 11725,
"text": "Validating the length of data field in database to length of data types in the application."
},
{
"code": null,
"e": 11918,
"s": 11817,
"text": "Checking if there are any unmapped tables or columns in the database from application field objects."
},
{
"code": null,
"e": 12019,
"s": 11918,
"text": "Checking if there are any unmapped tables or columns in the database from application field objects."
},
{
"code": null,
"e": 12143,
"s": 12019,
"text": "Naming conventions of database tables and columns are verified, if they are in accordance with business requirement or not."
},
{
"code": null,
"e": 12267,
"s": 12143,
"text": "Naming conventions of database tables and columns are verified, if they are in accordance with business requirement or not."
},
{
"code": null,
"e": 12389,
"s": 12267,
"text": "Validating the Keys and Indexes in the database, i.e., primary and foreign keys in tables are defined as per requirement."
},
{
"code": null,
"e": 12511,
"s": 12389,
"text": "Validating the Keys and Indexes in the database, i.e., primary and foreign keys in tables are defined as per requirement."
},
{
"code": null,
"e": 12598,
"s": 12511,
"text": "Check if the primary keys and their corresponding foreign keys are same in two tables."
},
{
"code": null,
"e": 12685,
"s": 12598,
"text": "Check if the primary keys and their corresponding foreign keys are same in two tables."
},
{
"code": null,
"e": 12751,
"s": 12685,
"text": "Check Unique and NOT NULL characteristics of keys are maintained."
},
{
"code": null,
"e": 12817,
"s": 12751,
"text": "Check Unique and NOT NULL characteristics of keys are maintained."
},
{
"code": null,
"e": 12893,
"s": 12817,
"text": "Length and data type of keys and indexes are maintained as per requirement."
},
{
"code": null,
"e": 12969,
"s": 12893,
"text": "Length and data type of keys and indexes are maintained as per requirement."
},
{
"code": null,
"e": 13012,
"s": 12969,
"text": "Database Server check involves verifying β"
},
{
"code": null,
"e": 13115,
"s": 13012,
"text": "If the database server can handle the expected number of transactions as per the business requirement."
},
{
"code": null,
"e": 13218,
"s": 13115,
"text": "If the database server can handle the expected number of transactions as per the business requirement."
},
{
"code": null,
"e": 13299,
"s": 13218,
"text": "If the configuration details of database servers meets the business requirement."
},
{
"code": null,
"e": 13380,
"s": 13299,
"text": "If the configuration details of database servers meets the business requirement."
},
{
"code": null,
"e": 13440,
"s": 13380,
"text": "If the user authorization is maintained as per requirement."
},
{
"code": null,
"e": 13500,
"s": 13440,
"text": "If the user authorization is maintained as per requirement."
},
{
"code": null,
"e": 13679,
"s": 13500,
"text": "Functional testing is performed keeping in mind an end-user point of view; whether the required transactions and operations run by the end-users meet the business specifications."
},
{
"code": null,
"e": 13872,
"s": 13679,
"text": "Black Box Testing involves verifying the integration of database to check the functionality. The test cases are simple and are used to verify incoming data and outgoing data from the function."
},
{
"code": null,
"e": 14037,
"s": 13872,
"text": "Various techniques such as cause-effect graphing technique, equivalence partitioning and boundary-value analysis are used to test the functionality of the database."
},
{
"code": null,
"e": 14069,
"s": 14037,
"text": "Its advantages are as follows β"
},
{
"code": null,
"e": 14142,
"s": 14069,
"text": "It is fairly simple and is performed in the early stages of development."
},
{
"code": null,
"e": 14214,
"s": 14142,
"text": "Cost of developing test-cases is less as compared to white-box testing."
},
{
"code": null,
"e": 14249,
"s": 14214,
"text": "Its disadvantages are as follows β"
},
{
"code": null,
"e": 14281,
"s": 14249,
"text": "A few errors cannot be detected"
},
{
"code": null,
"e": 14332,
"s": 14281,
"text": "It is unknown how much program needs to be tested."
},
{
"code": null,
"e": 14570,
"s": 14332,
"text": "White Box Testing deals with the internal structure of the database and the specification details are hidden from the users. It involves the testing of database triggers and logical views, which are going to support database refactoring."
},
{
"code": null,
"e": 14844,
"s": 14570,
"text": "It performs module testing of database functions, triggers, views, SQL queries etc. This type of testing validates database tables, data models, database schema etc. It checks rules of Referential integrity. It selects default table values to check on database consistency."
},
{
"code": null,
"e": 14973,
"s": 14844,
"text": "The most common techniques used to perform white box testing are condition coverage, decision coverage, statement coverage, etc."
},
{
"code": null,
"e": 15153,
"s": 14973,
"text": "Coding errors can be detected in white-box testing, so internal bugs in the database can be eliminated. The limitation of white-box testing is that SQL statements are not covered."
},
{
"code": null,
"e": 15349,
"s": 15153,
"text": "Nonfunctional testing involves performing load testing, stress testing, checking minimum system requirements to meet business specification, risk finding and performance optimization of database."
},
{
"code": null,
"e": 15466,
"s": 15349,
"text": "The primary target of load testing is to check if most running transactions have performance impact on the database."
},
{
"code": null,
"e": 15503,
"s": 15466,
"text": "In Load testing, the tester checks β"
},
{
"code": null,
"e": 15579,
"s": 15503,
"text": "The response time for executing the transactions for multiple remote users."
},
{
"code": null,
"e": 15633,
"s": 15579,
"text": "Time taken by the database to fetch specific records."
},
{
"code": null,
"e": 15687,
"s": 15633,
"text": "Examples of load testing in different testing types β"
},
{
"code": null,
"e": 15767,
"s": 15687,
"text": "Running most used transaction repeatedly to see performance of database system."
},
{
"code": null,
"e": 15822,
"s": 15767,
"text": "Downloading a series of large files from the internet."
},
{
"code": null,
"e": 15892,
"s": 15822,
"text": "Running multiple applications on a computer or server simultaneously."
},
{
"code": null,
"e": 16100,
"s": 15892,
"text": "Stress testing is performed to identify the system breakpoint. In this testing, application is loaded in such a way that the system fails at one point. This point is called the breakpoint of database system."
},
{
"code": null,
"e": 16257,
"s": 16100,
"text": "Determining the state of database transactions involves a significant amount of effort. Proper planning is required to avoid any time and cost-based issues."
},
{
"code": null,
"e": 16331,
"s": 16257,
"text": "The most commonly used stress testing tools are LoadRunner and WinRunner."
},
{
"code": null,
"e": 16760,
"s": 16331,
"text": "Let us take an example of Stress Testing. A CRM application can take a maximum user load of 50000 concurrent users. Suppose you increase the load to 51000 and make some transactions such as updating records or adding an entry. As soon as you do the transaction, the application can sync with the database system. So the next test is to perform with a user load of 52000. Sometimes, Stress Testing is also called Fatigue Testing."
},
{
"code": null,
"e": 16905,
"s": 16760,
"text": "The process to perform database testing is similar to testing of other applications. DB testing can be described with key processes given below."
},
{
"code": null,
"e": 16928,
"s": 16905,
"text": "Set up the environment"
},
{
"code": null,
"e": 16939,
"s": 16928,
"text": "Run a test"
},
{
"code": null,
"e": 16961,
"s": 16939,
"text": "Check the test result"
},
{
"code": null,
"e": 17004,
"s": 16961,
"text": "Validate according to the expected results"
},
{
"code": null,
"e": 17055,
"s": 17004,
"text": "Report the findings to the respective stakeholders"
},
{
"code": null,
"e": 17275,
"s": 17055,
"text": "Various SQL statements are used to develop the Test cases. The most common SQL statement, which is used to perform DB testing, is the Select statement. Apart from this, various DDL, DML, DCL statements can also be used."
},
{
"code": null,
"e": 17322,
"s": 17275,
"text": "Example β Create, Insert, Select, Update, etc."
},
{
"code": null,
"e": 17455,
"s": 17322,
"text": "DB testing is not a tedious process and includes various stages in database testing lifecycle in accordance with the test processes."
},
{
"code": null,
"e": 17496,
"s": 17455,
"text": "The key stages in database testing are β"
},
{
"code": null,
"e": 17523,
"s": 17496,
"text": "Checking the initial state"
},
{
"code": null,
"e": 17532,
"s": 17523,
"text": "Test run"
},
{
"code": null,
"e": 17574,
"s": 17532,
"text": "Outcome validation as per expected result"
},
{
"code": null,
"e": 17597,
"s": 17574,
"text": "Generating the results"
},
{
"code": null,
"e": 17831,
"s": 17597,
"text": "First stage in DB Testing is to check the initial state of the database before starting the testing process. Then database behavior is tested for defined test cases. In accordance with the results obtained, test cases are customized."
},
{
"code": null,
"e": 17923,
"s": 17831,
"text": "For successful database testing, the workflow given below is executed by every single test."
},
{
"code": null,
"e": 18015,
"s": 17923,
"text": "Cleaning up the database β If there is testable data in the database, it should be emptied."
},
{
"code": null,
"e": 18107,
"s": 18015,
"text": "Cleaning up the database β If there is testable data in the database, it should be emptied."
},
{
"code": null,
"e": 18219,
"s": 18107,
"text": "Set up Fixture β This involves entering the data into the database and check the current state of the database."
},
{
"code": null,
"e": 18331,
"s": 18219,
"text": "Set up Fixture β This involves entering the data into the database and check the current state of the database."
},
{
"code": null,
"e": 18591,
"s": 18331,
"text": "Perform test, verify results and generate results β The Test is run and the output is verified. If the output is as per expected results, the next step is to generate the results as per requirement. Otherwise, testing is repeated to find the bugs in database."
},
{
"code": null,
"e": 18851,
"s": 18591,
"text": "Perform test, verify results and generate results β The Test is run and the output is verified. If the output is as per expected results, the next step is to generate the results as per requirement. Otherwise, testing is repeated to find the bugs in database."
},
{
"code": null,
"e": 18943,
"s": 18851,
"text": "This chapter explains the most common techniques that are used to perform Database Testing."
},
{
"code": null,
"e": 19012,
"s": 18943,
"text": "As mentioned earlier, it involves testing each object in the Schema."
},
{
"code": null,
"e": 19043,
"s": 19012,
"text": "Verifying the name of database"
},
{
"code": null,
"e": 19097,
"s": 19043,
"text": "Verifying the data device, log device and dump device"
},
{
"code": null,
"e": 19151,
"s": 19097,
"text": "Verifying if enough space allocated for each database"
},
{
"code": null,
"e": 19185,
"s": 19151,
"text": "Verifying database option setting"
},
{
"code": null,
"e": 19278,
"s": 19185,
"text": "Verify the items given below to find out the differences between actual and applied setting."
},
{
"code": null,
"e": 19313,
"s": 19278,
"text": "Name of all the tables in database"
},
{
"code": null,
"e": 19348,
"s": 19313,
"text": "Name of all the tables in database"
},
{
"code": null,
"e": 19376,
"s": 19348,
"text": "Column names for each table"
},
{
"code": null,
"e": 19404,
"s": 19376,
"text": "Column names for each table"
},
{
"code": null,
"e": 19432,
"s": 19404,
"text": "Column types for each table"
},
{
"code": null,
"e": 19460,
"s": 19432,
"text": "Column types for each table"
},
{
"code": null,
"e": 19486,
"s": 19460,
"text": "NULL value checked or not"
},
{
"code": null,
"e": 19512,
"s": 19486,
"text": "NULL value checked or not"
},
{
"code": null,
"e": 19564,
"s": 19512,
"text": "Whether a default is bound to correct table columns"
},
{
"code": null,
"e": 19616,
"s": 19564,
"text": "Whether a default is bound to correct table columns"
},
{
"code": null,
"e": 19678,
"s": 19616,
"text": "Rule definitions to correct table names and access privileges"
},
{
"code": null,
"e": 19740,
"s": 19678,
"text": "Rule definitions to correct table names and access privileges"
},
{
"code": null,
"e": 19783,
"s": 19740,
"text": "Verify the Key and indexes in each table β"
},
{
"code": null,
"e": 19810,
"s": 19783,
"text": "Primary key for each table"
},
{
"code": null,
"e": 19837,
"s": 19810,
"text": "Primary key for each table"
},
{
"code": null,
"e": 19865,
"s": 19837,
"text": "Foreign keys for each table"
},
{
"code": null,
"e": 19893,
"s": 19865,
"text": "Foreign keys for each table"
},
{
"code": null,
"e": 20018,
"s": 19893,
"text": "Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique"
},
{
"code": null,
"e": 20143,
"s": 20018,
"text": "Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique"
},
{
"code": null,
"e": 20302,
"s": 20143,
"text": "It involves checking whether a stored procedure is defined and the output results are compared. In a Stored Procedure test, the following points are checked β"
},
{
"code": null,
"e": 20324,
"s": 20302,
"text": "Stored procedure name"
},
{
"code": null,
"e": 20346,
"s": 20324,
"text": "Stored procedure name"
},
{
"code": null,
"e": 20385,
"s": 20346,
"text": "Parameter names, parameter types, etc."
},
{
"code": null,
"e": 20424,
"s": 20385,
"text": "Parameter names, parameter types, etc."
},
{
"code": null,
"e": 20535,
"s": 20424,
"text": "Output β Whether the output contains many records. Zero rows are effected or only a few records are extracted."
},
{
"code": null,
"e": 20646,
"s": 20535,
"text": "Output β Whether the output contains many records. Zero rows are effected or only a few records are extracted."
},
{
"code": null,
"e": 20738,
"s": 20646,
"text": "What is the function of Stored Procedure and what a stored procedure is not supposed to do?"
},
{
"code": null,
"e": 20830,
"s": 20738,
"text": "What is the function of Stored Procedure and what a stored procedure is not supposed to do?"
},
{
"code": null,
"e": 20913,
"s": 20830,
"text": "Passing sample input queries to check if a stored procedure extracts correct data."
},
{
"code": null,
"e": 20996,
"s": 20913,
"text": "Passing sample input queries to check if a stored procedure extracts correct data."
},
{
"code": null,
"e": 21142,
"s": 20996,
"text": "Stored Procedure Parameters β Call stored procedure with boundary data and with valid data. Make each parameter invalid once and run a procedure."
},
{
"code": null,
"e": 21288,
"s": 21142,
"text": "Stored Procedure Parameters β Call stored procedure with boundary data and with valid data. Make each parameter invalid once and run a procedure."
},
{
"code": null,
"e": 21408,
"s": 21288,
"text": "Return values β Check the values that are returned by stored procedure. In case of a failure, nonzero must be returned."
},
{
"code": null,
"e": 21528,
"s": 21408,
"text": "Return values β Check the values that are returned by stored procedure. In case of a failure, nonzero must be returned."
},
{
"code": null,
"e": 21731,
"s": 21528,
"text": "Error messages check β Make changes in such a way that the stored procedure fails and generate every error message at least once. Check any exception scenarios when there is no predefined error message."
},
{
"code": null,
"e": 21934,
"s": 21731,
"text": "Error messages check β Make changes in such a way that the stored procedure fails and generate every error message at least once. Check any exception scenarios when there is no predefined error message."
},
{
"code": null,
"e": 21999,
"s": 21934,
"text": "In a Trigger test, the tester must perform the following tasks β"
},
{
"code": null,
"e": 22038,
"s": 21999,
"text": "Make sure the trigger name is correct."
},
{
"code": null,
"e": 22107,
"s": 22038,
"text": "Validate the trigger if it is generated for a specific table column."
},
{
"code": null,
"e": 22136,
"s": 22107,
"text": "Triggerβs update validation."
},
{
"code": null,
"e": 22171,
"s": 22136,
"text": "Update a record with a valid data."
},
{
"code": null,
"e": 22236,
"s": 22171,
"text": "Update a record with invalid data and cover every trigger error."
},
{
"code": null,
"e": 22305,
"s": 22236,
"text": "Update a record when it is still referenced by a row in other table."
},
{
"code": null,
"e": 22361,
"s": 22305,
"text": "Ensure rolling back transactions when a failure occurs."
},
{
"code": null,
"e": 22442,
"s": 22361,
"text": "Find out any cases in which a trigger is not supposed to roll back transactions."
},
{
"code": null,
"e": 22483,
"s": 22442,
"text": "Two types of tests should be performed β"
},
{
"code": null,
"e": 22525,
"s": 22483,
"text": "Setting up the database from scratch, and"
},
{
"code": null,
"e": 22557,
"s": 22525,
"text": "To set up an existing database."
},
{
"code": null,
"e": 22641,
"s": 22557,
"text": "Integration tests should be performed after you are through with component testing."
},
{
"code": null,
"e": 22797,
"s": 22641,
"text": "Stored procedures should be called intensively to select, insert, update, and delete records in different tables to find any conflicts and incompatibility."
},
{
"code": null,
"e": 22953,
"s": 22797,
"text": "Stored procedures should be called intensively to select, insert, update, and delete records in different tables to find any conflicts and incompatibility."
},
{
"code": null,
"e": 22996,
"s": 22953,
"text": "Any conflicts between schema and triggers."
},
{
"code": null,
"e": 23039,
"s": 22996,
"text": "Any conflicts between schema and triggers."
},
{
"code": null,
"e": 23091,
"s": 23039,
"text": "Any conflicts between stored procedures and schema."
},
{
"code": null,
"e": 23143,
"s": 23091,
"text": "Any conflicts between stored procedures and schema."
},
{
"code": null,
"e": 23197,
"s": 23143,
"text": "Any conflicts between stored procedures and triggers."
},
{
"code": null,
"e": 23251,
"s": 23197,
"text": "Any conflicts between stored procedures and triggers."
},
{
"code": null,
"e": 23400,
"s": 23251,
"text": "Functional testing can be performed by dividing the database into modules as per functionality. The functionalities are of the following two types β"
},
{
"code": null,
"e": 23651,
"s": 23400,
"text": "Type 1 β In Type 1 testing, find out the features of the project. For each major feature, find out the schema, triggers, and stored procedures responsible to implement that function and put them into a functional group. Then test each group together."
},
{
"code": null,
"e": 23902,
"s": 23651,
"text": "Type 1 β In Type 1 testing, find out the features of the project. For each major feature, find out the schema, triggers, and stored procedures responsible to implement that function and put them into a functional group. Then test each group together."
},
{
"code": null,
"e": 24084,
"s": 23902,
"text": "Type 2 β In Type 2 testing, the border of functional groups in a back-end is not obvious. You can check the data flow and see where you can check the data. Start from the front-end."
},
{
"code": null,
"e": 24266,
"s": 24084,
"text": "Type 2 β In Type 2 testing, the border of functional groups in a back-end is not obvious. You can check the data flow and see where you can check the data. Start from the front-end."
},
{
"code": null,
"e": 24302,
"s": 24266,
"text": "The following process takes place β"
},
{
"code": null,
"e": 24386,
"s": 24302,
"text": "When a service has a request or saves data, some stored procedures will get called."
},
{
"code": null,
"e": 24470,
"s": 24386,
"text": "When a service has a request or saves data, some stored procedures will get called."
},
{
"code": null,
"e": 24510,
"s": 24470,
"text": "The procedures will update some tables."
},
{
"code": null,
"e": 24550,
"s": 24510,
"text": "The procedures will update some tables."
},
{
"code": null,
"e": 24671,
"s": 24550,
"text": "Those stored procedures will be the place to start testing and those tables will be the place to check the test results."
},
{
"code": null,
"e": 24792,
"s": 24671,
"text": "Those stored procedures will be the place to start testing and those tables will be the place to check the test results."
},
{
"code": null,
"e": 24947,
"s": 24792,
"text": "Stress Testing involves getting a list of major database functions and corresponding stored procedures. Follow the steps given below for Stress Testing β "
},
{
"code": null,
"e": 25055,
"s": 24947,
"text": "Write test scripts to try those functions and every function must be checked at least once in a full cycle."
},
{
"code": null,
"e": 25163,
"s": 25055,
"text": "Write test scripts to try those functions and every function must be checked at least once in a full cycle."
},
{
"code": null,
"e": 25232,
"s": 25163,
"text": "Perform the test scripts again and again for a specific time period."
},
{
"code": null,
"e": 25301,
"s": 25232,
"text": "Perform the test scripts again and again for a specific time period."
},
{
"code": null,
"e": 25394,
"s": 25301,
"text": "Verifying the log files to check any deadlocks, failure out of memory, data corruption, etc."
},
{
"code": null,
"e": 25487,
"s": 25394,
"text": "Verifying the log files to check any deadlocks, failure out of memory, data corruption, etc."
},
{
"code": null,
"e": 25681,
"s": 25487,
"text": "If your database does not have any data problems or bugs, system performance can be checked. A poor system performance can be found in benchmark testing by checking the parameters given below β"
},
{
"code": null,
"e": 25706,
"s": 25681,
"text": "System level performance"
},
{
"code": null,
"e": 25751,
"s": 25706,
"text": "Identify most-likely-used functions/features"
},
{
"code": null,
"e": 25825,
"s": 25751,
"text": "Timing β maximum time, minimum time and average time to perform functions"
},
{
"code": null,
"e": 25839,
"s": 25825,
"text": "Access volume"
},
{
"code": null,
"e": 25990,
"s": 25839,
"text": "Back-end bugs can also be found sometimes by doing front-end testing. You can follow the simple steps given below to detect bugs by front-end testing."
},
{
"code": null,
"e": 26047,
"s": 25990,
"text": "Write queries from the front-end and issue the searches."
},
{
"code": null,
"e": 26104,
"s": 26047,
"text": "Write queries from the front-end and issue the searches."
},
{
"code": null,
"e": 26271,
"s": 26104,
"text": "Pick up an existing record, change the values in some fields, and save the record. (It involves the UPDATE statement or update stored procedures and update triggers.)"
},
{
"code": null,
"e": 26438,
"s": 26271,
"text": "Pick up an existing record, change the values in some fields, and save the record. (It involves the UPDATE statement or update stored procedures and update triggers.)"
},
{
"code": null,
"e": 26621,
"s": 26438,
"text": "Insert a new menu item in the front-end window. Fill in the information and save the record. (It involves the INSERT statements or insertion stored procedures and deletion triggers.)"
},
{
"code": null,
"e": 26804,
"s": 26621,
"text": "Insert a new menu item in the front-end window. Fill in the information and save the record. (It involves the INSERT statements or insertion stored procedures and deletion triggers.)"
},
{
"code": null,
"e": 26984,
"s": 26804,
"text": "Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves the DELETE statement or deletion stored procedures and deletion triggers.)"
},
{
"code": null,
"e": 27164,
"s": 26984,
"text": "Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves the DELETE statement or deletion stored procedures and deletion triggers.)"
},
{
"code": null,
"e": 27241,
"s": 27164,
"text": "Repeat these test-cases with invalid data and see how the database responds."
},
{
"code": null,
"e": 27318,
"s": 27241,
"text": "Repeat these test-cases with invalid data and see how the database responds."
},
{
"code": null,
"e": 27424,
"s": 27318,
"text": "In this chapter, we will see some common database test scenarios with respect to various testing methods."
},
{
"code": null,
"e": 27512,
"s": 27424,
"text": "Common database scenarios with respect to Structured Database Testing are given below β"
},
{
"code": null,
"e": 27692,
"s": 27512,
"text": "Verifying the name of database, verifying the data device, log device and dump device, verifying if enough space allocated for each database and verifying database option setting."
},
{
"code": null,
"e": 27872,
"s": 27692,
"text": "Verifying the name of database, verifying the data device, log device and dump device, verifying if enough space allocated for each database and verifying database option setting."
},
{
"code": null,
"e": 28091,
"s": 27872,
"text": "Names of all the tables in database, column names for each table, column types for each table, null value check or not. Verify the Key and indexes in each table: Primary key for each table, foreign keys for each table."
},
{
"code": null,
"e": 28310,
"s": 28091,
"text": "Names of all the tables in database, column names for each table, column types for each table, null value check or not. Verify the Key and indexes in each table: Primary key for each table, foreign keys for each table."
},
{
"code": null,
"e": 28436,
"s": 28310,
"text": "Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique."
},
{
"code": null,
"e": 28562,
"s": 28436,
"text": "Data types between a foreign key column and a column in other table Indices, clustered or non-clustered unique or not unique."
},
{
"code": null,
"e": 28643,
"s": 28562,
"text": "Common Database Test scenarios with respect to Functional Database Testing are β"
},
{
"code": null,
"e": 28819,
"s": 28643,
"text": "Finding out the schema, triggers and stored procedures responsible to implement that function and make them into a functional group and then each group can be tested together."
},
{
"code": null,
"e": 28995,
"s": 28819,
"text": "Finding out the schema, triggers and stored procedures responsible to implement that function and make them into a functional group and then each group can be tested together."
},
{
"code": null,
"e": 29075,
"s": 28995,
"text": "Check data flow and see where you can check the data. Start from the front-end."
},
{
"code": null,
"e": 29155,
"s": 29075,
"text": "Check data flow and see where you can check the data. Start from the front-end."
},
{
"code": null,
"e": 29240,
"s": 29155,
"text": "Common Database Test scenarios with respect to Non-Functional Database Testing are β"
},
{
"code": null,
"e": 29348,
"s": 29240,
"text": "Write test scripts to try major functions and every function must be checked at least once in a full cycle."
},
{
"code": null,
"e": 29456,
"s": 29348,
"text": "Write test scripts to try major functions and every function must be checked at least once in a full cycle."
},
{
"code": null,
"e": 29525,
"s": 29456,
"text": "Perform the test scripts again and again for a specific time period."
},
{
"code": null,
"e": 29594,
"s": 29525,
"text": "Perform the test scripts again and again for a specific time period."
},
{
"code": null,
"e": 29686,
"s": 29594,
"text": "Verifying the log files to check any deadlock, failure out of memory, data corruption, etc."
},
{
"code": null,
"e": 29778,
"s": 29686,
"text": "Verifying the log files to check any deadlock, failure out of memory, data corruption, etc."
},
{
"code": null,
"e": 29988,
"s": 29778,
"text": "Write queries from a front end and issue the searches. Pick up an existing record, change values in some fields and save the record. (It involves UPDATE statement or update stored procedures, update triggers.)"
},
{
"code": null,
"e": 30198,
"s": 29988,
"text": "Write queries from a front end and issue the searches. Pick up an existing record, change values in some fields and save the record. (It involves UPDATE statement or update stored procedures, update triggers.)"
},
{
"code": null,
"e": 30368,
"s": 30198,
"text": "Insert a new menu item in a front-end window. Fill in information and save the record. (It involves INSERT statements or insertion stored procedures, deletion triggers.)"
},
{
"code": null,
"e": 30538,
"s": 30368,
"text": "Insert a new menu item in a front-end window. Fill in information and save the record. (It involves INSERT statements or insertion stored procedures, deletion triggers.)"
},
{
"code": null,
"e": 30711,
"s": 30538,
"text": "Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves DELETE statement or deletion stored procedures, deletion triggers.)"
},
{
"code": null,
"e": 30884,
"s": 30711,
"text": "Pick up an existing record, click on the DELETE or REMOVE button, and confirm the deletion. (It involves DELETE statement or deletion stored procedures, deletion triggers.)"
},
{
"code": null,
"e": 30961,
"s": 30884,
"text": "Repeat these test-cases with invalid data and see how the database responds."
},
{
"code": null,
"e": 31038,
"s": 30961,
"text": "Repeat these test-cases with invalid data and see how the database responds."
},
{
"code": null,
"e": 31206,
"s": 31038,
"text": "Schemas, tables, stored procedures, and Triggers are key objects of a database. We have already shared DB testing types and test scenarios for these data base objects."
},
{
"code": null,
"e": 31439,
"s": 31206,
"text": "A database schema defines the structure of a database system in a format supported by the database management system. A Schema refers to how a database is structured (composed of database tables in the case of Relational Databases)."
},
{
"code": null,
"e": 31610,
"s": 31439,
"text": "The database schema is a set of formulas called integrity constraints imposed on a database. These integrity constraints ensure compatibility between parts of the schema."
},
{
"code": null,
"e": 31807,
"s": 31610,
"text": "In a relational database, the schema consists of tables, fields, views, indexes, packages, procedures, functions, triggers, types, materialized views, synonyms, database links, and other elements."
},
{
"code": null,
"e": 32096,
"s": 31807,
"text": "Schemas are generally stored in a data dictionary. Although a schema is defined in text database language, the term is often used to refer to a graphical depiction of the database structure. In other words, schema is the structure of the database that defines the objects in the database."
},
{
"code": null,
"e": 32150,
"s": 32096,
"text": "Common type of Schemas used in a data warehouse are β"
},
{
"code": null,
"e": 32162,
"s": 32150,
"text": "Star Schema"
},
{
"code": null,
"e": 32180,
"s": 32162,
"text": "Snowflakes Schema"
},
{
"code": null,
"e": 32194,
"s": 32180,
"text": "Galaxy Schema"
},
{
"code": null,
"e": 32287,
"s": 32194,
"text": "In a relational database, a table is used to organize the information into rows and columns."
},
{
"code": null,
"e": 32416,
"s": 32287,
"text": "Example β A Customer table contains information such as customer id, addresses, phone numbers, and so on as a series of columns."
},
{
"code": null,
"e": 32740,
"s": 32416,
"text": "Each single piece of data is a field in the table. A column consists of all the entries in a single field, such as the telephone numbers of all the customers. Fields are organized as records, which are complete sets of information (such as the set of information about a particular customer), each of which comprises a row."
},
{
"code": null,
"e": 32990,
"s": 32740,
"text": "A stored procedure is a series of SQL statements stored in the database in a compiled form and multiple programs can share it. The use of stored procedures can be helpful in maintaining data integrity, data control access and improving productivity."
},
{
"code": null,
"e": 33202,
"s": 32990,
"text": "A database trigger is code that is executed in response to certain events on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database."
},
{
"code": null,
"e": 33377,
"s": 33202,
"text": "Data Integrity is important in a database. It includes data validation before insertion, updates, and deletion. Triggers must be in place to validate reference table records."
},
{
"code": null,
"e": 33453,
"s": 33377,
"text": "For checking Data Integrity, you need to perform the following operations β"
},
{
"code": null,
"e": 33594,
"s": 33453,
"text": "You need to check major columns in each table and verify if any incorrect data exists. (Characters in name field, negative percentage, etc.)"
},
{
"code": null,
"e": 33735,
"s": 33594,
"text": "You need to check major columns in each table and verify if any incorrect data exists. (Characters in name field, negative percentage, etc.)"
},
{
"code": null,
"e": 33830,
"s": 33735,
"text": "Find out inconsistent data and insert them into relevant tables and see if any failure occurs."
},
{
"code": null,
"e": 33925,
"s": 33830,
"text": "Find out inconsistent data and insert them into relevant tables and see if any failure occurs."
},
{
"code": null,
"e": 34059,
"s": 33925,
"text": "Insert a child data before inserting its parentβs data. Try to delete a record that is still referenced by the data in another table."
},
{
"code": null,
"e": 34193,
"s": 34059,
"text": "Insert a child data before inserting its parentβs data. Try to delete a record that is still referenced by the data in another table."
},
{
"code": null,
"e": 34388,
"s": 34193,
"text": "If a data in a table is updated, check whether the other relevant data is updated as well. You need to ensure that replicated servers or databases are in sync and contain consistent information."
},
{
"code": null,
"e": 34583,
"s": 34388,
"text": "If a data in a table is updated, check whether the other relevant data is updated as well. You need to ensure that replicated servers or databases are in sync and contain consistent information."
},
{
"code": null,
"e": 34806,
"s": 34583,
"text": "Data mapping in a database is one of the key concept that needs to be validated by every tester. Usually the testers have to verify the user interface front end field mapping with the corresponding back end database field."
},
{
"code": null,
"e": 34994,
"s": 34806,
"text": "This information is given in Software requirement specification or business requirement specification SRS/BRS document. If mapping is not provided, then you need to check the coding part."
},
{
"code": null,
"e": 35171,
"s": 34994,
"text": "When you take any action in the front end application, there is a corresponding CRUD action get invoked, and tester have to check the every invoked action is successful or not."
},
{
"code": null,
"e": 35221,
"s": 35171,
"text": "Given below are the key aspects of Data Mapping β"
},
{
"code": null,
"e": 35410,
"s": 35221,
"text": "To check the fields in the UI/Front end forms and mapped consistently with the corresponding DB table. This mapping information is defined in the requirements documents as mentioned above."
},
{
"code": null,
"e": 35599,
"s": 35410,
"text": "To check the fields in the UI/Front end forms and mapped consistently with the corresponding DB table. This mapping information is defined in the requirements documents as mentioned above."
},
{
"code": null,
"e": 35758,
"s": 35599,
"text": "For any action performed in the front end of an application, a corresponding CRUD βCreate, Retrieve, Update and deleteβ action gets initiated at the back end."
},
{
"code": null,
"e": 35917,
"s": 35758,
"text": "For any action performed in the front end of an application, a corresponding CRUD βCreate, Retrieve, Update and deleteβ action gets initiated at the back end."
},
{
"code": null,
"e": 36031,
"s": 35917,
"text": "A tester will have to check if the right action is invoked and the invoked action in itself is successful or not."
},
{
"code": null,
"e": 36145,
"s": 36031,
"text": "A tester will have to check if the right action is invoked and the invoked action in itself is successful or not."
},
{
"code": null,
"e": 36207,
"s": 36145,
"text": "Given below are the steps followed for Data Mapping Testing β"
},
{
"code": null,
"e": 36261,
"s": 36207,
"text": "Step 1 β First check for syntax error in each script."
},
{
"code": null,
"e": 36315,
"s": 36261,
"text": "Step 1 β First check for syntax error in each script."
},
{
"code": null,
"e": 36399,
"s": 36315,
"text": "Step 2 β Next is to check for table mapping, column mapping, and data type mapping."
},
{
"code": null,
"e": 36483,
"s": 36399,
"text": "Step 2 β Next is to check for table mapping, column mapping, and data type mapping."
},
{
"code": null,
"e": 36520,
"s": 36483,
"text": "Step 3 β Verify lookup data mapping."
},
{
"code": null,
"e": 36557,
"s": 36520,
"text": "Step 3 β Verify lookup data mapping."
},
{
"code": null,
"e": 36631,
"s": 36557,
"text": "Step 4 β Run each script when records do not exist in destination tables."
},
{
"code": null,
"e": 36705,
"s": 36631,
"text": "Step 4 β Run each script when records do not exist in destination tables."
},
{
"code": null,
"e": 36788,
"s": 36705,
"text": "Step 5 β Run each script when the records already exist in the destination tables."
},
{
"code": null,
"e": 36871,
"s": 36788,
"text": "Step 5 β Run each script when the records already exist in the destination tables."
},
{
"code": null,
"e": 37079,
"s": 36871,
"text": "An application with more response time and poor performance can lead to huge problems. Database Load Testing is used to find any performance issues before you deploy your database applications for end users."
},
{
"code": null,
"e": 37325,
"s": 37079,
"text": "Database Load Testing helps you design database application for performance, reliability and scalability. Load Testing of Database applications involves testing the performance and scalability of your Database application with varying user load."
},
{
"code": null,
"e": 37529,
"s": 37325,
"text": "Database Load testing involves simulating real-life user load for the target Database application. It helps you determine how your Database application behaves when multiple users hits it simultaneously."
},
{
"code": null,
"e": 37705,
"s": 37529,
"text": "The primary target of Load Testing is to check if most running transactions have performance impact on the database. In load testing, you need to check the following aspects β"
},
{
"code": null,
"e": 37799,
"s": 37705,
"text": "The response time for executing the transactions for multiple remote users should be checked."
},
{
"code": null,
"e": 37893,
"s": 37799,
"text": "The response time for executing the transactions for multiple remote users should be checked."
},
{
"code": null,
"e": 38036,
"s": 37893,
"text": "With normal transactions, you should include one editable transaction to check the performance of the database for these type pf transactions."
},
{
"code": null,
"e": 38179,
"s": 38036,
"text": "With normal transactions, you should include one editable transaction to check the performance of the database for these type pf transactions."
},
{
"code": null,
"e": 38317,
"s": 38179,
"text": "With normal transactions, you should include one non-editing transaction to check performance of database for these type of transactions."
},
{
"code": null,
"e": 38455,
"s": 38317,
"text": "With normal transactions, you should include one non-editing transaction to check performance of database for these type of transactions."
},
{
"code": null,
"e": 38523,
"s": 38455,
"text": "Time taken by database to fetch specific records should be checked."
},
{
"code": null,
"e": 38591,
"s": 38523,
"text": "Time taken by database to fetch specific records should be checked."
},
{
"code": null,
"e": 38844,
"s": 38591,
"text": "Stress testing is performed to identify the system breakpoint. Here the application is loaded in such a way that the system fails at one point. This point is called the breakpoint of the database system. Stress testing is also known as Fatigue Testing."
},
{
"code": null,
"e": 39002,
"s": 38844,
"text": "Determining the state of database transactions involves a significant amount of effort. Proper planning is required to avoid any time- and cost-based issues."
},
{
"code": null,
"e": 39069,
"s": 39002,
"text": "The most common stress testing tools are LoadRunner and WinRunner."
},
{
"code": null,
"e": 39244,
"s": 39069,
"text": "There are various tools provided by vendors that can be used to generate Test data, to manage Test data and perform database testing like Load Testing and Regression Testing."
},
{
"code": null,
"e": 39294,
"s": 39244,
"text": "A few common tools that are used are given below."
},
{
"code": null,
"e": 39313,
"s": 39294,
"text": "Load Testing Tools"
},
{
"code": null,
"e": 39473,
"s": 39313,
"text": "These tools are used to put high usage loads on your database, which enables to determine whether your system's landscape will stand up to your business needs."
},
{
"code": null,
"e": 39489,
"s": 39473,
"text": "Web Performance"
},
{
"code": null,
"e": 39498,
"s": 39489,
"text": "Rad View"
},
{
"code": null,
"e": 39506,
"s": 39498,
"text": "Mercury"
},
{
"code": null,
"e": 39526,
"s": 39506,
"text": "Data Security Tools"
},
{
"code": null,
"e": 39630,
"s": 39526,
"text": "These tools are used to implement compliance and standards as per the information security regulations."
},
{
"code": null,
"e": 39653,
"s": 39630,
"text": "IBM Optim Data Privacy"
},
{
"code": null,
"e": 39679,
"s": 39653,
"text": "Test Data generator tools"
},
{
"code": null,
"e": 39906,
"s": 39679,
"text": "A tester uses these tools to generate the test data for a database system. These are mostly required when you have huge amount of data and you need sample to perform DB Testing. It is commonly used for Load and Stress testing."
},
{
"code": null,
"e": 39919,
"s": 39906,
"text": "Data Factory"
},
{
"code": null,
"e": 39938,
"s": 39919,
"text": "DTM Data Generator"
},
{
"code": null,
"e": 39949,
"s": 39938,
"text": "Turbo Data"
},
{
"code": null,
"e": 39975,
"s": 39949,
"text": "Test Data Management Tool"
},
{
"code": null,
"e": 40142,
"s": 39975,
"text": "These tools are used to maintain version control for test data. You have to define the expected results and then you compare it with the actual outcomes of the tests."
},
{
"code": null,
"e": 40173,
"s": 40142,
"text": "IBM Optim Test Data Management"
},
{
"code": null,
"e": 40203,
"s": 40173,
"text": "Tools to perform Unit Testing"
},
{
"code": null,
"e": 40272,
"s": 40203,
"text": "These tools are used to perform regression testing on your database."
},
{
"code": null,
"e": 40280,
"s": 40272,
"text": "SQLUnit"
},
{
"code": null,
"e": 40289,
"s": 40280,
"text": "TSQLUnit"
},
{
"code": null,
"e": 40295,
"s": 40289,
"text": "DBFit"
},
{
"code": null,
"e": 40302,
"s": 40295,
"text": "DBUnit"
},
{
"code": null,
"e": 40538,
"s": 40302,
"text": "The most important part of an organizational growth is its data. In case of a system failure, there is a need to restore the data. Back up is an exact copy of the database, which helps you to restore your data in case of any data loss."
},
{
"code": null,
"e": 40793,
"s": 40538,
"text": "Consider a finance company which has data related to its customers such as A/C number, customer names, credit and debits, duration, etc. How would such an organization deal with the pressure of losing such important information in case of a data failure?"
},
{
"code": null,
"e": 40957,
"s": 40793,
"text": "This is the reason you back up the data so that in case of any failure of a disk, disk controller, etc. you can rely on the backup to restore it into the database."
},
{
"code": null,
"e": 41006,
"s": 40957,
"text": "There are two types of backup that can be used β"
},
{
"code": null,
"e": 41182,
"s": 41006,
"text": "Physical Backups β Physical backup includes taking back up using third-party backup tools like Veritas Net Back, IBM Tivoli Manager or user manager backups using OS utilities."
},
{
"code": null,
"e": 41358,
"s": 41182,
"text": "Physical Backups β Physical backup includes taking back up using third-party backup tools like Veritas Net Back, IBM Tivoli Manager or user manager backups using OS utilities."
},
{
"code": null,
"e": 41485,
"s": 41358,
"text": "Logical Backups β Logical backup of database includes taking backups of logical objects like tables, indexes, procedures, etc."
},
{
"code": null,
"e": 41612,
"s": 41485,
"text": "Logical Backups β Logical backup of database includes taking backups of logical objects like tables, indexes, procedures, etc."
},
{
"code": null,
"e": 41746,
"s": 41612,
"text": "Example β One of common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup."
},
{
"code": null,
"e": 41780,
"s": 41746,
"text": "RMAN consists of two components β"
},
{
"code": null,
"e": 41826,
"s": 41780,
"text": "Target database for which backup is required."
},
{
"code": null,
"e": 41872,
"s": 41826,
"text": "Target database for which backup is required."
},
{
"code": null,
"e": 41929,
"s": 41872,
"text": "RMAN client is used to run commands to take data backup."
},
{
"code": null,
"e": 41986,
"s": 41929,
"text": "RMAN client is used to run commands to take data backup."
},
{
"code": null,
"e": 42089,
"s": 41986,
"text": "BACKUP VALIDATE is used to test if you are able to make a valid backup of database files. It ensures β"
},
{
"code": null,
"e": 42156,
"s": 42089,
"text": "If backup is in place for physical or logical objects of database."
},
{
"code": null,
"e": 42207,
"s": 42156,
"text": "If regular backups are set up for invaluable data."
},
{
"code": null,
"e": 42276,
"s": 42207,
"text": "If the backup tool meets the backup requirements of an organization."
},
{
"code": null,
"e": 42549,
"s": 42276,
"text": "Database recovery testing is used to ensure that the database is recovered. Recovery testing allows you to find out whether the application is running properly and to check retrieving invaluable data that would have been lost if your recovery method is not properly setup."
},
{
"code": null,
"e": 42692,
"s": 42549,
"text": "You also check if several critical processes are running smooth to ensure that the data recovery will pass smoothly through the testing phase."
},
{
"code": null,
"e": 42753,
"s": 42692,
"text": "You can perform the following checks for database recovery β"
},
{
"code": null,
"e": 42857,
"s": 42753,
"text": "Any errors or mistakes in the backup software and you need to resolve these issues at an earlier stage."
},
{
"code": null,
"e": 42961,
"s": 42857,
"text": "Any errors or mistakes in the backup software and you need to resolve these issues at an earlier stage."
},
{
"code": null,
"e": 43070,
"s": 42961,
"text": "You need to conduct the recovery testing so that you will know what to do in case of an emergency situation."
},
{
"code": null,
"e": 43179,
"s": 43070,
"text": "You need to conduct the recovery testing so that you will know what to do in case of an emergency situation."
},
{
"code": null,
"e": 43277,
"s": 43179,
"text": "You need to check recovery testing needs so that you can plan for an effective recovery strategy."
},
{
"code": null,
"e": 43375,
"s": 43277,
"text": "You need to check recovery testing needs so that you can plan for an effective recovery strategy."
},
{
"code": null,
"e": 43431,
"s": 43375,
"text": "You should also know how you can recover the documents."
},
{
"code": null,
"e": 43487,
"s": 43431,
"text": "You should also know how you can recover the documents."
},
{
"code": null,
"e": 43728,
"s": 43487,
"text": "You need to run the recovery tests in early phase of the project. This allows you to remove and throw away every type of errors from the system. Here is a list of some of important points, which should be considered at the time of testing β"
},
{
"code": null,
"e": 43795,
"s": 43728,
"text": "Time span when changes or modifications occurs in database system."
},
{
"code": null,
"e": 43862,
"s": 43795,
"text": "Time span when changes or modifications occurs in database system."
},
{
"code": null,
"e": 43921,
"s": 43862,
"text": "The period by which you want your recovery plan conducted."
},
{
"code": null,
"e": 43980,
"s": 43921,
"text": "The period by which you want your recovery plan conducted."
},
{
"code": null,
"e": 44106,
"s": 43980,
"text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software."
},
{
"code": null,
"e": 44232,
"s": 44106,
"text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software."
},
{
"code": null,
"e": 44460,
"s": 44232,
"text": "In database recovery testing, you need to run the test in the actual environment to check if the system or the data can actually be recovered in case of any disasters and any other unforeseen events in the business environment."
},
{
"code": null,
"e": 44536,
"s": 44460,
"text": "Given below are the common actions performed in Database Recovery Testing β"
},
{
"code": null,
"e": 44563,
"s": 44536,
"text": "Testing of database system"
},
{
"code": null,
"e": 44588,
"s": 44563,
"text": "Testing of the SQL files"
},
{
"code": null,
"e": 44613,
"s": 44588,
"text": "Testing of partial files"
},
{
"code": null,
"e": 44636,
"s": 44613,
"text": "Testing of data backup"
},
{
"code": null,
"e": 44659,
"s": 44636,
"text": "Testing of Backup tool"
},
{
"code": null,
"e": 44679,
"s": 44659,
"text": "Testing log backups"
},
{
"code": null,
"e": 44835,
"s": 44679,
"text": "Database security testing is done to find the loopholes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system."
},
{
"code": null,
"e": 45119,
"s": 44835,
"text": "The main target of database security testing is to find out vulnerabilities in a system and to determine whether its data and resources are protected from potential intruders. Security testing defines a way to identify potential vulnerabilities effectively, when performed regularly."
},
{
"code": null,
"e": 45200,
"s": 45119,
"text": "Given below are the primary objectives of performing database security testing β"
},
{
"code": null,
"e": 45215,
"s": 45200,
"text": "Authentication"
},
{
"code": null,
"e": 45229,
"s": 45215,
"text": "Authorization"
},
{
"code": null,
"e": 45245,
"s": 45229,
"text": "Confidentiality"
},
{
"code": null,
"e": 45258,
"s": 45245,
"text": "Availability"
},
{
"code": null,
"e": 45268,
"s": 45258,
"text": "Integrity"
},
{
"code": null,
"e": 45279,
"s": 45268,
"text": "Resilience"
},
{
"code": null,
"e": 45619,
"s": 45279,
"text": "This is most common type of attack in a database system where malicious SQL statements are inserted in the database system and are executed to get critical information from the database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this, user inputs fields should be carefully handled."
},
{
"code": null,
"e": 45819,
"s": 45619,
"text": "In this attack, a user already has some access in the database system and he only tries to elevate this access higher level so that he/she can perform some unauthorized activities in database system."
},
{
"code": null,
"e": 46055,
"s": 45819,
"text": "In this type of attack, an attacker makes a database system or application resource unavailable to its legitimate users. Applications can also be attacked in ways that render the application, and sometimes the entire machine, unusable."
},
{
"code": null,
"e": 46190,
"s": 46055,
"text": "Another type of attack is gaining unauthorized access to data within an application or database system. Unauthorized access includes β"
},
{
"code": null,
"e": 46246,
"s": 46190,
"text": "Unauthorized access to data via user based applications"
},
{
"code": null,
"e": 46304,
"s": 46246,
"text": "Unauthorized access to by monitoring the access of others"
},
{
"code": null,
"e": 46370,
"s": 46304,
"text": "Unauthorized access to reusable client authentication information"
},
{
"code": null,
"e": 46621,
"s": 46370,
"text": "In Identity Spoofing, a hacker uses the credentials of a user or device to launch attacks against network hosts, steal data or bypass access controls to database system. Preventing this attack requires IT-infrastructure and network-level mitigations."
},
{
"code": null,
"e": 46740,
"s": 46621,
"text": "In a data manipulation attack, a hacker changes data to gain some advantage or to damage the image of database owners."
},
{
"code": null,
"e": 46905,
"s": 46740,
"text": "A penetration test is an attack on a computer system with the intention of finding security loopholes, potentially gaining access to it, its functionality and data."
},
{
"code": null,
"e": 47141,
"s": 46905,
"text": "Risk Finding is a process of assessing and deciding on the risk involved with the type of loss and the possibility of vulnerability occurrence. This is determined within the organization by various interviews, discussions and analysis."
},
{
"code": null,
"e": 47513,
"s": 47141,
"text": "It involves checking the user inputs in application fields. For example, entering a special character like β,β or β;β in any text box in a user application should not be allowed. When a database error occurs, it means that the user input is inserted in some query, which is then executed by the application. In such a case, the application is vulnerable to SQL injection."
},
{
"code": null,
"e": 47819,
"s": 47513,
"text": "These attacks are a big threat to data as the attackers can get access to important information from the server database. To check SQL injection entry points into your web application, find out code from your code base where direct MySQL queries are executed on the database by accepting some user inputs."
},
{
"code": null,
"e": 47901,
"s": 47819,
"text": "SQL Injection Testing can be performed for Brackets, Commas, and Quotation marks."
},
{
"code": null,
"e": 48193,
"s": 47901,
"text": "This is the most important check while performing database system testing. To access critical information, hackers can use a password-cracking tool or can guess a common username/password. These common passwords are easily available on internet and also password cracking tools exist freely."
},
{
"code": null,
"e": 48451,
"s": 48193,
"text": "Therefore, it is necessary to check at the time of testing if the password policy is maintained in the system. In case of any banking and finance applications, there is a need to set a strict password policy on all the critical information database systems."
},
{
"code": null,
"e": 48786,
"s": 48451,
"text": "A security audit is a process of evaluating companyβs security policies at a regular time interval to determine whether necessary standards are followed or not. Various security standards can be followed as per business requirement to define the security policy and then assessment of set policies against those standards can be done."
},
{
"code": null,
"e": 48857,
"s": 48786,
"text": "Example of most common security standards are ISO 27001, BS15999, etc."
},
{
"code": null,
"e": 49020,
"s": 48857,
"text": "There are various system testing tools available in market, which can be used to test OS and application check. Some of the most common tools are discussed below."
},
{
"code": null,
"e": 49322,
"s": 49020,
"text": "It is a penetration-testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. It is commonly used for Windows, Linux, Mac OS."
},
{
"code": null,
"e": 49522,
"s": 49322,
"text": "All HTTP and HTTPS data between server and client, including cookies and form fields, can be intercepted and modified using these scanners. It is used for Cross-platform, Java JRE/JDK 1.4.2 or above."
},
{
"code": null,
"e": 49754,
"s": 49522,
"text": "It is an open source tool and human elements are attacked rather than the system element. It enables you to send emails, java applets etc. containing the attack code. It is preferred for Linux, Apple Mac OS X and Microsoft Windows."
},
{
"code": null,
"e": 49991,
"s": 49754,
"text": "This tool is used to scan their sites for vulnerabilities. Reports generated by the tool are meant to serve as a foundation for professional web application security assessments. It is preferred for Linux, FreeBSD, MacOS X, and Windows."
},
{
"code": null,
"e": 50215,
"s": 49991,
"text": "It is an open source, multiplatform web security tool that is used to find instances of SQL injection, cross-site scripting (XSS), and other vulnerabilities in web applications. It is preferred for Java, Linux, and Windows."
},
{
"code": null,
"e": 50496,
"s": 50215,
"text": "Wapiti is an open source and web-based tool that scans the web pages of the web application and check for scripts and forms where it can inject data. It is built with Python and can detect File handling errors, Database, XSS, LDAP and CRLF injections, Command execution detection."
},
{
"code": null,
"e": 50717,
"s": 50496,
"text": "It is written in Java and is used for analyzing the applications that communicate through HTTP/HTTPS protocols. This tool is primarily designed for developers who can write code themselves. This tool is not OS dependent."
},
{
"code": null,
"e": 51156,
"s": 50717,
"text": "To perform database testing successfully, a tester should collect the requirements from all the sources, like technical and functional requirements. There is a possibility that a few requirements are at a high level, so there is a need to breakdown those requirements into the small parts. Testing database is a complex task and the testers face many challenges while performing this testing. Most common database testing challenges are β"
},
{
"code": null,
"e": 51436,
"s": 51156,
"text": "A tester needs to identify the test items in database testing otherwise he may not have a clear understanding of what he would test and what he would not test. Therefore, if you are clear on the requirement, you may waste a lot of time testing uncritical objects in the database."
},
{
"code": null,
"e": 51673,
"s": 51436,
"text": "When you have a list of objects to test, next is to estimate the effort required to design the tests and execute the tests for each test item. Depending on their design and data size, some database tests may take a long time to execute."
},
{
"code": null,
"e": 51818,
"s": 51673,
"text": "As the database size is too large, it becomes a big challenge to find out the objects that have to be tested and those which are to be left out."
},
{
"code": null,
"e": 52073,
"s": 51818,
"text": "Normally testers are provided with a copy of the development database to test. That database only have little data, which is sufficient to run the application. So there is a need to test the development, staging and as well as production database system."
},
{
"code": null,
"e": 52335,
"s": 52073,
"text": "This is one of the common challenges in DB testing. Sometimes, it happens that you design or execute a test, and the database structure has been changed at that time. This is necessary that you should be aware of the changes made to the database during testing."
},
{
"code": null,
"e": 52616,
"s": 52335,
"text": "Once the database structure changes, you should analyze the impact of the changes and modify the tests. In addition, if multiple users use the test database, you would not be sure about the test results so you should ensure that the test database is used for testing purpose only."
},
{
"code": null,
"e": 52856,
"s": 52616,
"text": "Another challenge in DB testing is that you run multiple tests at the same time. You should run one test at a time at least for the performance tests. You do not want your database performing multiple tasks and under-reporting performance."
},
{
"code": null,
"e": 53109,
"s": 52856,
"text": "The database structure is normally complex and it has huge data, so there is a possibility that you are executing incomplete or same tests repeatedly. So there is a need to create a test plan and proceed accordingly and checking the progress regularly."
},
{
"code": null,
"e": 53221,
"s": 53109,
"text": "To test a database, you should have a good knowledge of SQL queries and the required database management tools."
},
{
"code": null,
"e": 53406,
"s": 53221,
"text": "Database testing includes performing the data validity, data Integrity testing, performance check related to database and testing of Procedures, triggers and functions in the database."
},
{
"code": null,
"e": 53654,
"s": 53406,
"text": "There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose."
},
{
"code": null,
"e": 53740,
"s": 53654,
"text": "Some of the common reasons why one needs to perform Database testing are as follows β"
},
{
"code": null,
"e": 53852,
"s": 53740,
"text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures."
},
{
"code": null,
"e": 53964,
"s": 53852,
"text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures."
},
{
"code": null,
"e": 54155,
"s": 53964,
"text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels."
},
{
"code": null,
"e": 54346,
"s": 54155,
"text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels."
},
{
"code": null,
"e": 54578,
"s": 54346,
"text": "Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system."
},
{
"code": null,
"e": 54810,
"s": 54578,
"text": "Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system."
},
{
"code": null,
"e": 55088,
"s": 54810,
"text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly."
},
{
"code": null,
"e": 55366,
"s": 55088,
"text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly."
},
{
"code": null,
"e": 55451,
"s": 55366,
"text": "The steps that you need to follow while performing database testing are as follows β"
},
{
"code": null,
"e": 55508,
"s": 55451,
"text": "The data that is being in the database must be verified."
},
{
"code": null,
"e": 55550,
"s": 55508,
"text": "Verify if the constraints are maintained."
},
{
"code": null,
"e": 55627,
"s": 55550,
"text": "The performance of the procedures and execution of triggers must be checked."
},
{
"code": null,
"e": 55680,
"s": 55627,
"text": "Roll back and commit of transaction must be checked."
},
{
"code": null,
"e": 55796,
"s": 55680,
"text": "On the basis of function and structure of a database, DB testing can be categorized into the following categories β"
},
{
"code": null,
"e": 55943,
"s": 55796,
"text": "Structural Database testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc."
},
{
"code": null,
"e": 56090,
"s": 55943,
"text": "Structural Database testing β It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc."
},
{
"code": null,
"e": 56259,
"s": 56090,
"text": "Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing."
},
{
"code": null,
"e": 56428,
"s": 56259,
"text": "Functional Testing β It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing."
},
{
"code": null,
"e": 56591,
"s": 56428,
"text": "Nonfunctional Testing β It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database."
},
{
"code": null,
"e": 56754,
"s": 56591,
"text": "Nonfunctional Testing β It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database."
},
{
"code": null,
"e": 56856,
"s": 56754,
"text": "The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc."
},
{
"code": null,
"e": 57021,
"s": 56856,
"text": "Joins are used to connect two or more tables in some logical manner. Common types of joins include: Inner join, Non-equijoin, Outer join, Self-join, and Cross join."
},
{
"code": null,
"e": 57110,
"s": 57021,
"text": "You can join a single table to itself. In this case, you are using the same table twice."
},
{
"code": null,
"e": 57143,
"s": 57110,
"text": "Step 1 β Connect to the database"
},
{
"code": null,
"e": 57250,
"s": 57143,
"text": "db_connect(query1 DRIVER {drivername};SERVER server_name;UID uidname;\n PWD password;DBQ database_name );"
},
{
"code": null,
"e": 57295,
"s": 57250,
"text": "Step 2 β Execute the query of the database β"
},
{
"code": null,
"e": 57394,
"s": 57295,
"text": "db_excecute_query (write the required query that is to execute); Specify the appropriate condition"
},
{
"code": null,
"e": 57447,
"s": 57394,
"text": "Step 3 β Disconnect the database connection by using"
},
{
"code": null,
"e": 57469,
"s": 57447,
"text": "db_disconnect(query);"
},
{
"code": null,
"e": 57588,
"s": 57469,
"text": "Using Output database checkpoints, SQL manual queries options must be selected. Here, the select query can be written."
},
{
"code": null,
"e": 57774,
"s": 57588,
"text": "First, check the requirement of the stored procedure. The next step is to check if indexes, joins, deletions, update are correct in comparison with tables mentioned in stored procedure."
},
{
"code": null,
"e": 57810,
"s": 57774,
"text": "Next, perform the following tasks β"
},
{
"code": null,
"e": 57929,
"s": 57810,
"text": "Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters."
},
{
"code": null,
"e": 58048,
"s": 57929,
"text": "Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters."
},
{
"code": null,
"e": 58108,
"s": 58048,
"text": "Execute the procedure with TOAD or MySQL or Query Analyzer."
},
{
"code": null,
"e": 58168,
"s": 58108,
"text": "Execute the procedure with TOAD or MySQL or Query Analyzer."
},
{
"code": null,
"e": 58284,
"s": 58168,
"text": "Re-execute the available procedures by sending different parameters, and check the results against expected values."
},
{
"code": null,
"e": 58400,
"s": 58284,
"text": "Re-execute the available procedures by sending different parameters, and check the results against expected values."
},
{
"code": null,
"e": 58462,
"s": 58400,
"text": "Concluding to the process, automate the tests with WinRunner."
},
{
"code": null,
"e": 58524,
"s": 58462,
"text": "Concluding to the process, automate the tests with WinRunner."
},
{
"code": null,
"e": 58852,
"s": 58524,
"text": "The tester should call the stored procedure in the database using the EXEC command. If any parameters are required, they must be passed. Different values of parameters must be passed to confirm if the stored procedure is executed or not. On calling this command it must check and verify the nature and behavior of the database."
},
{
"code": null,
"e": 58955,
"s": 58852,
"text": "Example β If the stored procedure is written to populate some table, the table values must be checked."
},
{
"code": null,
"e": 58995,
"s": 58955,
"text": "We have three types of SQL statements β"
},
{
"code": null,
"e": 59028,
"s": 58995,
"text": "Data Manipulation Language (DML)"
},
{
"code": null,
"e": 59059,
"s": 59028,
"text": "Data Definition Language (DDL)"
},
{
"code": null,
"e": 59087,
"s": 59059,
"text": "Data Control Language (DCL)"
},
{
"code": null,
"e": 59171,
"s": 59087,
"text": "DDL statements are used to define the database structure or schema. Some examples β"
},
{
"code": null,
"e": 59214,
"s": 59171,
"text": "CREATE β to create objects in the database"
},
{
"code": null,
"e": 59257,
"s": 59214,
"text": "CREATE β to create objects in the database"
},
{
"code": null,
"e": 59302,
"s": 59257,
"text": "ALTER β alters the structure of the database"
},
{
"code": null,
"e": 59347,
"s": 59302,
"text": "ALTER β alters the structure of the database"
},
{
"code": null,
"e": 59387,
"s": 59347,
"text": "DROP β delete objects from the database"
},
{
"code": null,
"e": 59427,
"s": 59387,
"text": "DROP β delete objects from the database"
},
{
"code": null,
"e": 59557,
"s": 59427,
"text": "Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement."
},
{
"code": null,
"e": 59578,
"s": 59557,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 59610,
"s": 59578,
"text": "Comparison/Relational Operators"
},
{
"code": null,
"e": 59628,
"s": 59610,
"text": "Logical Operators"
},
{
"code": null,
"e": 59642,
"s": 59628,
"text": "Set Operators"
},
{
"code": null,
"e": 59678,
"s": 59642,
"text": "Operators used to negate conditions"
},
{
"code": null,
"e": 59820,
"s": 59678,
"text": "Union is used to combine the results of two or more Select statements. However it will eliminate the duplicate rows. Union is a set operator."
},
{
"code": null,
"e": 59932,
"s": 59820,
"text": "Union is used to combine the results of two or more Select statements. However it will eliminate duplicate rows"
},
{
"code": null,
"e": 60011,
"s": 59932,
"text": "Union All operation is similar to Union, but it also shows the duplicate rows."
},
{
"code": null,
"e": 60130,
"s": 60011,
"text": "Triggers are used to maintain the Integrity of database. To check Trigger is fired or not you can check in audit logs."
},
{
"code": null,
"e": 60383,
"s": 60130,
"text": "Triggers canβt be invoked on demand. They are invoked when an associated action (insert, delete & update) happens on the table on which they are defined. Triggers are used to apply business rules, auditing and also for the referential integrity checks."
},
{
"code": null,
"e": 60615,
"s": 60383,
"text": "First, get the functional requirement. Then, understand the table structure, Joins, Cursors and Triggers, Stored procedure used, and other parameters. Next, you can write a test-case with different values as input to these objects."
},
{
"code": null,
"e": 60773,
"s": 60615,
"text": "DB testing involves testing of back-end components which are not visible to users. It includes database components and DBMS systems such as MySQL and Oracle."
},
{
"code": null,
"e": 60996,
"s": 60773,
"text": "Front-end testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc. These components are created using front-end development tools like VB.net, C#, Delphi, etc."
},
{
"code": null,
"e": 61144,
"s": 60996,
"text": "The process to perform database testing is similar to testing of other applications. DB testing can be described with the following key processes β"
},
{
"code": null,
"e": 61171,
"s": 61144,
"text": "Setting up the environment"
},
{
"code": null,
"e": 61182,
"s": 61171,
"text": "Run a test"
},
{
"code": null,
"e": 61204,
"s": 61182,
"text": "Check the test result"
},
{
"code": null,
"e": 61249,
"s": 61204,
"text": "Validating according to the expected results"
},
{
"code": null,
"e": 61300,
"s": 61249,
"text": "Report the findings to the respective stakeholders"
},
{
"code": null,
"e": 61509,
"s": 61300,
"text": "Various SQL statements are used to develop the Test cases. Most common SQL statement which is used to perform DB testing is select statement. Apart from this various DDL, DML, DCL statements can also be used."
},
{
"code": null,
"e": 61556,
"s": 61509,
"text": "Example β Create, Insert, Select, Update, etc."
},
{
"code": null,
"e": 61801,
"s": 61556,
"text": "A view is a table that does not really exist in its own right but is instead derived from one or more base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary."
},
{
"code": null,
"e": 61981,
"s": 61801,
"text": "Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the changes in the database. Hence accounts for logical data independence."
},
{
"code": null,
"e": 62050,
"s": 61981,
"text": "It specifies user views and their mappings to the conceptual schema."
},
{
"code": null,
"e": 62197,
"s": 62050,
"text": "It is a process of decomposing a table into multiple tables without losing any information. Normalization is done to achieve the following goals β"
},
{
"code": null,
"e": 62221,
"s": 62197,
"text": "To minimize redundancy."
},
{
"code": null,
"e": 62275,
"s": 62221,
"text": "To minimize insertion, deletion and update anomalies."
},
{
"code": null,
"e": 62443,
"s": 62275,
"text": "Indexing is a technique for determining how quickly specific data can be found. It is used for query performance optimization. Indexing can be of the following types β"
},
{
"code": null,
"e": 62472,
"s": 62443,
"text": "Binary search style indexing"
},
{
"code": null,
"e": 62488,
"s": 62472,
"text": "B-Tree indexing"
},
{
"code": null,
"e": 62511,
"s": 62488,
"text": "Inverted list indexing"
},
{
"code": null,
"e": 62533,
"s": 62511,
"text": "Memory resident table"
},
{
"code": null,
"e": 62548,
"s": 62533,
"text": "Table indexing"
},
{
"code": null,
"e": 62686,
"s": 62548,
"text": "SQL is a Structured Query language that is designed specifically for data access operations on normalized relational database structures."
},
{
"code": null,
"e": 62871,
"s": 62686,
"text": "The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them."
},
{
"code": null,
"e": 63080,
"s": 62871,
"text": "Stored procedures are used to perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client."
},
{
"code": null,
"e": 63226,
"s": 63080,
"text": "PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors β implicit and explicit."
},
{
"code": null,
"e": 63481,
"s": 63226,
"text": "Cold Backup β Cold back is known as taking back up of database files, redo logs, and control file when the instance is shut down. This is a file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy."
},
{
"code": null,
"e": 63686,
"s": 63481,
"text": "If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All the changes that are performed after the last backup is lost."
},
{
"code": null,
"e": 63861,
"s": 63686,
"text": "Hot Backup β Some databases canβt shut down while making a backup copy of the files, so cold backup is not an available option. For these types of database we use hot backup."
},
{
"code": null,
"e": 64206,
"s": 63861,
"text": "SQL subquery is a means of querying two or more tables at the same time. The subquery itself is an SQL SELECT statement contained within the WHERE clause of another SQL SELECT statement, and separated by being enclosed in parenthesis. Some subqueries have equivalent SQL join structures, but correlated subqueries cannot be duplicated by a join"
},
{
"code": null,
"e": 64263,
"s": 64206,
"text": "In such a case, you need to test the following aspects β"
},
{
"code": null,
"e": 64288,
"s": 64263,
"text": "Multivalued dependencies"
},
{
"code": null,
"e": 64312,
"s": 64288,
"text": "Functional dependencies"
},
{
"code": null,
"e": 64327,
"s": 64312,
"text": "Candidate keys"
},
{
"code": null,
"e": 64340,
"s": 64327,
"text": "Primary keys"
},
{
"code": null,
"e": 64353,
"s": 64340,
"text": "Foreign keys"
},
{
"code": null,
"e": 64558,
"s": 64353,
"text": "You can go to the database and run a relevant SQL query. In WinRunner, you can use database checkpoint function. If the application provides view function, then you can verify the same from the front-end."
},
{
"code": null,
"e": 64830,
"s": 64558,
"text": "Data-driven testing is defined as an automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface."
},
{
"code": null,
"e": 65066,
"s": 64830,
"text": "Once you execute the test-cases and find the defects that has been already detected and fixed. Re-execution of the same test with different input values to confirm the original defect has been successfully removed is called Re-testing."
},
{
"code": null,
"e": 65137,
"s": 65066,
"text": "Retesting is also called Data Driven Testing with a small difference β"
},
{
"code": null,
"e": 65242,
"s": 65137,
"text": "Retesting β It is a manual testing process whereas application testing done with entire new set of data."
},
{
"code": null,
"e": 65347,
"s": 65242,
"text": "Retesting β It is a manual testing process whereas application testing done with entire new set of data."
},
{
"code": null,
"e": 65613,
"s": 65347,
"text": "Data-driven Testing β It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface."
},
{
"code": null,
"e": 65879,
"s": 65613,
"text": "Data-driven Testing β It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface."
},
{
"code": null,
"e": 65925,
"s": 65879,
"text": "There are four types of data driven testing β"
},
{
"code": null,
"e": 65971,
"s": 65925,
"text": "Dynamic test data submission through keyboard"
},
{
"code": null,
"e": 66015,
"s": 65971,
"text": "Data Driven Tests via .txt, .doc flat files"
},
{
"code": null,
"e": 66055,
"s": 66015,
"text": "Data Driven Tests via front-end objects"
},
{
"code": null,
"e": 66089,
"s": 66055,
"text": "Data Driven Tests via excel sheet"
},
{
"code": null,
"e": 66245,
"s": 66089,
"text": "Performance testing is a software testing technique to determine how a system performs in terms of speed, sensitivity and stability under a heavy workload."
},
{
"code": null,
"e": 66336,
"s": 66245,
"text": "The following key points are to be considered while performing database recovery testing β"
},
{
"code": null,
"e": 66403,
"s": 66336,
"text": "Time span when changes or modifications occurs in database system."
},
{
"code": null,
"e": 66470,
"s": 66403,
"text": "Time span when changes or modifications occurs in database system."
},
{
"code": null,
"e": 66529,
"s": 66470,
"text": "The period by which you want your recovery plan conducted."
},
{
"code": null,
"e": 66588,
"s": 66529,
"text": "The period by which you want your recovery plan conducted."
},
{
"code": null,
"e": 66714,
"s": 66588,
"text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software."
},
{
"code": null,
"e": 66840,
"s": 66714,
"text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software."
},
{
"code": null,
"e": 66893,
"s": 66840,
"text": "The following tools are used to generate test data β"
},
{
"code": null,
"e": 66906,
"s": 66893,
"text": "Data Factory"
},
{
"code": null,
"e": 66925,
"s": 66906,
"text": "DTM Data Generator"
},
{
"code": null,
"e": 66936,
"s": 66925,
"text": "Turbo Data"
},
{
"code": null,
"e": 66985,
"s": 66936,
"text": "There are two types of backup that can be used β"
},
{
"code": null,
"e": 67159,
"s": 66985,
"text": "Physical Backups β Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities."
},
{
"code": null,
"e": 67333,
"s": 67159,
"text": "Physical Backups β Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities."
},
{
"code": null,
"e": 67460,
"s": 67333,
"text": "Logical Backups β Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc."
},
{
"code": null,
"e": 67587,
"s": 67460,
"text": "Logical Backups β Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc."
},
{
"code": null,
"e": 67706,
"s": 67587,
"text": "A common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup."
},
{
"code": null,
"e": 67773,
"s": 67706,
"text": "The following actions are performed in database recovery testing β"
},
{
"code": null,
"e": 67800,
"s": 67773,
"text": "Testing of database system"
},
{
"code": null,
"e": 67825,
"s": 67800,
"text": "Testing of the SQL files"
},
{
"code": null,
"e": 67850,
"s": 67825,
"text": "Testing of partial files"
},
{
"code": null,
"e": 67873,
"s": 67850,
"text": "Testing of data backup"
},
{
"code": null,
"e": 67896,
"s": 67873,
"text": "Testing of Backup tool"
},
{
"code": null,
"e": 67916,
"s": 67896,
"text": "Testing log backups"
},
{
"code": null,
"e": 68078,
"s": 67916,
"text": "Database security testing is performed to find the loop holes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system."
},
{
"code": null,
"e": 68150,
"s": 68078,
"text": "Database security testing is performed to check the following aspects β"
},
{
"code": null,
"e": 68165,
"s": 68150,
"text": "Authentication"
},
{
"code": null,
"e": 68179,
"s": 68165,
"text": "Authorization"
},
{
"code": null,
"e": 68195,
"s": 68179,
"text": "Confidentiality"
},
{
"code": null,
"e": 68208,
"s": 68195,
"text": "Availability"
},
{
"code": null,
"e": 68218,
"s": 68208,
"text": "Integrity"
},
{
"code": null,
"e": 68229,
"s": 68218,
"text": "Resilience"
},
{
"code": null,
"e": 68576,
"s": 68229,
"text": "SQL Injection threat is the most common type of attack in a database system where malicious SQL statements are inserted in database system and executed to get critical information from database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this user inputs fields should be carefully handled."
},
{
"code": null,
"e": 68736,
"s": 68576,
"text": "The following tools can be used to perform database security testing: Zed Attack Proxy, Paros, Social Engineer Toolkit, Skipfish, Vega, Wapiti, and Web Scarab."
},
{
"code": null,
"e": 68824,
"s": 68736,
"text": "The common challenges that one faces while performing database testing are as follows β"
},
{
"code": null,
"e": 68851,
"s": 68824,
"text": "Testing scope is too large"
},
{
"code": null,
"e": 68877,
"s": 68851,
"text": "Scaled-down test database"
},
{
"code": null,
"e": 68907,
"s": 68877,
"text": "Changes in database structure"
},
{
"code": null,
"e": 68926,
"s": 68907,
"text": "Complex Test Plans"
},
{
"code": null,
"e": 68952,
"s": 68926,
"text": "Good understanding of SQL"
},
{
"code": null,
"e": 68987,
"s": 68952,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 68998,
"s": 68987,
"text": " Syed Raza"
},
{
"code": null,
"e": 69031,
"s": 68998,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 69059,
"s": 69031,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 69093,
"s": 69059,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 69128,
"s": 69093,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 69163,
"s": 69128,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 69183,
"s": 69163,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 69216,
"s": 69183,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 69236,
"s": 69216,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 69269,
"s": 69236,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 69287,
"s": 69269,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 69294,
"s": 69287,
"text": " Print"
},
{
"code": null,
"e": 69305,
"s": 69294,
"text": " Add Notes"
}
] |
Eigenvector Computation and Low-Rank Approximations - GeeksforGeeks | 30 May, 2021
Prerequisites: Eigen Values and Eigen Vectors
Before getting into the in-depth math behind computations involved with Eigenvectors, let us briefly discuss what an eigenvalue and eigenvector actually are.
The word βeigenβ means βcharacteristicsβ. In general terms, the eigenvalues and eigenvectors give the characteristics of a matrix or a vector.
Eigenvector: It is a vector represented by a matrix X such that when X is multiplied with any matrix A, then the direction of the resultant matrix remains the same as vector X. Observe Fig 1 carefully to look at a graphical representation of an eigenvector.
Fig 1 : Eigenvector representation
In Fig 1, we observe the following scalar transformations:
After applying these transformations, the vectors v1β and v2β are in the same direction as v1 and v2. So as per our definition, these are considered as eigenvectors. But resultant vector v3β is not in the same direction as v3. Hence it cannot be considered as a eigenvector.
Eigenvalues: It tells us about the extent to which the eigenvector has been stretched or diminished. In the above case, the eigenvalues will be 1.5 and 0.5.
We can calculate eigenvalues of any matrix using the characteristic equation of the matrix (as discussed in the prerequisite article) that is:
The roots of the above equation (i.e. values of Ξ») gives us the eigenvalues.
Using the values of Ξ» obtained, we can find the corresponding eigenvectors using the equation given below.
Example Problem
Consider the following example for a better understanding. Let there be a 3Γ3 matrix X defined as:
Find the eigen values and eigen vectors corresponding to the matrix A.
1. Finding the eigen values.
Thus, the eigen values obtained are 1, 2 and 3.
2. Finding the eigen vectors.
Using the formula given above, we will calculate a corresponding eigen vector xi for each value of Ξ»i.
Thus, we obtain the eigen vectors X1, X2, X3 corresponding to each value of Ξ».
Rank of a (m x n) matrix is determined by the number of linearly independent rows present in the matrix. Consider the example given below for a better understanding.
All 3 rows of matrix A are linearly independent. Therefore, Rank ( A ) = 3.
Rank ( B ) = 2. This is because Row 3 is dependent on R1 and R2. [R3 <- R1 + R2]
For any matrix A of shape m x n, the following rank properties are applicable:
Rank (A) = Rank (AT)Rank (BAC) = Rank (A) provided B and C are invertible matrices.Rank (AB) β€ min{ Rank (A) + Rank (B) }
Rank (A) = Rank (AT)
Rank (BAC) = Rank (A) provided B and C are invertible matrices.
Rank (AB) β€ min{ Rank (A) + Rank (B) }
Before getting into Low-Rank Approximation, it is important to understand the following:
Matrix Factorization
Any matrix A of shape m x n having rank (A) = r is said to be factorized when it takes the form:
where, the shapes of the matrices are:
mat(A) -> m x n
mat(B) -> m x r
mat(C) -> n x r
Low Rank
We say that matrix A has a low rank if r << min {m,n}.
Based on the above two discussed method, we define LRA as:
For a matrix A of shape m x n and rank (A) << min {m, n}, the low-rank approximation of A is to find another matrix B such that rank (B) β€ rank (A). Intuitively, we tend to see how linearly similar matrix B is to the input matrix A. Mathematically, LRA is a minimization problem, in which we measure the fit between a given matrix (the data) and an approximating matrix (the optimization variable).
Let us assume 3 matrices X, Y, Z of dimensions (50 x 40), (50 x 10), (40 x 10) respectively where rank(X) = 10. Therefore, as per matrix factorization, the three matrices are of the form A = BCT. We observe that:
Amxn = BmxrCTrxn
No of elements/pixels in mat(A) = (50 x 40) = 2000
while
No of elements/pixels in mat(BCT) = (50 x 10) + (10 x 40) = 900.
Thus, by using low-rank approximation, we can reduce the number of pixels of input data by a significant amount. (1100 fewer pixels than input image in the above case)
This method is commonly used in Image Processing tasks where the input image (data) is very large and needs to be compressed before any processing task. Observe the two images of the same person given below.
After LRA image vs Input image
After applying LRA, we are able to obtain an image that is very similar to the original image by discarding some unimportant pixels, hence reducing the size of the image as well. After doing this, it becomes much easier to handle such large datasets and perform a variety of pre-processing tasks on them.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Intuition of Adam Optimizer
ML | Logistic Regression using Python
Principal Component Analysis with Python
CNN | Introduction to Pooling Layer
Normalization vs Standardization
Python | Decision Tree Regression using sklearn
Introduction to Recurrent Neural Network | [
{
"code": null,
"e": 24344,
"s": 24316,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 24390,
"s": 24344,
"text": "Prerequisites: Eigen Values and Eigen Vectors"
},
{
"code": null,
"e": 24548,
"s": 24390,
"text": "Before getting into the in-depth math behind computations involved with Eigenvectors, let us briefly discuss what an eigenvalue and eigenvector actually are."
},
{
"code": null,
"e": 24691,
"s": 24548,
"text": "The word βeigenβ means βcharacteristicsβ. In general terms, the eigenvalues and eigenvectors give the characteristics of a matrix or a vector."
},
{
"code": null,
"e": 24950,
"s": 24691,
"text": "Eigenvector: It is a vector represented by a matrix X such that when X is multiplied with any matrix A, then the direction of the resultant matrix remains the same as vector X. Observe Fig 1 carefully to look at a graphical representation of an eigenvector. "
},
{
"code": null,
"e": 24985,
"s": 24950,
"text": "Fig 1 : Eigenvector representation"
},
{
"code": null,
"e": 25044,
"s": 24985,
"text": "In Fig 1, we observe the following scalar transformations:"
},
{
"code": null,
"e": 25319,
"s": 25044,
"text": "After applying these transformations, the vectors v1β and v2β are in the same direction as v1 and v2. So as per our definition, these are considered as eigenvectors. But resultant vector v3β is not in the same direction as v3. Hence it cannot be considered as a eigenvector."
},
{
"code": null,
"e": 25476,
"s": 25319,
"text": "Eigenvalues: It tells us about the extent to which the eigenvector has been stretched or diminished. In the above case, the eigenvalues will be 1.5 and 0.5."
},
{
"code": null,
"e": 25619,
"s": 25476,
"text": "We can calculate eigenvalues of any matrix using the characteristic equation of the matrix (as discussed in the prerequisite article) that is:"
},
{
"code": null,
"e": 25697,
"s": 25619,
"text": "The roots of the above equation (i.e. values of Ξ») gives us the eigenvalues. "
},
{
"code": null,
"e": 25804,
"s": 25697,
"text": "Using the values of Ξ» obtained, we can find the corresponding eigenvectors using the equation given below."
},
{
"code": null,
"e": 25820,
"s": 25804,
"text": "Example Problem"
},
{
"code": null,
"e": 25919,
"s": 25820,
"text": "Consider the following example for a better understanding. Let there be a 3Γ3 matrix X defined as:"
},
{
"code": null,
"e": 25991,
"s": 25919,
"text": "Find the eigen values and eigen vectors corresponding to the matrix A. "
},
{
"code": null,
"e": 26020,
"s": 25991,
"text": "1. Finding the eigen values."
},
{
"code": null,
"e": 26069,
"s": 26020,
"text": "Thus, the eigen values obtained are 1, 2 and 3. "
},
{
"code": null,
"e": 26099,
"s": 26069,
"text": "2. Finding the eigen vectors."
},
{
"code": null,
"e": 26203,
"s": 26099,
"text": "Using the formula given above, we will calculate a corresponding eigen vector xi for each value of Ξ»i. "
},
{
"code": null,
"e": 26282,
"s": 26203,
"text": "Thus, we obtain the eigen vectors X1, X2, X3 corresponding to each value of Ξ»."
},
{
"code": null,
"e": 26449,
"s": 26282,
"text": "Rank of a (m x n) matrix is determined by the number of linearly independent rows present in the matrix. Consider the example given below for a better understanding. "
},
{
"code": null,
"e": 26525,
"s": 26449,
"text": "All 3 rows of matrix A are linearly independent. Therefore, Rank ( A ) = 3."
},
{
"code": null,
"e": 26606,
"s": 26525,
"text": "Rank ( B ) = 2. This is because Row 3 is dependent on R1 and R2. [R3 <- R1 + R2]"
},
{
"code": null,
"e": 26685,
"s": 26606,
"text": "For any matrix A of shape m x n, the following rank properties are applicable:"
},
{
"code": null,
"e": 26807,
"s": 26685,
"text": "Rank (A) = Rank (AT)Rank (BAC) = Rank (A) provided B and C are invertible matrices.Rank (AB) β€ min{ Rank (A) + Rank (B) }"
},
{
"code": null,
"e": 26828,
"s": 26807,
"text": "Rank (A) = Rank (AT)"
},
{
"code": null,
"e": 26892,
"s": 26828,
"text": "Rank (BAC) = Rank (A) provided B and C are invertible matrices."
},
{
"code": null,
"e": 26931,
"s": 26892,
"text": "Rank (AB) β€ min{ Rank (A) + Rank (B) }"
},
{
"code": null,
"e": 27020,
"s": 26931,
"text": "Before getting into Low-Rank Approximation, it is important to understand the following:"
},
{
"code": null,
"e": 27042,
"s": 27020,
"text": "Matrix Factorization "
},
{
"code": null,
"e": 27139,
"s": 27042,
"text": "Any matrix A of shape m x n having rank (A) = r is said to be factorized when it takes the form:"
},
{
"code": null,
"e": 27229,
"s": 27139,
"text": "where, the shapes of the matrices are:\n \nmat(A) -> m x n\nmat(B) -> m x r \nmat(C) -> n x r"
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "Low Rank"
},
{
"code": null,
"e": 27294,
"s": 27238,
"text": "We say that matrix A has a low rank if r << min {m,n}. "
},
{
"code": null,
"e": 27353,
"s": 27294,
"text": "Based on the above two discussed method, we define LRA as:"
},
{
"code": null,
"e": 27752,
"s": 27353,
"text": "For a matrix A of shape m x n and rank (A) << min {m, n}, the low-rank approximation of A is to find another matrix B such that rank (B) β€ rank (A). Intuitively, we tend to see how linearly similar matrix B is to the input matrix A. Mathematically, LRA is a minimization problem, in which we measure the fit between a given matrix (the data) and an approximating matrix (the optimization variable)."
},
{
"code": null,
"e": 27965,
"s": 27752,
"text": "Let us assume 3 matrices X, Y, Z of dimensions (50 x 40), (50 x 10), (40 x 10) respectively where rank(X) = 10. Therefore, as per matrix factorization, the three matrices are of the form A = BCT. We observe that:"
},
{
"code": null,
"e": 28105,
"s": 27965,
"text": "Amxn = BmxrCTrxn\n\nNo of elements/pixels in mat(A) = (50 x 40) = 2000\nwhile\nNo of elements/pixels in mat(BCT) = (50 x 10) + (10 x 40) = 900."
},
{
"code": null,
"e": 28273,
"s": 28105,
"text": "Thus, by using low-rank approximation, we can reduce the number of pixels of input data by a significant amount. (1100 fewer pixels than input image in the above case)"
},
{
"code": null,
"e": 28482,
"s": 28273,
"text": "This method is commonly used in Image Processing tasks where the input image (data) is very large and needs to be compressed before any processing task. Observe the two images of the same person given below. "
},
{
"code": null,
"e": 28513,
"s": 28482,
"text": "After LRA image vs Input image"
},
{
"code": null,
"e": 28819,
"s": 28513,
"text": "After applying LRA, we are able to obtain an image that is very similar to the original image by discarding some unimportant pixels, hence reducing the size of the image as well. After doing this, it becomes much easier to handle such large datasets and perform a variety of pre-processing tasks on them. "
},
{
"code": null,
"e": 28836,
"s": 28819,
"text": "Machine Learning"
},
{
"code": null,
"e": 28853,
"s": 28836,
"text": "Machine Learning"
},
{
"code": null,
"e": 28951,
"s": 28853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28984,
"s": 28951,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29023,
"s": 28984,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 29058,
"s": 29023,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29086,
"s": 29058,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 29124,
"s": 29086,
"text": "ML | Logistic Regression using Python"
},
{
"code": null,
"e": 29165,
"s": 29124,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29201,
"s": 29165,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 29234,
"s": 29201,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 29282,
"s": 29234,
"text": "Python | Decision Tree Regression using sklearn"
}
] |
What's the difference between "update" and "update_idletasks" in Tkinter? | Update method processes all the pending idle tasks, unvisited events, calling functions, and callbacks. The method is applicable for updating and processing all the events or tasks such as redrawing widgets, geometry management, configuring the widget property, etc.
It also ensures that if the application has any pending tasks, then it will just update or refresh the value that affects the whole part of the application. Using update for a single pending task would be nasty, thus Tkinter also provides the update_idletasks() method. It only updates the idle pending task that is stable or not updating in the application for some reason. It calls all the events that are pending without processing any other events or callback.
The update() and update_idletask() methods are useful for processing any pending or idle tasks. However, the only difference between update() and update_idletasks() is that update() processes all the events present in the application, while update_idletasks() only processes those events which are not running or stable.
We can understand the use and application of update_idletasks() method through this example.
# Import the tkinter library
from tkinter import *
from tkinter import ttk
import time
# Create an instance of tkinter frame
win= Tk()
# Set the size of the Tkinter window
win.geometry("700x350")
def add_Text():
for i in range(10):
label.config(text= "The loops starts from 1 to "+ str(i))
# Wait for two seconds
win.update_idletasks()
time.sleep(2)
label.config(text= i)
# Add a label text
label= Label(win, text="Original Text", font= ('Aerial 16'))
label.pack(pady= 30)
# Add a button to update the Label text
ttk.Button(win, text="Change Text", command= add_Text).pack(pady= 40)
win.mainloop()
Running the above code will display a window with a Label widget and a button.
When we press the button, the Label widget gets updated automatically in the given range of the loop. | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Update method processes all the pending idle tasks, unvisited events, calling functions, and callbacks. The method is applicable for updating and processing all the events or tasks such as redrawing widgets, geometry management, configuring the widget property, etc."
},
{
"code": null,
"e": 1794,
"s": 1329,
"text": "It also ensures that if the application has any pending tasks, then it will just update or refresh the value that affects the whole part of the application. Using update for a single pending task would be nasty, thus Tkinter also provides the update_idletasks() method. It only updates the idle pending task that is stable or not updating in the application for some reason. It calls all the events that are pending without processing any other events or callback."
},
{
"code": null,
"e": 2115,
"s": 1794,
"text": "The update() and update_idletask() methods are useful for processing any pending or idle tasks. However, the only difference between update() and update_idletasks() is that update() processes all the events present in the application, while update_idletasks() only processes those events which are not running or stable."
},
{
"code": null,
"e": 2208,
"s": 2115,
"text": "We can understand the use and application of update_idletasks() method through this example."
},
{
"code": null,
"e": 2843,
"s": 2208,
"text": "# Import the tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\nimport time\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the Tkinter window\nwin.geometry(\"700x350\")\ndef add_Text():\n for i in range(10):\n label.config(text= \"The loops starts from 1 to \"+ str(i))\n # Wait for two seconds\n win.update_idletasks()\n time.sleep(2)\n label.config(text= i)\n\n# Add a label text\nlabel= Label(win, text=\"Original Text\", font= ('Aerial 16'))\nlabel.pack(pady= 30)\n\n# Add a button to update the Label text\nttk.Button(win, text=\"Change Text\", command= add_Text).pack(pady= 40)\nwin.mainloop()"
},
{
"code": null,
"e": 2922,
"s": 2843,
"text": "Running the above code will display a window with a Label widget and a button."
},
{
"code": null,
"e": 3024,
"s": 2922,
"text": "When we press the button, the Label widget gets updated automatically in the given range of the loop."
}
] |
Deploying your Dash App to Heroku β THE MAGICAL GUIDE | Towards Data Science | So you have your Dash app running on your local machine and youβre finally ready to share it with the world on a public site.
The problem is: words like like Git, Flask, Gunicorn and Heroku sound like strange mythical creatures, even after a few drinks. Worry not: having just been through the process of deploying Dash to Heroku myself for the first time, Iβll share what Iβve learned along the way. Iβll outline some surprising pitfalls and solutions I found, in the hope this will save you time and effort. This is the guide I wish I had when I started.
QuickstartIβve built a Dash-Heroku starter pack on Github. This is a barebones Dash app fully setup and tested that runs on Heroku. It has all the necessary special files and tweaks so you can serve static files (such as images) which is the most common pain point. For first timers, Iβd recommend you get this demo running on Heroku first, and then transfer your locally running Dash project code carefully over to it :)
Background
The process to successfully deploy a Dash app on Heroku is not trivial for many first timers. For example, simply serving static files (like documents, audio, images, video) doesnβt work out of the box with Heroku like it does from your local machine. I didnβt realise this, along with a few other quirks.
This essay is designed to supplement the existing documentation, and attempts to fill in some gaps, explain the quirks, and provide a very brief fly-over of each component and how everything fits together. Iβll share notes from my personal experience. Iβll also attempt to explain the technology stack based on my imperfect understanding of how it all works. No doubt Iβve got some things wrong, so I welcome corrections from the community.
Assumptions
You have a running Dash app locally hosted (with a requirements.txt)
Youβre relatively new to Python
You have a strong cup of coffee (better yet, a glass of red)
Youβve never deployed a public web app before
Words like Heroku and Gunicorn scare you.
The Problem
In my research I scanned many blog articles and guides about deploying Dash to Heroku, but found most to be a little lacklustre or not specific to Dash. YouTube videos, too, are often super quick (do it in 15 minutes!!) and donβt explain the core concepts. The majority of the guidance Iβve seen so far is bare minimum, light on explanation, and doesnβt outline key issues youβll encounter in the detail you need. If youβre working with Dash, chances are you are new to Flask as well, so many concepts are not well understood. Iβve yet to read a guide that outlines the core concepts and pitfalls for specifically deploying a Dash app to Heroku. I believe this lack of comprehensive written guidance is a (solvable) barrier to entry for many potential Dash users.
How much pain is this going to be? (about 10 hours)
How hard really is it to Deploy to Heroku as a first timer? How much pain is involved? What problems will you encounter? Iβm glad you asked. In short, Iβd say optimistically it can be done in a few hours ground-up, but realistically about 10hrs for a first timer. Pain meter: medium spicy.
This is because it takes time to create the accounts and setup the environments like GitHub and Heroku command line interface, add special new files to your project directory (repository), modify the code in a few spots, and get used to the commands you need in order to see whatβs going on and make it all work. It can be a little daunting at first, but once youβve done the initial setup, youβre on easy street. Deploying code running on your laptop to your live public web app is a few mouse clicks and single command in a terminal, which is super cool. (Caveat: this does not cover security and authentication β this is purely to deploy a hobby app).
Why Heroku?
Like myself, youβve probably heard of Heroku as a well-loved platform for deploying hobbyist web applications for free. Of course, itβs not the only one β there are many, and it is scalable to enterprise-level deployments. But it is universally known and liked by the community, so I chose to go this route and see what all the fuss was about. Verdict so far: loving it. Key reasons the community loves Heroku (as far as I know):
Itβs free for hobby apps, which is great to get started and for demos
Itβs got clear, concise documentation
It natively supports Python web apps (read: minimal config needed)
What is Heroku?
Itβs a platform-as-a-service (PaaS) for deploying and hosting web applications. In the context of your Dash app, this means Heroku provides the physical hardware (storage, compute), software services (linux/unix/sql), and dependencies (packages), in a containerised environment to deploy and host your application on a publicly accessible URL (end-point). It does this through provision of virtualised linux containers called βDynosβ which essentially act as your personal linux webserver, with ram, cpu, and linux βinstalledβ. (Itβs not quite like this in reality but a good analogy).
Dynos come in a variety of shapes and sizes and can be scaled vertically (more ram, compute, storage per instance) or horizontally (duplicate dynos in parallel) as your specific project requirements demand. You can hot swap dyno types instantaneously at command line while your app is live, which is mint. The free version gets you one dyno with up to 500MB storage and 500MB ram. It sleeps after 30 minutes of inactivity, presumably so Heroku resources are not drained. So the catch with the free version is that your website can take a good 30β60 seconds to load initially, as your free Dyno is provisioned on demand. If you go to a paid plan, starting at about $7USD/month, your dyno(s) stay on and ready 24hrs/day.
The biggest constraint with Heroku dynos is RAM; you donβt get much. At least in my experience, Iβve found that Python (Dash) apps often require a decent amount of RAM as you are reading in Pandas dataframes and doing all sorts of fun stuff. Itβs fine for a single instance of your app for a select small group of users, but if you want to scale out you will need to run duplicate parallel instances of your app, and this will cost you $$ in RAM to either run more dynos in parallel, or multiple instances of your app in larger tier dynos.
Why GitHub?
In short β Heroku natively supports deploying repositories that reside in GitHub. This is good news. Basically it means if your project is already in a GitHub repository (free for private/public repos) then you can easily deploy it on Heroku AFTER you have added a few additional files that are outlined in the deployment guides, and in a section further below.
If youβve been developing your pet project on a local machine, before you can deploy on Heroku you first need to get your project onto GitHub. (Note you donβt have to use GitHub, but itβs an easy option.) This is an important step to take your code to a public (or private) cloud repository. Itβs a good move anyway because you have full versioning history, you are protected from hard drive failure, and you can share publicly or privately. It does, however, come with intellectual debt, with some interesting concepts and terminology to get your head around, like clone, fork, merge, push, pull, and commit.
Yet another barrier to newcomers is the issue with security and how this affects you accessing and changing the code in your cloud repository on GitHub or similar. Basically, GitHub wants a secure connection between your computer and its servers before it will happily accept code changes. There are two main ways it achieves this: using credential authentication over HTTPS (requiring a username/pass every time a connection is made), or via SSH public/private key encryption, which is not natively supported by Windows. This extra complication, combined with the other scary words like clone, fork, and merge can be a little overwhelming at first. Fear not: thereβs a desktop app that can setup a secure connection between itself and your GitHub repo, facilitating seamless easy updates to your code repository.
If youβre developing on a windows/mac machine (which I assume the majority of first timers are), Iβd highly recommend getting the Github Desktop application. This just makes the process of cloning, fetching and pushing changes back to your repository on Github MUCH easier without the need for any command line. Itβs not that Iβm against command line, itβs just that this particular process can be clunky on windows, requiring either user credential authentication or SSH keys mentioned above.
(Special note: if you are more hardcore you can of course install Windows Subsystem for Linux which is a way to have a fully functioning Linux system on Windows without the need for dual boot options etc. If you do this you can setup SSH keys and enjoy the benefits of linux for managing your code repo but itβs really not necessary for first timers.)
In short, you can avoid a lot of hassle just by using the Desktop app, and setting up the security within the app β then itβs single click of the mouse to commit changes and push updated code to your remote repo on GitHub.
What is Git?
No one really knows.
What is Gunicorn?
When you figure it out, let me know. Gunicorn, to the best of my understanding, is a production-ready HTTP server specifically for Python web applications which runs natively in Unix; itβs the thing that actually serves the web browser request. If youβve been developing your Dash app purely on your local machine @ βlocalhost:8080β or βhttp://127.0.0.1:8050/β you will be running a light weight HTTP server that is shipped with your Python installation. This is not Gunicorn. Itβs likely you have not yet glimpsed this rare and mythical creature of the forest.
The local HTTP server (shipped with your Python installation) is automatically run by your Python Kernel when your dash app is executed on your local machine. The issue is that itβs not designed for handling incoming traffic from a production website and so when you deploy to the web, you need a production-ready HTTP server. A popular one is Gunicorn. Notably, Heroku provides native support for Gunicorn, which makes things easy. Itβs all outlined in the guides, but just to clarify, all you need to do is add a single line of code to your dash app (βserver = app.serverβ), add Gunicorn into your requirements.txt so it is installed as a package on your local machine (and by Heroku during deployment), and reference it in a special file you will create called the Procfile. More on this later but I think itβs worth briefly touching on the HTTP server as itβs all a bit mysterious the first time.
What is Flask?
Before cups and bottles, in the medieval times people used to drink out of flasks. This of course has no bearing whatsoever on what Flask is in the context of Python, but hold onto the drinking analogy. Flask is a micro-framework for Python web applications. If you are not familiar with frameworks and why they matter, essentially they provide a structure (a pattern) for you to develop your project in a way that supports growth and multiple collaborators. Some are rigid and some are more flexible, but the ultimate goal is to help a complex project become manageable by separating functional components of code (and other things) into logical places, as well as providing tools and libraries to assist with common tasks (e.g. setting up sql databases, accessing the underlying host operating system, user authentication etc.)
Popular frameworks in Python include Flask and Django. In Ruby, you have probably heard of Ruby on Rails, which is a well known framework for developing Ruby web apps. If you are sticking to a bare minimum Dash app, you donβt need to worry about frameworks, but just note they are for proper, serious, software development and they are important. Your Dash app is in reality still a Flask app (Dash sits on top), Flask has just been hidden away behind the scenes. The reason Flask is popular is it is non-rigid, and does not enforce strict directory structures and file names. It can also be used piecemeal, so parts of it can be plucked out as needed, keeping the project as simple as it can be while retaining features. This is probably why Plotly chose it for Dash! To return to the βdrinking analogyβ: unlike many other frameworks, Flask as a framework can be βsippedβ as it is needed to support just the features that are what is needed for a given project, and no more.
Web is hard
This is a simple truth. Web is multi-layer, multi-language, multi-protocol, multi-platform, and multi-user. Itβs a mind-boggling chain of infrastructure bolted to other infrastructure to make a modern (scalable) web application run. For many non-IT people (and IT people for that matter), even the concept of a locally hosted webserver takes a bit of abstract thought, let alone understanding the true technology stack that lies underneath a real client-server architecture. Itβs also worth reflecting on just how new some of this technology really is, so Iβve indicated the year these tools were created in the table below.
The simplified technology stack
This is imperfect, so please help me to correct it. But itβs useful, I think, to see some of the layers required to get your code deployed onto the web. We start with your actual code at the very top of the stack, and drill down layers all the way to Heroku.
The point Iβm trying to make here is that this grossly oversimplified web technology stack is still far from simple; to say nothing about front end layers such as Javascript, CSS etc. Web is hard because of the sheer number of abstraction layers.
Dash, to me, is a beautiful abstraction at the very top of the technology stack β building upon everything below it β in order to simplify what is actually an insanely complex machine: the modern data-rich web application.
Dash-Heroku deployment, in a nutshell
What actually needs to be done:
Dash app running on localhostInstall GitSetup GitHub account (+ recommend install GitHub Desktop)Setup Heroku account (+ install the command line interface)Add dependencies and special files (i.e. install and import Gunicorn, create Procfile and runtime.txt)Clone repo from GitHub to local machine (only once)Create Heroku app linked to your repo (only once, ref deployment guides, Heroku CLI)Commit and push your code changes to GitHub repo (repetitively)Deploy/Re-deploy Heroku app by pushing changes (βgit push Heroku mainβ)
Dash app running on localhost
Install Git
Setup GitHub account (+ recommend install GitHub Desktop)
Setup Heroku account (+ install the command line interface)
Add dependencies and special files (i.e. install and import Gunicorn, create Procfile and runtime.txt)
Clone repo from GitHub to local machine (only once)
Create Heroku app linked to your repo (only once, ref deployment guides, Heroku CLI)
Commit and push your code changes to GitHub repo (repetitively)
Deploy/Re-deploy Heroku app by pushing changes (βgit push Heroku mainβ)
Just to be super clear here for those that are very new to this process. Once youβve created a Heroku app linked to your repo, this means that when changes are pushed to your Heroku remote repo on Github, this will actually trigger a Heroku build of your app. What that means is, when you type git push heroku mainthis is pushing your local code to your remote heroku repository on github (on a branch called main, which is the default primary). As soon as this happens, this will trigger a build and you should see this in your terminal (console) immediately after you type the command.
Deployment Guides
The guides below are concise and useful, and I would of course start with these. If Iβm honest, I think they are a little light on detail for newcomers and would benefit greatly by having a supplementary explanatory guide akin to something like this essay.
Plotlyβs Dash deployment guide
Herokuβs guide
Recommendations: Install Heroku command line interface (CLI) and GitHub Desktop if a windows/mac user
Also, this YouTube tutorial from a fellow Plotly Community Forum member.
My Dash-Heroku starter pack on GitHub is a running base to build on.
A quick note on the special files you need uniquely to get your python project deployed to Heroku. This is outlined in the deployment guide, so Iβve just provided a few notes from my experience:
Ingredient 1: Procfile
This strange extensionless file must reside in your project root, and tells Heroku how to handle web processes (in our case using Gunicorn HTTP server) and the name of your Python application.
Typically the Procfile would contain a single line:
web: gunicorn app:server
Where:
βweb:β tells Heroku the dyno main process is a web process
βgunicornβ tells heroku that the HTTP server to use is Gunicorn (for which it has native support for)
βappβ references the filename of the main python file without the .py extension. So if you follow the convention of βapp.pyβ you would use βappβ here. But note if your main python file is βanything.pyβ, you would have βanythingβ in place of βappβ.
βserverβ references the underlying flask app. Commonly you would define a variable βserver = app.serverβ and this references that variable, I believe. To be more confusing, the βappβ in this variable declaration actually refers to the dash instantiation variable in the snippet below:
app = dash.Dash(__name__)server = app.server
Yes I know what youβre thinking, this is finicky and itβs really easy to misunderstand with all these βappβ references everywhere. Take home is: as long as youβre using an app.py main file, as is the convention, and you declare a βserver = app.serverβ line of code after your Dash declaration, you can use the example Procfile and it should work. If you get anything with the Procfile wrong, pain and suffering will ensue.
To make the Procfile in Windows, you can just create a text file, and enter the single line. Then strip out the extension. This worked for me and I donβt need to have a secondary Procfile.win, which is sometimes talked about in the documentation. Not, Heroku is case-sensitive and the Procfile filename MUST be with a capital βPβ. Lower case βpβ will not be detected properly by Heroku.
Ingredient 2: runtime.txt
This file (which must also be in your root project folder) simply tells Heroku which Python runtime to use. Currently it can contain a single line, e.g.:
python-3.7.8
Just create this as a notepad .txt file in your project folder, and commit-push to your remote GitHub repo. Done.
Thatβs really it. Itβs mainly these two files (Procfile, runtime.txt) that Heroku needs in your repo project directory in order to work. As long as you have followed the basics, and added Gunicorn to your requirements.txt etc, in theory you are good to go.
Ingredient 3: perseverance
Not to be underestimated. Dogged... stubborn... raw perseverance is a key ingredient to the potion.
Youβve got your code in a GitHub repository, with the required tweaks and files created. You have Heroku CLI installed and have created a Heroku app linked to your GitHub repo. Itβs 4am and the sun is coming up soon. The scene is grim with pizza boxes on the floor and red wine stains on the keyboard. Itβs show time.
Cast the magic spell:
git push heroku main
These four words are the spell that makes the magic happen. Type them into the terminal in the right conditions, sit back smugly, and enjoy the show.
For those new to Heroku, if everything has worked after your βgit push Heroku mainβ from the terminal, your app will be deployed to a Heroku subdomain like:
http://blah.herokuapp.com/
If this is the case, recommend a little dance.
Copy-paste the URL displayed in the terminal into your browser and get ready...to be disappointed. Chances are the first time you will see βAPPLICATION ERRORβ in the browser or something like that. Donβt panic.
The first thing you should do is bring up the log (which is effectively your python console) and see whatβs going on, from the terminal. Any print statements, or logger outputs from your code will display here just as they do in the console on your local machine. But most importantly, you also see Heroku system outputs such as Dyno restarts, crashes, and error messages. This is the critical way to see whatβs happening with your app at a low level. I usually keep a dedicated CMD window open running Heroku logs, which is my console output.
View logs:
heroku logs --tail
Check for things like βModule not found errorsβ and simple things like that. The most common problems Iβve found are forgetting to add packages to my requirements.txt file because I frantically installed them to my local machine with conda/pip to get something working. If youβve found some obvious problems, fix them, commit-push your code to GitHub, and then redeploy from Heroku CLI with git push heroku main.
Notably though, the first time is indeed the hardest. Errors in your Procfile, for example, can still cause Heroku to deploy successfully, but the dynos will crash or fail to start, so definitely check the Procfile.
Special note if there are no changes to your remote repo on GitHub, Heroku will not deploy. (Which makes sense.) So if you have a GitHub repo cloned onto your local machine, and you are making changes, be sure to commit and push changes back to your remote GitHub repo first (either with command or with GitHub desktop), then in the Heroku CLI terminal, just type in the βgit push heroku mainβ deploy command.
Below is my cheat-sheet of important tips, pitfalls, and pitfall solutions when using Heroku.
Explicitly referencing your app name:
Note that Heroku can sometimes be funny about requiring you to explicitly specify your app in the command. If you just have a single Heroku app, often you can avoid it. But sometimes (without any apparent reason) you may need to append β-a <yourapp>β to the Heroku command.
Display current apps:
heroku apps
Display current dynos:
heroku psheroku ps -a <yourapp>
Scale dynos:
heroku ps:scale web=2:standard-1x
In this case, we are provisioning two standard-1x dynos to run concurrently. Special note, if WEB_CONCURRENCY=4, this means each Dyno can serve 4 simultaneous HTTP incoming requests, meaning your whole Dash application can serve 8 concurrent requests β the benefit of horizontal scaling. More on this later.
Run bash terminal:
heroku run bash -a <yourapp>
Restart dynos:
heroku dyno:restart
Add additional log metrics:
heroku labs:enable log-runtime-metrics
View logs:
heroku logs --tail
From the Heroku CLI (once logged in) when you have deployed your app, you can view a live log tail by typing
heroku logs --tail
Repeated just in case you missed it. This is mission critical. It essentially gives you your console output. One thing Iβd suggest is adding in a new feature that outputs resources statistics of your dyno(s) timestamped every ~20 seconds, like memory levels, cpu load etc, which is very useful. Type this in the Heroku CLI, to permanently add it:
heroku labs:enable log-runtime-metrics
I repeat: serving static files DOES NOT WORK. Something of paramount importance that is not obvious, is that out-of-the-box, Heroku (I think more correctly: Gunicorn itself) does not natively support serving static files. This means that while your python application itself can access files in any subfolder in your project folder (such as .csv files etc.), itβs a very different story to actually serve them via http in the client browser.
Any images, documents, video, audio, anything you are currently serving from your βlocalhostβ webserver will fail on deployment with Heroku. I believe this is a quirk of the PaaS model in that files themselves are not stored in the traditional way you would imagine them to be on a file system, so there are issues with low level connection/packet headers that are attached to files, and/or Gunicorn itself does not natively support serving static files. In any case, thereβs magic under the hood.
As an aside, if you donβt already know from the docs, itβs important to understand that the Heroku file system is not persistent. Like many of my past relationships, Herokuβs file system is ephemeral or transient; it lasts about as long as a one-night stand. With the exception of the files you deploy with your project repo (e.g. csv, json files etc.), any new files created at runtime will disappear after a few days, like that fleeting love interest that wasnβt to be, or that person who never called.
Anyway, to store and serve persistent static files, as I said, any files uploaded to Heroku as part of your project file suite will be fine, persistent, and accessible by your dash app internally. BUT the moment you want to serve static files externally to browser, you will rapidly run into problems. There are two main solutions I know of. One is simple and fast.
Solutions:
Host your files on a 3rd party like S3, Cloudfront and link the URL in your dash app (Worth doing if you will be hosting a serious footprint of files)Use the Whitenoise library. Quick and easy. A few lines of code and youβre serving files just like in your localhost setup.
Host your files on a 3rd party like S3, Cloudfront and link the URL in your dash app (Worth doing if you will be hosting a serious footprint of files)
Use the Whitenoise library. Quick and easy. A few lines of code and youβre serving files just like in your localhost setup.
Personally I found Whitenoise to be a life saver. Literally βpip install whitenoiseβ (and make sure itβs in your requirements.txt) and youβre almost there. A few lines of code needed in your dash app:
from whitenoise import WhiteNoiseserver = app.serverserver.wsgi_app = WhiteNoise(server.wsgi_app, root=βstatic/β)
You should already have the βserver=app.serverβ anyway, as this is needed by Gunicorn and for the Procfile.
What this essentially does is wrap Whitenoise around your underlying Flask app. You can then have a folder (which you must create) called βstatic/β in your root. Everything contained within this (including subfolders) can be statically served by Heroku. Images, videos, pdfs, whatever you want.
Special note: the βstaticβ folder effectively becomes root when you are serving files, so you would use βimage.blahβ in your code rather than βstatic/image.blahβ even though your actual file is in /static/image.blah.
Special note: Heroku is file extension case-sensitive. So blah.png is different to blah.PNG.
Also, donβt try to get smart and change the βstaticβ folder name in the Whitenoise code declaration to some arbitrary name or βassetsβ or anything like that: it must be βstaticβ due to an underlying Flask constraint.
This seems like a pretty major issue that I donβt think much documentation exists on. I spent a long time on Stack Overflow looking it up.
Also, the Whitenoise documentation is not specific to Dash β it is more focused on general Python apps which are typically Flask apps. This means that itβs still not obvious what you need to do, and the code snippets will not work without modification. For example Whitenoise states that, for Flask apps, you must add the following code to your app:
app.wsgi_app = WhiteNoise(app.wsgi_app, root=βstatic/β)
This wonβt work for your dash app. In this case βappβ is the Flask app. So in a Dash app (which sits on top of Flask) you actually need to replace the βappβ references (both of them) with βapp.serverβ in the snippet above to reference the underlying Flask app and for Whitenoise to work. Or simply define a variable such as βserver = app.serverβ and use the code snippet I outlined at the beginning of this section.
Again, lots of these things are a two second fix if you know how. But can cost you literally HOURS AND HOURS......AND HOURS of time if you donβt know. Trivial for Flask developers. Not trivial at all for newcomers.
For some reason, I had lots of trouble with this. Anyway, I managed to get it going by simply having a:
/assets/favicon.ico
From my root project directory. Special note that no other static files are served from here; itβs a stand-alone folder. In fact, donβt be lulled into thinking you can serve static files from your /assets folder on Heroku: you canβt. (see Whitenoise section).
Others have had problems with Heroku changing the extension name of the favicon causing it to fail. One failsafe option to note is that you can log into a Heroku Bash shell after you have deployed, and navigate to all your project folders/files to see what Heroku sees. See this post.
From heroku CLI:
heroku run bash -a <yourappname>
This will provision a new Dyno container running a Bash shell. Basically, itβs a terminal to your deployed app.
There is lots of βworkerβ and βwebβ terminology that gets confusing. Out of the box when using Gunicorn as your Python HTTP server, Heroku essentially guesses how many concurrent web-worker-processes to run for each dyno instance running your web app. Typically this is 1β6 concurrent βgunicorn β web-worker-processesβ per dyno for the commonly used hobby to standard 2-x dynos. This is how many client requests (i.e. from a web browser) can be simultaneously served by your app at an instantaneous point in time.
A Gunicorn web-worker-process is a process capable of serving a single HTTP request at a time. So if you only had one, this means your website becomes quite unresponsive with a few users making simultaneous requests, and having to wait for these requests to be actioned from a queue. Essentially this is the magic of what Gunicorn does: it forks the main web process running on its Dyno into multiple processes so that it can serve simultaneous HTTP requests from each given Dyno resource.
Web concurrency, in Heroku, therefore, essentially allows each dyno instance to carve up itβs resources to serve multiple concurrent HTTP requests, which it terms WEB_CONCURRENCY. Unfortunately this can sometimes lead to Heroku (by default) underestimating resources needed, and running over Dyno memory limits, causing failure, restarts, massive slow-downs due to disk swap having to be used, etc. At least, this is what I experienced. Basically, you donβt want to have too much web concurrency because it might break your dyno, and the default setting chosen by Heroku may be too high.
You donβt need to worry about this on day one β your app will work. But as you start load testing it, you may find you run into memory overrun issues and all sorts of things like that. If you have a high horsepower python application that chews resources, I suggest you manually set your WEB_CONCURRENCY variable in Heroku command line.
For example:
heroku config:set WEB_CONCURRENCY=3heroku config:set WEB_CONCURRENCY=3 -a <herokuappname>
The above statement variations tell Heroku to carve up Dyno resources to support 3 concurrent HTTP requests per Dyno, for all Dynos running a Web process for your app. (So if you have multiple Dynos serving your app in parallel, it automatically sets them all to this same setting).
If performance is not compromised, you can increase web concurrency to increase the number of clients you can serve in parallel, while minimising Dyno cost. If you need to serve more, you can scale Dynoβs horizontally knowing that each one can serve an explicit number of concurrent HTTP requests that you have set.
And of course, you can monitor this with βheroku logs --tailβ or in the Heroku dashboard βmetricsβ section.
Itβs important to be aware that Heroku has an immutable 30 second timeout for serving HTTP requests. This is a common problem especially encountered by Dash users because many of the data science applications have long load times β see this post. These might work fine running on your local host, but be aware that your Heroku deployed app must be able to serve within 30 seconds or it will time out. Heroku docs state a few work arounds but take special note of this problem.
If youβre new to GitHub, just know that you can have multiple βbranchesβ of your project, as you might take it in different directions. These can be merged or left as separate branches. The central branch by default is called βmasterβ or βmainβ in GitHub. When you create your Heroku app it interacts with your GitHub repository to create a kind of Heroku mirror image behind the scenes. If youβre developing your current code on a branch that is not master or main, prepare for pain. Itβs not that it canβt be done, I just had a lot of trouble with this when trying to deploy to Heroku. I found the best rule of thumb is to just develop all my code on the default βmain/masterβ branch in my GitHub repository.
A quick run down of other useful stuff.
Custom Domain
Itβs not too difficult to set up a custom domain for your Heroku app. Obviously, you need to purchase a domain first. Once youβve done that, the provider will typically have a portal where you can login and adjust settings.
Heroku will generate a unique DNS target in the SETTINGS area of the Heroku web portal dashboard, once logged in. Such as:
Animate-salamander-8duwlndghfqbtj0t90uep8bmu.herokudns.com
What you need to do is copy this (your own) DNS target from the Heroku web portal (settings page) and then login to your domain provider portal and for your domain, create a new βCNAME recordβ with host βwwwβ value βAnimate-salamander-8duwlndghfqbtj0t90uep8bmu.herokudns.comβ (your unique Heroku DNS target).
If it worked ok, in a few hours your new domain should work!
Essentially all this is doing is redirecting to the Heroku DNS target when someone types your actual domain name. If your new domain is www.blah.com it now has a CNAME record to redirect the incoming HTTP request to Heroku infrastructure, which then serves the actual page (as if youβd typed in blah.herokuapp.com). Itβs a tricky thing to set this stuff up because itβs not done very often and you donβt know if it has worked for hours (because it takes time for DNS servers around the world to replicate the new domain list). But there is good documentation.
Flask Caching on HerokuIf you have Flask Caching running on your local machine, itβs straight forward to setup on Heroku with a free Memcachier account. And the docs are good. You can cache to the ephemeral Heroku file-system without Memcachier, noting you might max out your 500MB of Dyno storage, otherwise you can get 100MB free high performance cache via Memcachier.
Getting Fancy with security and autoscaling etc.
When you want to go to the next level and setup auto-scaling of machines, proper security/authentication etc, I think this is when it starts becoming worth considering Dash Enterprise, upgrading to top-tier Dynos with Heroku (gets $$) OR going down the path of setting up custom infrastructure manually. If you are going manual you could, for example, provision your own virtual machines, set up containerised pipelines using Docker and Kubernetes, manage autoscaling/self healing with Rancher, etc. Itβs well and truly DevOps and cloud engineering territory. Iβm sure there are lots of other midrange steps you can take like run Docker to build your own containers to deploy, but I want to keep this guide to the bare minimum you need to get on Heroku.
Closing thoughts
For the newbies and hobbyists out there, I sincerely hope this short novel has been useful to help get your project up and running faster with less pain. Donβt forget I have a fully running starter pack on Github that you can use as a guide to see EXACTLY what you need as a bare minimum.
I think Dash is a game-changing tool that is helping to bring data science literacy (and data visualisation technology) to the mainstream public and business world. This can only be a good thing, and this is why Iβve taken the time to write this piece.
Final caveat: Iβm not an expert on web, but I do think there is a major gap in the documentation for new starters. Iβve done my best to research all the facts, so this content is to the best of my understanding. I certainly invite corrections and clarifications by the experts. | [
{
"code": null,
"e": 298,
"s": 172,
"text": "So you have your Dash app running on your local machine and youβre finally ready to share it with the world on a public site."
},
{
"code": null,
"e": 729,
"s": 298,
"text": "The problem is: words like like Git, Flask, Gunicorn and Heroku sound like strange mythical creatures, even after a few drinks. Worry not: having just been through the process of deploying Dash to Heroku myself for the first time, Iβll share what Iβve learned along the way. Iβll outline some surprising pitfalls and solutions I found, in the hope this will save you time and effort. This is the guide I wish I had when I started."
},
{
"code": null,
"e": 1151,
"s": 729,
"text": "QuickstartIβve built a Dash-Heroku starter pack on Github. This is a barebones Dash app fully setup and tested that runs on Heroku. It has all the necessary special files and tweaks so you can serve static files (such as images) which is the most common pain point. For first timers, Iβd recommend you get this demo running on Heroku first, and then transfer your locally running Dash project code carefully over to it :)"
},
{
"code": null,
"e": 1162,
"s": 1151,
"text": "Background"
},
{
"code": null,
"e": 1468,
"s": 1162,
"text": "The process to successfully deploy a Dash app on Heroku is not trivial for many first timers. For example, simply serving static files (like documents, audio, images, video) doesnβt work out of the box with Heroku like it does from your local machine. I didnβt realise this, along with a few other quirks."
},
{
"code": null,
"e": 1909,
"s": 1468,
"text": "This essay is designed to supplement the existing documentation, and attempts to fill in some gaps, explain the quirks, and provide a very brief fly-over of each component and how everything fits together. Iβll share notes from my personal experience. Iβll also attempt to explain the technology stack based on my imperfect understanding of how it all works. No doubt Iβve got some things wrong, so I welcome corrections from the community."
},
{
"code": null,
"e": 1921,
"s": 1909,
"text": "Assumptions"
},
{
"code": null,
"e": 1990,
"s": 1921,
"text": "You have a running Dash app locally hosted (with a requirements.txt)"
},
{
"code": null,
"e": 2022,
"s": 1990,
"text": "Youβre relatively new to Python"
},
{
"code": null,
"e": 2083,
"s": 2022,
"text": "You have a strong cup of coffee (better yet, a glass of red)"
},
{
"code": null,
"e": 2129,
"s": 2083,
"text": "Youβve never deployed a public web app before"
},
{
"code": null,
"e": 2171,
"s": 2129,
"text": "Words like Heroku and Gunicorn scare you."
},
{
"code": null,
"e": 2183,
"s": 2171,
"text": "The Problem"
},
{
"code": null,
"e": 2947,
"s": 2183,
"text": "In my research I scanned many blog articles and guides about deploying Dash to Heroku, but found most to be a little lacklustre or not specific to Dash. YouTube videos, too, are often super quick (do it in 15 minutes!!) and donβt explain the core concepts. The majority of the guidance Iβve seen so far is bare minimum, light on explanation, and doesnβt outline key issues youβll encounter in the detail you need. If youβre working with Dash, chances are you are new to Flask as well, so many concepts are not well understood. Iβve yet to read a guide that outlines the core concepts and pitfalls for specifically deploying a Dash app to Heroku. I believe this lack of comprehensive written guidance is a (solvable) barrier to entry for many potential Dash users."
},
{
"code": null,
"e": 2999,
"s": 2947,
"text": "How much pain is this going to be? (about 10 hours)"
},
{
"code": null,
"e": 3289,
"s": 2999,
"text": "How hard really is it to Deploy to Heroku as a first timer? How much pain is involved? What problems will you encounter? Iβm glad you asked. In short, Iβd say optimistically it can be done in a few hours ground-up, but realistically about 10hrs for a first timer. Pain meter: medium spicy."
},
{
"code": null,
"e": 3944,
"s": 3289,
"text": "This is because it takes time to create the accounts and setup the environments like GitHub and Heroku command line interface, add special new files to your project directory (repository), modify the code in a few spots, and get used to the commands you need in order to see whatβs going on and make it all work. It can be a little daunting at first, but once youβve done the initial setup, youβre on easy street. Deploying code running on your laptop to your live public web app is a few mouse clicks and single command in a terminal, which is super cool. (Caveat: this does not cover security and authentication β this is purely to deploy a hobby app)."
},
{
"code": null,
"e": 3956,
"s": 3944,
"text": "Why Heroku?"
},
{
"code": null,
"e": 4386,
"s": 3956,
"text": "Like myself, youβve probably heard of Heroku as a well-loved platform for deploying hobbyist web applications for free. Of course, itβs not the only one β there are many, and it is scalable to enterprise-level deployments. But it is universally known and liked by the community, so I chose to go this route and see what all the fuss was about. Verdict so far: loving it. Key reasons the community loves Heroku (as far as I know):"
},
{
"code": null,
"e": 4456,
"s": 4386,
"text": "Itβs free for hobby apps, which is great to get started and for demos"
},
{
"code": null,
"e": 4494,
"s": 4456,
"text": "Itβs got clear, concise documentation"
},
{
"code": null,
"e": 4561,
"s": 4494,
"text": "It natively supports Python web apps (read: minimal config needed)"
},
{
"code": null,
"e": 4577,
"s": 4561,
"text": "What is Heroku?"
},
{
"code": null,
"e": 5163,
"s": 4577,
"text": "Itβs a platform-as-a-service (PaaS) for deploying and hosting web applications. In the context of your Dash app, this means Heroku provides the physical hardware (storage, compute), software services (linux/unix/sql), and dependencies (packages), in a containerised environment to deploy and host your application on a publicly accessible URL (end-point). It does this through provision of virtualised linux containers called βDynosβ which essentially act as your personal linux webserver, with ram, cpu, and linux βinstalledβ. (Itβs not quite like this in reality but a good analogy)."
},
{
"code": null,
"e": 5882,
"s": 5163,
"text": "Dynos come in a variety of shapes and sizes and can be scaled vertically (more ram, compute, storage per instance) or horizontally (duplicate dynos in parallel) as your specific project requirements demand. You can hot swap dyno types instantaneously at command line while your app is live, which is mint. The free version gets you one dyno with up to 500MB storage and 500MB ram. It sleeps after 30 minutes of inactivity, presumably so Heroku resources are not drained. So the catch with the free version is that your website can take a good 30β60 seconds to load initially, as your free Dyno is provisioned on demand. If you go to a paid plan, starting at about $7USD/month, your dyno(s) stay on and ready 24hrs/day."
},
{
"code": null,
"e": 6422,
"s": 5882,
"text": "The biggest constraint with Heroku dynos is RAM; you donβt get much. At least in my experience, Iβve found that Python (Dash) apps often require a decent amount of RAM as you are reading in Pandas dataframes and doing all sorts of fun stuff. Itβs fine for a single instance of your app for a select small group of users, but if you want to scale out you will need to run duplicate parallel instances of your app, and this will cost you $$ in RAM to either run more dynos in parallel, or multiple instances of your app in larger tier dynos."
},
{
"code": null,
"e": 6434,
"s": 6422,
"text": "Why GitHub?"
},
{
"code": null,
"e": 6796,
"s": 6434,
"text": "In short β Heroku natively supports deploying repositories that reside in GitHub. This is good news. Basically it means if your project is already in a GitHub repository (free for private/public repos) then you can easily deploy it on Heroku AFTER you have added a few additional files that are outlined in the deployment guides, and in a section further below."
},
{
"code": null,
"e": 7406,
"s": 6796,
"text": "If youβve been developing your pet project on a local machine, before you can deploy on Heroku you first need to get your project onto GitHub. (Note you donβt have to use GitHub, but itβs an easy option.) This is an important step to take your code to a public (or private) cloud repository. Itβs a good move anyway because you have full versioning history, you are protected from hard drive failure, and you can share publicly or privately. It does, however, come with intellectual debt, with some interesting concepts and terminology to get your head around, like clone, fork, merge, push, pull, and commit."
},
{
"code": null,
"e": 8220,
"s": 7406,
"text": "Yet another barrier to newcomers is the issue with security and how this affects you accessing and changing the code in your cloud repository on GitHub or similar. Basically, GitHub wants a secure connection between your computer and its servers before it will happily accept code changes. There are two main ways it achieves this: using credential authentication over HTTPS (requiring a username/pass every time a connection is made), or via SSH public/private key encryption, which is not natively supported by Windows. This extra complication, combined with the other scary words like clone, fork, and merge can be a little overwhelming at first. Fear not: thereβs a desktop app that can setup a secure connection between itself and your GitHub repo, facilitating seamless easy updates to your code repository."
},
{
"code": null,
"e": 8714,
"s": 8220,
"text": "If youβre developing on a windows/mac machine (which I assume the majority of first timers are), Iβd highly recommend getting the Github Desktop application. This just makes the process of cloning, fetching and pushing changes back to your repository on Github MUCH easier without the need for any command line. Itβs not that Iβm against command line, itβs just that this particular process can be clunky on windows, requiring either user credential authentication or SSH keys mentioned above."
},
{
"code": null,
"e": 9066,
"s": 8714,
"text": "(Special note: if you are more hardcore you can of course install Windows Subsystem for Linux which is a way to have a fully functioning Linux system on Windows without the need for dual boot options etc. If you do this you can setup SSH keys and enjoy the benefits of linux for managing your code repo but itβs really not necessary for first timers.)"
},
{
"code": null,
"e": 9289,
"s": 9066,
"text": "In short, you can avoid a lot of hassle just by using the Desktop app, and setting up the security within the app β then itβs single click of the mouse to commit changes and push updated code to your remote repo on GitHub."
},
{
"code": null,
"e": 9302,
"s": 9289,
"text": "What is Git?"
},
{
"code": null,
"e": 9323,
"s": 9302,
"text": "No one really knows."
},
{
"code": null,
"e": 9341,
"s": 9323,
"text": "What is Gunicorn?"
},
{
"code": null,
"e": 9903,
"s": 9341,
"text": "When you figure it out, let me know. Gunicorn, to the best of my understanding, is a production-ready HTTP server specifically for Python web applications which runs natively in Unix; itβs the thing that actually serves the web browser request. If youβve been developing your Dash app purely on your local machine @ βlocalhost:8080β or βhttp://127.0.0.1:8050/β you will be running a light weight HTTP server that is shipped with your Python installation. This is not Gunicorn. Itβs likely you have not yet glimpsed this rare and mythical creature of the forest."
},
{
"code": null,
"e": 10804,
"s": 9903,
"text": "The local HTTP server (shipped with your Python installation) is automatically run by your Python Kernel when your dash app is executed on your local machine. The issue is that itβs not designed for handling incoming traffic from a production website and so when you deploy to the web, you need a production-ready HTTP server. A popular one is Gunicorn. Notably, Heroku provides native support for Gunicorn, which makes things easy. Itβs all outlined in the guides, but just to clarify, all you need to do is add a single line of code to your dash app (βserver = app.serverβ), add Gunicorn into your requirements.txt so it is installed as a package on your local machine (and by Heroku during deployment), and reference it in a special file you will create called the Procfile. More on this later but I think itβs worth briefly touching on the HTTP server as itβs all a bit mysterious the first time."
},
{
"code": null,
"e": 10819,
"s": 10804,
"text": "What is Flask?"
},
{
"code": null,
"e": 11649,
"s": 10819,
"text": "Before cups and bottles, in the medieval times people used to drink out of flasks. This of course has no bearing whatsoever on what Flask is in the context of Python, but hold onto the drinking analogy. Flask is a micro-framework for Python web applications. If you are not familiar with frameworks and why they matter, essentially they provide a structure (a pattern) for you to develop your project in a way that supports growth and multiple collaborators. Some are rigid and some are more flexible, but the ultimate goal is to help a complex project become manageable by separating functional components of code (and other things) into logical places, as well as providing tools and libraries to assist with common tasks (e.g. setting up sql databases, accessing the underlying host operating system, user authentication etc.)"
},
{
"code": null,
"e": 12625,
"s": 11649,
"text": "Popular frameworks in Python include Flask and Django. In Ruby, you have probably heard of Ruby on Rails, which is a well known framework for developing Ruby web apps. If you are sticking to a bare minimum Dash app, you donβt need to worry about frameworks, but just note they are for proper, serious, software development and they are important. Your Dash app is in reality still a Flask app (Dash sits on top), Flask has just been hidden away behind the scenes. The reason Flask is popular is it is non-rigid, and does not enforce strict directory structures and file names. It can also be used piecemeal, so parts of it can be plucked out as needed, keeping the project as simple as it can be while retaining features. This is probably why Plotly chose it for Dash! To return to the βdrinking analogyβ: unlike many other frameworks, Flask as a framework can be βsippedβ as it is needed to support just the features that are what is needed for a given project, and no more."
},
{
"code": null,
"e": 12637,
"s": 12625,
"text": "Web is hard"
},
{
"code": null,
"e": 13262,
"s": 12637,
"text": "This is a simple truth. Web is multi-layer, multi-language, multi-protocol, multi-platform, and multi-user. Itβs a mind-boggling chain of infrastructure bolted to other infrastructure to make a modern (scalable) web application run. For many non-IT people (and IT people for that matter), even the concept of a locally hosted webserver takes a bit of abstract thought, let alone understanding the true technology stack that lies underneath a real client-server architecture. Itβs also worth reflecting on just how new some of this technology really is, so Iβve indicated the year these tools were created in the table below."
},
{
"code": null,
"e": 13294,
"s": 13262,
"text": "The simplified technology stack"
},
{
"code": null,
"e": 13553,
"s": 13294,
"text": "This is imperfect, so please help me to correct it. But itβs useful, I think, to see some of the layers required to get your code deployed onto the web. We start with your actual code at the very top of the stack, and drill down layers all the way to Heroku."
},
{
"code": null,
"e": 13800,
"s": 13553,
"text": "The point Iβm trying to make here is that this grossly oversimplified web technology stack is still far from simple; to say nothing about front end layers such as Javascript, CSS etc. Web is hard because of the sheer number of abstraction layers."
},
{
"code": null,
"e": 14023,
"s": 13800,
"text": "Dash, to me, is a beautiful abstraction at the very top of the technology stack β building upon everything below it β in order to simplify what is actually an insanely complex machine: the modern data-rich web application."
},
{
"code": null,
"e": 14061,
"s": 14023,
"text": "Dash-Heroku deployment, in a nutshell"
},
{
"code": null,
"e": 14093,
"s": 14061,
"text": "What actually needs to be done:"
},
{
"code": null,
"e": 14621,
"s": 14093,
"text": "Dash app running on localhostInstall GitSetup GitHub account (+ recommend install GitHub Desktop)Setup Heroku account (+ install the command line interface)Add dependencies and special files (i.e. install and import Gunicorn, create Procfile and runtime.txt)Clone repo from GitHub to local machine (only once)Create Heroku app linked to your repo (only once, ref deployment guides, Heroku CLI)Commit and push your code changes to GitHub repo (repetitively)Deploy/Re-deploy Heroku app by pushing changes (βgit push Heroku mainβ)"
},
{
"code": null,
"e": 14651,
"s": 14621,
"text": "Dash app running on localhost"
},
{
"code": null,
"e": 14663,
"s": 14651,
"text": "Install Git"
},
{
"code": null,
"e": 14721,
"s": 14663,
"text": "Setup GitHub account (+ recommend install GitHub Desktop)"
},
{
"code": null,
"e": 14781,
"s": 14721,
"text": "Setup Heroku account (+ install the command line interface)"
},
{
"code": null,
"e": 14884,
"s": 14781,
"text": "Add dependencies and special files (i.e. install and import Gunicorn, create Procfile and runtime.txt)"
},
{
"code": null,
"e": 14936,
"s": 14884,
"text": "Clone repo from GitHub to local machine (only once)"
},
{
"code": null,
"e": 15021,
"s": 14936,
"text": "Create Heroku app linked to your repo (only once, ref deployment guides, Heroku CLI)"
},
{
"code": null,
"e": 15085,
"s": 15021,
"text": "Commit and push your code changes to GitHub repo (repetitively)"
},
{
"code": null,
"e": 15157,
"s": 15085,
"text": "Deploy/Re-deploy Heroku app by pushing changes (βgit push Heroku mainβ)"
},
{
"code": null,
"e": 15745,
"s": 15157,
"text": "Just to be super clear here for those that are very new to this process. Once youβve created a Heroku app linked to your repo, this means that when changes are pushed to your Heroku remote repo on Github, this will actually trigger a Heroku build of your app. What that means is, when you type git push heroku mainthis is pushing your local code to your remote heroku repository on github (on a branch called main, which is the default primary). As soon as this happens, this will trigger a build and you should see this in your terminal (console) immediately after you type the command."
},
{
"code": null,
"e": 15763,
"s": 15745,
"text": "Deployment Guides"
},
{
"code": null,
"e": 16020,
"s": 15763,
"text": "The guides below are concise and useful, and I would of course start with these. If Iβm honest, I think they are a little light on detail for newcomers and would benefit greatly by having a supplementary explanatory guide akin to something like this essay."
},
{
"code": null,
"e": 16051,
"s": 16020,
"text": "Plotlyβs Dash deployment guide"
},
{
"code": null,
"e": 16066,
"s": 16051,
"text": "Herokuβs guide"
},
{
"code": null,
"e": 16168,
"s": 16066,
"text": "Recommendations: Install Heroku command line interface (CLI) and GitHub Desktop if a windows/mac user"
},
{
"code": null,
"e": 16241,
"s": 16168,
"text": "Also, this YouTube tutorial from a fellow Plotly Community Forum member."
},
{
"code": null,
"e": 16310,
"s": 16241,
"text": "My Dash-Heroku starter pack on GitHub is a running base to build on."
},
{
"code": null,
"e": 16505,
"s": 16310,
"text": "A quick note on the special files you need uniquely to get your python project deployed to Heroku. This is outlined in the deployment guide, so Iβve just provided a few notes from my experience:"
},
{
"code": null,
"e": 16528,
"s": 16505,
"text": "Ingredient 1: Procfile"
},
{
"code": null,
"e": 16721,
"s": 16528,
"text": "This strange extensionless file must reside in your project root, and tells Heroku how to handle web processes (in our case using Gunicorn HTTP server) and the name of your Python application."
},
{
"code": null,
"e": 16773,
"s": 16721,
"text": "Typically the Procfile would contain a single line:"
},
{
"code": null,
"e": 16798,
"s": 16773,
"text": "web: gunicorn app:server"
},
{
"code": null,
"e": 16805,
"s": 16798,
"text": "Where:"
},
{
"code": null,
"e": 16864,
"s": 16805,
"text": "βweb:β tells Heroku the dyno main process is a web process"
},
{
"code": null,
"e": 16966,
"s": 16864,
"text": "βgunicornβ tells heroku that the HTTP server to use is Gunicorn (for which it has native support for)"
},
{
"code": null,
"e": 17214,
"s": 16966,
"text": "βappβ references the filename of the main python file without the .py extension. So if you follow the convention of βapp.pyβ you would use βappβ here. But note if your main python file is βanything.pyβ, you would have βanythingβ in place of βappβ."
},
{
"code": null,
"e": 17499,
"s": 17214,
"text": "βserverβ references the underlying flask app. Commonly you would define a variable βserver = app.serverβ and this references that variable, I believe. To be more confusing, the βappβ in this variable declaration actually refers to the dash instantiation variable in the snippet below:"
},
{
"code": null,
"e": 17544,
"s": 17499,
"text": "app = dash.Dash(__name__)server = app.server"
},
{
"code": null,
"e": 17967,
"s": 17544,
"text": "Yes I know what youβre thinking, this is finicky and itβs really easy to misunderstand with all these βappβ references everywhere. Take home is: as long as youβre using an app.py main file, as is the convention, and you declare a βserver = app.serverβ line of code after your Dash declaration, you can use the example Procfile and it should work. If you get anything with the Procfile wrong, pain and suffering will ensue."
},
{
"code": null,
"e": 18354,
"s": 17967,
"text": "To make the Procfile in Windows, you can just create a text file, and enter the single line. Then strip out the extension. This worked for me and I donβt need to have a secondary Procfile.win, which is sometimes talked about in the documentation. Not, Heroku is case-sensitive and the Procfile filename MUST be with a capital βPβ. Lower case βpβ will not be detected properly by Heroku."
},
{
"code": null,
"e": 18380,
"s": 18354,
"text": "Ingredient 2: runtime.txt"
},
{
"code": null,
"e": 18534,
"s": 18380,
"text": "This file (which must also be in your root project folder) simply tells Heroku which Python runtime to use. Currently it can contain a single line, e.g.:"
},
{
"code": null,
"e": 18547,
"s": 18534,
"text": "python-3.7.8"
},
{
"code": null,
"e": 18661,
"s": 18547,
"text": "Just create this as a notepad .txt file in your project folder, and commit-push to your remote GitHub repo. Done."
},
{
"code": null,
"e": 18918,
"s": 18661,
"text": "Thatβs really it. Itβs mainly these two files (Procfile, runtime.txt) that Heroku needs in your repo project directory in order to work. As long as you have followed the basics, and added Gunicorn to your requirements.txt etc, in theory you are good to go."
},
{
"code": null,
"e": 18945,
"s": 18918,
"text": "Ingredient 3: perseverance"
},
{
"code": null,
"e": 19045,
"s": 18945,
"text": "Not to be underestimated. Dogged... stubborn... raw perseverance is a key ingredient to the potion."
},
{
"code": null,
"e": 19363,
"s": 19045,
"text": "Youβve got your code in a GitHub repository, with the required tweaks and files created. You have Heroku CLI installed and have created a Heroku app linked to your GitHub repo. Itβs 4am and the sun is coming up soon. The scene is grim with pizza boxes on the floor and red wine stains on the keyboard. Itβs show time."
},
{
"code": null,
"e": 19385,
"s": 19363,
"text": "Cast the magic spell:"
},
{
"code": null,
"e": 19406,
"s": 19385,
"text": "git push heroku main"
},
{
"code": null,
"e": 19556,
"s": 19406,
"text": "These four words are the spell that makes the magic happen. Type them into the terminal in the right conditions, sit back smugly, and enjoy the show."
},
{
"code": null,
"e": 19713,
"s": 19556,
"text": "For those new to Heroku, if everything has worked after your βgit push Heroku mainβ from the terminal, your app will be deployed to a Heroku subdomain like:"
},
{
"code": null,
"e": 19740,
"s": 19713,
"text": "http://blah.herokuapp.com/"
},
{
"code": null,
"e": 19787,
"s": 19740,
"text": "If this is the case, recommend a little dance."
},
{
"code": null,
"e": 19998,
"s": 19787,
"text": "Copy-paste the URL displayed in the terminal into your browser and get ready...to be disappointed. Chances are the first time you will see βAPPLICATION ERRORβ in the browser or something like that. Donβt panic."
},
{
"code": null,
"e": 20542,
"s": 19998,
"text": "The first thing you should do is bring up the log (which is effectively your python console) and see whatβs going on, from the terminal. Any print statements, or logger outputs from your code will display here just as they do in the console on your local machine. But most importantly, you also see Heroku system outputs such as Dyno restarts, crashes, and error messages. This is the critical way to see whatβs happening with your app at a low level. I usually keep a dedicated CMD window open running Heroku logs, which is my console output."
},
{
"code": null,
"e": 20553,
"s": 20542,
"text": "View logs:"
},
{
"code": null,
"e": 20572,
"s": 20553,
"text": "heroku logs --tail"
},
{
"code": null,
"e": 20985,
"s": 20572,
"text": "Check for things like βModule not found errorsβ and simple things like that. The most common problems Iβve found are forgetting to add packages to my requirements.txt file because I frantically installed them to my local machine with conda/pip to get something working. If youβve found some obvious problems, fix them, commit-push your code to GitHub, and then redeploy from Heroku CLI with git push heroku main."
},
{
"code": null,
"e": 21201,
"s": 20985,
"text": "Notably though, the first time is indeed the hardest. Errors in your Procfile, for example, can still cause Heroku to deploy successfully, but the dynos will crash or fail to start, so definitely check the Procfile."
},
{
"code": null,
"e": 21611,
"s": 21201,
"text": "Special note if there are no changes to your remote repo on GitHub, Heroku will not deploy. (Which makes sense.) So if you have a GitHub repo cloned onto your local machine, and you are making changes, be sure to commit and push changes back to your remote GitHub repo first (either with command or with GitHub desktop), then in the Heroku CLI terminal, just type in the βgit push heroku mainβ deploy command."
},
{
"code": null,
"e": 21705,
"s": 21611,
"text": "Below is my cheat-sheet of important tips, pitfalls, and pitfall solutions when using Heroku."
},
{
"code": null,
"e": 21743,
"s": 21705,
"text": "Explicitly referencing your app name:"
},
{
"code": null,
"e": 22017,
"s": 21743,
"text": "Note that Heroku can sometimes be funny about requiring you to explicitly specify your app in the command. If you just have a single Heroku app, often you can avoid it. But sometimes (without any apparent reason) you may need to append β-a <yourapp>β to the Heroku command."
},
{
"code": null,
"e": 22039,
"s": 22017,
"text": "Display current apps:"
},
{
"code": null,
"e": 22051,
"s": 22039,
"text": "heroku apps"
},
{
"code": null,
"e": 22074,
"s": 22051,
"text": "Display current dynos:"
},
{
"code": null,
"e": 22106,
"s": 22074,
"text": "heroku psheroku ps -a <yourapp>"
},
{
"code": null,
"e": 22119,
"s": 22106,
"text": "Scale dynos:"
},
{
"code": null,
"e": 22153,
"s": 22119,
"text": "heroku ps:scale web=2:standard-1x"
},
{
"code": null,
"e": 22461,
"s": 22153,
"text": "In this case, we are provisioning two standard-1x dynos to run concurrently. Special note, if WEB_CONCURRENCY=4, this means each Dyno can serve 4 simultaneous HTTP incoming requests, meaning your whole Dash application can serve 8 concurrent requests β the benefit of horizontal scaling. More on this later."
},
{
"code": null,
"e": 22480,
"s": 22461,
"text": "Run bash terminal:"
},
{
"code": null,
"e": 22509,
"s": 22480,
"text": "heroku run bash -a <yourapp>"
},
{
"code": null,
"e": 22524,
"s": 22509,
"text": "Restart dynos:"
},
{
"code": null,
"e": 22544,
"s": 22524,
"text": "heroku dyno:restart"
},
{
"code": null,
"e": 22572,
"s": 22544,
"text": "Add additional log metrics:"
},
{
"code": null,
"e": 22611,
"s": 22572,
"text": "heroku labs:enable log-runtime-metrics"
},
{
"code": null,
"e": 22622,
"s": 22611,
"text": "View logs:"
},
{
"code": null,
"e": 22641,
"s": 22622,
"text": "heroku logs --tail"
},
{
"code": null,
"e": 22750,
"s": 22641,
"text": "From the Heroku CLI (once logged in) when you have deployed your app, you can view a live log tail by typing"
},
{
"code": null,
"e": 22769,
"s": 22750,
"text": "heroku logs --tail"
},
{
"code": null,
"e": 23116,
"s": 22769,
"text": "Repeated just in case you missed it. This is mission critical. It essentially gives you your console output. One thing Iβd suggest is adding in a new feature that outputs resources statistics of your dyno(s) timestamped every ~20 seconds, like memory levels, cpu load etc, which is very useful. Type this in the Heroku CLI, to permanently add it:"
},
{
"code": null,
"e": 23155,
"s": 23116,
"text": "heroku labs:enable log-runtime-metrics"
},
{
"code": null,
"e": 23597,
"s": 23155,
"text": "I repeat: serving static files DOES NOT WORK. Something of paramount importance that is not obvious, is that out-of-the-box, Heroku (I think more correctly: Gunicorn itself) does not natively support serving static files. This means that while your python application itself can access files in any subfolder in your project folder (such as .csv files etc.), itβs a very different story to actually serve them via http in the client browser."
},
{
"code": null,
"e": 24095,
"s": 23597,
"text": "Any images, documents, video, audio, anything you are currently serving from your βlocalhostβ webserver will fail on deployment with Heroku. I believe this is a quirk of the PaaS model in that files themselves are not stored in the traditional way you would imagine them to be on a file system, so there are issues with low level connection/packet headers that are attached to files, and/or Gunicorn itself does not natively support serving static files. In any case, thereβs magic under the hood."
},
{
"code": null,
"e": 24600,
"s": 24095,
"text": "As an aside, if you donβt already know from the docs, itβs important to understand that the Heroku file system is not persistent. Like many of my past relationships, Herokuβs file system is ephemeral or transient; it lasts about as long as a one-night stand. With the exception of the files you deploy with your project repo (e.g. csv, json files etc.), any new files created at runtime will disappear after a few days, like that fleeting love interest that wasnβt to be, or that person who never called."
},
{
"code": null,
"e": 24966,
"s": 24600,
"text": "Anyway, to store and serve persistent static files, as I said, any files uploaded to Heroku as part of your project file suite will be fine, persistent, and accessible by your dash app internally. BUT the moment you want to serve static files externally to browser, you will rapidly run into problems. There are two main solutions I know of. One is simple and fast."
},
{
"code": null,
"e": 24977,
"s": 24966,
"text": "Solutions:"
},
{
"code": null,
"e": 25251,
"s": 24977,
"text": "Host your files on a 3rd party like S3, Cloudfront and link the URL in your dash app (Worth doing if you will be hosting a serious footprint of files)Use the Whitenoise library. Quick and easy. A few lines of code and youβre serving files just like in your localhost setup."
},
{
"code": null,
"e": 25402,
"s": 25251,
"text": "Host your files on a 3rd party like S3, Cloudfront and link the URL in your dash app (Worth doing if you will be hosting a serious footprint of files)"
},
{
"code": null,
"e": 25526,
"s": 25402,
"text": "Use the Whitenoise library. Quick and easy. A few lines of code and youβre serving files just like in your localhost setup."
},
{
"code": null,
"e": 25727,
"s": 25526,
"text": "Personally I found Whitenoise to be a life saver. Literally βpip install whitenoiseβ (and make sure itβs in your requirements.txt) and youβre almost there. A few lines of code needed in your dash app:"
},
{
"code": null,
"e": 25841,
"s": 25727,
"text": "from whitenoise import WhiteNoiseserver = app.serverserver.wsgi_app = WhiteNoise(server.wsgi_app, root=βstatic/β)"
},
{
"code": null,
"e": 25949,
"s": 25841,
"text": "You should already have the βserver=app.serverβ anyway, as this is needed by Gunicorn and for the Procfile."
},
{
"code": null,
"e": 26244,
"s": 25949,
"text": "What this essentially does is wrap Whitenoise around your underlying Flask app. You can then have a folder (which you must create) called βstatic/β in your root. Everything contained within this (including subfolders) can be statically served by Heroku. Images, videos, pdfs, whatever you want."
},
{
"code": null,
"e": 26461,
"s": 26244,
"text": "Special note: the βstaticβ folder effectively becomes root when you are serving files, so you would use βimage.blahβ in your code rather than βstatic/image.blahβ even though your actual file is in /static/image.blah."
},
{
"code": null,
"e": 26554,
"s": 26461,
"text": "Special note: Heroku is file extension case-sensitive. So blah.png is different to blah.PNG."
},
{
"code": null,
"e": 26771,
"s": 26554,
"text": "Also, donβt try to get smart and change the βstaticβ folder name in the Whitenoise code declaration to some arbitrary name or βassetsβ or anything like that: it must be βstaticβ due to an underlying Flask constraint."
},
{
"code": null,
"e": 26910,
"s": 26771,
"text": "This seems like a pretty major issue that I donβt think much documentation exists on. I spent a long time on Stack Overflow looking it up."
},
{
"code": null,
"e": 27260,
"s": 26910,
"text": "Also, the Whitenoise documentation is not specific to Dash β it is more focused on general Python apps which are typically Flask apps. This means that itβs still not obvious what you need to do, and the code snippets will not work without modification. For example Whitenoise states that, for Flask apps, you must add the following code to your app:"
},
{
"code": null,
"e": 27316,
"s": 27260,
"text": "app.wsgi_app = WhiteNoise(app.wsgi_app, root=βstatic/β)"
},
{
"code": null,
"e": 27732,
"s": 27316,
"text": "This wonβt work for your dash app. In this case βappβ is the Flask app. So in a Dash app (which sits on top of Flask) you actually need to replace the βappβ references (both of them) with βapp.serverβ in the snippet above to reference the underlying Flask app and for Whitenoise to work. Or simply define a variable such as βserver = app.serverβ and use the code snippet I outlined at the beginning of this section."
},
{
"code": null,
"e": 27947,
"s": 27732,
"text": "Again, lots of these things are a two second fix if you know how. But can cost you literally HOURS AND HOURS......AND HOURS of time if you donβt know. Trivial for Flask developers. Not trivial at all for newcomers."
},
{
"code": null,
"e": 28051,
"s": 27947,
"text": "For some reason, I had lots of trouble with this. Anyway, I managed to get it going by simply having a:"
},
{
"code": null,
"e": 28071,
"s": 28051,
"text": "/assets/favicon.ico"
},
{
"code": null,
"e": 28331,
"s": 28071,
"text": "From my root project directory. Special note that no other static files are served from here; itβs a stand-alone folder. In fact, donβt be lulled into thinking you can serve static files from your /assets folder on Heroku: you canβt. (see Whitenoise section)."
},
{
"code": null,
"e": 28616,
"s": 28331,
"text": "Others have had problems with Heroku changing the extension name of the favicon causing it to fail. One failsafe option to note is that you can log into a Heroku Bash shell after you have deployed, and navigate to all your project folders/files to see what Heroku sees. See this post."
},
{
"code": null,
"e": 28633,
"s": 28616,
"text": "From heroku CLI:"
},
{
"code": null,
"e": 28666,
"s": 28633,
"text": "heroku run bash -a <yourappname>"
},
{
"code": null,
"e": 28778,
"s": 28666,
"text": "This will provision a new Dyno container running a Bash shell. Basically, itβs a terminal to your deployed app."
},
{
"code": null,
"e": 29292,
"s": 28778,
"text": "There is lots of βworkerβ and βwebβ terminology that gets confusing. Out of the box when using Gunicorn as your Python HTTP server, Heroku essentially guesses how many concurrent web-worker-processes to run for each dyno instance running your web app. Typically this is 1β6 concurrent βgunicorn β web-worker-processesβ per dyno for the commonly used hobby to standard 2-x dynos. This is how many client requests (i.e. from a web browser) can be simultaneously served by your app at an instantaneous point in time."
},
{
"code": null,
"e": 29782,
"s": 29292,
"text": "A Gunicorn web-worker-process is a process capable of serving a single HTTP request at a time. So if you only had one, this means your website becomes quite unresponsive with a few users making simultaneous requests, and having to wait for these requests to be actioned from a queue. Essentially this is the magic of what Gunicorn does: it forks the main web process running on its Dyno into multiple processes so that it can serve simultaneous HTTP requests from each given Dyno resource."
},
{
"code": null,
"e": 30370,
"s": 29782,
"text": "Web concurrency, in Heroku, therefore, essentially allows each dyno instance to carve up itβs resources to serve multiple concurrent HTTP requests, which it terms WEB_CONCURRENCY. Unfortunately this can sometimes lead to Heroku (by default) underestimating resources needed, and running over Dyno memory limits, causing failure, restarts, massive slow-downs due to disk swap having to be used, etc. At least, this is what I experienced. Basically, you donβt want to have too much web concurrency because it might break your dyno, and the default setting chosen by Heroku may be too high."
},
{
"code": null,
"e": 30707,
"s": 30370,
"text": "You donβt need to worry about this on day one β your app will work. But as you start load testing it, you may find you run into memory overrun issues and all sorts of things like that. If you have a high horsepower python application that chews resources, I suggest you manually set your WEB_CONCURRENCY variable in Heroku command line."
},
{
"code": null,
"e": 30720,
"s": 30707,
"text": "For example:"
},
{
"code": null,
"e": 30810,
"s": 30720,
"text": "heroku config:set WEB_CONCURRENCY=3heroku config:set WEB_CONCURRENCY=3 -a <herokuappname>"
},
{
"code": null,
"e": 31093,
"s": 30810,
"text": "The above statement variations tell Heroku to carve up Dyno resources to support 3 concurrent HTTP requests per Dyno, for all Dynos running a Web process for your app. (So if you have multiple Dynos serving your app in parallel, it automatically sets them all to this same setting)."
},
{
"code": null,
"e": 31409,
"s": 31093,
"text": "If performance is not compromised, you can increase web concurrency to increase the number of clients you can serve in parallel, while minimising Dyno cost. If you need to serve more, you can scale Dynoβs horizontally knowing that each one can serve an explicit number of concurrent HTTP requests that you have set."
},
{
"code": null,
"e": 31517,
"s": 31409,
"text": "And of course, you can monitor this with βheroku logs --tailβ or in the Heroku dashboard βmetricsβ section."
},
{
"code": null,
"e": 31994,
"s": 31517,
"text": "Itβs important to be aware that Heroku has an immutable 30 second timeout for serving HTTP requests. This is a common problem especially encountered by Dash users because many of the data science applications have long load times β see this post. These might work fine running on your local host, but be aware that your Heroku deployed app must be able to serve within 30 seconds or it will time out. Heroku docs state a few work arounds but take special note of this problem."
},
{
"code": null,
"e": 32705,
"s": 31994,
"text": "If youβre new to GitHub, just know that you can have multiple βbranchesβ of your project, as you might take it in different directions. These can be merged or left as separate branches. The central branch by default is called βmasterβ or βmainβ in GitHub. When you create your Heroku app it interacts with your GitHub repository to create a kind of Heroku mirror image behind the scenes. If youβre developing your current code on a branch that is not master or main, prepare for pain. Itβs not that it canβt be done, I just had a lot of trouble with this when trying to deploy to Heroku. I found the best rule of thumb is to just develop all my code on the default βmain/masterβ branch in my GitHub repository."
},
{
"code": null,
"e": 32745,
"s": 32705,
"text": "A quick run down of other useful stuff."
},
{
"code": null,
"e": 32759,
"s": 32745,
"text": "Custom Domain"
},
{
"code": null,
"e": 32983,
"s": 32759,
"text": "Itβs not too difficult to set up a custom domain for your Heroku app. Obviously, you need to purchase a domain first. Once youβve done that, the provider will typically have a portal where you can login and adjust settings."
},
{
"code": null,
"e": 33106,
"s": 32983,
"text": "Heroku will generate a unique DNS target in the SETTINGS area of the Heroku web portal dashboard, once logged in. Such as:"
},
{
"code": null,
"e": 33166,
"s": 33106,
"text": "Animate-salamander-8duwlndghfqbtj0t90uep8bmu.herokudns.com "
},
{
"code": null,
"e": 33475,
"s": 33166,
"text": "What you need to do is copy this (your own) DNS target from the Heroku web portal (settings page) and then login to your domain provider portal and for your domain, create a new βCNAME recordβ with host βwwwβ value βAnimate-salamander-8duwlndghfqbtj0t90uep8bmu.herokudns.comβ (your unique Heroku DNS target)."
},
{
"code": null,
"e": 33536,
"s": 33475,
"text": "If it worked ok, in a few hours your new domain should work!"
},
{
"code": null,
"e": 34096,
"s": 33536,
"text": "Essentially all this is doing is redirecting to the Heroku DNS target when someone types your actual domain name. If your new domain is www.blah.com it now has a CNAME record to redirect the incoming HTTP request to Heroku infrastructure, which then serves the actual page (as if youβd typed in blah.herokuapp.com). Itβs a tricky thing to set this stuff up because itβs not done very often and you donβt know if it has worked for hours (because it takes time for DNS servers around the world to replicate the new domain list). But there is good documentation."
},
{
"code": null,
"e": 34467,
"s": 34096,
"text": "Flask Caching on HerokuIf you have Flask Caching running on your local machine, itβs straight forward to setup on Heroku with a free Memcachier account. And the docs are good. You can cache to the ephemeral Heroku file-system without Memcachier, noting you might max out your 500MB of Dyno storage, otherwise you can get 100MB free high performance cache via Memcachier."
},
{
"code": null,
"e": 34516,
"s": 34467,
"text": "Getting Fancy with security and autoscaling etc."
},
{
"code": null,
"e": 35270,
"s": 34516,
"text": "When you want to go to the next level and setup auto-scaling of machines, proper security/authentication etc, I think this is when it starts becoming worth considering Dash Enterprise, upgrading to top-tier Dynos with Heroku (gets $$) OR going down the path of setting up custom infrastructure manually. If you are going manual you could, for example, provision your own virtual machines, set up containerised pipelines using Docker and Kubernetes, manage autoscaling/self healing with Rancher, etc. Itβs well and truly DevOps and cloud engineering territory. Iβm sure there are lots of other midrange steps you can take like run Docker to build your own containers to deploy, but I want to keep this guide to the bare minimum you need to get on Heroku."
},
{
"code": null,
"e": 35287,
"s": 35270,
"text": "Closing thoughts"
},
{
"code": null,
"e": 35576,
"s": 35287,
"text": "For the newbies and hobbyists out there, I sincerely hope this short novel has been useful to help get your project up and running faster with less pain. Donβt forget I have a fully running starter pack on Github that you can use as a guide to see EXACTLY what you need as a bare minimum."
},
{
"code": null,
"e": 35829,
"s": 35576,
"text": "I think Dash is a game-changing tool that is helping to bring data science literacy (and data visualisation technology) to the mainstream public and business world. This can only be a good thing, and this is why Iβve taken the time to write this piece."
}
] |
How to draw a circle in OpenCV using C++? | A circle has a center and a radius. To draw a circle using OpenCV, we have to define the center and the radius. In OpenCV we have to include <imgproc.hpp> header because 'circle()' function is defined in this header.
The basic syntax of this method is as follows β
circle(whiteMatrix, center,radius, line_Color, thickness);
The following program represents how to draw a circle in OpenCV.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix
Point center(100, 100);//Declaring the center point
int radius = 50; //Declaring the radius
Scalar line_Color(0, 0, 0);//Color of the circle
int thickness = 2;//thickens of the line
namedWindow("whiteMatrix");//Declaring a window to show the circle
circle(whiteMatrix, center,radius, line_Color, thickness);//Using circle()function to draw the line//
imshow("WhiteMatrix", whiteMatrix);//Showing the circle//
waitKey(0);//Waiting for Keystroke//
return 0;
} | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "A circle has a center and a radius. To draw a circle using OpenCV, we have to define the center and the radius. In OpenCV we have to include <imgproc.hpp> header because 'circle()' function is defined in this header."
},
{
"code": null,
"e": 1327,
"s": 1279,
"text": "The basic syntax of this method is as follows β"
},
{
"code": null,
"e": 1386,
"s": 1327,
"text": "circle(whiteMatrix, center,radius, line_Color, thickness);"
},
{
"code": null,
"e": 1451,
"s": 1386,
"text": "The following program represents how to draw a circle in OpenCV."
},
{
"code": null,
"e": 2173,
"s": 1451,
"text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace cv;\nusing namespace std;\nint main() {\n Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix\n Point center(100, 100);//Declaring the center point\n int radius = 50; //Declaring the radius\n Scalar line_Color(0, 0, 0);//Color of the circle\n int thickness = 2;//thickens of the line\n namedWindow(\"whiteMatrix\");//Declaring a window to show the circle\n circle(whiteMatrix, center,radius, line_Color, thickness);//Using circle()function to draw the line//\n imshow(\"WhiteMatrix\", whiteMatrix);//Showing the circle//\n waitKey(0);//Waiting for Keystroke//\n return 0;\n}"
}
] |
Data Visualization: Say it with Charts in Python | by Angel Das | Towards Data Science | Business Intelligence, BI is a concept that usually involves the delivery and integration of appropriate and valuable business information in an organization. Companies use BI to detect significant events like gaining insights into customer behavior, monitoring key performance indicators over time and gaining market and sales intelligence to adapt quickly to their changing and dynamic business. Visualization forms the backbone of any BI, hence an analyst or data scientist needs to understand the nuances of visualization and how it plays an important role in communicating insights and findings effectively.
We will lay down some business questions using real-world data and get an understanding of how to create presentations in Python that are powerful, effective and insightful, the PEI framework of visualization.
Importance of visualization in the analytics industry
How to decide on which chart to use
Introduction and background to matplotlib and seaborn in python
A series of graphs and visualization using python to answer relevant questions from a real-world data
Best practices of storytelling using visualization
Data and analytics are changing the basis of competition. Leading companies are using their capabilities not only to improve their core operations but to launch entirely new business models. Topline KPIs (Key Performing Indicators) are becoming the need of the hour with CXOs keeping a constant track of the ever dynamic market thus enabling them to make informed decisions at scale. Dashboards are becoming popular among the stakeholders and with the large influx of data collected over numerous data sources, visualization forms the key to analyzing this data. In short four main reasons to build visuals involve:
For exploratory data analysis popularly referred to as the data EDACommunicate topline findings clearly to different stakeholdersShare unbiased representation of the dataUsing visualization to support findings, insights, and recommendations
For exploratory data analysis popularly referred to as the data EDA
Communicate topline findings clearly to different stakeholders
Share unbiased representation of the data
Using visualization to support findings, insights, and recommendations
Before we start let us take a look at the fundamentals of charts in visualization. Charts generally fall under two broad categories:
Data charts, also called quantitative charts, depict numbers graphically to make a point. They include pie charts, bar graphs, stacked bar graphs, scatter plots, line charts, etc.
Concept charts, also called non-quantitative charts, use words and images. Concept charts describe a situation, such as interaction, interrelationship, leverage or forces at work. Some common examples are process flow charts, gantt charts, matrix, etc.
Data charts are the most widely used chart type in the analytics industry. From dashboards, regular reports to presentations they play an important role in communicating our analysis in a way that stakeholders can understand. Concept chart plays a major role in consulting and strategy outlining, especially in scenarios where stepwise outlining of strategy is important or scenarios that require a SWOT analysis (Strength, Weakness, Opportunities, Threat).
Want to read more about the current BI trends in the market?
towardsdatascience.com
While working with platforms like Excel, Python, R, Tableau, R Shiny, Power BI or Qliksense, users are exposed to multiple chart layouts that are attractive and eye-catching. However, in the world of analytics more than creating an attractive visualization, it is important to create a visualization that is effective and impactive. Below is the selection framework the forms the basis of any chart selection.
Matplotlib is one of the most widely used data visualization libraries in Python. It was created by John Hunter, who was a neurobiologist and was working on analyzing Electrocorticography signals. His team had access to a licensed version of proprietary software for the analysis and was able to use it in turns only. To avoid this limitation, John developed a MATLAB based version which in the later stages was equipped with a scripting interface for quick and easy generation of graphics, currently known as matplotlib.
Matplotlib operates on a three-layer architecture system, The Backend Layer, Artist Layer & Scripting Layer.
Letβs look at the code below:
# β β β β β β β β β β β β - Backend Layer, Figure Canvas Layer: Encompases area in which figures are drawn β β β β β β β β β β β β -from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas#β β β β β β β β β β β β -From Artist layer, importing Artist Figure: Artist layer knows how to use a renderer to draw an object----------------------from matplotlib.figure import Figurefig=Figure()canvas=FigureCanvas(fig) #-----passing object of artist layer to backend layer (Figure Canvas)#β β β β β β β β β β β β -Using numpy to create random variables----------------------import numpy as npx=np.random.rand(100)#β β β β β β β β β β β β -Plotting a histogram---------------------ax=fig.add_subplot(111)ax.hist(x,100)ax.set_title('Normal Distribution')fig.savefig('matplotlib_histogram.png')
We can see that to plot a histogram of random numbers using a combination of backend and artist layer, we need to work out multiple lines of the code snippet. To reduce this effort, Matplotlib introduced the scripting layer called Pyplot.
βmatplotlib.pyplotβ is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some changes to a figure, e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states are preserved across function calls so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes.
import matplotlib.pyplot as plt#β β β β β β β β β β β β -Using numpy to create random variables----------------------import numpy as npx=np.random.rand(100)plt.hist(x,100) #-----100 refers to the number of binsplt.title(βNormal distribution Graphβ)plt.xlabel(βRandom numbers generatedβ)plt.ylabel(βDensityβ)plt.show()
The same output can be generated directly through pyplot using fewer lines of code.
Letβs take a look at the example below to understand how we can create different plots using matplotlib and pyplot in python. We will be using the Suicide Rates Overview Data from Kaggle to plot some of the graphs discussed above.
#β β β β β β β β β β β β -Reading dataset β β β β β β β β β β β -import pandas as pdsuicide_data=pd.read_csv(βC:/Users/91905/Desktop/master.csvβ)suicide_data.head()#We can summarize data by multiple columns like country, year, age, #generation etc. For the sake of simplicity we will try and the #answer the following questions#1. How total suicide number in the globe changed with time#2. Total suicides by gender and age bucket separately#3. Total suicides by gender across age buckets#4. Proportion of suicides by generation#5. Distribution of suicides till date using box plot and histogram#β β β β β β β β β β β β -Since data is at different levels, we will try and summarize the data by year, --------------#β β β β β β β β β β β β -sex, age, sex+age and generation--------------year_summary=suicide_data.groupby('year').agg(tot_suicide=('suicides_no','sum')).sort_values(by='year',ascending=True)gender_summary=suicide_data.groupby('sex').agg(tot_suicide=('suicides_no','sum')).sort_values(by='sex',ascending=True)age_summary=suicide_data.groupby('age').agg(tot_suicide=('suicides_no','sum')).sort_values(by='tot_suicide',ascending=True)#β β β β β β β β β β β β -Line Graph to see the trend over years-----------------import matplotlib.pyplot as pltimport numpy as np%matplotlib inlineyear_summary.plot(kind='line', figsize=(10,6));plt.title('Summary of Suicides by Year');plt.xlabel('Year');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Bar graph to compare suicides by gender and age-------------gender_summary.plot(kind='bar', figsize=(10,6));plt.title('Summary of Suicides by Gender');plt.xlabel('Sex');plt.ylabel('#Suicides');age_summary.plot(kind='bar', figsize=(10,6));plt.title('Summary of Suicides by Age');plt.xlabel('Age');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Total suicides by age and gender together----gender_age_summary=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).unstack()gender_age_summary.head()gender_age_summary.plot(kind='bar', figsize=(10,6), stacked=True);plt.title('Summary of Suicides by Genger & Age');plt.xlabel('Age');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Proportion of Suicide by Generationβ β β β β β β β β β β β -generation_summary=suicide_data.groupby('generation').agg(tot_suicide=('suicides_no','sum')).sort_values(by='tot_suicide',ascending=False).reset_index()generation_summary.head(10)#β β β β β β β β β β β β -Plotting pie chartβ β β β β β β β β β β β -fig1, ax1 = plt.subplots();fig1.set_size_inches(8,6)ax1.pie(generation_summary['tot_suicide'],labels=generation_summary['generation'],autopct='%1.0f%%',shadow=True);ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.plt.title('% Suicides across Generation')plt.show();#β β β β β β β β β β β β -Histogram Plotβ β β β β β β β β β β β -year_summary.plot(kind='box', figsize=(10,6)); #----------To plot histogram change kind='box' to kind='hist'plt.title('Distribution of suicide figures');
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn usually targets statistical data visualization but provides smarter and enhanced layouts.
Useful tips β use sns.set(color_codes=True) before using the seaborn functionality. This adds a nice background to your visualization.
Letβs try and recreate the above graphs using Seaborn
import seaborn as snssns.set(color_codes=True)#β β β β β β β β β β β β -Suicides by year--------------------------year_summary=suicide_data.groupby('year').agg(tot_suicide=('suicides_no','sum')).sort_values \ (by='year',ascending=True).reset_index()year_summary.head()#β β β β β β β β β β β β -Using Seaborn to plot trend of suicide with time-------------------------------fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')sns.lineplot(year_summary['year'],year_summary['tot_suicide']);#β β β β β β β β β β β β -Summary by Gender------------------------------------------gender_summary=suicide_data.groupby('sex').agg(tot_suicide=('suicides_no','sum')).sort_values(by='sex',ascending=True).reset_index()fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')ax=sns.barplot(gender_summary['sex'],gender_summary['tot_suicide']);ax.set(xlabel='Gender', ylabel='#Suicides');plt.show()#β β β β β β β β β β β β -Summary by Gender/age------------------------------------------gender_age_summary=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).reset_index()gender_age_summary.head()fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')ax=sns.barplot(x=gender_age_summary['sex'],y=gender_age_summary['tot_suicide'],hue=gender_age_summary['age']);ax.set(xlabel='Gender', ylabel='#Suicides');plt.show()gender_age_summary1=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).unstack()gender_age_summary1.head()#β β β β β β β β β β β β -Stack bar--------------------------------sns.set()gender_age_summary1.plot(kind='bar', stacked=True)#β β β β β β β β β β β β -Checking correlation between suicide, population and gdp per capitasns.pairplot(suicide_data[['suicides_no', 'population', 'gdp_per_capita ($)']], size=4, aspect=1);#β β β β β β β β β β β β -Boxplotβ β β β β β β β β β β β -sns.boxplot(gender_age_summary['sex'],gender_age_summary['tot_suicide']);
Here are the few best practices you should follow while creating a presentation or visualization:
Define the problem statement clearly and use a top-down approach to break it into multiple hypotheses. In the above case study, the problem statement involves understanding the suicide rates across different countries and factors influencing them. So before jumping into a visualization list down all possible factors that might affect suicide rates, e.g. age, gender, GDP, population, growth, generation, etc.Identify the key factors that might add value to your story. Think of how the factors can be interconnected to get a bigger picture of what is happening. e.g. instead of looking at suicides by age and gender separately try comparing the suicide rate across both the groups. You can derive quality insights like, Male individuals with age between 18 and 25 have higher suicide ratesOnce you decide on the factors ensure you use the chart selection framework to decide which graph suits the bestEnsure consistency in formatting across all your graphs which includes color, text size, title size, axis spacing, legend position and alignment of chart objectsBelow every visualization call out a few findings; This will help you stitch together a story for your stakeholder
Define the problem statement clearly and use a top-down approach to break it into multiple hypotheses. In the above case study, the problem statement involves understanding the suicide rates across different countries and factors influencing them. So before jumping into a visualization list down all possible factors that might affect suicide rates, e.g. age, gender, GDP, population, growth, generation, etc.
Identify the key factors that might add value to your story. Think of how the factors can be interconnected to get a bigger picture of what is happening. e.g. instead of looking at suicides by age and gender separately try comparing the suicide rate across both the groups. You can derive quality insights like, Male individuals with age between 18 and 25 have higher suicide rates
Once you decide on the factors ensure you use the chart selection framework to decide which graph suits the best
Ensure consistency in formatting across all your graphs which includes color, text size, title size, axis spacing, legend position and alignment of chart objects
Below every visualization call out a few findings; This will help you stitch together a story for your stakeholder
New to the Data Science Industry? Here are a few tips and tricks for you to start!
towardsdatascience.com
towardsdatascience.com
About the Author: Advanced analytics professional and management consultant helping companies find solutions for diverse problems through a mix of business, technology, and math on organizational data. A Data Science enthusiast, here to share, learn and contribute; You can connect with me on Linked and Twitter; | [
{
"code": null,
"e": 784,
"s": 171,
"text": "Business Intelligence, BI is a concept that usually involves the delivery and integration of appropriate and valuable business information in an organization. Companies use BI to detect significant events like gaining insights into customer behavior, monitoring key performance indicators over time and gaining market and sales intelligence to adapt quickly to their changing and dynamic business. Visualization forms the backbone of any BI, hence an analyst or data scientist needs to understand the nuances of visualization and how it plays an important role in communicating insights and findings effectively."
},
{
"code": null,
"e": 994,
"s": 784,
"text": "We will lay down some business questions using real-world data and get an understanding of how to create presentations in Python that are powerful, effective and insightful, the PEI framework of visualization."
},
{
"code": null,
"e": 1048,
"s": 994,
"text": "Importance of visualization in the analytics industry"
},
{
"code": null,
"e": 1084,
"s": 1048,
"text": "How to decide on which chart to use"
},
{
"code": null,
"e": 1148,
"s": 1084,
"text": "Introduction and background to matplotlib and seaborn in python"
},
{
"code": null,
"e": 1250,
"s": 1148,
"text": "A series of graphs and visualization using python to answer relevant questions from a real-world data"
},
{
"code": null,
"e": 1301,
"s": 1250,
"text": "Best practices of storytelling using visualization"
},
{
"code": null,
"e": 1917,
"s": 1301,
"text": "Data and analytics are changing the basis of competition. Leading companies are using their capabilities not only to improve their core operations but to launch entirely new business models. Topline KPIs (Key Performing Indicators) are becoming the need of the hour with CXOs keeping a constant track of the ever dynamic market thus enabling them to make informed decisions at scale. Dashboards are becoming popular among the stakeholders and with the large influx of data collected over numerous data sources, visualization forms the key to analyzing this data. In short four main reasons to build visuals involve:"
},
{
"code": null,
"e": 2158,
"s": 1917,
"text": "For exploratory data analysis popularly referred to as the data EDACommunicate topline findings clearly to different stakeholdersShare unbiased representation of the dataUsing visualization to support findings, insights, and recommendations"
},
{
"code": null,
"e": 2226,
"s": 2158,
"text": "For exploratory data analysis popularly referred to as the data EDA"
},
{
"code": null,
"e": 2289,
"s": 2226,
"text": "Communicate topline findings clearly to different stakeholders"
},
{
"code": null,
"e": 2331,
"s": 2289,
"text": "Share unbiased representation of the data"
},
{
"code": null,
"e": 2402,
"s": 2331,
"text": "Using visualization to support findings, insights, and recommendations"
},
{
"code": null,
"e": 2535,
"s": 2402,
"text": "Before we start let us take a look at the fundamentals of charts in visualization. Charts generally fall under two broad categories:"
},
{
"code": null,
"e": 2715,
"s": 2535,
"text": "Data charts, also called quantitative charts, depict numbers graphically to make a point. They include pie charts, bar graphs, stacked bar graphs, scatter plots, line charts, etc."
},
{
"code": null,
"e": 2968,
"s": 2715,
"text": "Concept charts, also called non-quantitative charts, use words and images. Concept charts describe a situation, such as interaction, interrelationship, leverage or forces at work. Some common examples are process flow charts, gantt charts, matrix, etc."
},
{
"code": null,
"e": 3426,
"s": 2968,
"text": "Data charts are the most widely used chart type in the analytics industry. From dashboards, regular reports to presentations they play an important role in communicating our analysis in a way that stakeholders can understand. Concept chart plays a major role in consulting and strategy outlining, especially in scenarios where stepwise outlining of strategy is important or scenarios that require a SWOT analysis (Strength, Weakness, Opportunities, Threat)."
},
{
"code": null,
"e": 3487,
"s": 3426,
"text": "Want to read more about the current BI trends in the market?"
},
{
"code": null,
"e": 3510,
"s": 3487,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3920,
"s": 3510,
"text": "While working with platforms like Excel, Python, R, Tableau, R Shiny, Power BI or Qliksense, users are exposed to multiple chart layouts that are attractive and eye-catching. However, in the world of analytics more than creating an attractive visualization, it is important to create a visualization that is effective and impactive. Below is the selection framework the forms the basis of any chart selection."
},
{
"code": null,
"e": 4442,
"s": 3920,
"text": "Matplotlib is one of the most widely used data visualization libraries in Python. It was created by John Hunter, who was a neurobiologist and was working on analyzing Electrocorticography signals. His team had access to a licensed version of proprietary software for the analysis and was able to use it in turns only. To avoid this limitation, John developed a MATLAB based version which in the later stages was equipped with a scripting interface for quick and easy generation of graphics, currently known as matplotlib."
},
{
"code": null,
"e": 4551,
"s": 4442,
"text": "Matplotlib operates on a three-layer architecture system, The Backend Layer, Artist Layer & Scripting Layer."
},
{
"code": null,
"e": 4581,
"s": 4551,
"text": "Letβs look at the code below:"
},
{
"code": null,
"e": 5384,
"s": 4581,
"text": "# β β β β β β β β β β β β - Backend Layer, Figure Canvas Layer: Encompases area in which figures are drawn β β β β β β β β β β β β -from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas#β β β β β β β β β β β β -From Artist layer, importing Artist Figure: Artist layer knows how to use a renderer to draw an object----------------------from matplotlib.figure import Figurefig=Figure()canvas=FigureCanvas(fig) #-----passing object of artist layer to backend layer (Figure Canvas)#β β β β β β β β β β β β -Using numpy to create random variables----------------------import numpy as npx=np.random.rand(100)#β β β β β β β β β β β β -Plotting a histogram---------------------ax=fig.add_subplot(111)ax.hist(x,100)ax.set_title('Normal Distribution')fig.savefig('matplotlib_histogram.png')"
},
{
"code": null,
"e": 5623,
"s": 5384,
"text": "We can see that to plot a histogram of random numbers using a combination of backend and artist layer, we need to work out multiple lines of the code snippet. To reduce this effort, Matplotlib introduced the scripting layer called Pyplot."
},
{
"code": null,
"e": 6122,
"s": 5623,
"text": "βmatplotlib.pyplotβ is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some changes to a figure, e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states are preserved across function calls so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes."
},
{
"code": null,
"e": 6440,
"s": 6122,
"text": "import matplotlib.pyplot as plt#β β β β β β β β β β β β -Using numpy to create random variables----------------------import numpy as npx=np.random.rand(100)plt.hist(x,100) #-----100 refers to the number of binsplt.title(βNormal distribution Graphβ)plt.xlabel(βRandom numbers generatedβ)plt.ylabel(βDensityβ)plt.show()"
},
{
"code": null,
"e": 6524,
"s": 6440,
"text": "The same output can be generated directly through pyplot using fewer lines of code."
},
{
"code": null,
"e": 6755,
"s": 6524,
"text": "Letβs take a look at the example below to understand how we can create different plots using matplotlib and pyplot in python. We will be using the Suicide Rates Overview Data from Kaggle to plot some of the graphs discussed above."
},
{
"code": null,
"e": 9728,
"s": 6755,
"text": "#β β β β β β β β β β β β -Reading dataset β β β β β β β β β β β -import pandas as pdsuicide_data=pd.read_csv(βC:/Users/91905/Desktop/master.csvβ)suicide_data.head()#We can summarize data by multiple columns like country, year, age, #generation etc. For the sake of simplicity we will try and the #answer the following questions#1. How total suicide number in the globe changed with time#2. Total suicides by gender and age bucket separately#3. Total suicides by gender across age buckets#4. Proportion of suicides by generation#5. Distribution of suicides till date using box plot and histogram#β β β β β β β β β β β β -Since data is at different levels, we will try and summarize the data by year, --------------#β β β β β β β β β β β β -sex, age, sex+age and generation--------------year_summary=suicide_data.groupby('year').agg(tot_suicide=('suicides_no','sum')).sort_values(by='year',ascending=True)gender_summary=suicide_data.groupby('sex').agg(tot_suicide=('suicides_no','sum')).sort_values(by='sex',ascending=True)age_summary=suicide_data.groupby('age').agg(tot_suicide=('suicides_no','sum')).sort_values(by='tot_suicide',ascending=True)#β β β β β β β β β β β β -Line Graph to see the trend over years-----------------import matplotlib.pyplot as pltimport numpy as np%matplotlib inlineyear_summary.plot(kind='line', figsize=(10,6));plt.title('Summary of Suicides by Year');plt.xlabel('Year');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Bar graph to compare suicides by gender and age-------------gender_summary.plot(kind='bar', figsize=(10,6));plt.title('Summary of Suicides by Gender');plt.xlabel('Sex');plt.ylabel('#Suicides');age_summary.plot(kind='bar', figsize=(10,6));plt.title('Summary of Suicides by Age');plt.xlabel('Age');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Total suicides by age and gender together----gender_age_summary=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).unstack()gender_age_summary.head()gender_age_summary.plot(kind='bar', figsize=(10,6), stacked=True);plt.title('Summary of Suicides by Genger & Age');plt.xlabel('Age');plt.ylabel('#Suicides');#β β β β β β β β β β β β -Proportion of Suicide by Generationβ β β β β β β β β β β β -generation_summary=suicide_data.groupby('generation').agg(tot_suicide=('suicides_no','sum')).sort_values(by='tot_suicide',ascending=False).reset_index()generation_summary.head(10)#β β β β β β β β β β β β -Plotting pie chartβ β β β β β β β β β β β -fig1, ax1 = plt.subplots();fig1.set_size_inches(8,6)ax1.pie(generation_summary['tot_suicide'],labels=generation_summary['generation'],autopct='%1.0f%%',shadow=True);ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.plt.title('% Suicides across Generation')plt.show();#β β β β β β β β β β β β -Histogram Plotβ β β β β β β β β β β β -year_summary.plot(kind='box', figsize=(10,6)); #----------To plot histogram change kind='box' to kind='hist'plt.title('Distribution of suicide figures');"
},
{
"code": null,
"e": 9990,
"s": 9728,
"text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn usually targets statistical data visualization but provides smarter and enhanced layouts."
},
{
"code": null,
"e": 10125,
"s": 9990,
"text": "Useful tips β use sns.set(color_codes=True) before using the seaborn functionality. This adds a nice background to your visualization."
},
{
"code": null,
"e": 10179,
"s": 10125,
"text": "Letβs try and recreate the above graphs using Seaborn"
},
{
"code": null,
"e": 12175,
"s": 10179,
"text": "import seaborn as snssns.set(color_codes=True)#β β β β β β β β β β β β -Suicides by year--------------------------year_summary=suicide_data.groupby('year').agg(tot_suicide=('suicides_no','sum')).sort_values \\ (by='year',ascending=True).reset_index()year_summary.head()#β β β β β β β β β β β β -Using Seaborn to plot trend of suicide with time-------------------------------fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')sns.lineplot(year_summary['year'],year_summary['tot_suicide']);#β β β β β β β β β β β β -Summary by Gender------------------------------------------gender_summary=suicide_data.groupby('sex').agg(tot_suicide=('suicides_no','sum')).sort_values(by='sex',ascending=True).reset_index()fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')ax=sns.barplot(gender_summary['sex'],gender_summary['tot_suicide']);ax.set(xlabel='Gender', ylabel='#Suicides');plt.show()#β β β β β β β β β β β β -Summary by Gender/age------------------------------------------gender_age_summary=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).reset_index()gender_age_summary.head()fig, ax = plt.subplots(figsize=(10,6));plt.title('#Suicides across Years')ax=sns.barplot(x=gender_age_summary['sex'],y=gender_age_summary['tot_suicide'],hue=gender_age_summary['age']);ax.set(xlabel='Gender', ylabel='#Suicides');plt.show()gender_age_summary1=suicide_data.groupby(['sex','age']).agg(tot_suicide=('suicides_no','sum')).unstack()gender_age_summary1.head()#β β β β β β β β β β β β -Stack bar--------------------------------sns.set()gender_age_summary1.plot(kind='bar', stacked=True)#β β β β β β β β β β β β -Checking correlation between suicide, population and gdp per capitasns.pairplot(suicide_data[['suicides_no', 'population', 'gdp_per_capita ($)']], size=4, aspect=1);#β β β β β β β β β β β β -Boxplotβ β β β β β β β β β β β -sns.boxplot(gender_age_summary['sex'],gender_age_summary['tot_suicide']);"
},
{
"code": null,
"e": 12273,
"s": 12175,
"text": "Here are the few best practices you should follow while creating a presentation or visualization:"
},
{
"code": null,
"e": 13452,
"s": 12273,
"text": "Define the problem statement clearly and use a top-down approach to break it into multiple hypotheses. In the above case study, the problem statement involves understanding the suicide rates across different countries and factors influencing them. So before jumping into a visualization list down all possible factors that might affect suicide rates, e.g. age, gender, GDP, population, growth, generation, etc.Identify the key factors that might add value to your story. Think of how the factors can be interconnected to get a bigger picture of what is happening. e.g. instead of looking at suicides by age and gender separately try comparing the suicide rate across both the groups. You can derive quality insights like, Male individuals with age between 18 and 25 have higher suicide ratesOnce you decide on the factors ensure you use the chart selection framework to decide which graph suits the bestEnsure consistency in formatting across all your graphs which includes color, text size, title size, axis spacing, legend position and alignment of chart objectsBelow every visualization call out a few findings; This will help you stitch together a story for your stakeholder"
},
{
"code": null,
"e": 13863,
"s": 13452,
"text": "Define the problem statement clearly and use a top-down approach to break it into multiple hypotheses. In the above case study, the problem statement involves understanding the suicide rates across different countries and factors influencing them. So before jumping into a visualization list down all possible factors that might affect suicide rates, e.g. age, gender, GDP, population, growth, generation, etc."
},
{
"code": null,
"e": 14245,
"s": 13863,
"text": "Identify the key factors that might add value to your story. Think of how the factors can be interconnected to get a bigger picture of what is happening. e.g. instead of looking at suicides by age and gender separately try comparing the suicide rate across both the groups. You can derive quality insights like, Male individuals with age between 18 and 25 have higher suicide rates"
},
{
"code": null,
"e": 14358,
"s": 14245,
"text": "Once you decide on the factors ensure you use the chart selection framework to decide which graph suits the best"
},
{
"code": null,
"e": 14520,
"s": 14358,
"text": "Ensure consistency in formatting across all your graphs which includes color, text size, title size, axis spacing, legend position and alignment of chart objects"
},
{
"code": null,
"e": 14635,
"s": 14520,
"text": "Below every visualization call out a few findings; This will help you stitch together a story for your stakeholder"
},
{
"code": null,
"e": 14718,
"s": 14635,
"text": "New to the Data Science Industry? Here are a few tips and tricks for you to start!"
},
{
"code": null,
"e": 14741,
"s": 14718,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 14764,
"s": 14741,
"text": "towardsdatascience.com"
}
] |
Java - Numbers Class | Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.
int i = 5000;
float gpa = 13.65f;
double mask = 125;
However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class.
And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package.
Following is an example of boxing and unboxing β
public class Test {
public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
This will produce the following result β
15
When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer.
Following is the list of the instance methods that all the subclasses of the Number class implements β
Converts the value of this Number object to the xxx data type and returns it.
Compares this Number object to the argument.
Determines whether this number object is equal to the argument.
Returns an Integer object holding the value of the specified primitive.
Returns a String object representing the value of a specified int or Integer.
This method is used to get the primitive data type of a certain String.
Returns the absolute value of the argument.
Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
Returns the largest integer that is less than or equal to the argument. Returned as a double.
Returns the integer that is closest in value to the argument. Returned as a double.
Returns the closest long or int, as indicated by the method's return type to the argument.
Returns the smaller of the two arguments.
Returns the larger of the two arguments.
Returns the base of the natural logarithms, e, to the power of the argument.
Returns the natural logarithm of the argument.
Returns the value of the first argument raised to the power of the second argument.
Returns the square root of the argument.
Returns the sine of the specified double value.
Returns the cosine of the specified double value.
Returns the tangent of the specified double value.
Returns the arcsine of the specified double value.
Returns the arccosine of the specified double value.
Returns the arctangent of the specified double value.
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
Converts the argument to degrees.
Converts the argument to radians.
Returns a random number.
In the next section, we will be going through the Character class in Java. You will be learning how to use object Characters and primitive data type char in Java.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2480,
"s": 2377,
"text": "Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc."
},
{
"code": null,
"e": 2533,
"s": 2480,
"text": "int i = 5000;\nfloat gpa = 13.65f;\ndouble mask = 125;"
},
{
"code": null,
"e": 2703,
"s": 2533,
"text": "However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes."
},
{
"code": null,
"e": 2816,
"s": 2703,
"text": "All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number."
},
{
"code": null,
"e": 3143,
"s": 2816,
"text": "The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class."
},
{
"code": null,
"e": 3303,
"s": 3143,
"text": "And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package."
},
{
"code": null,
"e": 3352,
"s": 3303,
"text": "Following is an example of boxing and unboxing β"
},
{
"code": null,
"e": 3562,
"s": 3352,
"text": "public class Test {\n\n public static void main(String args[]) {\n Integer x = 5; // boxes int to an Integer object\n x = x + 10; // unboxes the Integer to a int\n System.out.println(x); \n }\n}"
},
{
"code": null,
"e": 3603,
"s": 3562,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 3607,
"s": 3603,
"text": "15\n"
},
{
"code": null,
"e": 3765,
"s": 3607,
"text": "When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer."
},
{
"code": null,
"e": 3868,
"s": 3765,
"text": "Following is the list of the instance methods that all the subclasses of the Number class implements β"
},
{
"code": null,
"e": 3946,
"s": 3868,
"text": "Converts the value of this Number object to the xxx data type and returns it."
},
{
"code": null,
"e": 3991,
"s": 3946,
"text": "Compares this Number object to the argument."
},
{
"code": null,
"e": 4055,
"s": 3991,
"text": "Determines whether this number object is equal to the argument."
},
{
"code": null,
"e": 4127,
"s": 4055,
"text": "Returns an Integer object holding the value of the specified primitive."
},
{
"code": null,
"e": 4205,
"s": 4127,
"text": "Returns a String object representing the value of a specified int or Integer."
},
{
"code": null,
"e": 4277,
"s": 4205,
"text": "This method is used to get the primitive data type of a certain String."
},
{
"code": null,
"e": 4321,
"s": 4277,
"text": "Returns the absolute value of the argument."
},
{
"code": null,
"e": 4419,
"s": 4321,
"text": "Returns the smallest integer that is greater than or equal to the argument. Returned as a double."
},
{
"code": null,
"e": 4513,
"s": 4419,
"text": "Returns the largest integer that is less than or equal to the argument. Returned as a double."
},
{
"code": null,
"e": 4597,
"s": 4513,
"text": "Returns the integer that is closest in value to the argument. Returned as a double."
},
{
"code": null,
"e": 4688,
"s": 4597,
"text": "Returns the closest long or int, as indicated by the method's return type to the argument."
},
{
"code": null,
"e": 4730,
"s": 4688,
"text": "Returns the smaller of the two arguments."
},
{
"code": null,
"e": 4771,
"s": 4730,
"text": "Returns the larger of the two arguments."
},
{
"code": null,
"e": 4848,
"s": 4771,
"text": "Returns the base of the natural logarithms, e, to the power of the argument."
},
{
"code": null,
"e": 4895,
"s": 4848,
"text": "Returns the natural logarithm of the argument."
},
{
"code": null,
"e": 4979,
"s": 4895,
"text": "Returns the value of the first argument raised to the power of the second argument."
},
{
"code": null,
"e": 5020,
"s": 4979,
"text": "Returns the square root of the argument."
},
{
"code": null,
"e": 5068,
"s": 5020,
"text": "Returns the sine of the specified double value."
},
{
"code": null,
"e": 5118,
"s": 5068,
"text": "Returns the cosine of the specified double value."
},
{
"code": null,
"e": 5169,
"s": 5118,
"text": "Returns the tangent of the specified double value."
},
{
"code": null,
"e": 5220,
"s": 5169,
"text": "Returns the arcsine of the specified double value."
},
{
"code": null,
"e": 5273,
"s": 5220,
"text": "Returns the arccosine of the specified double value."
},
{
"code": null,
"e": 5327,
"s": 5273,
"text": "Returns the arctangent of the specified double value."
},
{
"code": null,
"e": 5417,
"s": 5327,
"text": "Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta."
},
{
"code": null,
"e": 5451,
"s": 5417,
"text": "Converts the argument to degrees."
},
{
"code": null,
"e": 5485,
"s": 5451,
"text": "Converts the argument to radians."
},
{
"code": null,
"e": 5510,
"s": 5485,
"text": "Returns a random number."
},
{
"code": null,
"e": 5673,
"s": 5510,
"text": "In the next section, we will be going through the Character class in Java. You will be learning how to use object Characters and primitive data type char in Java."
},
{
"code": null,
"e": 5706,
"s": 5673,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5722,
"s": 5706,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5755,
"s": 5722,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5771,
"s": 5755,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5806,
"s": 5771,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5820,
"s": 5806,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5854,
"s": 5820,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5868,
"s": 5854,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5905,
"s": 5868,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5920,
"s": 5905,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5953,
"s": 5920,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5972,
"s": 5953,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5979,
"s": 5972,
"text": " Print"
},
{
"code": null,
"e": 5990,
"s": 5979,
"text": " Add Notes"
}
] |
Python - Find the length of the last word in a string | When it is required to find the length of the last word in a string, a method is defined that removes the extra empty spaces in a string, and iterates through the string. It iterates until the last word has been found. Then, its length is found and returned as output.
Below is a demonstration of the same
def last_word_length(my_string):
init_val = 0
processed_str = my_string.strip()
for i in range(len(processed_str)):
if processed_str[i] == " ":
init_val = 0
else:
init_val += 1
return init_val
my_input = "Hi how are you Will"
print("The string is :")
print(my_input)
print("The length of the last word is :")
print(last_word_length(my_input))
The string is :
Hi how are you Will
The length of the last word is :
4
A method named βlast_word_lengthβ is defined that takes a string as a parameter.
A method named βlast_word_lengthβ is defined that takes a string as a parameter.
It initializes a value to 0.
It initializes a value to 0.
The string is stripped of extra spaces, and is iterated over.
The string is stripped of extra spaces, and is iterated over.
When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1.
When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1.
Outside the method, a string is defined and is displayed on the console.
Outside the method, a string is defined and is displayed on the console.
The method is called by passing this string as a parameter.
The method is called by passing this string as a parameter.
The output is displayed on the console.
The output is displayed on the console. | [
{
"code": null,
"e": 1331,
"s": 1062,
"text": "When it is required to find the length of the last word in a string, a method is defined that removes the extra empty spaces in a string, and iterates through the string. It iterates until the last word has been found. Then, its length is found and returned as output."
},
{
"code": null,
"e": 1368,
"s": 1331,
"text": "Below is a demonstration of the same"
},
{
"code": null,
"e": 1756,
"s": 1368,
"text": "def last_word_length(my_string):\n init_val = 0\n\n processed_str = my_string.strip()\n\n for i in range(len(processed_str)):\n if processed_str[i] == \" \":\n init_val = 0\n else:\n init_val += 1\n return init_val\n\nmy_input = \"Hi how are you Will\"\nprint(\"The string is :\")\nprint(my_input)\nprint(\"The length of the last word is :\")\nprint(last_word_length(my_input))"
},
{
"code": null,
"e": 1827,
"s": 1756,
"text": "The string is :\nHi how are you Will\nThe length of the last word is :\n4"
},
{
"code": null,
"e": 1908,
"s": 1827,
"text": "A method named βlast_word_lengthβ is defined that takes a string as a parameter."
},
{
"code": null,
"e": 1989,
"s": 1908,
"text": "A method named βlast_word_lengthβ is defined that takes a string as a parameter."
},
{
"code": null,
"e": 2018,
"s": 1989,
"text": "It initializes a value to 0."
},
{
"code": null,
"e": 2047,
"s": 2018,
"text": "It initializes a value to 0."
},
{
"code": null,
"e": 2109,
"s": 2047,
"text": "The string is stripped of extra spaces, and is iterated over."
},
{
"code": null,
"e": 2171,
"s": 2109,
"text": "The string is stripped of extra spaces, and is iterated over."
},
{
"code": null,
"e": 2265,
"s": 2171,
"text": "When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1."
},
{
"code": null,
"e": 2359,
"s": 2265,
"text": "When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1."
},
{
"code": null,
"e": 2432,
"s": 2359,
"text": "Outside the method, a string is defined and is displayed on the console."
},
{
"code": null,
"e": 2505,
"s": 2432,
"text": "Outside the method, a string is defined and is displayed on the console."
},
{
"code": null,
"e": 2565,
"s": 2505,
"text": "The method is called by passing this string as a parameter."
},
{
"code": null,
"e": 2625,
"s": 2565,
"text": "The method is called by passing this string as a parameter."
},
{
"code": null,
"e": 2665,
"s": 2625,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 2705,
"s": 2665,
"text": "The output is displayed on the console."
}
] |
Reverse a String | Practice | GeeksforGeeks | Given a String S , print the reverse of the string as output.
Example 1:
Input: S = "GeeksforGeeks"
Output: "skeeGrofskeeG"
Explanation: Element at first is at last and
last is at first, second is at second last and
second last is at second position and so on .
Example 2:
Input: S = "ReversE"
Output: "EsreveR"
Explanation: "E" at first and "R" at last and
"e" at second last and "s" at second and
so on .
Your Task:
You dont need to read input or print anything. Complete the function revStr() which takes S as input parameter and returns the reversed string .
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1<= |S| <=1000
+1
samisalgaonkar1 week ago
Python:
return S[::-1]
-1
ksvijayan062 weeks ago
Java Loop approach
class Solution {
static String revStr(String S) {
// code here
char[] arr = S.toCharArray();
for(int i =0, j =arr.length-1; i<j; i++, j--){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
String s = new String(arr);
return s;
}
}
0
sachinmishraravi3 weeks ago
java
StringBuilder sb= new StringBuilder(S);
sb.reverse();
return sb.toString();
+2
19tuec1323 weeks ago
//single line
return new StringBuilder(S).reverse().toString();
0
purisaurabh28854 weeks ago
string revStr(string S) { // code here( int start = 0; int end = S.size()-1; while(start < end) { swap(S[start] , S[end]); start++; end--; } return S; }
+1
akashboswas21 month ago
class Solution { static String revStr(String S) { // code here StringBuilder b=new StringBuilder(S); b.reverse(); return b.toString(); }}
0
whitehatonion1 month ago
class Solution { static String revStr(String S) { // code here StringBuilder a = new StringBuilder(S); a.reverse(); return a.toString(); }}
-1
neelasatyasai931 month ago
#PYTHON
class Solution: def revStr (ob, S): return S[: : -1]
+1
atif836141 month ago
String res = ""; for(int i=S.length()-1;i>=0;i--) { res = res +S.charAt(i); } return res; }
0
sonalyadav452 months ago
static String revStr(String S) { // code here StringBuffer reverseStr = new StringBuffer(S); return reverseStr.reverse().toString(); }
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": 300,
"s": 226,
"text": "Given a String S , print the reverse of the string as output.\n\nExample 1:"
},
{
"code": null,
"e": 492,
"s": 300,
"text": "Input: S = \"GeeksforGeeks\"\nOutput: \"skeeGrofskeeG\" \nExplanation: Element at first is at last and\nlast is at first, second is at second last and \nsecond last is at second position and so on .\n"
},
{
"code": null,
"e": 503,
"s": 492,
"text": "Example 2:"
},
{
"code": null,
"e": 637,
"s": 503,
"text": "Input: S = \"ReversE\"\nOutput: \"EsreveR\"\nExplanation: \"E\" at first and \"R\" at last and\n\"e\" at second last and \"s\" at second and\nso on ."
},
{
"code": null,
"e": 892,
"s": 637,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function revStr() which takes S as input parameter and returns the reversed string .\n\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\n\nConstraints:\n1<= |S| <=1000"
},
{
"code": null,
"e": 895,
"s": 892,
"text": "+1"
},
{
"code": null,
"e": 920,
"s": 895,
"text": "samisalgaonkar1 week ago"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python:"
},
{
"code": null,
"e": 943,
"s": 928,
"text": "return S[::-1]"
},
{
"code": null,
"e": 946,
"s": 943,
"text": "-1"
},
{
"code": null,
"e": 969,
"s": 946,
"text": "ksvijayan062 weeks ago"
},
{
"code": null,
"e": 988,
"s": 969,
"text": "Java Loop approach"
},
{
"code": null,
"e": 1319,
"s": 990,
"text": "class Solution {\n static String revStr(String S) {\n // code here\n char[] arr = S.toCharArray();\n for(int i =0, j =arr.length-1; i<j; i++, j--){\n char temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n String s = new String(arr);\n return s;\n }\n\n}"
},
{
"code": null,
"e": 1321,
"s": 1319,
"text": "0"
},
{
"code": null,
"e": 1349,
"s": 1321,
"text": "sachinmishraravi3 weeks ago"
},
{
"code": null,
"e": 1354,
"s": 1349,
"text": "java"
},
{
"code": null,
"e": 1463,
"s": 1354,
"text": " StringBuilder sb= new StringBuilder(S);\n \n sb.reverse();\n return sb.toString();"
},
{
"code": null,
"e": 1466,
"s": 1463,
"text": "+2"
},
{
"code": null,
"e": 1487,
"s": 1466,
"text": "19tuec1323 weeks ago"
},
{
"code": null,
"e": 1502,
"s": 1487,
"text": "//single line "
},
{
"code": null,
"e": 1552,
"s": 1502,
"text": "return new StringBuilder(S).reverse().toString();"
},
{
"code": null,
"e": 1554,
"s": 1552,
"text": "0"
},
{
"code": null,
"e": 1581,
"s": 1554,
"text": "purisaurabh28854 weeks ago"
},
{
"code": null,
"e": 1826,
"s": 1581,
"text": "string revStr(string S) { // code here( int start = 0; int end = S.size()-1; while(start < end) { swap(S[start] , S[end]); start++; end--; } return S; }"
},
{
"code": null,
"e": 1829,
"s": 1826,
"text": "+1"
},
{
"code": null,
"e": 1853,
"s": 1829,
"text": "akashboswas21 month ago"
},
{
"code": null,
"e": 2047,
"s": 1853,
"text": "class Solution { static String revStr(String S) { // code here StringBuilder b=new StringBuilder(S); b.reverse(); return b.toString(); }}"
},
{
"code": null,
"e": 2049,
"s": 2047,
"text": "0"
},
{
"code": null,
"e": 2074,
"s": 2049,
"text": "whitehatonion1 month ago"
},
{
"code": null,
"e": 2236,
"s": 2074,
"text": "class Solution { static String revStr(String S) { // code here StringBuilder a = new StringBuilder(S); a.reverse(); return a.toString(); }}"
},
{
"code": null,
"e": 2239,
"s": 2236,
"text": "-1"
},
{
"code": null,
"e": 2266,
"s": 2239,
"text": "neelasatyasai931 month ago"
},
{
"code": null,
"e": 2274,
"s": 2266,
"text": "#PYTHON"
},
{
"code": null,
"e": 2335,
"s": 2274,
"text": "class Solution: def revStr (ob, S): return S[: : -1]"
},
{
"code": null,
"e": 2338,
"s": 2335,
"text": "+1"
},
{
"code": null,
"e": 2359,
"s": 2338,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 2455,
"s": 2359,
"text": "String res = \"\"; for(int i=S.length()-1;i>=0;i--) { res = res +S.charAt(i); } return res; }"
},
{
"code": null,
"e": 2457,
"s": 2455,
"text": "0"
},
{
"code": null,
"e": 2482,
"s": 2457,
"text": "sonalyadav452 months ago"
},
{
"code": null,
"e": 2635,
"s": 2482,
"text": "static String revStr(String S) { // code here StringBuffer reverseStr = new StringBuffer(S); return reverseStr.reverse().toString(); }"
},
{
"code": null,
"e": 2781,
"s": 2635,
"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": 2817,
"s": 2781,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2827,
"s": 2817,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2837,
"s": 2827,
"text": "\nContest\n"
},
{
"code": null,
"e": 2900,
"s": 2837,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3048,
"s": 2900,
"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": 3256,
"s": 3048,
"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": 3362,
"s": 3256,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
The Depressing Challenges Facing The Julia Programming Language In 2021 | by Emmett Boudreau | Towards Data Science | The Julia programming language has been quite an object of interest in the wonderful world of programming recently, and this is for good reason in my subjective opinion. There are so many things to love about Julia that simply are not existent in other languages. However, no programming language is without its issues, and being relatively new to the world of Data Science, Julia has a multitude of different challenges it needs to overcome in order to truly break through into this industry.
Before we dive into the problems with Julia, and certain issues that the language has right now, let us first touch on why this language is worth using and saving. Firstly, it has been coined before that all of the programming language paradigms have already been created and worked with, but Julia proved this not to be the case. Before we dive into Juliaβs paradigm, let us first briefly remind ourselves what a paradigm is. A programming paradigm is just a system that is used for types and methods to interact with one another. I actually have an entire article on programming paradigms that goes a bit more into depth, and is almost a year old now you may read here:
towardsdatascience.com
Julia took the idea of a programming paradigm and centered it around the generic programming concept multiple dispatch. Multiple dispatch has its roots seeded in a small functional programming language from the 80βs called ML. Although the language itself certainly did not make a huge splash in the market, some of the genius ideas which were conceived in that code base have of course been completely considered in all sorts of modern multi-paradigm applications. And this brings us back to Julia, which has taken multiple dispatch and the parametric polymorphism generic programming concept to an entirely new level. Julia resides in its own new paradigm that was conceived with the language, the multiple dispatch paradigm.
Frankly, all of the fantastic ideas that the Julia developers came up with to use multiple dispatch, such as inner and outer constructors, and abstract-type hierarchies deserves its own article. However, given all of these interesting features, Julia is a very unique language to program in. For me subjectively, multiple dispatch feels like a very natural and intuitive way to program. Working with methods more like property of the types we are working with, with calls that can completely change what they do depending on the type passed through them, just feels like the most natural approach to programming one could have.
On top of just being an awesome language to write, Julia is fast β like really fast. Julia often trails just behind much lower-level languages like C and Rust while still remaining ridiculously simple to write. This is where the tired old motto will show its ugly head again, ideally for the last time...
β Walks like Python, Runs like C.β
You can certainly understand why this motto was chosen. Julia code can look very similar to Python and be incredibly easy to use. Even better, the code runs nearly as fast as C in most cases, but why is this motto strange? Because Julia resides in an entirely different programming paradigm to Python, of course! Regardless, the point of this motto still makes sense, and can give one a good idea what Julia is about. Now that we understand why Julia is uncontested on many fronts, and what the language is all about, let us dive into some of the issues that the language is facing this year in its struggle to remain relevant in multiple scientific discipline.
Easily the biggest thing that affects new Julia users, and the Julia community as a whole is Juliaβs ecosystem. While Julia does have the ability to call Python, for example, as well as has many different ported packages from that language and others, in many cases it is just odd to call on those languages from Julia. While PyCall and similar programming interfaces for other languages tend to be well-programmed and actually work really well with data-types, running the code in Python rather than Julia destroys the whole purpose of using Julia in the first place. Ultimately, the packages tend to go even slower than they would in Python, so why you would use Julia in this way is a very curious question.
If I were to name off some machine-learning packages I would actually recommend someone to use in Julia, I would honestly struggle to provide solid examples. Still, I will do my best to provide some prominent packages I like to use personally for each individual portion of Data Science. When it comes to machine learning, for neural networks I would definitely recommend the Flux library. The Flux library is actually quite robust, and has been in development for a while now.
Another great library you should certainly look into is Lathe, for which I am the creator. Lathe includes a few nice machine-learning models that might come in handy, with more coming soon. The biggest focus of the package with the release of the next long-term non-breaking version is preprocessing, however. In Julia, there really are not that great of preprocessing tools, encoders, scalers, and even train-test-split functions or objects are really hard to come by. That being said, Lathe includes all of those, along with a pipelining interface. Frankly, there is a lot of work to be done, particularly in the consistency and documentation department. However, this is set to change in a few weeks with the release of 0.2.0, which will be a significant step up in the abilities of the package. Other than Lathe and Flux, I would recommend Knet and GLM. Here are links to all of the packages I just mentioned. GLM is a library of generalized linear models, and Knet is a less-robust neural network framework.
github.com
fluxml.ai
github.com
github.com
I also have introductory articles for both Lathe and Flux that can certainly help to get you started, which I would highly recommend if you have interest in Julia, but are not sure where to start. The Flux tutorial will go over creating an image classifier with Flux, and the Lathe tutorial will take you through pre-processing, encoding, and fitting a random forest classifier before building, serializing, and even deploying with Ubuntu and NGINX β it is certainly a concise tutorial.
medium.com
towardsdatascience.com
Moving on on the ecosystem front, let us consider statistics. Julia has quite a hefty and mature statistics ecosystem that I actually think most developers will find no problem with. The only issue with this ecosystem is that it will be a little segmented, you can expect to add a lot of dependencies for a project that might require a lot of testing and so forth. Even further, these statistical packages are not necessarily targeted at Data Science, however, Lathe does happen to have a smaller statistics library with some great functions for working with data when it comes to Data Science-friendly statistics. These packages are StatsBase, Statistics, Distributions, Lathe, and many many more. Part of the problem is what I touched on, the packages are everywhere and often rely on each other. I think part of the reason this can actually be quite problematic is that Julia does have a thing called pre-compilation, where packages and their respective dependencies are compiled in advance β which can lead to some pretty horrible startup-to-execution times in the language when each package has twenty dependencies to pre-compile. This is actually a big complaint among Julia users, especially those who are new to the language.
I think the problem there is that Julia has an awesome typing and extension system. It is easy to extend the abilities and types from a certain module using a different module. And this is very often done across a broad array of packages. Personally, I have always been one for keeping dependencies low! And in Julia, with pre-compilation times being sometimes quite ridiculous.
Returning to the ecosystem conversation, one region I think Julia does have very well-covered is the data-visualization part of Data Science. With awesome packages like GadFly and VegaLite doing an amazing job of displaying data in multiple dimensions with stunning and sometimes interactive visualizations, Julia does truly have some awesome choices when it comes to plotting. There is of course also the Plots.jl package, which comes with GR and Matplotlib. However, I think although this is a go-to for newbies, and is easy to use, it is also a horrible choice. The pre-compilation times are just ridiculous. The visual performance is also terrible, as well as the time-to-first-plot. To top off the other two packages on this list, however, we also have Plot.ly coming into the field. Since this is a Data Science blog and Data Science publication, I doubt I need to go into much detail on what exactly Plot.ly is. Here is a link to all of the packages I mentioned that I actually love.
github.com
github.com
github.com
I also have an article that compares the visualization options of Julia, excluding Plot.ly, as it was not yet released when this article was published:
towardsdatascience.com
Finally, we will move onto likely my least favorite implementation β data management. For data management in Julia right now, there is one quintessential option, DataFrames.jl. DataFrames.jl is a rather mature, but not incredibly mature package for handling data in Julia. Part of the problem with this package is that it is, like many other packages we have touched on, very intertwined with the ecosystem. This means immediately pre-compile times are high, and DataFrames.jl also is developed rather slowly because even the biggest contributor is also working on many other packages, some of which are on the back-end of DataFrames.jl.
Needless to say, when it comes to a lot of dependencies for DataFrames.jl, DataFrames.jl cannot move forward without them. I also think that the API is a tid-bit tedious to use. Of course, this is my subjective opinion, I still love this package, but there are certainly some ways I would like to handle my data differently to how DataFrames.jl handles it. That in mind, I am actually creating my own DataFrames package, OddFrames.jl. While it is still in an early version, I would definitely check up on it, as I have been putting effort into it recently prior to releasing a new version of Lathe, which I plan to include support for OddFrames with. Here is a link to both DataFrames.jl and OddFrames.jl, for those who are interested. OddFrames.jl can be looked at as a Pandas-like API with some Julian approaches to certain aspects, and some unique features thrown in there as well. It mixes typical functional programming and object-oriented programming, along with some indexing tricks for some pretty interesting results!
github.com
github.com
Also, if you are interested in getting started in DataFrames.jl, I have another article that could potentially help you with that:
towardsdatascience.com
Another significant problem with Julia software that some might actually not expect is documentation. There are many Julia packages with absolutely no documentation at all. Of course, this makes Julian software extremely more difficult to use compared to more mature options with advanced documentation that is constantly maintained by several developers. Many of the Julian packages that are commonly used in the language for various domains, not just Data Science, are only maintained by a very small amount of people.
That being said, Julia does have a rather cool implementation when it comes to automated documentation. There is a package called Documenter.jl that will automatically create documentation web-pages for you, which needless to say is awesome! However, this also is somewhat part of the problem, because it is easy to simply call Documenter.jl with auto-doc and do nothing else β which creates a multitude of problems for packages because it is hard to find the documentation you might actually need to use. This is especially true when only automated documentation is used and there is no organization to the documentation web-pages. If you would like to learn more about Documenter.jl, you may take a look at an article I wrote about it specifically here (yes I have quite a catalog built up at this point that comes in handy.):
towardsdatascience.com
And wow, that is from over a year ago!
Another really cool thing about this documentation is that an automated bot is able to both generate it and serve pages. That being said, this exactly exists on the wonderful Julia hub. It is one of those things where Julia is so close, and has a lot of really cool ideas, but they are either in the works or not quite into fruition yet. Or in many cases β not taken advantage of nearly to their potential. I have a whole article where I talk about Julia hub and how awesome it is, as well that I really enjoyed writing β also I really love the artwork I did for it for some reason. Anyway, you can check it out here:
towardsdatascience.com
The last that I think Julia needs to overcome to break out as incredibly successful is really finding its position in the market. Julia Computing has expressed undoubtedly that their goal is not to replace Python, but instead to co-exist with Python. The question still remains, however, what exactly does this mean? As I have expressed in this article and tested in the past, Julia as a back-end for Python simply is not that feasible of an option. This is even more so the case when we consider that Python has a close relationship with C, which tends to run a lot faster as a back-end language β and frankly, while being more difficult than Python and Julia, is still not that hard of a language to write.
This raises the question,
β Where exactly does Julia belong?β
As a personal lover of the programming languageβs paradigm, and just so many aspects of the language as well, I would love to see it become a frequently used language in my domain, Data Science. Julia seemed to have gained steam in the past year or two, but also seems to have peaked a little bit late last year. We can see from the PYPL Index that Julia is about to succumb to Haskell after just falling less popular than Perl.
pypl.github.io
However, knowing the industry β these things do go up and down. That being said, I do think that this is a vital time for some ecosystem improvements to come to the language. The language simply needs better packages, with better documentation, and even more familiar with expressions. It is quite painful to come into this weird new world of Julia and having to use something like
select!(df[!, Not(:B)])
In order to drop a column from a DataFrame. I mean this is a very Julian approach to such a thing, but I think those coming from the world of
df.drop()
might find this kind of confusing thing agitating. I think Julia needs a clear sense of direction in this regard. If the goal is to become the new crown jewel of Data Science, then we must build an ecosystem to support such a thing. However, if the goal is to work alongside Python, then we need more sturdy APIs to do so. As of right now, without the purpose of developing new software for use in the future of Julia, the language is basically just a talking point that is capable of a few things.
That last paragraph might sound harsh, but I am just worried. I really love Julia, in case you have not noticed yet. I love how much it has taught me, I love how it is unique and has its own awesome paradigm that I find to be incredibly expressive. I love how it never feels like the language is in the way, and there is no other language I would ever write essentially anything in. Even when I write Python, I find myself sometimes writing Julia, or wishing I was currently writing Julia so I could do this or that to solve a problem I am dealing with.
I have been using Julia since 2017 now, that is about four years of experience in this language, and I must say β I have certainly fallen in love with it. However, the fact that I do not see a clear direction for the language, or its ecosystem, makes me genuinely upset. Julia almost feels like my baby, it really is my language. You know how you program all over the place, and you eventually find the one? I used to think that language for me was C++, but after getting into Julia, I really discovered what I love in a programming language, and Julia is certainly that.
If you are in any scientific discipline, or even a general purpose programmer, I highly recommend giving Julia a try. I believe that every programmer should strive to learn at least one programming language from each programming paradigm. That in mind, while Julia, like many other modern programming languages, is multi-paradigm and takes advantage of many generic programming concepts, I think it is a great option for learning functional, methodized programming concepts in an environment similar to Pythonβs. Thank you very much for reading my article! Please support the Julia ecosystem and language, because it is truly a fantastic β and still underrated thing! Have a great day! | [
{
"code": null,
"e": 666,
"s": 172,
"text": "The Julia programming language has been quite an object of interest in the wonderful world of programming recently, and this is for good reason in my subjective opinion. There are so many things to love about Julia that simply are not existent in other languages. However, no programming language is without its issues, and being relatively new to the world of Data Science, Julia has a multitude of different challenges it needs to overcome in order to truly break through into this industry."
},
{
"code": null,
"e": 1338,
"s": 666,
"text": "Before we dive into the problems with Julia, and certain issues that the language has right now, let us first touch on why this language is worth using and saving. Firstly, it has been coined before that all of the programming language paradigms have already been created and worked with, but Julia proved this not to be the case. Before we dive into Juliaβs paradigm, let us first briefly remind ourselves what a paradigm is. A programming paradigm is just a system that is used for types and methods to interact with one another. I actually have an entire article on programming paradigms that goes a bit more into depth, and is almost a year old now you may read here:"
},
{
"code": null,
"e": 1361,
"s": 1338,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2089,
"s": 1361,
"text": "Julia took the idea of a programming paradigm and centered it around the generic programming concept multiple dispatch. Multiple dispatch has its roots seeded in a small functional programming language from the 80βs called ML. Although the language itself certainly did not make a huge splash in the market, some of the genius ideas which were conceived in that code base have of course been completely considered in all sorts of modern multi-paradigm applications. And this brings us back to Julia, which has taken multiple dispatch and the parametric polymorphism generic programming concept to an entirely new level. Julia resides in its own new paradigm that was conceived with the language, the multiple dispatch paradigm."
},
{
"code": null,
"e": 2717,
"s": 2089,
"text": "Frankly, all of the fantastic ideas that the Julia developers came up with to use multiple dispatch, such as inner and outer constructors, and abstract-type hierarchies deserves its own article. However, given all of these interesting features, Julia is a very unique language to program in. For me subjectively, multiple dispatch feels like a very natural and intuitive way to program. Working with methods more like property of the types we are working with, with calls that can completely change what they do depending on the type passed through them, just feels like the most natural approach to programming one could have."
},
{
"code": null,
"e": 3022,
"s": 2717,
"text": "On top of just being an awesome language to write, Julia is fast β like really fast. Julia often trails just behind much lower-level languages like C and Rust while still remaining ridiculously simple to write. This is where the tired old motto will show its ugly head again, ideally for the last time..."
},
{
"code": null,
"e": 3057,
"s": 3022,
"text": "β Walks like Python, Runs like C.β"
},
{
"code": null,
"e": 3719,
"s": 3057,
"text": "You can certainly understand why this motto was chosen. Julia code can look very similar to Python and be incredibly easy to use. Even better, the code runs nearly as fast as C in most cases, but why is this motto strange? Because Julia resides in an entirely different programming paradigm to Python, of course! Regardless, the point of this motto still makes sense, and can give one a good idea what Julia is about. Now that we understand why Julia is uncontested on many fronts, and what the language is all about, let us dive into some of the issues that the language is facing this year in its struggle to remain relevant in multiple scientific discipline."
},
{
"code": null,
"e": 4430,
"s": 3719,
"text": "Easily the biggest thing that affects new Julia users, and the Julia community as a whole is Juliaβs ecosystem. While Julia does have the ability to call Python, for example, as well as has many different ported packages from that language and others, in many cases it is just odd to call on those languages from Julia. While PyCall and similar programming interfaces for other languages tend to be well-programmed and actually work really well with data-types, running the code in Python rather than Julia destroys the whole purpose of using Julia in the first place. Ultimately, the packages tend to go even slower than they would in Python, so why you would use Julia in this way is a very curious question."
},
{
"code": null,
"e": 4908,
"s": 4430,
"text": "If I were to name off some machine-learning packages I would actually recommend someone to use in Julia, I would honestly struggle to provide solid examples. Still, I will do my best to provide some prominent packages I like to use personally for each individual portion of Data Science. When it comes to machine learning, for neural networks I would definitely recommend the Flux library. The Flux library is actually quite robust, and has been in development for a while now."
},
{
"code": null,
"e": 5921,
"s": 4908,
"text": "Another great library you should certainly look into is Lathe, for which I am the creator. Lathe includes a few nice machine-learning models that might come in handy, with more coming soon. The biggest focus of the package with the release of the next long-term non-breaking version is preprocessing, however. In Julia, there really are not that great of preprocessing tools, encoders, scalers, and even train-test-split functions or objects are really hard to come by. That being said, Lathe includes all of those, along with a pipelining interface. Frankly, there is a lot of work to be done, particularly in the consistency and documentation department. However, this is set to change in a few weeks with the release of 0.2.0, which will be a significant step up in the abilities of the package. Other than Lathe and Flux, I would recommend Knet and GLM. Here are links to all of the packages I just mentioned. GLM is a library of generalized linear models, and Knet is a less-robust neural network framework."
},
{
"code": null,
"e": 5932,
"s": 5921,
"text": "github.com"
},
{
"code": null,
"e": 5942,
"s": 5932,
"text": "fluxml.ai"
},
{
"code": null,
"e": 5953,
"s": 5942,
"text": "github.com"
},
{
"code": null,
"e": 5964,
"s": 5953,
"text": "github.com"
},
{
"code": null,
"e": 6451,
"s": 5964,
"text": "I also have introductory articles for both Lathe and Flux that can certainly help to get you started, which I would highly recommend if you have interest in Julia, but are not sure where to start. The Flux tutorial will go over creating an image classifier with Flux, and the Lathe tutorial will take you through pre-processing, encoding, and fitting a random forest classifier before building, serializing, and even deploying with Ubuntu and NGINX β it is certainly a concise tutorial."
},
{
"code": null,
"e": 6462,
"s": 6451,
"text": "medium.com"
},
{
"code": null,
"e": 6485,
"s": 6462,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7719,
"s": 6485,
"text": "Moving on on the ecosystem front, let us consider statistics. Julia has quite a hefty and mature statistics ecosystem that I actually think most developers will find no problem with. The only issue with this ecosystem is that it will be a little segmented, you can expect to add a lot of dependencies for a project that might require a lot of testing and so forth. Even further, these statistical packages are not necessarily targeted at Data Science, however, Lathe does happen to have a smaller statistics library with some great functions for working with data when it comes to Data Science-friendly statistics. These packages are StatsBase, Statistics, Distributions, Lathe, and many many more. Part of the problem is what I touched on, the packages are everywhere and often rely on each other. I think part of the reason this can actually be quite problematic is that Julia does have a thing called pre-compilation, where packages and their respective dependencies are compiled in advance β which can lead to some pretty horrible startup-to-execution times in the language when each package has twenty dependencies to pre-compile. This is actually a big complaint among Julia users, especially those who are new to the language."
},
{
"code": null,
"e": 8098,
"s": 7719,
"text": "I think the problem there is that Julia has an awesome typing and extension system. It is easy to extend the abilities and types from a certain module using a different module. And this is very often done across a broad array of packages. Personally, I have always been one for keeping dependencies low! And in Julia, with pre-compilation times being sometimes quite ridiculous."
},
{
"code": null,
"e": 9089,
"s": 8098,
"text": "Returning to the ecosystem conversation, one region I think Julia does have very well-covered is the data-visualization part of Data Science. With awesome packages like GadFly and VegaLite doing an amazing job of displaying data in multiple dimensions with stunning and sometimes interactive visualizations, Julia does truly have some awesome choices when it comes to plotting. There is of course also the Plots.jl package, which comes with GR and Matplotlib. However, I think although this is a go-to for newbies, and is easy to use, it is also a horrible choice. The pre-compilation times are just ridiculous. The visual performance is also terrible, as well as the time-to-first-plot. To top off the other two packages on this list, however, we also have Plot.ly coming into the field. Since this is a Data Science blog and Data Science publication, I doubt I need to go into much detail on what exactly Plot.ly is. Here is a link to all of the packages I mentioned that I actually love."
},
{
"code": null,
"e": 9100,
"s": 9089,
"text": "github.com"
},
{
"code": null,
"e": 9111,
"s": 9100,
"text": "github.com"
},
{
"code": null,
"e": 9122,
"s": 9111,
"text": "github.com"
},
{
"code": null,
"e": 9274,
"s": 9122,
"text": "I also have an article that compares the visualization options of Julia, excluding Plot.ly, as it was not yet released when this article was published:"
},
{
"code": null,
"e": 9297,
"s": 9274,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9935,
"s": 9297,
"text": "Finally, we will move onto likely my least favorite implementation β data management. For data management in Julia right now, there is one quintessential option, DataFrames.jl. DataFrames.jl is a rather mature, but not incredibly mature package for handling data in Julia. Part of the problem with this package is that it is, like many other packages we have touched on, very intertwined with the ecosystem. This means immediately pre-compile times are high, and DataFrames.jl also is developed rather slowly because even the biggest contributor is also working on many other packages, some of which are on the back-end of DataFrames.jl."
},
{
"code": null,
"e": 10962,
"s": 9935,
"text": "Needless to say, when it comes to a lot of dependencies for DataFrames.jl, DataFrames.jl cannot move forward without them. I also think that the API is a tid-bit tedious to use. Of course, this is my subjective opinion, I still love this package, but there are certainly some ways I would like to handle my data differently to how DataFrames.jl handles it. That in mind, I am actually creating my own DataFrames package, OddFrames.jl. While it is still in an early version, I would definitely check up on it, as I have been putting effort into it recently prior to releasing a new version of Lathe, which I plan to include support for OddFrames with. Here is a link to both DataFrames.jl and OddFrames.jl, for those who are interested. OddFrames.jl can be looked at as a Pandas-like API with some Julian approaches to certain aspects, and some unique features thrown in there as well. It mixes typical functional programming and object-oriented programming, along with some indexing tricks for some pretty interesting results!"
},
{
"code": null,
"e": 10973,
"s": 10962,
"text": "github.com"
},
{
"code": null,
"e": 10984,
"s": 10973,
"text": "github.com"
},
{
"code": null,
"e": 11115,
"s": 10984,
"text": "Also, if you are interested in getting started in DataFrames.jl, I have another article that could potentially help you with that:"
},
{
"code": null,
"e": 11138,
"s": 11115,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11659,
"s": 11138,
"text": "Another significant problem with Julia software that some might actually not expect is documentation. There are many Julia packages with absolutely no documentation at all. Of course, this makes Julian software extremely more difficult to use compared to more mature options with advanced documentation that is constantly maintained by several developers. Many of the Julian packages that are commonly used in the language for various domains, not just Data Science, are only maintained by a very small amount of people."
},
{
"code": null,
"e": 12488,
"s": 11659,
"text": "That being said, Julia does have a rather cool implementation when it comes to automated documentation. There is a package called Documenter.jl that will automatically create documentation web-pages for you, which needless to say is awesome! However, this also is somewhat part of the problem, because it is easy to simply call Documenter.jl with auto-doc and do nothing else β which creates a multitude of problems for packages because it is hard to find the documentation you might actually need to use. This is especially true when only automated documentation is used and there is no organization to the documentation web-pages. If you would like to learn more about Documenter.jl, you may take a look at an article I wrote about it specifically here (yes I have quite a catalog built up at this point that comes in handy.):"
},
{
"code": null,
"e": 12511,
"s": 12488,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12550,
"s": 12511,
"text": "And wow, that is from over a year ago!"
},
{
"code": null,
"e": 13168,
"s": 12550,
"text": "Another really cool thing about this documentation is that an automated bot is able to both generate it and serve pages. That being said, this exactly exists on the wonderful Julia hub. It is one of those things where Julia is so close, and has a lot of really cool ideas, but they are either in the works or not quite into fruition yet. Or in many cases β not taken advantage of nearly to their potential. I have a whole article where I talk about Julia hub and how awesome it is, as well that I really enjoyed writing β also I really love the artwork I did for it for some reason. Anyway, you can check it out here:"
},
{
"code": null,
"e": 13191,
"s": 13168,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13900,
"s": 13191,
"text": "The last that I think Julia needs to overcome to break out as incredibly successful is really finding its position in the market. Julia Computing has expressed undoubtedly that their goal is not to replace Python, but instead to co-exist with Python. The question still remains, however, what exactly does this mean? As I have expressed in this article and tested in the past, Julia as a back-end for Python simply is not that feasible of an option. This is even more so the case when we consider that Python has a close relationship with C, which tends to run a lot faster as a back-end language β and frankly, while being more difficult than Python and Julia, is still not that hard of a language to write."
},
{
"code": null,
"e": 13926,
"s": 13900,
"text": "This raises the question,"
},
{
"code": null,
"e": 13962,
"s": 13926,
"text": "β Where exactly does Julia belong?β"
},
{
"code": null,
"e": 14391,
"s": 13962,
"text": "As a personal lover of the programming languageβs paradigm, and just so many aspects of the language as well, I would love to see it become a frequently used language in my domain, Data Science. Julia seemed to have gained steam in the past year or two, but also seems to have peaked a little bit late last year. We can see from the PYPL Index that Julia is about to succumb to Haskell after just falling less popular than Perl."
},
{
"code": null,
"e": 14406,
"s": 14391,
"text": "pypl.github.io"
},
{
"code": null,
"e": 14788,
"s": 14406,
"text": "However, knowing the industry β these things do go up and down. That being said, I do think that this is a vital time for some ecosystem improvements to come to the language. The language simply needs better packages, with better documentation, and even more familiar with expressions. It is quite painful to come into this weird new world of Julia and having to use something like"
},
{
"code": null,
"e": 14812,
"s": 14788,
"text": "select!(df[!, Not(:B)])"
},
{
"code": null,
"e": 14954,
"s": 14812,
"text": "In order to drop a column from a DataFrame. I mean this is a very Julian approach to such a thing, but I think those coming from the world of"
},
{
"code": null,
"e": 14964,
"s": 14954,
"text": "df.drop()"
},
{
"code": null,
"e": 15463,
"s": 14964,
"text": "might find this kind of confusing thing agitating. I think Julia needs a clear sense of direction in this regard. If the goal is to become the new crown jewel of Data Science, then we must build an ecosystem to support such a thing. However, if the goal is to work alongside Python, then we need more sturdy APIs to do so. As of right now, without the purpose of developing new software for use in the future of Julia, the language is basically just a talking point that is capable of a few things."
},
{
"code": null,
"e": 16017,
"s": 15463,
"text": "That last paragraph might sound harsh, but I am just worried. I really love Julia, in case you have not noticed yet. I love how much it has taught me, I love how it is unique and has its own awesome paradigm that I find to be incredibly expressive. I love how it never feels like the language is in the way, and there is no other language I would ever write essentially anything in. Even when I write Python, I find myself sometimes writing Julia, or wishing I was currently writing Julia so I could do this or that to solve a problem I am dealing with."
},
{
"code": null,
"e": 16589,
"s": 16017,
"text": "I have been using Julia since 2017 now, that is about four years of experience in this language, and I must say β I have certainly fallen in love with it. However, the fact that I do not see a clear direction for the language, or its ecosystem, makes me genuinely upset. Julia almost feels like my baby, it really is my language. You know how you program all over the place, and you eventually find the one? I used to think that language for me was C++, but after getting into Julia, I really discovered what I love in a programming language, and Julia is certainly that."
}
] |
Consul - Working with Microservices | In this chapter, we will understand how Microservices work with Consul. We will also learn how the following components affect Consul.
Using docker
Building Registrator for Service Discovery
Using rkt and Nomad
Let us now discuss each of these in detail.
Before starting, please do not use this setup in production as it is used for demo purposes only. Docker is a container based service using which we can easily deploy our applications. For using Consul, we are going to use the image at the following link β0
https://hub.docker.com/r/progrium/consul/.
It is being assumed that your system has Docker installed and properly configured. Let us try pulling down the image from the Docker hub, by running the following command β
$ docker pull progrium/consul
The output would be as shown in the following screenshot.
We are going to publish some interfaces with their ports (using -p option on Docker) in the following manner.
8400 (RPC)
8500 (HTTP)
8600 (DNS)
Also as per the pull made, we are going to set the name of the hostname as node1.You can change it to anything you want by using the -h flag with some hostname of your own as shown below.
$ docker run -p 8400:8400 -p 8500:8500 -p 8600:53/udp -h node1 progrium/consul
-server -bootstrap
The output would be as shown in the following screenshot.
You can also enable the UI mode for the Consul using β
$ docker run -p 8400:8400 -p 8500:8500 -p 8600:53/udp -h node1 progrium/consul
-server -bootstrap -ui-dir /ui
You can check the UI based output on http://localhost:8500. The following screenshot gives you a better idea regarding the UI based output.
For using consul over various docker containers on different nodes, we can run the following commands on different nodes β
$ docker run -d --name node1 -h node1 progrium/consul -server -bootstrap-expect 3
Where, -bootstrap-expect 3 means that the consul server will wait until there are 3 peers connected before self-bootstrapping and becoming a working cluster.
Before going any further, we need to get the container's internal IP by inspecting the container. For our use, case purpose, we are going to declare the $ JOIN_IP.
$ JOIN_IP = "$(docker inspect -f '{{.NetworkSettings.IPAddress}}' node1)"
So, let us start Node2 and tell it to join Node1 using the variable declared in the program given above.
$docker run -d --name node2 -h node2 progrium/consul -server -join $JOIN_IP
$ docker run -d --name node3 -h node3 progrium/consul -server -join $JOIN_IP
Registrator automatically registers and deregisters services for any Docker container by inspecting containers as they come online. The Registrator we are about to use currently supports pluggable service registries, which currently includes Consul, Etcd and SkyDNS2. The usage of Registrator is highly recommended when we are interacting with different services over the network.
$ docker pull gliderlabs/registrator:latest
The output would be as shown in the following screenshot.
$ docker run -d \
--name = registrator \
--net = host \
--volume = /var/run/docker.sock:/tmp/docker.sock \
gliderlabs/registrator:latest \
consul://localhost:8500
The output would be as shown in the following screenshot.
The output you have received is the ID of the Docker Container that you have just started. You can check whether the container is running or not by using the command β
$ docker ps -a
he output would be as shown in the following screenshot.
You can also view the logs of Registrator by using the following command.
$ docker logs registrator
The rkt is another container-based service, which you can use in your environment. It is built by CoreOS. The main reason for building rkt was to improve the security that was one of the crisis issues for Docker back when it was still in development in 2013-14.
As for Consul, we can use the Rkt Registrator for working on service discovery with Consul. This particular Registrator project, which is covered for rkt is under development and is not recommended for production level use.
You can check if rkt is installed or not, by going to its path and running the following command.
$ ./rkt
You can check the output to check, if it is correctly installed or not as shown in the following screenshot.
For trying out rkt and Consul please check out β https://github.com/r3boot/rkt-registrator.
One of the most commonly used and a favorite option is the Nomad tool. Nomad is a tool for managing a cluster of machines and running applications on them. It is similar to Mesos or Kubernetes. By default, Nomad covers the Docker and rkt driver within itself. So, if you are looking for a large-scale deployment of containers with Consul. Nomad might be a good solution to it. Check out β https://www.nomadproject.io/docs/drivers/rkt.html for further information on Nomad.
140 Lectures
20 hours
Juan Galvan
86 Lectures
6.5 hours
John Colley
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1937,
"s": 1802,
"text": "In this chapter, we will understand how Microservices work with Consul. We will also learn how the following components affect Consul."
},
{
"code": null,
"e": 1950,
"s": 1937,
"text": "Using docker"
},
{
"code": null,
"e": 1993,
"s": 1950,
"text": "Building Registrator for Service Discovery"
},
{
"code": null,
"e": 2013,
"s": 1993,
"text": "Using rkt and Nomad"
},
{
"code": null,
"e": 2057,
"s": 2013,
"text": "Let us now discuss each of these in detail."
},
{
"code": null,
"e": 2315,
"s": 2057,
"text": "Before starting, please do not use this setup in production as it is used for demo purposes only. Docker is a container based service using which we can easily deploy our applications. For using Consul, we are going to use the image at the following link β0"
},
{
"code": null,
"e": 2358,
"s": 2315,
"text": "https://hub.docker.com/r/progrium/consul/."
},
{
"code": null,
"e": 2531,
"s": 2358,
"text": "It is being assumed that your system has Docker installed and properly configured. Let us try pulling down the image from the Docker hub, by running the following command β"
},
{
"code": null,
"e": 2562,
"s": 2531,
"text": "$ docker pull progrium/consul\n"
},
{
"code": null,
"e": 2620,
"s": 2562,
"text": "The output would be as shown in the following screenshot."
},
{
"code": null,
"e": 2730,
"s": 2620,
"text": "We are going to publish some interfaces with their ports (using -p option on Docker) in the following manner."
},
{
"code": null,
"e": 2741,
"s": 2730,
"text": "8400 (RPC)"
},
{
"code": null,
"e": 2753,
"s": 2741,
"text": "8500 (HTTP)"
},
{
"code": null,
"e": 2764,
"s": 2753,
"text": "8600 (DNS)"
},
{
"code": null,
"e": 2952,
"s": 2764,
"text": "Also as per the pull made, we are going to set the name of the hostname as node1.You can change it to anything you want by using the -h flag with some hostname of your own as shown below."
},
{
"code": null,
"e": 3051,
"s": 2952,
"text": "$ docker run -p 8400:8400 -p 8500:8500 -p 8600:53/udp -h node1 progrium/consul\n-server -bootstrap\n"
},
{
"code": null,
"e": 3109,
"s": 3051,
"text": "The output would be as shown in the following screenshot."
},
{
"code": null,
"e": 3164,
"s": 3109,
"text": "You can also enable the UI mode for the Consul using β"
},
{
"code": null,
"e": 3275,
"s": 3164,
"text": "$ docker run -p 8400:8400 -p 8500:8500 -p 8600:53/udp -h node1 progrium/consul\n-server -bootstrap -ui-dir /ui\n"
},
{
"code": null,
"e": 3415,
"s": 3275,
"text": "You can check the UI based output on http://localhost:8500. The following screenshot gives you a better idea regarding the UI based output."
},
{
"code": null,
"e": 3538,
"s": 3415,
"text": "For using consul over various docker containers on different nodes, we can run the following commands on different nodes β"
},
{
"code": null,
"e": 3621,
"s": 3538,
"text": "$ docker run -d --name node1 -h node1 progrium/consul -server -bootstrap-expect 3\n"
},
{
"code": null,
"e": 3779,
"s": 3621,
"text": "Where, -bootstrap-expect 3 means that the consul server will wait until there are 3 peers connected before self-bootstrapping and becoming a working cluster."
},
{
"code": null,
"e": 3943,
"s": 3779,
"text": "Before going any further, we need to get the container's internal IP by inspecting the container. For our use, case purpose, we are going to declare the $ JOIN_IP."
},
{
"code": null,
"e": 4018,
"s": 3943,
"text": "$ JOIN_IP = \"$(docker inspect -f '{{.NetworkSettings.IPAddress}}' node1)\"\n"
},
{
"code": null,
"e": 4123,
"s": 4018,
"text": "So, let us start Node2 and tell it to join Node1 using the variable declared in the program given above."
},
{
"code": null,
"e": 4200,
"s": 4123,
"text": "$docker run -d --name node2 -h node2 progrium/consul -server -join $JOIN_IP\n"
},
{
"code": null,
"e": 4278,
"s": 4200,
"text": "$ docker run -d --name node3 -h node3 progrium/consul -server -join $JOIN_IP\n"
},
{
"code": null,
"e": 4659,
"s": 4278,
"text": "Registrator automatically registers and deregisters services for any Docker container by inspecting containers as they come online. The Registrator we are about to use currently supports pluggable service registries, which currently includes Consul, Etcd and SkyDNS2. The usage of Registrator is highly recommended when we are interacting with different services over the network."
},
{
"code": null,
"e": 4704,
"s": 4659,
"text": "$ docker pull gliderlabs/registrator:latest\n"
},
{
"code": null,
"e": 4762,
"s": 4704,
"text": "The output would be as shown in the following screenshot."
},
{
"code": null,
"e": 4927,
"s": 4762,
"text": "$ docker run -d \\\n--name = registrator \\\n--net = host \\\n--volume = /var/run/docker.sock:/tmp/docker.sock \\\ngliderlabs/registrator:latest \\\n consul://localhost:8500\n"
},
{
"code": null,
"e": 4985,
"s": 4927,
"text": "The output would be as shown in the following screenshot."
},
{
"code": null,
"e": 5153,
"s": 4985,
"text": "The output you have received is the ID of the Docker Container that you have just started. You can check whether the container is running or not by using the command β"
},
{
"code": null,
"e": 5169,
"s": 5153,
"text": "$ docker ps -a\n"
},
{
"code": null,
"e": 5226,
"s": 5169,
"text": "he output would be as shown in the following screenshot."
},
{
"code": null,
"e": 5300,
"s": 5226,
"text": "You can also view the logs of Registrator by using the following command."
},
{
"code": null,
"e": 5327,
"s": 5300,
"text": "$ docker logs registrator\n"
},
{
"code": null,
"e": 5589,
"s": 5327,
"text": "The rkt is another container-based service, which you can use in your environment. It is built by CoreOS. The main reason for building rkt was to improve the security that was one of the crisis issues for Docker back when it was still in development in 2013-14."
},
{
"code": null,
"e": 5813,
"s": 5589,
"text": "As for Consul, we can use the Rkt Registrator for working on service discovery with Consul. This particular Registrator project, which is covered for rkt is under development and is not recommended for production level use."
},
{
"code": null,
"e": 5911,
"s": 5813,
"text": "You can check if rkt is installed or not, by going to its path and running the following command."
},
{
"code": null,
"e": 5920,
"s": 5911,
"text": "$ ./rkt\n"
},
{
"code": null,
"e": 6029,
"s": 5920,
"text": "You can check the output to check, if it is correctly installed or not as shown in the following screenshot."
},
{
"code": null,
"e": 6121,
"s": 6029,
"text": "For trying out rkt and Consul please check out β https://github.com/r3boot/rkt-registrator."
},
{
"code": null,
"e": 6594,
"s": 6121,
"text": "One of the most commonly used and a favorite option is the Nomad tool. Nomad is a tool for managing a cluster of machines and running applications on them. It is similar to Mesos or Kubernetes. By default, Nomad covers the Docker and rkt driver within itself. So, if you are looking for a large-scale deployment of containers with Consul. Nomad might be a good solution to it. Check out β https://www.nomadproject.io/docs/drivers/rkt.html for further information on Nomad."
},
{
"code": null,
"e": 6629,
"s": 6594,
"text": "\n 140 Lectures \n 20 hours \n"
},
{
"code": null,
"e": 6642,
"s": 6629,
"text": " Juan Galvan"
},
{
"code": null,
"e": 6677,
"s": 6642,
"text": "\n 86 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6690,
"s": 6677,
"text": " John Colley"
},
{
"code": null,
"e": 6697,
"s": 6690,
"text": " Print"
},
{
"code": null,
"e": 6708,
"s": 6697,
"text": " Add Notes"
}
] |
Visualizing 3D Seismic Volumes Made Easy with Python and Mayavi | by Ahmad Mustafa | Towards Data Science | Visualization of migrated, post-stack seismic volumes is a very crucial component of interpretation workflows, be it to pick salt domes, interpret horizons, identify fault planes, or classify rock facies.
While there are already professional tools like OpendTect and Petrel available to experienced seismic interpreters, setting up a project from scratch in either of these software tools can be overwhelming for beginners and non-specialists, considering all of the various parameters that need to be set before one can visualize the seismic volume of interest. This is not to mention the inconvenience of working with different data types for processing and loading data for visualization, especially in the context of Data Science projects with seismic volumes β repeatedly converting seismic data back and forth between different data types at different stages of processing can be very time consuming and inconvenient for users.
I recently came across a very handy, open-source visualization tool, Mayavi, that allows seamless integration of visualization of 3D data like seismic volumes into data science workflows with Python. It is made all the better owing to its very interactive capabilities, where one may drag inline/crossline/depth slices throughout the volume at different angles to examine the features of interest. An example screenshot of such a 3-D visualization is shown below.
This post will walk you through some basic code to get you up and running with using Mayavi for visualizing seismic volumes along with their various interpreted features by seismic interpreters.
Detailed instructions for downloading Mayavi and setting it up for use with Python may be found directly on its homepage. Refer here for more details.
For our purposes, we will be concerned with using the mlab API for using Mayavi as a 3-D plotting tool in python scripts. Assuming everything went smoothly in the last step, use the following code snippet to import mlab:
import numpy as np # import numpy for data loadingfrom mayavi import mlab # import mlab
Seismic datasets usually come in the popular .segy (pronounced: seg-y) format. In addition to storing amplitude data, segy files contain a variety of header information, like the crossline and inline numbers associated with each trace, time sample information etc. However, popular machine learning and data science tools usually ask for data to be in the form of numpy arrays. If your data happens to be in segy format, you may use the popular python package, Segyio, to convert it to a numpy array. See here, for more details, instructions, and examples on using Segyio, refer to their GitHub page.
For the rest of this post, we assume you are working with the Netherlands Offshore F3 Blockβs seismic data and its interpreted labels, as developed by the OLIVES lab at Georgia Tech. For more information on this work, refer to the Github page here. Notice that converting the data to numpy format will make it lose tertiary information contained in the headers of the original segy file. But this is OK, since we are usually interested just in the amplitudes and labels for the specific purpose of visualization. Use the following code snippet to load both the raw seismic amplitudes and the associated rock facies labels as 3-D arrays.
seismic_path = 'data/train/train_seismic.npy' label_path = 'data/train/train_labels.npy' seismic = np.load(seismic_path) # load 3-D seismiclabels = np.load(label_path) # load 3-D labels
Creating a visualization instance with Mayavi consists of two components: setting up a figure environment and secondly, populating this figure with views of the data one is interested in. This concept is somewhat similar to how one performs visualization with the popular Matplotlib library in Python. Set up the figure object using the code below:
fig = mlab.figure(figure='seismic', bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
This is where we add views of data to the figure object we just created. To view orthogonal slices in 3-D data arrays, the function in mlab API we are interested in is volume_slice. It takes as input the data array, the index of the slice one is interested in, the orientation of the slice, and the figure object to populate with this information. You may add as many slices in either of the three orientations you want. The slice index specifies the slice you will be looking at the first time the figure pops into view, but being interactive, you may then drag it to the position you want. See the code snippet below for visualizing slices along each of the crossline, inline, and depth orientations in the seismic volume we loaded above.
scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.show()
This produces the visualization shown below:
You may want to explore different colormaps to suit best your application. One may also add information to the axes in this figure by a slightly modified version of the code snippet above:
scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.axes(xlabel='Inline', ylabel='Crossline', zlabel='Depth', nb_labels=10) # Add axes labels mlab.show()
This produces the figure below:
Finally, one may render multiple data arrays onto the same figure object for an even more enriching experience with visualization. The interpretations of the seismic volume we used label all voxels in salt domes as the integer β3β. This is done by invoking the mlab APIβs function, contour3d, that plots iso-surfaces in a 3-D volume given a list of integer(s) associated with the iso-surface(s). The following snippet of code overlays the interpreted salt dome in the migrated dataset on to the raw seismic amplitudes, producing the figure shown underneath:
scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.contour3d(labels, contours=[3], figure=fig) # plot isosurface mlab.show()
Visualization is a crucial tool in any interpreterβs toolbox. Conventional seismic visualization packages offer several inconveniences when it comes to visualizing migrated seismic volumes, especially for data science workflows. This is where the popular visualization package, Mayavi comes in, providing several handy features for quickly and efficiently setting up visualizations of migrated seismic volumes and their interpretations. We walked you through using some of these features in a Python environment. We hope this post proves beneficial to interpreters and non-experts in their interpretation workflows involving Python. | [
{
"code": null,
"e": 252,
"s": 47,
"text": "Visualization of migrated, post-stack seismic volumes is a very crucial component of interpretation workflows, be it to pick salt domes, interpret horizons, identify fault planes, or classify rock facies."
},
{
"code": null,
"e": 981,
"s": 252,
"text": "While there are already professional tools like OpendTect and Petrel available to experienced seismic interpreters, setting up a project from scratch in either of these software tools can be overwhelming for beginners and non-specialists, considering all of the various parameters that need to be set before one can visualize the seismic volume of interest. This is not to mention the inconvenience of working with different data types for processing and loading data for visualization, especially in the context of Data Science projects with seismic volumes β repeatedly converting seismic data back and forth between different data types at different stages of processing can be very time consuming and inconvenient for users."
},
{
"code": null,
"e": 1445,
"s": 981,
"text": "I recently came across a very handy, open-source visualization tool, Mayavi, that allows seamless integration of visualization of 3D data like seismic volumes into data science workflows with Python. It is made all the better owing to its very interactive capabilities, where one may drag inline/crossline/depth slices throughout the volume at different angles to examine the features of interest. An example screenshot of such a 3-D visualization is shown below."
},
{
"code": null,
"e": 1640,
"s": 1445,
"text": "This post will walk you through some basic code to get you up and running with using Mayavi for visualizing seismic volumes along with their various interpreted features by seismic interpreters."
},
{
"code": null,
"e": 1791,
"s": 1640,
"text": "Detailed instructions for downloading Mayavi and setting it up for use with Python may be found directly on its homepage. Refer here for more details."
},
{
"code": null,
"e": 2012,
"s": 1791,
"text": "For our purposes, we will be concerned with using the mlab API for using Mayavi as a 3-D plotting tool in python scripts. Assuming everything went smoothly in the last step, use the following code snippet to import mlab:"
},
{
"code": null,
"e": 2111,
"s": 2012,
"text": "import numpy as np # import numpy for data loadingfrom mayavi import mlab # import mlab"
},
{
"code": null,
"e": 2712,
"s": 2111,
"text": "Seismic datasets usually come in the popular .segy (pronounced: seg-y) format. In addition to storing amplitude data, segy files contain a variety of header information, like the crossline and inline numbers associated with each trace, time sample information etc. However, popular machine learning and data science tools usually ask for data to be in the form of numpy arrays. If your data happens to be in segy format, you may use the popular python package, Segyio, to convert it to a numpy array. See here, for more details, instructions, and examples on using Segyio, refer to their GitHub page."
},
{
"code": null,
"e": 3349,
"s": 2712,
"text": "For the rest of this post, we assume you are working with the Netherlands Offshore F3 Blockβs seismic data and its interpreted labels, as developed by the OLIVES lab at Georgia Tech. For more information on this work, refer to the Github page here. Notice that converting the data to numpy format will make it lose tertiary information contained in the headers of the original segy file. But this is OK, since we are usually interested just in the amplitudes and labels for the specific purpose of visualization. Use the following code snippet to load both the raw seismic amplitudes and the associated rock facies labels as 3-D arrays."
},
{
"code": null,
"e": 3551,
"s": 3349,
"text": "seismic_path = 'data/train/train_seismic.npy' label_path = 'data/train/train_labels.npy' seismic = np.load(seismic_path) # load 3-D seismiclabels = np.load(label_path) # load 3-D labels"
},
{
"code": null,
"e": 3900,
"s": 3551,
"text": "Creating a visualization instance with Mayavi consists of two components: setting up a figure environment and secondly, populating this figure with views of the data one is interested in. This concept is somewhat similar to how one performs visualization with the popular Matplotlib library in Python. Set up the figure object using the code below:"
},
{
"code": null,
"e": 3974,
"s": 3900,
"text": "fig = mlab.figure(figure='seismic', bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))"
},
{
"code": null,
"e": 4715,
"s": 3974,
"text": "This is where we add views of data to the figure object we just created. To view orthogonal slices in 3-D data arrays, the function in mlab API we are interested in is volume_slice. It takes as input the data array, the index of the slice one is interested in, the orientation of the slice, and the figure object to populate with this information. You may add as many slices in either of the three orientations you want. The slice index specifies the slice you will be looking at the first time the figure pops into view, but being interactive, you may then drag it to the position you want. See the code snippet below for visualizing slices along each of the crossline, inline, and depth orientations in the seismic volume we loaded above."
},
{
"code": null,
"e": 5071,
"s": 4715,
"text": "scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.show()"
},
{
"code": null,
"e": 5116,
"s": 5071,
"text": "This produces the visualization shown below:"
},
{
"code": null,
"e": 5305,
"s": 5116,
"text": "You may want to explore different colormaps to suit best your application. One may also add information to the axes in this figure by a slightly modified version of the code snippet above:"
},
{
"code": null,
"e": 5784,
"s": 5305,
"text": "scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.axes(xlabel='Inline', ylabel='Crossline', zlabel='Depth', nb_labels=10) # Add axes labels mlab.show()"
},
{
"code": null,
"e": 5816,
"s": 5784,
"text": "This produces the figure below:"
},
{
"code": null,
"e": 6374,
"s": 5816,
"text": "Finally, one may render multiple data arrays onto the same figure object for an even more enriching experience with visualization. The interpretations of the seismic volume we used label all voxels in salt domes as the integer β3β. This is done by invoking the mlab APIβs function, contour3d, that plots iso-surfaces in a 3-D volume given a list of integer(s) associated with the iso-surface(s). The following snippet of code overlays the interpreted salt dome in the migrated dataset on to the raw seismic amplitudes, producing the figure shown underneath:"
},
{
"code": null,
"e": 6800,
"s": 6374,
"text": "scalars = seismic # specifying the data arraymlab.volume_slice(scalars, slice_index=0, plane_orientation='x_axes', figure=fig) # crossline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='y_axes', figure=fig) # inline slicemlab.volume_slice(scalars, slice_index=0, plane_orientation='z_axes', figure=fig) # depth slicemlab.contour3d(labels, contours=[3], figure=fig) # plot isosurface mlab.show()"
}
] |
iText - Link Annotation | In this chapter, we will see how to add link annotation to a PDF document using iText library.
You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor.
To use text annotation in your PDF document, you need to create an object of PdfTextAnnotation class and add this to the PdfPage.
Following are the steps to use text annotation in a PDF document.
The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created.
Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below.
// Creating a PdfWriter
String dest = "C:/itextExamples/linkAnnotation.pdf";
PdfWriter writer = new PdfWriter(dest);
When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified.
The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor.
Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below.
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class.
The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument.
Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below.
// Creating a Document
Document document = new Document(pdfDoc);
The PdfAnnotation class of the package com.itextpdf.kernel.pdf.annot represents the superclass of all the annotations.
Among its derived classes, PdfLinkAnnotation class represents the link annotation. Create an object of this class, as shown below.
// Creating a PdfLinkAnnotation object
Rectangle rect = new Rectangle(0, 0);
PdfLinkAnnotation annotation = new PdfLinkAnnotation(rect);
Set action to the annotation using the setAction() method of the PdfLinkAnnotation class, as shown below.
// Setting action of the annotation
PdfAction action = PdfAction.createURI("http: // www.tutorialspoint.com/");
annotation.setAction(action);
Create a link by instantiating the Link class of the package com.itextpdf.layout.element, as shown below.
// Creating a link
Link link = new Link("Click here", annotation);
Create a new paragraph by instantiating the Paragraph class and add the link created in the previous step using the add() method of this class, as shown below.
// Creating a paragraph
Paragraph paragraph = new Paragraph("Hi welcome to Tutorialspoint ");
// Adding link to paragraph
paragraph.add(link.setUnderline());
Add the paragraph to the document using the add() method of the Document class, as shown below.
// Adding paragraph to document
document.add(paragraph);
Close the document using the close() method of the Document class, as shown below.
// Closing the document
document.close();
The following Java program demonstrates how to add link annotation to a PDF document using the iText library.
It creates a PDF document with the name linkAnnotation.pdf, adds a link annotation to it, and saves it in the path C:/itextExamples/
Save this code in a file with the name LinkAnnotation.java.
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;
public class LinkAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/linkAnnotation.pdf";
PdfWriter writer = new
PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a PdfLinkAnnotation object
Rectangle rect = new Rectangle(0, 0);
PdfLinkAnnotation annotation = new PdfLinkAnnotation(rect);
// Setting action of the annotation
PdfAction action = PdfAction.createURI("http:// www.tutorialspoint.com/");
annotation.setAction(action);
// Creating a link
Link link = new Link("Click here", annotation);
// Creating a paragraph
Paragraph paragraph = new Paragraph("Hi welcome to Tutorialspoint ");
// Adding link to paragraph
paragraph.add(link.setUnderline());
// Adding paragraph to document
document.add(paragraph);
// Closing the document
document.close();
System.out.println("Annotation added successfully");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands β
javac LinkAnnotation.java
java LinkAnnotation
Upon execution, the above program creates a PDF document displaying the following message.
Annotation added successfully
If you verify the specified path, you can find the created PDF document, as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2463,
"s": 2368,
"text": "In this chapter, we will see how to add link annotation to a PDF document using iText library."
},
{
"code": null,
"e": 2642,
"s": 2463,
"text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor."
},
{
"code": null,
"e": 2772,
"s": 2642,
"text": "To use text annotation in your PDF document, you need to create an object of PdfTextAnnotation class and add this to the PdfPage."
},
{
"code": null,
"e": 2838,
"s": 2772,
"text": "Following are the steps to use text annotation in a PDF document."
},
{
"code": null,
"e": 3067,
"s": 2838,
"text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created."
},
{
"code": null,
"e": 3216,
"s": 3067,
"text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below."
},
{
"code": null,
"e": 3337,
"s": 3216,
"text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/linkAnnotation.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n"
},
{
"code": null,
"e": 3477,
"s": 3337,
"text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified."
},
{
"code": null,
"e": 3729,
"s": 3477,
"text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor."
},
{
"code": null,
"e": 3831,
"s": 3729,
"text": "Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below."
},
{
"code": null,
"e": 3907,
"s": 3831,
"text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n"
},
{
"code": null,
"e": 4078,
"s": 3907,
"text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class."
},
{
"code": null,
"e": 4272,
"s": 4078,
"text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument."
},
{
"code": null,
"e": 4397,
"s": 4272,
"text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below."
},
{
"code": null,
"e": 4466,
"s": 4397,
"text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n"
},
{
"code": null,
"e": 4585,
"s": 4466,
"text": "The PdfAnnotation class of the package com.itextpdf.kernel.pdf.annot represents the superclass of all the annotations."
},
{
"code": null,
"e": 4716,
"s": 4585,
"text": "Among its derived classes, PdfLinkAnnotation class represents the link annotation. Create an object of this class, as shown below."
},
{
"code": null,
"e": 4857,
"s": 4716,
"text": "// Creating a PdfLinkAnnotation object \nRectangle rect = new Rectangle(0, 0); \nPdfLinkAnnotation annotation = new PdfLinkAnnotation(rect); \n"
},
{
"code": null,
"e": 4963,
"s": 4857,
"text": "Set action to the annotation using the setAction() method of the PdfLinkAnnotation class, as shown below."
},
{
"code": null,
"e": 5109,
"s": 4963,
"text": "// Setting action of the annotation \nPdfAction action = PdfAction.createURI(\"http: // www.tutorialspoint.com/\"); \nannotation.setAction(action); \n"
},
{
"code": null,
"e": 5215,
"s": 5109,
"text": "Create a link by instantiating the Link class of the package com.itextpdf.layout.element, as shown below."
},
{
"code": null,
"e": 5285,
"s": 5215,
"text": "// Creating a link \nLink link = new Link(\"Click here\", annotation); \n"
},
{
"code": null,
"e": 5445,
"s": 5285,
"text": "Create a new paragraph by instantiating the Paragraph class and add the link created in the previous step using the add() method of this class, as shown below."
},
{
"code": null,
"e": 5615,
"s": 5445,
"text": "// Creating a paragraph \nParagraph paragraph = new Paragraph(\"Hi welcome to Tutorialspoint \"); \n\n// Adding link to paragraph \nparagraph.add(link.setUnderline());\n"
},
{
"code": null,
"e": 5711,
"s": 5615,
"text": "Add the paragraph to the document using the add() method of the Document class, as shown below."
},
{
"code": null,
"e": 5771,
"s": 5711,
"text": "// Adding paragraph to document \ndocument.add(paragraph); \n"
},
{
"code": null,
"e": 5854,
"s": 5771,
"text": "Close the document using the close() method of the Document class, as shown below."
},
{
"code": null,
"e": 5899,
"s": 5854,
"text": "// Closing the document \ndocument.close(); \n"
},
{
"code": null,
"e": 6009,
"s": 5899,
"text": "The following Java program demonstrates how to add link annotation to a PDF document using the iText library."
},
{
"code": null,
"e": 6142,
"s": 6009,
"text": "It creates a PDF document with the name linkAnnotation.pdf, adds a link annotation to it, and saves it in the path C:/itextExamples/"
},
{
"code": null,
"e": 6202,
"s": 6142,
"text": "Save this code in a file with the name LinkAnnotation.java."
},
{
"code": null,
"e": 8044,
"s": 6202,
"text": "import com.itextpdf.kernel.geom.Rectangle; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.action.PdfAction; \nimport com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.element.Link; \nimport com.itextpdf.layout.element.Paragraph; \n\npublic class LinkAnnotation { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter \n String dest = \"C:/itextExamples/linkAnnotation.pdf\"; \n \n PdfWriter writer = new \n PdfWriter(dest); \n \n // Creating a PdfDocument \n PdfDocument pdf = new PdfDocument(writer); \n \n // Creating a Document\n Document document = new Document(pdf); \n \n // Creating a PdfLinkAnnotation object \n Rectangle rect = new Rectangle(0, 0); \n PdfLinkAnnotation annotation = new PdfLinkAnnotation(rect); \n \n // Setting action of the annotation \n PdfAction action = PdfAction.createURI(\"http:// www.tutorialspoint.com/\"); \n annotation.setAction(action); \n \n // Creating a link \n Link link = new Link(\"Click here\", annotation); \n \n // Creating a paragraph \n Paragraph paragraph = new Paragraph(\"Hi welcome to Tutorialspoint \"); \n \n // Adding link to paragraph \n paragraph.add(link.setUnderline()); \n \n // Adding paragraph to document \n document.add(paragraph); \n\n // Closing the document \n document.close(); \n \n System.out.println(\"Annotation added successfully\"); \n } \n} "
},
{
"code": null,
"e": 8139,
"s": 8044,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands β"
},
{
"code": null,
"e": 8188,
"s": 8139,
"text": "javac LinkAnnotation.java \njava LinkAnnotation \n"
},
{
"code": null,
"e": 8279,
"s": 8188,
"text": "Upon execution, the above program creates a PDF document displaying the following message."
},
{
"code": null,
"e": 8310,
"s": 8279,
"text": "Annotation added successfully\n"
},
{
"code": null,
"e": 8399,
"s": 8310,
"text": "If you verify the specified path, you can find the created PDF document, as shown below."
},
{
"code": null,
"e": 8406,
"s": 8399,
"text": " Print"
},
{
"code": null,
"e": 8417,
"s": 8406,
"text": " Add Notes"
}
] |
Collection Interface in Java with Examples - GeeksforGeeks | 07 Aug, 2021
The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set.
For Example, the HashSet class implements the Set interface which is a subinterface of the Collection interface. If a collection implementation doesnβt implement a particular operation, it should define the corresponding method to throw UnsupportedOperationException.
The Hierarchy of Collection
It implements the Iterable<E> interface. The sub-interfaces of Collection are BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Deque<E>, EventSet, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>, TransferQueue<E> .
SubInterfaces of Collection Interface
All the Classes of the Collection Framework implement the subInterfaces of the Collection Interface. All the methods of Collection interfaces are also contained in itβs subinterfaces. These subInterfaces are sometimes called as Collection Types or SubTypes of Collection. These include the following:
List: This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example,
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
Set: A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is used when we wish to avoid the duplication of the objects and wish to store only the unique objects. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object with any of these classes. For example,
Set<T> hs = new HashSet<> ();
Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
Where T is the type of the object.
SortedSet: This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For example,
SortedSet<T> ts = new TreeSet<> ();
Where T is the type of the object.
Queue: As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold at the first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, Deque, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes. For example,
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.
Deque: This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both the ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since this class implements the deque, we can instantiate a deque object with this class. For example,
Deque<T> ad = new ArrayDeque<> ();
Where T is the type of the object.
Declaration:
public interface Collection<E> extends Iterable<E>
Here, E is the type of elements stored in the collection.
Example:
Java
// Java program to illustrate Collection interface import java.io.*;import java.util.*; public class CollectionDemo { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Output the present list System.out.println("The list is: " + list); // Adding new elements to the end list.add("Last"); list.add("Element"); // printing the new list System.out.println("The new List is: " + list); }}
The list is: [Geeks, for, Geeks]
The new List is: [Geeks, for, Geeks, Last, Element]
The Collection interface is implemented by AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentHashMap.KeySetView, ConcurrentLinkedDeque, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector.
Syntax:
Collection<E> objectName = new ArrayList<E>();
Here, E is the type of elements stored in the collection.
Note: In the above syntax, we can replace any class with ArrayList if that class implements the Collection interface.
1. Adding Elements
The add(E e) and addAll(Collection c) methods provided by Collection can be used to add elements.
Java
// Java code to illustrate adding// elements to the Collection import java.io.*;import java.util.*; public class AddingElementsExample { public static void main(String[] args) { // create an empty array list with an initial // capacity Collection<Integer> list1 = new ArrayList<Integer>(5); // use add() method to add elements in the list list1.add(15); list1.add(20); list1.add(25); // prints all the elements available in list for (Integer number : list1) { System.out.println("Number = " + number); } // Creating an empty ArrayList Collection<Integer> list2 = new ArrayList<Integer>(); // Appending the collection to the list list2.addAll(list1); // displaying the modified ArrayList System.out.println("The new ArrayList is: " + list2); }}
Number = 15
Number = 20
Number = 25
The new ArrayList is: [15, 20, 25]
2. Removing Elements
The remove(E e) and removeAll(Collection c) methods can be used to remove a particular element or a Collection of elements from a collection.
Java
// Java program to demonstrate removing// elements from a Collection import java.util.*; public class RemoveElementsExample { public static void main(String[] argv) throws Exception { // Creating object of HashSet<Integer> Collection<Integer> set1 = new HashSet<Integer>(); // Populating arrset1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println("Initial set1 : " + set1); // remove a particular element set1.remove(4); // print modified set1 System.out.println("set1 after removing 4 : " + set1); // Creating another object of HashSet<Integer> Collection<Integer> set2 = new HashSet<Integer>(); set2.add(1); set2.add(2); set2.add(3); // print set2 System.out.println("Collection Elements to be removed : " + set2); // Removing elements from set1 // specified in set2 // using removeAll() method set1.removeAll(set2); // print arrset1 System.out.println("set 1 after removeAll() operation : " + set1); }}
Initial set1 : [1, 2, 3, 4, 5]
set1 after removing 4 : [1, 2, 3, 5]
Collection Elements to be removed : [1, 2, 3]
set 1 after removeAll() operation : [5]
3. Iterating
To iterate over the elements of Collection we can use iterator() method.
Java
// Java code to illustrate iterating// over a Collection import java.util.*; public class IteratingExample { public static void main(String[] args) { // Create and populate the list Collection<String> list = new LinkedList<>(); list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("is"); list.add("a"); list.add("CS"); list.add("Students"); list.add("Portal"); // Displaying the list System.out.println("The list is: " + list); // Create an iterator for the list // using iterator() method Iterator<String> iter = list.iterator(); // Displaying the values after iterating // through the list System.out.println("\nThe iterator values" + " of list are: "); while (iter.hasNext()) { System.out.print(iter.next() + " "); } }}
The list is: [Geeks, for, Geeks, is, a, CS, Students, Portal]
The iterator values of list are:
Geeks for Geeks is a CS Students Portal
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html
saurabh1990aror
sumitgumber28
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23974,
"s": 23946,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 24310,
"s": 23974,
"text": "The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. "
},
{
"code": null,
"e": 24578,
"s": 24310,
"text": "For Example, the HashSet class implements the Set interface which is a subinterface of the Collection interface. If a collection implementation doesnβt implement a particular operation, it should define the corresponding method to throw UnsupportedOperationException."
},
{
"code": null,
"e": 24606,
"s": 24578,
"text": "The Hierarchy of Collection"
},
{
"code": null,
"e": 24851,
"s": 24606,
"text": "It implements the Iterable<E> interface. The sub-interfaces of Collection are BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Deque<E>, EventSet, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>, TransferQueue<E> ."
},
{
"code": null,
"e": 24889,
"s": 24851,
"text": "SubInterfaces of Collection Interface"
},
{
"code": null,
"e": 25190,
"s": 24889,
"text": "All the Classes of the Collection Framework implement the subInterfaces of the Collection Interface. All the methods of Collection interfaces are also contained in itβs subinterfaces. These subInterfaces are sometimes called as Collection Types or SubTypes of Collection. These include the following:"
},
{
"code": null,
"e": 25634,
"s": 25190,
"text": "List: This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example,"
},
{
"code": null,
"e": 25668,
"s": 25634,
"text": "List <T> al = new ArrayList<> ();"
},
{
"code": null,
"e": 25703,
"s": 25668,
"text": "List <T> ll = new LinkedList<> ();"
},
{
"code": null,
"e": 25733,
"s": 25703,
"text": "List <T> v = new Vector<> ();"
},
{
"code": null,
"e": 25767,
"s": 25733,
"text": "Where T is the type of the object"
},
{
"code": null,
"e": 26192,
"s": 25767,
"text": "Set: A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is used when we wish to avoid the duplication of the objects and wish to store only the unique objects. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object with any of these classes. For example,"
},
{
"code": null,
"e": 26222,
"s": 26192,
"text": "Set<T> hs = new HashSet<> ();"
},
{
"code": null,
"e": 26259,
"s": 26222,
"text": "Set<T> lhs = new LinkedHashSet<> ();"
},
{
"code": null,
"e": 26289,
"s": 26259,
"text": "Set<T> ts = new TreeSet<> ();"
},
{
"code": null,
"e": 26324,
"s": 26289,
"text": "Where T is the type of the object."
},
{
"code": null,
"e": 26766,
"s": 26324,
"text": "SortedSet: This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For example,"
},
{
"code": null,
"e": 26802,
"s": 26766,
"text": "SortedSet<T> ts = new TreeSet<> ();"
},
{
"code": null,
"e": 26837,
"s": 26802,
"text": "Where T is the type of the object."
},
{
"code": null,
"e": 27440,
"s": 26837,
"text": "Queue: As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold at the first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, Deque, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes. For example,"
},
{
"code": null,
"e": 27479,
"s": 27440,
"text": "Queue <T> pq = new PriorityQueue<> ();"
},
{
"code": null,
"e": 27515,
"s": 27479,
"text": "Queue <T> ad = new ArrayDeque<> ();"
},
{
"code": null,
"e": 27550,
"s": 27515,
"text": "Where T is the type of the object."
},
{
"code": null,
"e": 27959,
"s": 27550,
"text": "Deque: This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both the ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since this class implements the deque, we can instantiate a deque object with this class. For example,"
},
{
"code": null,
"e": 27994,
"s": 27959,
"text": "Deque<T> ad = new ArrayDeque<> ();"
},
{
"code": null,
"e": 28029,
"s": 27994,
"text": "Where T is the type of the object."
},
{
"code": null,
"e": 28042,
"s": 28029,
"text": "Declaration:"
},
{
"code": null,
"e": 28093,
"s": 28042,
"text": "public interface Collection<E> extends Iterable<E>"
},
{
"code": null,
"e": 28151,
"s": 28093,
"text": "Here, E is the type of elements stored in the collection."
},
{
"code": null,
"e": 28160,
"s": 28151,
"text": "Example:"
},
{
"code": null,
"e": 28165,
"s": 28160,
"text": "Java"
},
{
"code": "// Java program to illustrate Collection interface import java.io.*;import java.util.*; public class CollectionDemo { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Output the present list System.out.println(\"The list is: \" + list); // Adding new elements to the end list.add(\"Last\"); list.add(\"Element\"); // printing the new list System.out.println(\"The new List is: \" + list); }}",
"e": 28836,
"s": 28165,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28836,
"text": "The list is: [Geeks, for, Geeks]\nThe new List is: [Geeks, for, Geeks, Last, Element]"
},
{
"code": null,
"e": 29545,
"s": 28921,
"text": "The Collection interface is implemented by AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentHashMap.KeySetView, ConcurrentLinkedDeque, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector."
},
{
"code": null,
"e": 29554,
"s": 29545,
"text": "Syntax: "
},
{
"code": null,
"e": 29601,
"s": 29554,
"text": "Collection<E> objectName = new ArrayList<E>();"
},
{
"code": null,
"e": 29659,
"s": 29601,
"text": "Here, E is the type of elements stored in the collection."
},
{
"code": null,
"e": 29778,
"s": 29659,
"text": "Note: In the above syntax, we can replace any class with ArrayList if that class implements the Collection interface. "
},
{
"code": null,
"e": 29798,
"s": 29778,
"text": "1. Adding Elements "
},
{
"code": null,
"e": 29897,
"s": 29798,
"text": "The add(E e) and addAll(Collection c) methods provided by Collection can be used to add elements. "
},
{
"code": null,
"e": 29902,
"s": 29897,
"text": "Java"
},
{
"code": "// Java code to illustrate adding// elements to the Collection import java.io.*;import java.util.*; public class AddingElementsExample { public static void main(String[] args) { // create an empty array list with an initial // capacity Collection<Integer> list1 = new ArrayList<Integer>(5); // use add() method to add elements in the list list1.add(15); list1.add(20); list1.add(25); // prints all the elements available in list for (Integer number : list1) { System.out.println(\"Number = \" + number); } // Creating an empty ArrayList Collection<Integer> list2 = new ArrayList<Integer>(); // Appending the collection to the list list2.addAll(list1); // displaying the modified ArrayList System.out.println(\"The new ArrayList is: \" + list2); }}",
"e": 30784,
"s": 29902,
"text": null
},
{
"code": null,
"e": 30855,
"s": 30784,
"text": "Number = 15\nNumber = 20\nNumber = 25\nThe new ArrayList is: [15, 20, 25]"
},
{
"code": null,
"e": 30876,
"s": 30855,
"text": "2. Removing Elements"
},
{
"code": null,
"e": 31019,
"s": 30876,
"text": "The remove(E e) and removeAll(Collection c) methods can be used to remove a particular element or a Collection of elements from a collection. "
},
{
"code": null,
"e": 31024,
"s": 31019,
"text": "Java"
},
{
"code": "// Java program to demonstrate removing// elements from a Collection import java.util.*; public class RemoveElementsExample { public static void main(String[] argv) throws Exception { // Creating object of HashSet<Integer> Collection<Integer> set1 = new HashSet<Integer>(); // Populating arrset1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println(\"Initial set1 : \" + set1); // remove a particular element set1.remove(4); // print modified set1 System.out.println(\"set1 after removing 4 : \" + set1); // Creating another object of HashSet<Integer> Collection<Integer> set2 = new HashSet<Integer>(); set2.add(1); set2.add(2); set2.add(3); // print set2 System.out.println(\"Collection Elements to be removed : \" + set2); // Removing elements from set1 // specified in set2 // using removeAll() method set1.removeAll(set2); // print arrset1 System.out.println(\"set 1 after removeAll() operation : \" + set1); }}",
"e": 32210,
"s": 31024,
"text": null
},
{
"code": null,
"e": 32364,
"s": 32210,
"text": "Initial set1 : [1, 2, 3, 4, 5]\nset1 after removing 4 : [1, 2, 3, 5]\nCollection Elements to be removed : [1, 2, 3]\nset 1 after removeAll() operation : [5]"
},
{
"code": null,
"e": 32378,
"s": 32364,
"text": "3. Iterating "
},
{
"code": null,
"e": 32452,
"s": 32378,
"text": "To iterate over the elements of Collection we can use iterator() method. "
},
{
"code": null,
"e": 32457,
"s": 32452,
"text": "Java"
},
{
"code": "// Java code to illustrate iterating// over a Collection import java.util.*; public class IteratingExample { public static void main(String[] args) { // Create and populate the list Collection<String> list = new LinkedList<>(); list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"is\"); list.add(\"a\"); list.add(\"CS\"); list.add(\"Students\"); list.add(\"Portal\"); // Displaying the list System.out.println(\"The list is: \" + list); // Create an iterator for the list // using iterator() method Iterator<String> iter = list.iterator(); // Displaying the values after iterating // through the list System.out.println(\"\\nThe iterator values\" + \" of list are: \"); while (iter.hasNext()) { System.out.print(iter.next() + \" \"); } }}",
"e": 33356,
"s": 32457,
"text": null
},
{
"code": null,
"e": 33493,
"s": 33356,
"text": "The list is: [Geeks, for, Geeks, is, a, CS, Students, Portal]\n\nThe iterator values of list are: \nGeeks for Geeks is a CS Students Portal"
},
{
"code": null,
"e": 33500,
"s": 33493,
"text": "METHOD"
},
{
"code": null,
"e": 33512,
"s": 33500,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 33519,
"s": 33512,
"text": "METHOD"
},
{
"code": null,
"e": 33531,
"s": 33519,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 33629,
"s": 33531,
"text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html"
},
{
"code": null,
"e": 33647,
"s": 33631,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 33661,
"s": 33647,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33678,
"s": 33661,
"text": "Java-Collections"
},
{
"code": null,
"e": 33683,
"s": 33678,
"text": "Java"
},
{
"code": null,
"e": 33688,
"s": 33683,
"text": "Java"
},
{
"code": null,
"e": 33705,
"s": 33688,
"text": "Java-Collections"
},
{
"code": null,
"e": 33803,
"s": 33705,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33818,
"s": 33803,
"text": "Stream In Java"
},
{
"code": null,
"e": 33864,
"s": 33818,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33885,
"s": 33864,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33904,
"s": 33885,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33934,
"s": 33904,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 33951,
"s": 33934,
"text": "Generics in Java"
},
{
"code": null,
"e": 33994,
"s": 33951,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 34023,
"s": 33994,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 34044,
"s": 34023,
"text": "Introduction to Java"
}
] |
Yii - Using Cookies | Cookies allow data to be persisted across requests. In PHP, you may access them through the $_COOKIE variable. Yii represents cookie as an object of the yii\web\Cookie class. In this chapter, we describe several methods for reading cookies.
Step 1 β Create an actionReadCookies method in the SiteController.
public function actionReadCookies() {
// get cookies from the "request" component
$cookies = Yii::$app->request->cookies;
// get the "language" cookie value
// if the cookie does not exist, return "ru" as the default value
$language = $cookies->getValue('language', 'ru');
// an alternative way of getting the "language" cookie value
if (($cookie = $cookies->get('language')) !== null) {
$language = $cookie->value;
}
// you may also use $cookies like an array
if (isset($cookies['language'])) {
$language = $cookies['language']->value;
}
// check if there is a "language" cookie
if ($cookies->has('language')) echo "Current language: $language";
}
Step 2 β To see sending cookies in action, create a method called actionSendCookies in the SiteController.
public function actionSendCookies() {
// get cookies from the "response" component
$cookies = Yii::$app->response->cookies;
// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => 'ru-RU',
]));
$cookies->add(new \yii\web\Cookie([
'name' => 'username',
'value' => 'John',
]));
$cookies->add(new \yii\web\Cookie([
'name' => 'country',
'value' => 'USA',
]));
}
Step 3 β Now, if you go to http://localhost:8080/index.php?r=site/send-cookies, you will notice that cookies are saved inside the browser.
In Yii, by default, cookie validation is enabled. It protects the cookies from being modified on the client side. The hash string from the config/web.php file signs each cookie.
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is
//required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
//'showScriptName' => false,
//'enablePrettyUrl' => true,
//'enableStrictParsing' => true,
//'suffix' => '/'
],
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
?>
You can disable cookie validation by setting the yii\web\Request::$enableCookieValidation property to false.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3074,
"s": 2833,
"text": "Cookies allow data to be persisted across requests. In PHP, you may access them through the $_COOKIE variable. Yii represents cookie as an object of the yii\\web\\Cookie class. In this chapter, we describe several methods for reading cookies."
},
{
"code": null,
"e": 3141,
"s": 3074,
"text": "Step 1 β Create an actionReadCookies method in the SiteController."
},
{
"code": null,
"e": 3857,
"s": 3141,
"text": "public function actionReadCookies() { \n // get cookies from the \"request\" component \n $cookies = Yii::$app->request->cookies; \n // get the \"language\" cookie value \n // if the cookie does not exist, return \"ru\" as the default value \n $language = $cookies->getValue('language', 'ru'); \n // an alternative way of getting the \"language\" cookie value \n if (($cookie = $cookies->get('language')) !== null) { \n $language = $cookie->value; \n } \n // you may also use $cookies like an array \n if (isset($cookies['language'])) { \n $language = $cookies['language']->value; \n } \n // check if there is a \"language\" cookie \n if ($cookies->has('language')) echo \"Current language: $language\"; \n}"
},
{
"code": null,
"e": 3964,
"s": 3857,
"text": "Step 2 β To see sending cookies in action, create a method called actionSendCookies in the SiteController."
},
{
"code": null,
"e": 4461,
"s": 3964,
"text": "public function actionSendCookies() { \n // get cookies from the \"response\" component \n $cookies = Yii::$app->response->cookies; \n // add a new cookie to the response to be sent \n $cookies->add(new \\yii\\web\\Cookie([ \n 'name' => 'language', \n 'value' => 'ru-RU', \n ])); \n $cookies->add(new \\yii\\web\\Cookie([\n 'name' => 'username', \n 'value' => 'John', \n ])); \n $cookies->add(new \\yii\\web\\Cookie([ \n 'name' => 'country', \n 'value' => 'USA', \n ])); \n} "
},
{
"code": null,
"e": 4600,
"s": 4461,
"text": "Step 3 β Now, if you go to http://localhost:8080/index.php?r=site/send-cookies, you will notice that cookies are saved inside the browser."
},
{
"code": null,
"e": 4778,
"s": 4600,
"text": "In Yii, by default, cookie validation is enabled. It protects the cookies from being modified on the client side. The hash string from the config/web.php file signs each cookie."
},
{
"code": null,
"e": 6877,
"s": 4778,
"text": "<?php \n $params = require(__DIR__ . '/params.php'); \n $config = [ \n 'id' => 'basic', \n 'basePath' => dirname(__DIR__), \n 'bootstrap' => ['log'], \n 'components' => [ \n 'request' => [ \n // !!! insert a secret key in the following (if it is empty) - this is \n //required by cookie validation \n 'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO', \n ], \n 'cache' => [ \n 'class' => 'yii\\caching\\FileCache', \n ], \n 'user' => [ \n 'identityClass' => 'app\\models\\User', \n 'enableAutoLogin' => true, \n ], \n 'errorHandler' => [ \n 'errorAction' => 'site/error', \n ], \n 'mailer' => [ \n 'class' => 'yii\\swiftmailer\\Mailer', \n // send all mails to a file by default. You have to set \n // 'useFileTransport' to false and configure a transport \n // for the mailer to send real emails. \n 'useFileTransport' => true, \n ], \n 'log' => [ \n 'traceLevel' => YII_DEBUG ? 3 : 0, \n 'targets' => [ \n [ \n 'class' => 'yii\\log\\FileTarget', \n 'levels' => ['error', 'warning'], \n ], \n ], \n ], \n 'urlManager' => [ \n //'showScriptName' => false, \n //'enablePrettyUrl' => true, \n //'enableStrictParsing' => true, \n //'suffix' => '/' \n ], \n 'db' => require(__DIR__ . '/db.php'), \n ], \n 'modules' => [ \n 'hello' => [ \n 'class' => 'app\\modules\\hello\\Hello', \n ], \n ], \n 'params' => $params,\n ]; \n if (YII_ENV_DEV) { \n // configuration adjustments for 'dev' environment \n $config['bootstrap'][] = 'debug'; \n $config['modules']['debug'] = [ \n 'class' => 'yii\\debug\\Module', \n ]; \n $config['bootstrap'][] = 'gii'; \n $config['modules']['gii'] = [ \n 'class' => 'yii\\gii\\Module', \n ]; \n } \n return $config; \n?>"
},
{
"code": null,
"e": 6986,
"s": 6877,
"text": "You can disable cookie validation by setting the yii\\web\\Request::$enableCookieValidation property to false."
},
{
"code": null,
"e": 6993,
"s": 6986,
"text": " Print"
},
{
"code": null,
"e": 7004,
"s": 6993,
"text": " Add Notes"
}
] |
Find the foot of perpendicular of a point in a 3 D plane - GeeksforGeeks | 11 May, 2021
Given a point (x1, y1, z1) in 3-D and coefficients of the equation of plane, we have to find the foot of perpendicular of a point in a 3 D plane.Examples:
Input: a = 1, b = -2, c = 0, d = 0, x = -1, y = 3, z = 4 Output: x2 = 0.4 y2 = 0.2 z2 = 4.0Input: a = 2, b = -1, c = 1, d = 3, x = 1, y = 3, z = 4 Output: x2 = -1.0 y2 = 4.0 z2 = 3.0
Approach: Equation of plane is given as ax + by + cz + d = 0. Therefore, the direction ratios of the normal to the plane are (a, b, c). Let N be the foot of perpendicular from given point to the given plane so, line PN has directed ratios (a, b, c) and it passes through P(x1, y1, z1). The equation of line PN will be as:-
(x β x1) / a = (y β y1) / b = (z β z1) / c = k
Hence any point on line PN can be written as:-
x = a * k + x1 y = b * k + y1 z = c * k + z1
since N lies in both line and plane so will satisfy(ax + by + cz + d = 0).
=>a * (a * k + x1) + b * (b * k + y1) + c * (c * k + z1) + d = 0. =>a * a * k + a * x1 + b * b * k + b * y1 + c * c * k + c * z1 + d = 0. =>(a * a + b * b + c * c)k = -a * x1 β b * y1 β c * z1 β d. =>k = (-a * x1 β b * y1 β c * z1 β d) / (a * a + b * b + c * c).
Now, the coordinates of Point N in terms of k will be:-
x2 = a * k + x1 y2 = b * k + y1 z2 = c * k + z1
Below is the implementation of the above:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find// foot of perpendicular// of a point in a 3 D plane.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // Function to find foot of perpendicularvoid foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; std::cout << std::fixed; std::cout << std::setprecision(1); cout << " x2 = " << x2; cout << " y2 = " << y2; cout << " z2 = " << z2;} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); return 0;}// This code is contributed by Amber_Saxena.
// Java program to find// foot of perpendicular// of a point in a 3 D plane.import java.util.*;import java.text.*; class solution{ // Function to find foot of perpendicularstatic void foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; DecimalFormat form = new DecimalFormat("0.0"); System.out.print(" x2 = " +form.format(x2)); System.out.print(" y2 = " +form.format(y2)); System.out.print( " z2 = " +form.format(z2));} // Driver Codepublic static void main(String arr[]){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); }}
# Python3 program to find# foot of perpendicular# of a point in a 3 D plane. # Function to find foot of perpendiculardef foot(a, b, c, d, x1, y1, z1) : k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c); x2 = a * k + x1; y2 = b * k + y1; z2 = c * k + z1; print("x2 =",round(x2,1)) print("y2 =",round(y2,1)) print("z2 =",round(z2,1)) # Driver Codeif __name__ == "__main__" : a = 1 b = -2 c = 0 d = 0 x1 = -1 y1 = 3 z1 = 4 # function call foot(a, b, c, d, x1, y1, z1) # This code is contributed by Ryuga
// C# program to find// foot of perpendicular// of a point in a 3 D plane.using System;using System.Globalization; class GFG{ // Function to find foot of perpendicularstatic void foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; NumberFormatInfo form = new NumberFormatInfo(); form.NumberDecimalSeparator = "."; Console.Write(" x2 = " + x2.ToString(form)); Console.Write(" y2 = " + y2.ToString(form)); Console.Write( " z2 = " + z2.ToString(form));} // Driver Codepublic static void Main(String []arr){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1);}} // This code contributed by Rajput-Ji
<?php// PHP program to find foot of perpendicular// of a point in a 3 D plane. // Function to find foot of perpendicularfunction foot($a, $b, $c, $d, $x1, $y1, $z1){ $k = (-$a * $x1 - $b * $y1 - $c * $z1 - $d) / ($a * $a + $b * $b + $c * $c); $x2 = $a * $k + $x1; $y2 = $b * $k + $y1; $z2 = $c * $k + $z1; echo "x2 = " . round($x2, 1); echo " y2 = " . round($y2, 1); echo " z2 = " . round($z2, 1);} // Driver Code$a = 1; $b = -2; $c = 0; $d = 0;$x1 = -1; $y1 = 3; $z1 = 4; // function callfoot($a, $b, $c, $d, $x1, $y1, $z1); // This code is contributed by ita_c?>
<script> // JavaScript program to find // foot of perpendicular // of a point in a 3 D plane. // Function to find foot of perpendicular function foot(a, b, c, d, x1, y1, z1) { var k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c); var x2 = a * k + x1; var y2 = b * k + y1; var z2 = c * k + z1; document.write("x2 =" + x2.toFixed(1) + " "); document.write("y2 =" + y2.toFixed(1) + " "); document.write("z2 =" + z2.toFixed(1) + " "); } // Driver Code var a = 1; var b = -2; var c = 0; var d = 0; var x1 = -1; var y1 = 3; var z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); </script>
x2 = 0.4 y2 = 0.2 z2 = 4.0
SURENDRA_GANGWAR
ankthon
ukasp
Rajput-Ji
rdtank
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Line Clipping | Set 1 (CohenβSutherland Algorithm)
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 25070,
"s": 25042,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25227,
"s": 25070,
"text": "Given a point (x1, y1, z1) in 3-D and coefficients of the equation of plane, we have to find the foot of perpendicular of a point in a 3 D plane.Examples: "
},
{
"code": null,
"e": 25410,
"s": 25227,
"text": "Input: a = 1, b = -2, c = 0, d = 0, x = -1, y = 3, z = 4 Output: x2 = 0.4 y2 = 0.2 z2 = 4.0Input: a = 2, b = -1, c = 1, d = 3, x = 1, y = 3, z = 4 Output: x2 = -1.0 y2 = 4.0 z2 = 3.0"
},
{
"code": null,
"e": 25738,
"s": 25414,
"text": "Approach: Equation of plane is given as ax + by + cz + d = 0. Therefore, the direction ratios of the normal to the plane are (a, b, c). Let N be the foot of perpendicular from given point to the given plane so, line PN has directed ratios (a, b, c) and it passes through P(x1, y1, z1). The equation of line PN will be as:- "
},
{
"code": null,
"e": 25785,
"s": 25738,
"text": "(x β x1) / a = (y β y1) / b = (z β z1) / c = k"
},
{
"code": null,
"e": 25833,
"s": 25785,
"text": "Hence any point on line PN can be written as:- "
},
{
"code": null,
"e": 25878,
"s": 25833,
"text": "x = a * k + x1 y = b * k + y1 z = c * k + z1"
},
{
"code": null,
"e": 25954,
"s": 25878,
"text": "since N lies in both line and plane so will satisfy(ax + by + cz + d = 0). "
},
{
"code": null,
"e": 26217,
"s": 25954,
"text": "=>a * (a * k + x1) + b * (b * k + y1) + c * (c * k + z1) + d = 0. =>a * a * k + a * x1 + b * b * k + b * y1 + c * c * k + c * z1 + d = 0. =>(a * a + b * b + c * c)k = -a * x1 β b * y1 β c * z1 β d. =>k = (-a * x1 β b * y1 β c * z1 β d) / (a * a + b * b + c * c)."
},
{
"code": null,
"e": 26275,
"s": 26217,
"text": "Now, the coordinates of Point N in terms of k will be:- "
},
{
"code": null,
"e": 26323,
"s": 26275,
"text": "x2 = a * k + x1 y2 = b * k + y1 z2 = c * k + z1"
},
{
"code": null,
"e": 26367,
"s": 26323,
"text": "Below is the implementation of the above: "
},
{
"code": null,
"e": 26371,
"s": 26367,
"text": "C++"
},
{
"code": null,
"e": 26376,
"s": 26371,
"text": "Java"
},
{
"code": null,
"e": 26384,
"s": 26376,
"text": "Python3"
},
{
"code": null,
"e": 26387,
"s": 26384,
"text": "C#"
},
{
"code": null,
"e": 26391,
"s": 26387,
"text": "PHP"
},
{
"code": null,
"e": 26402,
"s": 26391,
"text": "Javascript"
},
{
"code": "// C++ program to find// foot of perpendicular// of a point in a 3 D plane.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // Function to find foot of perpendicularvoid foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; std::cout << std::fixed; std::cout << std::setprecision(1); cout << \" x2 = \" << x2; cout << \" y2 = \" << y2; cout << \" z2 = \" << z2;} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); return 0;}// This code is contributed by Amber_Saxena.",
"e": 27283,
"s": 26402,
"text": null
},
{
"code": "// Java program to find// foot of perpendicular// of a point in a 3 D plane.import java.util.*;import java.text.*; class solution{ // Function to find foot of perpendicularstatic void foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; DecimalFormat form = new DecimalFormat(\"0.0\"); System.out.print(\" x2 = \" +form.format(x2)); System.out.print(\" y2 = \" +form.format(y2)); System.out.print( \" z2 = \" +form.format(z2));} // Driver Codepublic static void main(String arr[]){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); }}",
"e": 28140,
"s": 27283,
"text": null
},
{
"code": "# Python3 program to find# foot of perpendicular# of a point in a 3 D plane. # Function to find foot of perpendiculardef foot(a, b, c, d, x1, y1, z1) : k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c); x2 = a * k + x1; y2 = b * k + y1; z2 = c * k + z1; print(\"x2 =\",round(x2,1)) print(\"y2 =\",round(y2,1)) print(\"z2 =\",round(z2,1)) # Driver Codeif __name__ == \"__main__\" : a = 1 b = -2 c = 0 d = 0 x1 = -1 y1 = 3 z1 = 4 # function call foot(a, b, c, d, x1, y1, z1) # This code is contributed by Ryuga",
"e": 28706,
"s": 28140,
"text": null
},
{
"code": "// C# program to find// foot of perpendicular// of a point in a 3 D plane.using System;using System.Globalization; class GFG{ // Function to find foot of perpendicularstatic void foot(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; NumberFormatInfo form = new NumberFormatInfo(); form.NumberDecimalSeparator = \".\"; Console.Write(\" x2 = \" + x2.ToString(form)); Console.Write(\" y2 = \" + y2.ToString(form)); Console.Write( \" z2 = \" + z2.ToString(form));} // Driver Codepublic static void Main(String []arr){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call foot(a, b, c, d, x1, y1, z1);}} // This code contributed by Rajput-Ji",
"e": 29649,
"s": 28706,
"text": null
},
{
"code": "<?php// PHP program to find foot of perpendicular// of a point in a 3 D plane. // Function to find foot of perpendicularfunction foot($a, $b, $c, $d, $x1, $y1, $z1){ $k = (-$a * $x1 - $b * $y1 - $c * $z1 - $d) / ($a * $a + $b * $b + $c * $c); $x2 = $a * $k + $x1; $y2 = $b * $k + $y1; $z2 = $c * $k + $z1; echo \"x2 = \" . round($x2, 1); echo \" y2 = \" . round($y2, 1); echo \" z2 = \" . round($z2, 1);} // Driver Code$a = 1; $b = -2; $c = 0; $d = 0;$x1 = -1; $y1 = 3; $z1 = 4; // function callfoot($a, $b, $c, $d, $x1, $y1, $z1); // This code is contributed by ita_c?>",
"e": 30253,
"s": 29649,
"text": null
},
{
"code": "<script> // JavaScript program to find // foot of perpendicular // of a point in a 3 D plane. // Function to find foot of perpendicular function foot(a, b, c, d, x1, y1, z1) { var k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c); var x2 = a * k + x1; var y2 = b * k + y1; var z2 = c * k + z1; document.write(\"x2 =\" + x2.toFixed(1) + \" \"); document.write(\"y2 =\" + y2.toFixed(1) + \" \"); document.write(\"z2 =\" + z2.toFixed(1) + \" \"); } // Driver Code var a = 1; var b = -2; var c = 0; var d = 0; var x1 = -1; var y1 = 3; var z1 = 4; // function call foot(a, b, c, d, x1, y1, z1); </script>",
"e": 30990,
"s": 30253,
"text": null
},
{
"code": null,
"e": 31017,
"s": 30990,
"text": "x2 = 0.4 y2 = 0.2 z2 = 4.0"
},
{
"code": null,
"e": 31036,
"s": 31019,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31044,
"s": 31036,
"text": "ankthon"
},
{
"code": null,
"e": 31050,
"s": 31044,
"text": "ukasp"
},
{
"code": null,
"e": 31060,
"s": 31050,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31067,
"s": 31060,
"text": "rdtank"
},
{
"code": null,
"e": 31077,
"s": 31067,
"text": "Geometric"
},
{
"code": null,
"e": 31096,
"s": 31077,
"text": "School Programming"
},
{
"code": null,
"e": 31106,
"s": 31096,
"text": "Geometric"
},
{
"code": null,
"e": 31204,
"s": 31106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31257,
"s": 31204,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 31291,
"s": 31257,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 31349,
"s": 31291,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 31398,
"s": 31349,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 31449,
"s": 31398,
"text": "Line Clipping | Set 1 (CohenβSutherland Algorithm)"
},
{
"code": null,
"e": 31467,
"s": 31449,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31483,
"s": 31467,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 31502,
"s": 31483,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31527,
"s": 31502,
"text": "Reverse a string in Java"
}
] |
Accessibility in React.js | The aria-* attributes on html elements are also supported in React.js as well. The other attributes are generally written in camel-case but these aria-* are written in hyphen-cased.
<input
type = "text"
aria-label = {labelText}
aria-required = "true"
onChange = {changeHandler}
value = {inputValue}
name = "userInput"
/>
Sometimes we break the semantics of the html if we use parent div in React.js
render(){
return(
<div>
<h1>Test</h1>
</div>
);
}
Div can cause semantics issue if working with table, list etc. To avoid this we can use React provided fragment as shown below β
import React, { Fragment } from βreactβ;
function MessageList({ message }) {
return (
<Fragment>
<dt>{ message.key }</dt>
<dd>{message.description}</dd>
</Fragment>
);
}
We can also use it with map a collection of items to an array of fragments β
function MessageList(props) {
return (
<dl>
{props.messages.map( message => (
// Fragments should also have a `key` prop when mapping collections
<Fragment key = { message.id}>
<dt>{message.from}</dt>
<dd>{message.To}</dd>
</Fragment>
))}
</dl>
);
}
The short syntax of fragment is writing just >>
import React, { Fragment } from βreactβ;
function MessageList({ message }) {
return (
<>
<dt>{ message.key }</dt>
<dd>{message.description}</dd>
</>
);
}
Instead of writing for attribute in label, we write it as htmlFor
<label htmlFor = "userID">Name:</label>
<input id = "userID" type = "text" name = "name"/>
Focus control with ref β
We can create ref as β
This.userInput = React.createRef();
getFocus() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.userInput.current.focus();
}
To work the ref through the higher order components, its needed to use forward ref. | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "The aria-* attributes on html elements are also supported in React.js as well. The other attributes are generally written in camel-case but these aria-* are written in hyphen-cased."
},
{
"code": null,
"e": 1401,
"s": 1244,
"text": "<input\n type = \"text\"\n aria-label = {labelText}\n aria-required = \"true\"\n onChange = {changeHandler}\n value = {inputValue}\n name = \"userInput\"\n/>"
},
{
"code": null,
"e": 1479,
"s": 1401,
"text": "Sometimes we break the semantics of the html if we use parent div in React.js"
},
{
"code": null,
"e": 1556,
"s": 1479,
"text": "render(){\n return(\n <div>\n <h1>Test</h1>\n </div>\n );\n}"
},
{
"code": null,
"e": 1685,
"s": 1556,
"text": "Div can cause semantics issue if working with table, list etc. To avoid this we can use React provided fragment as shown below β"
},
{
"code": null,
"e": 1891,
"s": 1685,
"text": "import React, { Fragment } from βreactβ;\nfunction MessageList({ message }) {\n return (\n <Fragment>\n <dt>{ message.key }</dt>\n <dd>{message.description}</dd>\n </Fragment>\n );\n}"
},
{
"code": null,
"e": 1968,
"s": 1891,
"text": "We can also use it with map a collection of items to an array of fragments β"
},
{
"code": null,
"e": 2320,
"s": 1968,
"text": "function MessageList(props) {\n return (\n <dl>\n {props.messages.map( message => (\n // Fragments should also have a `key` prop when mapping collections\n <Fragment key = { message.id}>\n <dt>{message.from}</dt>\n <dd>{message.To}</dd>\n </Fragment>\n ))}\n </dl>\n );\n}"
},
{
"code": null,
"e": 2368,
"s": 2320,
"text": "The short syntax of fragment is writing just >>"
},
{
"code": null,
"e": 2558,
"s": 2368,
"text": "import React, { Fragment } from βreactβ;\nfunction MessageList({ message }) {\n return (\n <>\n <dt>{ message.key }</dt>\n <dd>{message.description}</dd>\n </>\n );\n}"
},
{
"code": null,
"e": 2624,
"s": 2558,
"text": "Instead of writing for attribute in label, we write it as htmlFor"
},
{
"code": null,
"e": 2715,
"s": 2624,
"text": "<label htmlFor = \"userID\">Name:</label>\n<input id = \"userID\" type = \"text\" name = \"name\"/>"
},
{
"code": null,
"e": 2740,
"s": 2715,
"text": "Focus control with ref β"
},
{
"code": null,
"e": 2763,
"s": 2740,
"text": "We can create ref as β"
},
{
"code": null,
"e": 2967,
"s": 2763,
"text": "This.userInput = React.createRef();\ngetFocus() {\n // Explicitly focus the text input using the raw DOM API\n // Note: we're accessing \"current\" to get the DOM node\n this.userInput.current.focus();\n}"
},
{
"code": null,
"e": 3051,
"s": 2967,
"text": "To work the ref through the higher order components, its needed to use forward ref."
}
] |
Java program to count upper and lower case characters in a given string | In order to count upper and lower case character we have to first find weather a given character is in upper case or in lower case.For this we would take concept of ASCII value of each character in Java.
In Java as we know for each character has corresponding ASCII value so we would compare each character that it lies in the range of upper case or in lower case.In below example first convert string to a character array for easy transverse,then find weather it lies in upper case or lower case range also setted counter for upper case and lower case which get increased as character lies accordingly.
Live Demo
public class CountUpperLower {
public static void main(String[] args) {
String str1 = "AbRtt";
int upperCase = 0;
int lowerCase = 0;
char[] ch = str1.toCharArray();
for(char chh : ch) {
if(chh >='A' && chh <='Z') {
upperCase++;
} else if (chh >= 'a' && chh <= 'z') {
lowerCase++;
} else {
continue;
}
}
System.out.println("Count of Uppercase letter/s is/are " + upperCase + " and of Lowercase letter/s is/are " + lowerCase);
}
}
Count of Uppercase letter/s is/are 2 and of Lowercase letter/s is/are 3 | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "In order to count upper and lower case character we have to first find weather a given character is in upper case or in lower case.For this we would take concept of ASCII value of each character in Java."
},
{
"code": null,
"e": 1666,
"s": 1266,
"text": "In Java as we know for each character has corresponding ASCII value so we would compare each character that it lies in the range of upper case or in lower case.In below example first convert string to a character array for easy transverse,then find weather it lies in upper case or lower case range also setted counter for upper case and lower case which get increased as character lies accordingly."
},
{
"code": null,
"e": 1677,
"s": 1666,
"text": " Live Demo"
},
{
"code": null,
"e": 2232,
"s": 1677,
"text": "public class CountUpperLower {\n public static void main(String[] args) {\n String str1 = \"AbRtt\";\n int upperCase = 0;\n int lowerCase = 0;\n char[] ch = str1.toCharArray();\n for(char chh : ch) {\n if(chh >='A' && chh <='Z') {\n upperCase++;\n } else if (chh >= 'a' && chh <= 'z') {\n lowerCase++;\n } else {\n continue;\n }\n }\n System.out.println(\"Count of Uppercase letter/s is/are \" + upperCase + \" and of Lowercase letter/s is/are \" + lowerCase);\n }\n}"
},
{
"code": null,
"e": 2304,
"s": 2232,
"text": "Count of Uppercase letter/s is/are 2 and of Lowercase letter/s is/are 3"
}
] |
Shell Script To Check For a Valid Floating-Point Value - GeeksforGeeks | 20 Apr, 2021
User Input can be hectic to manage especially if itβs about numbers. Letβs say you wanted to perform mathematical calculations in your app or script. Itβs not hard to say that it will have to deal with floating-point numbers. Itβs easy in many statically typed programming languages but if it has to do in terminals then that can get quite annoying as shell scripting or bash doesnβt have any data types.
We have to deal without data types and make use of programming skills to actually make it work. Hopefully, we have regular expressions in Bash to deal with such problems. Regular Expressions or RegEx, in short, is an expression as the name suggests that can find certain patterns in a text field. It quite a powerful tool to have in a Programmerβs toolkit. So, letβs see how to solve the problem.
So letβs find a modular approach to the problem statement. We need to check whether the input variable is a decimal (floating-point) number or not. To do that we must have only digits in the variable and just a single decimal point. The decimal point can be anywhere, but it has to be only one. To check if only digits are present we can use Regular Expression and further we can also check for a decimal point from the second to the second-last character as a decimal point cannot be in the beginning and at the end. We can simply use conditional statements to verify these necessary conditions.
Firstly we will take the user input and store it in any preferable named variable.
We are using read to prompt the user for input. Along with the βreadβ command we will be using -p as an argument to the base βreadβ command for a prompt that displays the text such as enter the number or any preferable relevant information.
Now we need to check that the input is a number or not. This allows us to be sure for the next condition to be a floating-point value otherwise it will conflict with numbers and floating-point numbers.
Regular Expression allows us to find a pattern in the text or a variable. Here we are using n as an input variable. We use =~ to make bash aware that the coming expression is a RegEx. After that, we use ^ and $ for checking the pattern from start to end.
A number can have positive or negative signs so does a floating value and hence it is applied to both conditions. Anything between [ ] has to match with the input, in this case, we include 0-9 as any number can be in the input. We have added a β?β after the +- signs to make those optional i.e. itβs not mandatory to include + to indicate the numbers as positive. An * sign to repeat the previous expression zero times or more times as to include more digits furthermore. After a number is being identified we use β+β to include the following conditions to the preceding once or more times. The β\β in the floating-point condition is just behaving to turn as an ordinary character. We finally add β.β between β\β and β?β to merge the expressions and to make decimal optional, but it wonβt call a number as the condition is already satisfied by the previous if condition. Hence, we end the expression with the β$β sign and print the satisfied condition of the input being an integer, floating-point value, or any expression.
#!/bin/bash
# User Input
read -p "Enter the number : " n
# Check for a number
if [[ $n =~ ^[+-]?[0-9]+$ ]];then
echo "The Input is an integer."
# Check for a floating number
elif [[ $n =~ ^[+-]?[0-9]*\.?[0-9]+$ ]];then
echo "Input is a float "
else
echo "The input is not a number."
fi
Output:
ShellScript Output with many test-cases
By making a Shell Script using Regular Expression we verified a user input to be a floating-point number or not. The script doesnβt consider scientific notation as a floating-point value that also can be achieved but to keep it simple for simplistic use this is working accurately.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24041,
"s": 24013,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 24446,
"s": 24041,
"text": "User Input can be hectic to manage especially if itβs about numbers. Letβs say you wanted to perform mathematical calculations in your app or script. Itβs not hard to say that it will have to deal with floating-point numbers. Itβs easy in many statically typed programming languages but if it has to do in terminals then that can get quite annoying as shell scripting or bash doesnβt have any data types."
},
{
"code": null,
"e": 24843,
"s": 24446,
"text": "We have to deal without data types and make use of programming skills to actually make it work. Hopefully, we have regular expressions in Bash to deal with such problems. Regular Expressions or RegEx, in short, is an expression as the name suggests that can find certain patterns in a text field. It quite a powerful tool to have in a Programmerβs toolkit. So, letβs see how to solve the problem."
},
{
"code": null,
"e": 25442,
"s": 24843,
"text": "So letβs find a modular approach to the problem statement. We need to check whether the input variable is a decimal (floating-point) number or not. To do that we must have only digits in the variable and just a single decimal point. The decimal point can be anywhere, but it has to be only one. To check if only digits are present we can use Regular Expression and further we can also check for a decimal point from the second to the second-last character as a decimal point cannot be in the beginning and at the end. We can simply use conditional statements to verify these necessary conditions. "
},
{
"code": null,
"e": 25526,
"s": 25442,
"text": "Firstly we will take the user input and store it in any preferable named variable. "
},
{
"code": null,
"e": 25767,
"s": 25526,
"text": "We are using read to prompt the user for input. Along with the βreadβ command we will be using -p as an argument to the base βreadβ command for a prompt that displays the text such as enter the number or any preferable relevant information."
},
{
"code": null,
"e": 25969,
"s": 25767,
"text": "Now we need to check that the input is a number or not. This allows us to be sure for the next condition to be a floating-point value otherwise it will conflict with numbers and floating-point numbers."
},
{
"code": null,
"e": 26224,
"s": 25969,
"text": "Regular Expression allows us to find a pattern in the text or a variable. Here we are using n as an input variable. We use =~ to make bash aware that the coming expression is a RegEx. After that, we use ^ and $ for checking the pattern from start to end."
},
{
"code": null,
"e": 27249,
"s": 26224,
"text": "A number can have positive or negative signs so does a floating value and hence it is applied to both conditions. Anything between [ ] has to match with the input, in this case, we include 0-9 as any number can be in the input. We have added a β?β after the +- signs to make those optional i.e. itβs not mandatory to include + to indicate the numbers as positive. An * sign to repeat the previous expression zero times or more times as to include more digits furthermore. After a number is being identified we use β+β to include the following conditions to the preceding once or more times. The β\\β in the floating-point condition is just behaving to turn as an ordinary character. We finally add β.β between β\\β and β?β to merge the expressions and to make decimal optional, but it wonβt call a number as the condition is already satisfied by the previous if condition. Hence, we end the expression with the β$β sign and print the satisfied condition of the input being an integer, floating-point value, or any expression."
},
{
"code": null,
"e": 27540,
"s": 27249,
"text": "#!/bin/bash\n\n# User Input\nread -p \"Enter the number : \" n\n\n\n# Check for a number\nif [[ $n =~ ^[+-]?[0-9]+$ ]];then\necho \"The Input is an integer.\"\n\n\n# Check for a floating number\nelif [[ $n =~ ^[+-]?[0-9]*\\.?[0-9]+$ ]];then\necho \"Input is a float \"\nelse\necho \"The input is not a number.\"\nfi"
},
{
"code": null,
"e": 27548,
"s": 27540,
"text": "Output:"
},
{
"code": null,
"e": 27588,
"s": 27548,
"text": "ShellScript Output with many test-cases"
},
{
"code": null,
"e": 27871,
"s": 27588,
"text": "By making a Shell Script using Regular Expression we verified a user input to be a floating-point number or not. The script doesnβt consider scientific notation as a floating-point value that also can be achieved but to keep it simple for simplistic use this is working accurately. "
},
{
"code": null,
"e": 27878,
"s": 27871,
"text": "Picked"
},
{
"code": null,
"e": 27891,
"s": 27878,
"text": "Shell Script"
},
{
"code": null,
"e": 27902,
"s": 27891,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28000,
"s": 27902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28009,
"s": 28000,
"text": "Comments"
},
{
"code": null,
"e": 28022,
"s": 28009,
"text": "Old Comments"
},
{
"code": null,
"e": 28048,
"s": 28022,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28085,
"s": 28048,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28119,
"s": 28085,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28154,
"s": 28119,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28180,
"s": 28154,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28217,
"s": 28180,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28257,
"s": 28217,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 28286,
"s": 28257,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28328,
"s": 28286,
"text": "Named Pipe or FIFO with example C program"
}
] |
What is COBOL host variable equivalent for various DB2 data types? | Problem: How will the COBOL-DB2 program behave when there is a mismatch between the host variable and number of columns in the SELECT statement?
In case there is a mismatch in the number of columns and number of host variables, the query will fail. For example, if we have used the below query in a COBOL-DB2 program which processes the ORDERS DB2 table.
EXEC SQL
SELECT ORDER_ID,
ORDER_AMOUNT,
ORDER_DATE,
ORDER_STATUS
INTO :WS-ORDER-ID,
:WS-ORDER-AMOUNT,
:WS-ORDER-DATE,
FROM ORDERS WHERE ORDER_DATE = β2020-09-15β
END-EXEC
There is a mismatch in the number of columns and host variables. There are a total 4 columns used in the SELECT statement and for them only 3 host variables are used. In this case the query will fail and there are two ways in which we can detect this condition.
The SQLWARN3 field of SQLCA will get the value as βWβ in case there is a mismatch.
In some installations the SQLCODE field for SQLCA gets the error code as -804 when there is a mismatch.
We can use IF condition to check the value in SQLWARN3 or SQLCODE and direct the program processing accordingly.
Following is an example.
IF SQLWARN3 = βWβ
PERFORM X00-ABEND-SECTION
ELSE
PERFORM A100-SELECT-RESULT
END-IF | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "Problem: How will the COBOL-DB2 program behave when there is a mismatch between the host variable and number of columns in the SELECT statement?"
},
{
"code": null,
"e": 1417,
"s": 1207,
"text": "In case there is a mismatch in the number of columns and number of host variables, the query will fail. For example, if we have used the below query in a COBOL-DB2 program which processes the ORDERS DB2 table."
},
{
"code": null,
"e": 1627,
"s": 1417,
"text": "EXEC SQL\n SELECT ORDER_ID,\n ORDER_AMOUNT,\n ORDER_DATE,\n ORDER_STATUS\n INTO :WS-ORDER-ID,\n :WS-ORDER-AMOUNT,\n :WS-ORDER-DATE,\n FROM ORDERS WHERE ORDER_DATE = β2020-09-15β\nEND-EXEC"
},
{
"code": null,
"e": 1889,
"s": 1627,
"text": "There is a mismatch in the number of columns and host variables. There are a total 4 columns used in the SELECT statement and for them only 3 host variables are used. In this case the query will fail and there are two ways in which we can detect this condition."
},
{
"code": null,
"e": 1972,
"s": 1889,
"text": "The SQLWARN3 field of SQLCA will get the value as βWβ in case there is a mismatch."
},
{
"code": null,
"e": 2076,
"s": 1972,
"text": "In some installations the SQLCODE field for SQLCA gets the error code as -804 when there is a mismatch."
},
{
"code": null,
"e": 2189,
"s": 2076,
"text": "We can use IF condition to check the value in SQLWARN3 or SQLCODE and direct the program processing accordingly."
},
{
"code": null,
"e": 2214,
"s": 2189,
"text": "Following is an example."
},
{
"code": null,
"e": 2303,
"s": 2214,
"text": "IF SQLWARN3 = βWβ\n PERFORM X00-ABEND-SECTION\nELSE\n PERFORM A100-SELECT-RESULT\nEND-IF"
}
] |
Graphs and ML: Multiple Linear Regression | by Lauren Shin | Towards Data Science | Last time, I used simple linear regression from the Neo4j browser to create a model for short-term rentals in Austin, TX. In this post, I demonstrate how, with a few small tweaks, the same set of user-defined procedures can create a linear regression model with multiple independent variables. This is referred to as multiple linear regression.
We previously used a short-term rental listingβs total number of rooms to predict its price per night. However, there are obviously other factors unaccounted for that might influence price. For example, a listingβs proximity to popular tourist areas may greatly impact its value. Letβs take another look at Willβs data model to consider what additional information might be used to predict rental price.
Since weβre not given an address, it would be difficult to analyze a listingβs location relative to the most popular destinations in Austin. Instead, consider the (:Review)-[:REVIEWS]->(:Listing) relationship. In my previous post, I restricted my data set to only include listings that had at least one review. I did this to eliminate listings new to the market with potentially unreliable pricing, and it greatly improved the fit of my model. Now, letβs go a bit deeper and use a listingβs number of reviews in addition to its number of rooms to predict nightly price.
Note, I am just playing around and do not really have statistical justification for assuming that number of reviews influences listing price. I mainly did this to demonstrate how to create a model with multiple independent variables. It would be interesting to next analyze the reviewβs comments and somehow quantify the textβs positive/negative feedback.
Before we dive back into the Austin rental market, I will review the important details of multiple linear regression. Remember that in simple linear regression, we wish to predict the value of the dependent variable, βyβ using the value of a single independent variable, βxβ. The difference is that in multiple linear regression, we use multiple independent variables (x1, x2, ..., xp) to predict y instead of just one.
Visual understanding of multiple linear regression is a bit more complex and depends on the number of independent variables (p). If p = 1, this is just an instance of simple linear regression and the (x1, y) data points lie on a standard 2-D coordinate system (with an x and y-axis). Linear regression finds the line through the points that best βfitsβ the data.
If p = 2, these (x1, x2, y) data points lie in a 3-D coordinate system (with x, y, and z axes) and multiple linear regression finds the plane that best fits the data points.
For greater numbers of independent variables, visual understanding is more abstract. For p independent variables, the data points (x1, x2, x3 ..., xp, y) exist in a p + 1 -dimensional space. What really matters is that the linear model (which is p -dimensional) can be represented by the p + 1 coefficients Ξ²0, Ξ²1, ..., Ξ²p so that y is approximated by the equation y = Ξ²0 + Ξ²1*x1 + Ξ²2*x2 + ... + Ξ²p*xp.
There are two types of multiple linear regression: ordinary least squares (OLS) and generalized least squares (GLS). The main difference between the two is that OLS assumes there is not a strong correlation between any two independent variables. GLS deals with correlated independent variables by transforming the data and then using OLS to build the model with transformed data.
These procedures use the method of OLS. Therefore, to build a successful model you should first think through the relationships between your variables. It might not be a good idea to include bedrooms and accommodates as two separate independent variables, because itβs likely that number of bedrooms and number of guests accommodated have a strong positive correlation. On the other hand, there is no clear logical relationship between number of reviews and number of rooms. For a more quantitative analysis, pick independent variables so that each pair has a Pearson correlation coefficient near zero (see below).
Alright, letβs go through a set of queries that build a multiple linear regression model in Neo4j.
Download and install the jar-file from the latest linear regression release. Run :play http://guides.neo4j.com/listings from the Neo4j browser and follow the import queries in order to create Willβs short term rental listing graph. Refer to my previous post for a more thorough guide to installing the linear regression procedures and importing the Austin rental data set.
Once you have the data set imported and procedures installed, we split the data set into a 75:25 (training:testing) sample. Letβs build from the final model from last time and again only consider listings with at least one review. Label 75% with :Train.
MATCH (list:Listing)-[:IN_NEIGHBORHOOD]->(:Neighborhood {neighborhood_id:'78704'}) WHERE exists(list.bedrooms) AND exists(list.bathrooms) AND exists(list.price) AND (:Review)-[:REVIEWS]->(list)WITH regression.linear.split(collect(id(list)), 0.75) AS trainingIDsMATCH (list:Listing) WHERE id(list) in trainingIDs SET list:Train
And add the :Test label to the remaining 25%.
MATCH (list:Listing)-[n:IN_NEIGHBORHOOD]->(hood:Neighborhood {neighborhood_id:'78704'})WHERE exists(list.bedrooms) AND exists(list.bathrooms) AND exists(list.price) AND (:Review)-[:REVIEWS]->(list) AND NOT list:Train SET list:Test
If youβd like to know the Pearson correlation between the independent variables, use the function regression.linear.correlation(List<Double> first, List<Double> second). One of the List<Double> inputs to this function contains aggregated βnumber of reviewsβ data from many listings, and each βnumber of reviewsβ is calculated by aggregating relationships from each listing. We cannot perform two levels of aggregation (collect(count(r))) in the same query. Therefore, we must perform two queries.
First store a num_reviews property on the data set listings.
MATCH (:Review)-[r:REVIEWS]->(list) WHERE list:Train OR list:TestWITH list, count(r) AS num_reviewsSET list.num_reviews = num_reviews
Then collect (num_reviews, rooms) data from all listings and calculate correlation.
MATCH (list) WHERE list:Test OR list:TrainWITH collect(list.num_reviews) as reviews, collect(list.bedrooms + list.bathrooms) as roomsRETURN regression.linear.correlation(reviews, rooms)
Pearsonβs correlation coefficients are in the range [-1, 1], with 0 meaning no correlation, 1 perfect positive correlation, and -1 perfect negative correlation. The number of reviews and number of rooms have a correlation -0.125, which indicates a very weak negative correlation. OLS is an acceptable method for this small correlation, so we can move forward with the model. Read more about interpreting correlation coefficients.
We call the same create procedure but now our model framework is 'Multiple' instead of 'Simple' and the number of independent variables is 2 instead of 1.
CALL regression.linear.create( 'mlr rental prices', 'Multiple', true, 2)
Add known data in the same format as with simple linear regression. Just add another entry (number of reviews) to the list of independent variables.
MATCH (list:Train)WHERE NOT list:Seen CALL regression.linear.add( 'mlr rental prices', [list.bedrooms + list.bathrooms, list.num_reviews], list.price) SET list:Seen RETURN count(list)
We must train the model so that line parameters (Ξ²i), coefficient of determination (R2), etc. are calculated before accepting testing data or making predictions. If you forget this step and then try to add testing data or make predictions, your model will automatically be trained first.
CALL regression.linear.train('mlr rental prices')
Note, you can still add more training data after calling the train procedure. You just need to make another call to train before testing the new model!
Analyze the modelβs performance on unseen data. Remember that when you add test data, an additional parameter 'test' is required as input to the procedure regression.linear.add.
MATCH (list:Test) WHERE NOT list:SeenCALL regression.linear.add( 'mlr rental prices', [list.bedrooms + list.bathrooms, list.num_reviews], list.price, 'test') SET list:Seen RETURN count(list)
Now that all the testing data is added, call the test procedure to calculate measurements (in testInfo below) that allow us to analyze the modelβs performance.
CALL regression.linear.test('mlr rental prices')
You can also return information about the model at any time with a call to the info procedure.
CALL regression.linear.info('mlr rental prices')
Letβs look at adjusted R2. This value is similar to the R2 we considered in my last post, but it is adjusted so that, as independent variables are added to the model, adjusted R2 does not increase unless the model is improved more than it would by chance. Therefore, when comparing our multiple linear regression model (with two independent variables) to the prior model (with just one independent variable), adjusted R2 is a better measurement of success.
We typically look for R2 values greater than 0.6, but values closer to 1 indicate a better linear fit. Here, training adjusted R2 = 0.517 and testing adjusted R2 = 0.556. Last time, our R2 values were 0.500 and 0.559 for training and testing respectively. The model created with multiple linear regression performs a little bit better than the simple regression model from last time on training data, and about the same on testing data. Can you find better independent variables and improve my work?
At Neo4j, my colleagues and I are currently facing the question: Where do machine learning and artificial intelligence fit in with graph databases? There are several answers to this question, none of them the βrightβ answer. In my previous post, I demonstrated how a simple machine learning model can be built on data in the graph in order to avoid exporting to another software. In this post, another interesting aspect emerged: the ability to build models with data stored inherently in the graphβs structure. We were able to easily retrieve βnumber of reviewsβ data by counting the number of (:Review)-[:REVIEWS]->(:Listing) relationships on each listing. In this regard, graph databases increase the types of data we can easily access in order to build machine learning models.
Going forward, I would love to explore how machine learning models can more effectively utilize the graph structure of the data set to learn and make predictions.
Hereβs a quick list of the tweaks you must make to use the regression.linear.* procedures for multiple linear regression:
Specify model type βMultipleβ during regression.linear.create
Specify number of independent variables during regression.linear.create
No regression.linear.remove method for testing or training data
You cannot copy training data form one model to another with regression.linear.copy
You should train the model with a call to regression.linear.train before testing, analyzing, or predicting
Look at adjusted R2 to more accurately compare models with different numbers of independent variables
regression.linear.data returns the modelβs parameters, not its byte[] serialization. Therefore, you cannot use regression.linear.load. (I would like to fix this)
This project is experimental, so I really appreciate any feedback. Checkout the procedure repository and reach out on LinkedIn or @ML_auren.
Itβs time for me to move away from this linearly modeled world, and onto classifiers built with logistic regression. Stay tuned for a new set of procedures and a new data set! | [
{
"code": null,
"e": 517,
"s": 172,
"text": "Last time, I used simple linear regression from the Neo4j browser to create a model for short-term rentals in Austin, TX. In this post, I demonstrate how, with a few small tweaks, the same set of user-defined procedures can create a linear regression model with multiple independent variables. This is referred to as multiple linear regression."
},
{
"code": null,
"e": 921,
"s": 517,
"text": "We previously used a short-term rental listingβs total number of rooms to predict its price per night. However, there are obviously other factors unaccounted for that might influence price. For example, a listingβs proximity to popular tourist areas may greatly impact its value. Letβs take another look at Willβs data model to consider what additional information might be used to predict rental price."
},
{
"code": null,
"e": 1491,
"s": 921,
"text": "Since weβre not given an address, it would be difficult to analyze a listingβs location relative to the most popular destinations in Austin. Instead, consider the (:Review)-[:REVIEWS]->(:Listing) relationship. In my previous post, I restricted my data set to only include listings that had at least one review. I did this to eliminate listings new to the market with potentially unreliable pricing, and it greatly improved the fit of my model. Now, letβs go a bit deeper and use a listingβs number of reviews in addition to its number of rooms to predict nightly price."
},
{
"code": null,
"e": 1847,
"s": 1491,
"text": "Note, I am just playing around and do not really have statistical justification for assuming that number of reviews influences listing price. I mainly did this to demonstrate how to create a model with multiple independent variables. It would be interesting to next analyze the reviewβs comments and somehow quantify the textβs positive/negative feedback."
},
{
"code": null,
"e": 2267,
"s": 1847,
"text": "Before we dive back into the Austin rental market, I will review the important details of multiple linear regression. Remember that in simple linear regression, we wish to predict the value of the dependent variable, βyβ using the value of a single independent variable, βxβ. The difference is that in multiple linear regression, we use multiple independent variables (x1, x2, ..., xp) to predict y instead of just one."
},
{
"code": null,
"e": 2630,
"s": 2267,
"text": "Visual understanding of multiple linear regression is a bit more complex and depends on the number of independent variables (p). If p = 1, this is just an instance of simple linear regression and the (x1, y) data points lie on a standard 2-D coordinate system (with an x and y-axis). Linear regression finds the line through the points that best βfitsβ the data."
},
{
"code": null,
"e": 2804,
"s": 2630,
"text": "If p = 2, these (x1, x2, y) data points lie in a 3-D coordinate system (with x, y, and z axes) and multiple linear regression finds the plane that best fits the data points."
},
{
"code": null,
"e": 3207,
"s": 2804,
"text": "For greater numbers of independent variables, visual understanding is more abstract. For p independent variables, the data points (x1, x2, x3 ..., xp, y) exist in a p + 1 -dimensional space. What really matters is that the linear model (which is p -dimensional) can be represented by the p + 1 coefficients Ξ²0, Ξ²1, ..., Ξ²p so that y is approximated by the equation y = Ξ²0 + Ξ²1*x1 + Ξ²2*x2 + ... + Ξ²p*xp."
},
{
"code": null,
"e": 3587,
"s": 3207,
"text": "There are two types of multiple linear regression: ordinary least squares (OLS) and generalized least squares (GLS). The main difference between the two is that OLS assumes there is not a strong correlation between any two independent variables. GLS deals with correlated independent variables by transforming the data and then using OLS to build the model with transformed data."
},
{
"code": null,
"e": 4202,
"s": 3587,
"text": "These procedures use the method of OLS. Therefore, to build a successful model you should first think through the relationships between your variables. It might not be a good idea to include bedrooms and accommodates as two separate independent variables, because itβs likely that number of bedrooms and number of guests accommodated have a strong positive correlation. On the other hand, there is no clear logical relationship between number of reviews and number of rooms. For a more quantitative analysis, pick independent variables so that each pair has a Pearson correlation coefficient near zero (see below)."
},
{
"code": null,
"e": 4301,
"s": 4202,
"text": "Alright, letβs go through a set of queries that build a multiple linear regression model in Neo4j."
},
{
"code": null,
"e": 4674,
"s": 4301,
"text": "Download and install the jar-file from the latest linear regression release. Run :play http://guides.neo4j.com/listings from the Neo4j browser and follow the import queries in order to create Willβs short term rental listing graph. Refer to my previous post for a more thorough guide to installing the linear regression procedures and importing the Austin rental data set."
},
{
"code": null,
"e": 4928,
"s": 4674,
"text": "Once you have the data set imported and procedures installed, we split the data set into a 75:25 (training:testing) sample. Letβs build from the final model from last time and again only consider listings with at least one review. Label 75% with :Train."
},
{
"code": null,
"e": 5260,
"s": 4928,
"text": "MATCH (list:Listing)-[:IN_NEIGHBORHOOD]->(:Neighborhood {neighborhood_id:'78704'}) WHERE exists(list.bedrooms) AND exists(list.bathrooms) AND exists(list.price) AND (:Review)-[:REVIEWS]->(list)WITH regression.linear.split(collect(id(list)), 0.75) AS trainingIDsMATCH (list:Listing) WHERE id(list) in trainingIDs SET list:Train"
},
{
"code": null,
"e": 5306,
"s": 5260,
"text": "And add the :Test label to the remaining 25%."
},
{
"code": null,
"e": 5544,
"s": 5306,
"text": "MATCH (list:Listing)-[n:IN_NEIGHBORHOOD]->(hood:Neighborhood {neighborhood_id:'78704'})WHERE exists(list.bedrooms) AND exists(list.bathrooms) AND exists(list.price) AND (:Review)-[:REVIEWS]->(list) AND NOT list:Train SET list:Test"
},
{
"code": null,
"e": 6041,
"s": 5544,
"text": "If youβd like to know the Pearson correlation between the independent variables, use the function regression.linear.correlation(List<Double> first, List<Double> second). One of the List<Double> inputs to this function contains aggregated βnumber of reviewsβ data from many listings, and each βnumber of reviewsβ is calculated by aggregating relationships from each listing. We cannot perform two levels of aggregation (collect(count(r))) in the same query. Therefore, we must perform two queries."
},
{
"code": null,
"e": 6102,
"s": 6041,
"text": "First store a num_reviews property on the data set listings."
},
{
"code": null,
"e": 6236,
"s": 6102,
"text": "MATCH (:Review)-[r:REVIEWS]->(list) WHERE list:Train OR list:TestWITH list, count(r) AS num_reviewsSET list.num_reviews = num_reviews"
},
{
"code": null,
"e": 6320,
"s": 6236,
"text": "Then collect (num_reviews, rooms) data from all listings and calculate correlation."
},
{
"code": null,
"e": 6511,
"s": 6320,
"text": "MATCH (list) WHERE list:Test OR list:TrainWITH collect(list.num_reviews) as reviews, collect(list.bedrooms + list.bathrooms) as roomsRETURN regression.linear.correlation(reviews, rooms)"
},
{
"code": null,
"e": 6941,
"s": 6511,
"text": "Pearsonβs correlation coefficients are in the range [-1, 1], with 0 meaning no correlation, 1 perfect positive correlation, and -1 perfect negative correlation. The number of reviews and number of rooms have a correlation -0.125, which indicates a very weak negative correlation. OLS is an acceptable method for this small correlation, so we can move forward with the model. Read more about interpreting correlation coefficients."
},
{
"code": null,
"e": 7096,
"s": 6941,
"text": "We call the same create procedure but now our model framework is 'Multiple' instead of 'Simple' and the number of independent variables is 2 instead of 1."
},
{
"code": null,
"e": 7178,
"s": 7096,
"text": "CALL regression.linear.create( 'mlr rental prices', 'Multiple', true, 2)"
},
{
"code": null,
"e": 7327,
"s": 7178,
"text": "Add known data in the same format as with simple linear regression. Just add another entry (number of reviews) to the list of independent variables."
},
{
"code": null,
"e": 7540,
"s": 7327,
"text": "MATCH (list:Train)WHERE NOT list:Seen CALL regression.linear.add( 'mlr rental prices', [list.bedrooms + list.bathrooms, list.num_reviews], list.price) SET list:Seen RETURN count(list)"
},
{
"code": null,
"e": 7828,
"s": 7540,
"text": "We must train the model so that line parameters (Ξ²i), coefficient of determination (R2), etc. are calculated before accepting testing data or making predictions. If you forget this step and then try to add testing data or make predictions, your model will automatically be trained first."
},
{
"code": null,
"e": 7878,
"s": 7828,
"text": "CALL regression.linear.train('mlr rental prices')"
},
{
"code": null,
"e": 8030,
"s": 7878,
"text": "Note, you can still add more training data after calling the train procedure. You just need to make another call to train before testing the new model!"
},
{
"code": null,
"e": 8208,
"s": 8030,
"text": "Analyze the modelβs performance on unseen data. Remember that when you add test data, an additional parameter 'test' is required as input to the procedure regression.linear.add."
},
{
"code": null,
"e": 8438,
"s": 8208,
"text": "MATCH (list:Test) WHERE NOT list:SeenCALL regression.linear.add( 'mlr rental prices', [list.bedrooms + list.bathrooms, list.num_reviews], list.price, 'test') SET list:Seen RETURN count(list)"
},
{
"code": null,
"e": 8598,
"s": 8438,
"text": "Now that all the testing data is added, call the test procedure to calculate measurements (in testInfo below) that allow us to analyze the modelβs performance."
},
{
"code": null,
"e": 8647,
"s": 8598,
"text": "CALL regression.linear.test('mlr rental prices')"
},
{
"code": null,
"e": 8742,
"s": 8647,
"text": "You can also return information about the model at any time with a call to the info procedure."
},
{
"code": null,
"e": 8792,
"s": 8742,
"text": "CALL regression.linear.info('mlr rental prices') "
},
{
"code": null,
"e": 9249,
"s": 8792,
"text": "Letβs look at adjusted R2. This value is similar to the R2 we considered in my last post, but it is adjusted so that, as independent variables are added to the model, adjusted R2 does not increase unless the model is improved more than it would by chance. Therefore, when comparing our multiple linear regression model (with two independent variables) to the prior model (with just one independent variable), adjusted R2 is a better measurement of success."
},
{
"code": null,
"e": 9749,
"s": 9249,
"text": "We typically look for R2 values greater than 0.6, but values closer to 1 indicate a better linear fit. Here, training adjusted R2 = 0.517 and testing adjusted R2 = 0.556. Last time, our R2 values were 0.500 and 0.559 for training and testing respectively. The model created with multiple linear regression performs a little bit better than the simple regression model from last time on training data, and about the same on testing data. Can you find better independent variables and improve my work?"
},
{
"code": null,
"e": 10531,
"s": 9749,
"text": "At Neo4j, my colleagues and I are currently facing the question: Where do machine learning and artificial intelligence fit in with graph databases? There are several answers to this question, none of them the βrightβ answer. In my previous post, I demonstrated how a simple machine learning model can be built on data in the graph in order to avoid exporting to another software. In this post, another interesting aspect emerged: the ability to build models with data stored inherently in the graphβs structure. We were able to easily retrieve βnumber of reviewsβ data by counting the number of (:Review)-[:REVIEWS]->(:Listing) relationships on each listing. In this regard, graph databases increase the types of data we can easily access in order to build machine learning models."
},
{
"code": null,
"e": 10694,
"s": 10531,
"text": "Going forward, I would love to explore how machine learning models can more effectively utilize the graph structure of the data set to learn and make predictions."
},
{
"code": null,
"e": 10816,
"s": 10694,
"text": "Hereβs a quick list of the tweaks you must make to use the regression.linear.* procedures for multiple linear regression:"
},
{
"code": null,
"e": 10878,
"s": 10816,
"text": "Specify model type βMultipleβ during regression.linear.create"
},
{
"code": null,
"e": 10950,
"s": 10878,
"text": "Specify number of independent variables during regression.linear.create"
},
{
"code": null,
"e": 11014,
"s": 10950,
"text": "No regression.linear.remove method for testing or training data"
},
{
"code": null,
"e": 11098,
"s": 11014,
"text": "You cannot copy training data form one model to another with regression.linear.copy"
},
{
"code": null,
"e": 11205,
"s": 11098,
"text": "You should train the model with a call to regression.linear.train before testing, analyzing, or predicting"
},
{
"code": null,
"e": 11307,
"s": 11205,
"text": "Look at adjusted R2 to more accurately compare models with different numbers of independent variables"
},
{
"code": null,
"e": 11469,
"s": 11307,
"text": "regression.linear.data returns the modelβs parameters, not its byte[] serialization. Therefore, you cannot use regression.linear.load. (I would like to fix this)"
},
{
"code": null,
"e": 11610,
"s": 11469,
"text": "This project is experimental, so I really appreciate any feedback. Checkout the procedure repository and reach out on LinkedIn or @ML_auren."
}
] |
JavaScript Date setHours() Method | Javascript date setHours() method sets the hours for a specified date according to local time.
Its syntax is as follows β
Date.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
Note β Parameters in the bracket are always optional.
hoursValue β An integer between 0 and 23, representing the hour.
hoursValue β An integer between 0 and 23, representing the hour.
minutesValue β An integer between 0 and 59, representing the minutes.
minutesValue β An integer between 0 and 59, representing the minutes.
secondsValue β An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue.
secondsValue β An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue.
msValue β A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
msValue β A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the values returned from the getUTCMinutes, getUTCSeconds, and getMilliseconds methods are used.
Try the following example.
<html>
<head>
<title>JavaScript setHours Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setHours( 02 );
document.write( dt );
</script>
</body>
</html>
Thu Aug 28 2008 02:30:00 GMT+0530 (India Standard Time)
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2561,
"s": 2466,
"text": "Javascript date setHours() method sets the hours for a specified date according to local time."
},
{
"code": null,
"e": 2588,
"s": 2561,
"text": "Its syntax is as follows β"
},
{
"code": null,
"e": 2658,
"s": 2588,
"text": "Date.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])\n"
},
{
"code": null,
"e": 2712,
"s": 2658,
"text": "Note β Parameters in the bracket are always optional."
},
{
"code": null,
"e": 2777,
"s": 2712,
"text": "hoursValue β An integer between 0 and 23, representing the hour."
},
{
"code": null,
"e": 2842,
"s": 2777,
"text": "hoursValue β An integer between 0 and 23, representing the hour."
},
{
"code": null,
"e": 2912,
"s": 2842,
"text": "minutesValue β An integer between 0 and 59, representing the minutes."
},
{
"code": null,
"e": 2982,
"s": 2912,
"text": "minutesValue β An integer between 0 and 59, representing the minutes."
},
{
"code": null,
"e": 3135,
"s": 2982,
"text": "secondsValue β An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue."
},
{
"code": null,
"e": 3288,
"s": 3135,
"text": "secondsValue β An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue."
},
{
"code": null,
"e": 3452,
"s": 3288,
"text": "msValue β A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue."
},
{
"code": null,
"e": 3616,
"s": 3452,
"text": "msValue β A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue."
},
{
"code": null,
"e": 3791,
"s": 3616,
"text": "If you do not specify the minutesValue, secondsValue, and msValue parameters, the values returned from the getUTCMinutes, getUTCSeconds, and getMilliseconds methods are used."
},
{
"code": null,
"e": 3818,
"s": 3791,
"text": "Try the following example."
},
{
"code": null,
"e": 4098,
"s": 3818,
"text": "<html>\n <head>\n <title>JavaScript setHours Method</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n var dt = new Date( \"Aug 28, 2008 23:30:00\" );\n dt.setHours( 02 );\n document.write( dt ); \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4156,
"s": 4098,
"text": "Thu Aug 28 2008 02:30:00 GMT+0530 (India Standard Time) \n"
},
{
"code": null,
"e": 4191,
"s": 4156,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4205,
"s": 4191,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4239,
"s": 4205,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4253,
"s": 4239,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4288,
"s": 4253,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4305,
"s": 4288,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4340,
"s": 4305,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4357,
"s": 4340,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4390,
"s": 4357,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4418,
"s": 4390,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4452,
"s": 4418,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 4480,
"s": 4452,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4487,
"s": 4480,
"text": " Print"
},
{
"code": null,
"e": 4498,
"s": 4487,
"text": " Add Notes"
}
] |
How to pass optional parameters to a function in Python? - GeeksforGeeks | 04 Sep, 2021
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified.
In this way, the user can call the function by either passing those optional parameters or just passing the required parameters.
There are two main ways to pass optional parameters in python
Without using keyword arguments.
By using keyword arguments.
Some main point to be taken care while passing without using keyword arguments is :
The order of parameters should be maintained i.e. the order in which parameters are defined in function should be maintained while calling the function.
The values for the non-optional parameters should be passed otherwise it will throw an error.
The value of the default arguments can be either passed or ignored.
Below are some codes which explain this concept.
Example 1:
Python3
# Here b is predefined and hence is optional.
def func(a, b=1098):
return a+b
print(func(2, 2))
# this 1 is represented as 'a' in the function and
# function uses the default value of b
print(func(1))
Output:
4
1099
Example 2: we can also pass strings.
Python3
# Here string2 is the default string used
def fun2(string1, string2="Geeks"):
print(string1 + string2)
# calling the function using default value
fun2('GeeksFor')
# calling without default value.
fun2('GeeksFor', "Geeks")
Output:
GeeksForGeeks
GeeksForGeeks
When functions are defined then the parameters are written in the form βdatatype keyword-nameβ. So python provides a mechanism to call the function using the keyword name for passing the values. This helps the programmer by relieving them not to learn the sequence or the order in which the parameters are to be passed.
Some important points we need to remember are as follows:
In this case, we are not required to maintain the order of passing the values.
There should be no difference between the passed and declared keyword names.
Below is the code for its implementation.
Python3
# Here string2 is the default string used
def fun2(string1, string2="Geeks"):
print(string1 + string2)
# Thiscan be a way where no order is needed.
fun2(string2='GeeksFor', string1="Geeks")
# since we are not mentioning the non-default argument
# so it will give error.
fun2(string2='GeeksFor')
Output:
As we can see that we donβt require any order to be maintained in the above example. Also, we can see that when we try to pass only the optional parameters then it raises an error. This happens since optional parameters can be omitted as they have a default with them, but we cannot omit required parameters (string1 in the above case.) Hence, it shows an error with the flag: βmissing 1 required argumentβ.
This example will give a more insight idea of above topic:
Python3
def func(a, b, c='geeks'):
print(a, "type is", type(a))
print(b, "type is", type(b))
print(c, "type is", type(c))
# The optional parameters will not decide
# the type of parameter passed.
# also the order is maintained
print("first call")
func(2, 'z', 2.0)
# below call uses the default
# mentioned value of c
print("second call")
func(2, 1)
# The below call (in comments) will give an error
# since other required parameter is not passed.
# func('a')
print("third call")
func(c=2, b=3, a='geeks')
Output:
first call
2 type is <class 'int'>
z type is <class 'str'>
2.0 type is <class 'float'>
second call
2 type is <class 'int'>
1 type is <class 'int'>
geeks type is <class 'str'>
third call
geeks type is <class 'str'>
3 type is <class 'int'>
2 type is <class 'int'>
So basically python functional calls checks only if the required number of functional parameters are passed or not.
Below shows the case where a user tries to pass arguments in both ways discussed above along with the precaution given:
Python3
def comp(a, b=2):
if(a < b):
print("first parameter is smaller")
if(a > b):
print("second parameter is smaller")
if(a == b):
print("both are of equal value.")
print("first call")
comp(1)
print("second call")
comp(2, 1)
print("third call")
comp(b=1, a=-1)
print("fourth call")
comp(-1, b=0)
Output:
first call
first parameter is smaller
second call
second parameter is smaller
third call
first parameter is smaller
fourth call
first parameter is smaller
So one thing we should remember that the keyword argument should used after all positional arguments are passed. Hence this is an important thing we must keep in mind while passing parameters in both ways to same function.
saeedy2007
simmytarika5
Picked
Python-Functions
Technical Scripter 2020
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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24364,
"s": 24333,
"text": " \n04 Sep, 2021\n"
},
{
"code": null,
"e": 24621,
"s": 24364,
"text": "In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified."
},
{
"code": null,
"e": 24751,
"s": 24621,
"text": "In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. "
},
{
"code": null,
"e": 24814,
"s": 24751,
"text": "There are two main ways to pass optional parameters in python "
},
{
"code": null,
"e": 24847,
"s": 24814,
"text": "Without using keyword arguments."
},
{
"code": null,
"e": 24875,
"s": 24847,
"text": "By using keyword arguments."
},
{
"code": null,
"e": 24959,
"s": 24875,
"text": "Some main point to be taken care while passing without using keyword arguments is :"
},
{
"code": null,
"e": 25112,
"s": 24959,
"text": "The order of parameters should be maintained i.e. the order in which parameters are defined in function should be maintained while calling the function."
},
{
"code": null,
"e": 25206,
"s": 25112,
"text": "The values for the non-optional parameters should be passed otherwise it will throw an error."
},
{
"code": null,
"e": 25274,
"s": 25206,
"text": "The value of the default arguments can be either passed or ignored."
},
{
"code": null,
"e": 25323,
"s": 25274,
"text": "Below are some codes which explain this concept."
},
{
"code": null,
"e": 25334,
"s": 25323,
"text": "Example 1:"
},
{
"code": null,
"e": 25342,
"s": 25334,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Here b is predefined and hence is optional.\ndef func(a, b=1098):\n return a+b\n \n \nprint(func(2, 2))\n \n# this 1 is represented as 'a' in the function and\n# function uses the default value of b\nprint(func(1))\n\n\n\n\n\n",
"e": 25576,
"s": 25352,
"text": null
},
{
"code": null,
"e": 25584,
"s": 25576,
"text": "Output:"
},
{
"code": null,
"e": 25591,
"s": 25584,
"text": "4\n1099"
},
{
"code": null,
"e": 25628,
"s": 25591,
"text": "Example 2: we can also pass strings."
},
{
"code": null,
"e": 25636,
"s": 25628,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Here string2 is the default string used\ndef fun2(string1, string2=\"Geeks\"):\n print(string1 + string2)\n \n \n# calling the function using default value\nfun2('GeeksFor')\n \n# calling without default value.\nfun2('GeeksFor', \"Geeks\")\n\n\n\n\n\n",
"e": 25891,
"s": 25646,
"text": null
},
{
"code": null,
"e": 25899,
"s": 25891,
"text": "Output:"
},
{
"code": null,
"e": 25927,
"s": 25899,
"text": "GeeksForGeeks\nGeeksForGeeks"
},
{
"code": null,
"e": 26247,
"s": 25927,
"text": "When functions are defined then the parameters are written in the form βdatatype keyword-nameβ. So python provides a mechanism to call the function using the keyword name for passing the values. This helps the programmer by relieving them not to learn the sequence or the order in which the parameters are to be passed."
},
{
"code": null,
"e": 26305,
"s": 26247,
"text": "Some important points we need to remember are as follows:"
},
{
"code": null,
"e": 26384,
"s": 26305,
"text": "In this case, we are not required to maintain the order of passing the values."
},
{
"code": null,
"e": 26461,
"s": 26384,
"text": "There should be no difference between the passed and declared keyword names."
},
{
"code": null,
"e": 26503,
"s": 26461,
"text": "Below is the code for its implementation."
},
{
"code": null,
"e": 26511,
"s": 26503,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Here string2 is the default string used\ndef fun2(string1, string2=\"Geeks\"):\n print(string1 + string2)\n \n \n# Thiscan be a way where no order is needed.\nfun2(string2='GeeksFor', string1=\"Geeks\")\n \n# since we are not mentioning the non-default argument\n# so it will give error.\nfun2(string2='GeeksFor')\n\n\n\n\n\n",
"e": 26839,
"s": 26521,
"text": null
},
{
"code": null,
"e": 26847,
"s": 26839,
"text": "Output:"
},
{
"code": null,
"e": 27255,
"s": 26847,
"text": "As we can see that we donβt require any order to be maintained in the above example. Also, we can see that when we try to pass only the optional parameters then it raises an error. This happens since optional parameters can be omitted as they have a default with them, but we cannot omit required parameters (string1 in the above case.) Hence, it shows an error with the flag: βmissing 1 required argumentβ."
},
{
"code": null,
"e": 27314,
"s": 27255,
"text": "This example will give a more insight idea of above topic:"
},
{
"code": null,
"e": 27322,
"s": 27314,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\ndef func(a, b, c='geeks'):\n print(a, \"type is\", type(a))\n print(b, \"type is\", type(b))\n print(c, \"type is\", type(c))\n \n \n# The optional parameters will not decide\n# the type of parameter passed.\n# also the order is maintained\nprint(\"first call\")\nfunc(2, 'z', 2.0)\n \n# below call uses the default\n# mentioned value of c\nprint(\"second call\")\nfunc(2, 1)\n \n# The below call (in comments) will give an error\n# since other required parameter is not passed.\n# func('a')\nprint(\"third call\")\nfunc(c=2, b=3, a='geeks')\n\n\n\n\n\n",
"e": 27863,
"s": 27332,
"text": null
},
{
"code": null,
"e": 27871,
"s": 27863,
"text": "Output:"
},
{
"code": null,
"e": 28133,
"s": 27871,
"text": "first call\n2 type is <class 'int'>\nz type is <class 'str'>\n2.0 type is <class 'float'>\nsecond call\n2 type is <class 'int'>\n1 type is <class 'int'>\ngeeks type is <class 'str'>\nthird call\ngeeks type is <class 'str'>\n3 type is <class 'int'>\n2 type is <class 'int'>"
},
{
"code": null,
"e": 28249,
"s": 28133,
"text": "So basically python functional calls checks only if the required number of functional parameters are passed or not."
},
{
"code": null,
"e": 28369,
"s": 28249,
"text": "Below shows the case where a user tries to pass arguments in both ways discussed above along with the precaution given:"
},
{
"code": null,
"e": 28377,
"s": 28369,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\ndef comp(a, b=2):\n if(a < b):\n print(\"first parameter is smaller\")\n if(a > b):\n print(\"second parameter is smaller\")\n if(a == b):\n print(\"both are of equal value.\")\n \n \nprint(\"first call\")\ncomp(1)\nprint(\"second call\")\ncomp(2, 1)\nprint(\"third call\")\ncomp(b=1, a=-1)\nprint(\"fourth call\")\ncomp(-1, b=0)\n\n\n\n\n\n",
"e": 28730,
"s": 28387,
"text": null
},
{
"code": null,
"e": 28738,
"s": 28730,
"text": "Output:"
},
{
"code": null,
"e": 28893,
"s": 28738,
"text": "first call\nfirst parameter is smaller\nsecond call\nsecond parameter is smaller\nthird call\nfirst parameter is smaller\nfourth call\nfirst parameter is smaller"
},
{
"code": null,
"e": 29116,
"s": 28893,
"text": "So one thing we should remember that the keyword argument should used after all positional arguments are passed. Hence this is an important thing we must keep in mind while passing parameters in both ways to same function."
},
{
"code": null,
"e": 29127,
"s": 29116,
"text": "saeedy2007"
},
{
"code": null,
"e": 29140,
"s": 29127,
"text": "simmytarika5"
},
{
"code": null,
"e": 29149,
"s": 29140,
"text": "\nPicked\n"
},
{
"code": null,
"e": 29168,
"s": 29149,
"text": "\nPython-Functions\n"
},
{
"code": null,
"e": 29194,
"s": 29168,
"text": "\nTechnical Scripter 2020\n"
},
{
"code": null,
"e": 29203,
"s": 29194,
"text": "\nPython\n"
},
{
"code": null,
"e": 29224,
"s": 29203,
"text": "\nTechnical Scripter\n"
},
{
"code": null,
"e": 29429,
"s": 29224,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29461,
"s": 29429,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29503,
"s": 29461,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29559,
"s": 29503,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29601,
"s": 29559,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29632,
"s": 29601,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29654,
"s": 29632,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29709,
"s": 29654,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29748,
"s": 29709,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29777,
"s": 29748,
"text": "Create a directory in Python"
}
] |
How to change app language when user selects language in Android? | This example demonstrates how do I change app language when user selects language.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/thank_you"
android:textSize="24sp"
android:layout_centerInParent="true"
android:layout_below="@id/spinner"/>
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.java
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
Locale locale;
String currentLanguage = "en", currentLang;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentLanguage = getIntent().getStringExtra(currentLang);
spinner = findViewById(R.id.spinner);
List<String> list = new ArrayList<>();
list.add("Select Language");
list.add("English");
list.add("EspanΜol");
list.add("FrancΜ§ais");
list.add("Hindi");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
break;
case 1:
setLocale("en");
break;
case 2:
setLocale("es");
break;
case 3:
setLocale("fr");
break;
case 4:
setLocale("hi");
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setLocale(String localeName) {
if (!localeName.equals(currentLanguage)) {
locale = new Locale(localeName);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this,
MainActivity.class);
refresh.putExtra(currentLang, localeName);
startActivity(refresh);
} else {
Toast.makeText(MainActivity.this, "Language
already selected!", Toast.LENGTH_SHORT).show();
}
}
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}
Step 4 β Create values-es, values-fr, values-hi and add the following code β
values-hi/strings.xml
<resources>
<string name="app_name">Sample</string>
<string name="thank_you">ΰ€§ΰ€¨ΰ₯ΰ€―ΰ€΅ΰ€Ύΰ€¦</string>
</resources>
values-fr/strings.xml
<resources>
<string name="app_name">Sample</string>
<string name="thank_you">Je vous remercie</string>
</resources>
values-es/strings.xml
<resources>
<string name="app_name">Sample</string>
<string name="thank_you">Gracias</string>
</resources>
strings.xml
<resources>
<string name="app_name">Sample</string>
<string name="thank_you">Thank you</string>
</resources>
Step 5 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrates how do I change app language when user selects language."
},
{
"code": null,
"e": 1274,
"s": 1145,
"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": 1339,
"s": 1274,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2107,
"s": 1339,
"text": "<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <Spinner\n android:id=\"@+id/spinner\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n <TextView\n android:id=\"@+id/string\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/thank_you\"\n android:textSize=\"24sp\"\n android:layout_centerInParent=\"true\"\n android:layout_below=\"@id/spinner\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2164,
"s": 2107,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5100,
"s": 2164,
"text": "import android.content.Intent;\nimport android.content.res.Configuration;\nimport android.content.res.Resources;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.DisplayMetrics;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Spinner;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\npublic class MainActivity extends AppCompatActivity {\n Spinner spinner;\n Locale locale;\n String currentLanguage = \"en\", currentLang;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n currentLanguage = getIntent().getStringExtra(currentLang);\n spinner = findViewById(R.id.spinner);\n List<String> list = new ArrayList<>();\n list.add(\"Select Language\");\n list.add(\"English\");\n list.add(\"EspanΜol\");\n list.add(\"FrancΜ§ais\");\n list.add(\"Hindi\");\n ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, list);\n adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(adapter);\n spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n switch (position) {\n case 0:\n break;\n case 1:\n setLocale(\"en\");\n break;\n case 2:\n setLocale(\"es\");\n break;\n case 3:\n setLocale(\"fr\");\n break;\n case 4:\n setLocale(\"hi\");\n break;\n }\n }\n @Override\n public void onNothingSelected(AdapterView<?> parent) {\n }\n });\n }\n private void setLocale(String localeName) {\n if (!localeName.equals(currentLanguage)) {\n locale = new Locale(localeName);\n Resources res = getResources();\n DisplayMetrics dm = res.getDisplayMetrics();\n Configuration conf = res.getConfiguration();\n conf.locale = locale;\n res.updateConfiguration(conf, dm);\n Intent refresh = new Intent(this,\n MainActivity.class);\n refresh.putExtra(currentLang, localeName);\n startActivity(refresh);\n } else {\n Toast.makeText(MainActivity.this, \"Language\n already selected!\", Toast.LENGTH_SHORT).show();\n }\n }\n public void onBackPressed() {\n Intent intent = new Intent(Intent.ACTION_MAIN);\n intent.addCategory(Intent.CATEGORY_HOME);\n intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n startActivity(intent);\n finish();\n System.exit(0);\n }\n}"
},
{
"code": null,
"e": 5177,
"s": 5100,
"text": "Step 4 β Create values-es, values-fr, values-hi and add the following code β"
},
{
"code": null,
"e": 5199,
"s": 5177,
"text": "values-hi/strings.xml"
},
{
"code": null,
"e": 5312,
"s": 5199,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"thank_you\">ΰ€§ΰ€¨ΰ₯ΰ€―ΰ€΅ΰ€Ύΰ€¦</string>\n</resources>"
},
{
"code": null,
"e": 5334,
"s": 5312,
"text": "values-fr/strings.xml"
},
{
"code": null,
"e": 5456,
"s": 5334,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"thank_you\">Je vous remercie</string>\n</resources>"
},
{
"code": null,
"e": 5478,
"s": 5456,
"text": "values-es/strings.xml"
},
{
"code": null,
"e": 5591,
"s": 5478,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"thank_you\">Gracias</string>\n</resources>"
},
{
"code": null,
"e": 5603,
"s": 5591,
"text": "strings.xml"
},
{
"code": null,
"e": 5718,
"s": 5603,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"thank_you\">Thank you</string>\n</resources>"
},
{
"code": null,
"e": 5773,
"s": 5718,
"text": "Step 5 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6479,
"s": 5773,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6825,
"s": 6479,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
}
] |
What are Backslash character constants in C language? | A backslash ( \ ) that allows a visual representation of some nongraphic characters introduces an escape.
One of the common escape constants is the newline character ( \n ).
The backslash characters are as follows β
Following is the C program for the backslash character constants β
Live Demo
#include<stdio.h>
#define PI 3.14
float area;
void main(){
double r;
r=1.0;
area = PI * r * r;
printf("Area is %d \n", area); // /n is used to enter the next statement in newline
}
Area is 1492442840 | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "A backslash ( \\ ) that allows a visual representation of some nongraphic characters introduces an escape."
},
{
"code": null,
"e": 1236,
"s": 1168,
"text": "One of the common escape constants is the newline character ( \\n )."
},
{
"code": null,
"e": 1278,
"s": 1236,
"text": "The backslash characters are as follows β"
},
{
"code": null,
"e": 1345,
"s": 1278,
"text": "Following is the C program for the backslash character constants β"
},
{
"code": null,
"e": 1356,
"s": 1345,
"text": " Live Demo"
},
{
"code": null,
"e": 1549,
"s": 1356,
"text": "#include<stdio.h>\n#define PI 3.14\nfloat area;\nvoid main(){\n double r;\n r=1.0;\n area = PI * r * r;\n printf(\"Area is %d \\n\", area); // /n is used to enter the next statement in newline\n}"
},
{
"code": null,
"e": 1568,
"s": 1549,
"text": "Area is 1492442840"
}
] |
How do we access elements from the two-dimensional array in C#? | A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns.
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array.
int x = a[1,1];
Console.WriteLine(x);
Let us see an example that shows how to access elements from two-dimensional array.
Live Demo
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
int x = a[1,1];
Console.WriteLine(x);
Console.ReadKey();
}
}
}
a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8
2 | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns."
},
{
"code": null,
"e": 1287,
"s": 1166,
"text": "An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array."
},
{
"code": null,
"e": 1325,
"s": 1287,
"text": "int x = a[1,1];\nConsole.WriteLine(x);"
},
{
"code": null,
"e": 1409,
"s": 1325,
"text": "Let us see an example that shows how to access elements from two-dimensional array."
},
{
"code": null,
"e": 1420,
"s": 1409,
"text": " Live Demo"
},
{
"code": null,
"e": 1964,
"s": 1420,
"text": "using System;\nnamespace Demo {\n class MyArray {\n static void Main(string[] args) {\n /* an array with 5 rows and 2 columns*/\n int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };\n int i, j;\n /* output each array element's value */\n for (i = 0; i < 5; i++) {\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0},{1}] = {2}\", i, j, a[i,j]);\n }\n }\n int x = a[1,1];\n Console.WriteLine(x);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2076,
"s": 1964,
"text": "a[0,0] = 0\na[0,1] = 0\na[1,0] = 1\na[1,1] = 2\na[2,0] = 2\na[2,1] = 4\na[3,0] = 3\na[3,1] = 6\na[4,0] = 4\na[4,1] = 8\n2"
}
] |
5 NLP Topics And Projects You Should Know About! | by Bharath K | Towards Data Science | Natural Language Processing (NLP) is one of the most intriguing and fascinating aspects of Artificial Intelligence. With the continuous evolution and development of NLP in recent years, it is essential to know about the most advanced and high-quality topics that every individual Data Science enthusiast or aspirant must focus on to achieve a higher rate of success in the field.
The interactions between the software and humans is becoming significantly easier, thanks to the advancements in the field of Natural Language Processing. The AI programs tend to computes, process, and analyze large amounts of natural language data to provide the user with a decent semantic and accurate reply to the users.
Despite the numerous challenges faced in the field of NLP, like making the AI understand the true semantic meaning of the sentences, we have made tremendous progress and have come a long way in the field of Natural Language Processing.
If you are curious about more awesome projects with Python and Data Science, feel free to check out the link below, where fifteen such best projects are covered for 2021 and beyond. In this article, we will focus on the five NLP topics and projects every enthusiast of the subject should know about and aim to achieve perfection!
towardsdatascience.com
One of the most essential Natural Language Processing (NLP) tools for solving many types of problems is the NLTK library. The natural language toolkit (NLTK) offers numerous utility for solving a multitude of Natural Language Processing problems. The NLTK library is very well suited for linguistic-based tasks. It offers a wide range of options for tasks such as classification, tokenization, stemming, tagging, parsing, and semantic reasoning.
The best part about utilizing this library with machine learning and deep learning is you can create numerous high-quality projects. The features of the NLTK library module are broad. There is so much you can do with this library and then use the methods of the bag of words, Term frequency-inverse document frequency (TF-IDF), word to vectors, and other similar methods to approach these tasks and problems.
Below is an example sample code that shows how you can create datasets and essay vectors for large datasets and then make use of hyperparameter tuning along with NLP techniques and machine learning algorithms like NaiΜve Bayes, Decision trees, and other similar machine learning approaches to solve these complex and complicated problems quite easily.
Sample Code:
vectorizer = CountVectorizer(min_df=10,ngram_range=(1,4), max_features=50000)vectorizer.fit(X_train['essay'].values) # fit has to happen only on train data# we use the fitted CountVectorizer to convert the text to vectorX_train_essay_bow = vectorizer.transform(X_train['essay'].values)X_cv_essay_bow = vectorizer.transform(X_cv['essay'].values)X_test_essay_bow = vectorizer.transform(X_test['essay'].values)
To learn more about how you can simplify your Natural Language Processing projects with Regular Expressions, I would highly recommend all of you to check out the link provided below. It covers how you can utilizer the four basic regular expression operations for a majority of the pre-processing on essays and text datasets for your projects.
towardsdatascience.com
One of the most significant tasks that are accomplished with the help of Artificial Intelligence is the prediction of the next words or sentences that are to occur in the following line or lines. This task is one of the more basic and useful functionalities of Natural Language Processing (NLP) in machine learning and deep learning.
To solve the following task of predicting the concurrent or closest words in machine learning, the concept of similarity can be utilized to achieve the desired results. The concurrent word vector with smaller distances is interlinked. Machine learning algorithms like support vector machines (SVMs), decision trees, and other similar methods can be utilized for solving tasks like next word predictions and other such indistinguishable tasks.
The more popular approach to solving these complex problems is to ensure that we effectively use the concepts of deep learning to solve them. The methods of building neural network architectures using Recurrent Neural Networks is one such common method to solve the task of the next-word predictions. However, due to the issues of exploding and vanishing gradients, other alternatives to RNNs like the long-short term memory (LSTM) are used as an amazing alternative method to approach these tasks.
A unique way of solving these tasks includes the utilization of 1-Dimensional convolution neural networks to create a linking to the word vectors. I would recommend the viewers to check out one of my following projects on the prediction of the next word, where I have implemented the following procedure with the help of a couple of stacked LSTMs.
towardsdatascience.com
One of the most popular applications of Natural Language Processing is the use of chatbots. Chatbots are employed by most major tech-giants, large companies, and even smaller startups on websites to greet people, introduce the fundamental aspects of the company to the visitors, viewers, or audiences, and also answer some of the common questions that the first time site visitors may have.
They are also useful for providing clarifications to some issues that the users might encounter during the browsing of their website. Chatbots can also be deployed for more generic use cases for the majority of the public audiences. The most popular virtual assistants like Google Assistant, Siri, Alexa, etc., among many others, also have the ability to act as chatbots.
The conversations of the chatbots can either be carried out in a traditional method of in-line texting or a more modern approach of speech translation. The use cases of chatbots in the current generation are increasing rapidly. More people and companies are trying to implement them as well. In the field of NLP, the rise of chatbots is an extremely important scenario and something that every enthusiast of the subject must look forward to implementing.
I would highly encourage checking out the numerous methods of working on these chatbots. There are several deep learning algorithms and methods to obtain desirable results on these chatbots. One such unique method is by the construction of these chatbots by making use of the 1-Dimensional Convolutional Neural Networks. Check out the article link provided below to gain a more intuitive understanding of the following.
towardsdatascience.com
Transformers are one of the most significant architectures of the current deep learning era. They aim to solve the sequence to sequence tasks with greater ease. They have the ability to retain long chains of data. And hence, they have a high range of dependability while handling long-range sequences. They utilize the concepts of self-attention to solve complex tasks without the use of sequence-aligned RNNs or convolution.
Transformers are an innovative development in the field of Natural Language Processing. They have the ability to solve complex tasks such as machine translation with greater ease. The topic and project concept of machine translation will be discussed in further detail in the next section of this article.
These transformers also find their utility in numerous tasks such as information retrieval, text classification, document summarization, image captioning, and genome analysis. I would highly recommend doing in-depth research and learning more on the topic of transformers to gain further intuition and understanding of this modern evolution of transformers.
When you trying to talk to a person from another country and you both donβt know a common language, the use of a translator is often required to communicate and agree to terms on a particular contract or deal. Whenever you want to communicate in a foreign language, you can make use of the Google translate function to convert the sentence from one language to another.
Upon typing a particular sentence in English and asking Google translate to convert it into the language of German, the translator usually does a decent job of converting the sentence in English to a sentence in German without changing the actual semantic meaning of a sentence. This task is referred to as Machine Translation.
Machine translation is one of the most useful and significant tasks of natural language processing. Every enthusiast must work on accomplishing the task of machine translation with the help of either the TensorFlow library or the Pytorch library. By using these libraries, you must try to construct a Sequence To Sequence model that can achieve the task of solving the problem of machine translation while achieving the highest possible accuracy. There are a lot of amazing modern methods that are being developed to approach these tasks.
Natural Language Processing is one of the best subjects and sub-topics to learn in Artificial Intelligence. There are so many research papers and articles that are being published continuously. Rapid developments and extensive research are consistently taking place on a daily basis. In the upcoming years, a lot more amazing discoveries to be made in the following field.
In this article, we have discussed five Natural Language Processing (NLP) concepts and project topics that every enthusiast should know about and explore. They constitute the most crucial and vital aspects of these modern-day NLP applications. The demand and significance of these moderately advanced fields are rapidly increasing every day. Hence, this time is one of the most effective periods for aspirants to invest in and learn more.
In my opinion, all of the viewers who are interested and passionate about the field of Natural Language Processing should research more on these topics and try to learn more about the significant aspects of these concepts. After gaining a decent amount of theoretical knowledge, I would highly encourage the viewers to take a dive into the practical world and start implementing these projects on their own.
If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible.
Check out some of my other articles that you might enjoy reading!
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day! | [
{
"code": null,
"e": 551,
"s": 171,
"text": "Natural Language Processing (NLP) is one of the most intriguing and fascinating aspects of Artificial Intelligence. With the continuous evolution and development of NLP in recent years, it is essential to know about the most advanced and high-quality topics that every individual Data Science enthusiast or aspirant must focus on to achieve a higher rate of success in the field."
},
{
"code": null,
"e": 876,
"s": 551,
"text": "The interactions between the software and humans is becoming significantly easier, thanks to the advancements in the field of Natural Language Processing. The AI programs tend to computes, process, and analyze large amounts of natural language data to provide the user with a decent semantic and accurate reply to the users."
},
{
"code": null,
"e": 1112,
"s": 876,
"text": "Despite the numerous challenges faced in the field of NLP, like making the AI understand the true semantic meaning of the sentences, we have made tremendous progress and have come a long way in the field of Natural Language Processing."
},
{
"code": null,
"e": 1442,
"s": 1112,
"text": "If you are curious about more awesome projects with Python and Data Science, feel free to check out the link below, where fifteen such best projects are covered for 2021 and beyond. In this article, we will focus on the five NLP topics and projects every enthusiast of the subject should know about and aim to achieve perfection!"
},
{
"code": null,
"e": 1465,
"s": 1442,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1911,
"s": 1465,
"text": "One of the most essential Natural Language Processing (NLP) tools for solving many types of problems is the NLTK library. The natural language toolkit (NLTK) offers numerous utility for solving a multitude of Natural Language Processing problems. The NLTK library is very well suited for linguistic-based tasks. It offers a wide range of options for tasks such as classification, tokenization, stemming, tagging, parsing, and semantic reasoning."
},
{
"code": null,
"e": 2320,
"s": 1911,
"text": "The best part about utilizing this library with machine learning and deep learning is you can create numerous high-quality projects. The features of the NLTK library module are broad. There is so much you can do with this library and then use the methods of the bag of words, Term frequency-inverse document frequency (TF-IDF), word to vectors, and other similar methods to approach these tasks and problems."
},
{
"code": null,
"e": 2672,
"s": 2320,
"text": "Below is an example sample code that shows how you can create datasets and essay vectors for large datasets and then make use of hyperparameter tuning along with NLP techniques and machine learning algorithms like NaiΜve Bayes, Decision trees, and other similar machine learning approaches to solve these complex and complicated problems quite easily."
},
{
"code": null,
"e": 2685,
"s": 2672,
"text": "Sample Code:"
},
{
"code": null,
"e": 3093,
"s": 2685,
"text": "vectorizer = CountVectorizer(min_df=10,ngram_range=(1,4), max_features=50000)vectorizer.fit(X_train['essay'].values) # fit has to happen only on train data# we use the fitted CountVectorizer to convert the text to vectorX_train_essay_bow = vectorizer.transform(X_train['essay'].values)X_cv_essay_bow = vectorizer.transform(X_cv['essay'].values)X_test_essay_bow = vectorizer.transform(X_test['essay'].values)"
},
{
"code": null,
"e": 3436,
"s": 3093,
"text": "To learn more about how you can simplify your Natural Language Processing projects with Regular Expressions, I would highly recommend all of you to check out the link provided below. It covers how you can utilizer the four basic regular expression operations for a majority of the pre-processing on essays and text datasets for your projects."
},
{
"code": null,
"e": 3459,
"s": 3436,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3793,
"s": 3459,
"text": "One of the most significant tasks that are accomplished with the help of Artificial Intelligence is the prediction of the next words or sentences that are to occur in the following line or lines. This task is one of the more basic and useful functionalities of Natural Language Processing (NLP) in machine learning and deep learning."
},
{
"code": null,
"e": 4236,
"s": 3793,
"text": "To solve the following task of predicting the concurrent or closest words in machine learning, the concept of similarity can be utilized to achieve the desired results. The concurrent word vector with smaller distances is interlinked. Machine learning algorithms like support vector machines (SVMs), decision trees, and other similar methods can be utilized for solving tasks like next word predictions and other such indistinguishable tasks."
},
{
"code": null,
"e": 4735,
"s": 4236,
"text": "The more popular approach to solving these complex problems is to ensure that we effectively use the concepts of deep learning to solve them. The methods of building neural network architectures using Recurrent Neural Networks is one such common method to solve the task of the next-word predictions. However, due to the issues of exploding and vanishing gradients, other alternatives to RNNs like the long-short term memory (LSTM) are used as an amazing alternative method to approach these tasks."
},
{
"code": null,
"e": 5083,
"s": 4735,
"text": "A unique way of solving these tasks includes the utilization of 1-Dimensional convolution neural networks to create a linking to the word vectors. I would recommend the viewers to check out one of my following projects on the prediction of the next word, where I have implemented the following procedure with the help of a couple of stacked LSTMs."
},
{
"code": null,
"e": 5106,
"s": 5083,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5497,
"s": 5106,
"text": "One of the most popular applications of Natural Language Processing is the use of chatbots. Chatbots are employed by most major tech-giants, large companies, and even smaller startups on websites to greet people, introduce the fundamental aspects of the company to the visitors, viewers, or audiences, and also answer some of the common questions that the first time site visitors may have."
},
{
"code": null,
"e": 5869,
"s": 5497,
"text": "They are also useful for providing clarifications to some issues that the users might encounter during the browsing of their website. Chatbots can also be deployed for more generic use cases for the majority of the public audiences. The most popular virtual assistants like Google Assistant, Siri, Alexa, etc., among many others, also have the ability to act as chatbots."
},
{
"code": null,
"e": 6324,
"s": 5869,
"text": "The conversations of the chatbots can either be carried out in a traditional method of in-line texting or a more modern approach of speech translation. The use cases of chatbots in the current generation are increasing rapidly. More people and companies are trying to implement them as well. In the field of NLP, the rise of chatbots is an extremely important scenario and something that every enthusiast of the subject must look forward to implementing."
},
{
"code": null,
"e": 6744,
"s": 6324,
"text": "I would highly encourage checking out the numerous methods of working on these chatbots. There are several deep learning algorithms and methods to obtain desirable results on these chatbots. One such unique method is by the construction of these chatbots by making use of the 1-Dimensional Convolutional Neural Networks. Check out the article link provided below to gain a more intuitive understanding of the following."
},
{
"code": null,
"e": 6767,
"s": 6744,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7193,
"s": 6767,
"text": "Transformers are one of the most significant architectures of the current deep learning era. They aim to solve the sequence to sequence tasks with greater ease. They have the ability to retain long chains of data. And hence, they have a high range of dependability while handling long-range sequences. They utilize the concepts of self-attention to solve complex tasks without the use of sequence-aligned RNNs or convolution."
},
{
"code": null,
"e": 7499,
"s": 7193,
"text": "Transformers are an innovative development in the field of Natural Language Processing. They have the ability to solve complex tasks such as machine translation with greater ease. The topic and project concept of machine translation will be discussed in further detail in the next section of this article."
},
{
"code": null,
"e": 7857,
"s": 7499,
"text": "These transformers also find their utility in numerous tasks such as information retrieval, text classification, document summarization, image captioning, and genome analysis. I would highly recommend doing in-depth research and learning more on the topic of transformers to gain further intuition and understanding of this modern evolution of transformers."
},
{
"code": null,
"e": 8227,
"s": 7857,
"text": "When you trying to talk to a person from another country and you both donβt know a common language, the use of a translator is often required to communicate and agree to terms on a particular contract or deal. Whenever you want to communicate in a foreign language, you can make use of the Google translate function to convert the sentence from one language to another."
},
{
"code": null,
"e": 8555,
"s": 8227,
"text": "Upon typing a particular sentence in English and asking Google translate to convert it into the language of German, the translator usually does a decent job of converting the sentence in English to a sentence in German without changing the actual semantic meaning of a sentence. This task is referred to as Machine Translation."
},
{
"code": null,
"e": 9094,
"s": 8555,
"text": "Machine translation is one of the most useful and significant tasks of natural language processing. Every enthusiast must work on accomplishing the task of machine translation with the help of either the TensorFlow library or the Pytorch library. By using these libraries, you must try to construct a Sequence To Sequence model that can achieve the task of solving the problem of machine translation while achieving the highest possible accuracy. There are a lot of amazing modern methods that are being developed to approach these tasks."
},
{
"code": null,
"e": 9467,
"s": 9094,
"text": "Natural Language Processing is one of the best subjects and sub-topics to learn in Artificial Intelligence. There are so many research papers and articles that are being published continuously. Rapid developments and extensive research are consistently taking place on a daily basis. In the upcoming years, a lot more amazing discoveries to be made in the following field."
},
{
"code": null,
"e": 9906,
"s": 9467,
"text": "In this article, we have discussed five Natural Language Processing (NLP) concepts and project topics that every enthusiast should know about and explore. They constitute the most crucial and vital aspects of these modern-day NLP applications. The demand and significance of these moderately advanced fields are rapidly increasing every day. Hence, this time is one of the most effective periods for aspirants to invest in and learn more."
},
{
"code": null,
"e": 10314,
"s": 9906,
"text": "In my opinion, all of the viewers who are interested and passionate about the field of Natural Language Processing should research more on these topics and try to learn more about the significant aspects of these concepts. After gaining a decent amount of theoretical knowledge, I would highly encourage the viewers to take a dive into the practical world and start implementing these projects on their own."
},
{
"code": null,
"e": 10512,
"s": 10314,
"text": "If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible."
},
{
"code": null,
"e": 10578,
"s": 10512,
"text": "Check out some of my other articles that you might enjoy reading!"
},
{
"code": null,
"e": 10601,
"s": 10578,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10624,
"s": 10601,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10647,
"s": 10624,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10670,
"s": 10647,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10693,
"s": 10670,
"text": "towardsdatascience.com"
}
] |
Unix / Linux - Shell String Operators Example | The following string operators are supported by Bourne Shell.
Assume variable a holds "abc" and variable b holds "efg" then β
Here is an example which uses all the string operators β
#!/bin/sh
a="abc"
b="efg"
if [ $a = $b ]
then
echo "$a = $b : a is equal to b"
else
echo "$a = $b: a is not equal to b"
fi
if [ $a != $b ]
then
echo "$a != $b : a is not equal to b"
else
echo "$a != $b: a is equal to b"
fi
if [ -z $a ]
then
echo "-z $a : string length is zero"
else
echo "-z $a : string length is not zero"
fi
if [ -n $a ]
then
echo "-n $a : string length is not zero"
else
echo "-n $a : string length is zero"
fi
if [ $a ]
then
echo "$a : string is not empty"
else
echo "$a : string is empty"
fi
The above script will generate the following result β
abc = efg: a is not equal to b
abc != efg : a is not equal to b
-z abc : string length is not zero
-n abc : string length is not zero
abc : string is not empty
The following points need to be considered while using the operator β
There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2.
There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2.
if...then...else...fi statement is a decision-making statement which has been explained in the next chapter.
if...then...else...fi statement is a decision-making statement which has been explained in the next chapter.
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": 2809,
"s": 2747,
"text": "The following string operators are supported by Bourne Shell."
},
{
"code": null,
"e": 2873,
"s": 2809,
"text": "Assume variable a holds \"abc\" and variable b holds \"efg\" then β"
},
{
"code": null,
"e": 2930,
"s": 2873,
"text": "Here is an example which uses all the string operators β"
},
{
"code": null,
"e": 3480,
"s": 2930,
"text": "#!/bin/sh\n\na=\"abc\"\nb=\"efg\"\n\nif [ $a = $b ]\nthen\n echo \"$a = $b : a is equal to b\"\nelse\n echo \"$a = $b: a is not equal to b\"\nfi\n\nif [ $a != $b ]\nthen\n echo \"$a != $b : a is not equal to b\"\nelse\n echo \"$a != $b: a is equal to b\"\nfi\n\nif [ -z $a ]\nthen\n echo \"-z $a : string length is zero\"\nelse\n echo \"-z $a : string length is not zero\"\nfi\n\nif [ -n $a ]\nthen\n echo \"-n $a : string length is not zero\"\nelse\n echo \"-n $a : string length is zero\"\nfi\n\nif [ $a ]\nthen\n echo \"$a : string is not empty\"\nelse\n echo \"$a : string is empty\"\nfi"
},
{
"code": null,
"e": 3534,
"s": 3480,
"text": "The above script will generate the following result β"
},
{
"code": null,
"e": 3695,
"s": 3534,
"text": "abc = efg: a is not equal to b\nabc != efg : a is not equal to b\n-z abc : string length is not zero\n-n abc : string length is not zero\nabc : string is not empty\n"
},
{
"code": null,
"e": 3765,
"s": 3695,
"text": "The following points need to be considered while using the operator β"
},
{
"code": null,
"e": 3893,
"s": 3765,
"text": "There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2."
},
{
"code": null,
"e": 4021,
"s": 3893,
"text": "There must be spaces between the operators and the expressions. For example, 2+2 is not correct. It should be written as 2 + 2."
},
{
"code": null,
"e": 4130,
"s": 4021,
"text": "if...then...else...fi statement is a decision-making statement which has been explained in the next chapter."
},
{
"code": null,
"e": 4239,
"s": 4130,
"text": "if...then...else...fi statement is a decision-making statement which has been explained in the next chapter."
},
{
"code": null,
"e": 4274,
"s": 4239,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4302,
"s": 4274,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4336,
"s": 4302,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4353,
"s": 4336,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4386,
"s": 4353,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4397,
"s": 4386,
"text": " Pradeep D"
},
{
"code": null,
"e": 4432,
"s": 4397,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4448,
"s": 4432,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4481,
"s": 4448,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4493,
"s": 4481,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4525,
"s": 4493,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4533,
"s": 4525,
"text": " Uplatz"
},
{
"code": null,
"e": 4540,
"s": 4533,
"text": " Print"
},
{
"code": null,
"e": 4551,
"s": 4540,
"text": " Add Notes"
}
] |
Histograms with Plotly Express. Themes & Templates | by DariΜo Weitz | Towards Data Science | Plotly Express (PE) is a high-level wrapper for Plotly.py fully compatible with the rest of the Plotly ecosystem. Based on the JavaScript library D3.js., it also has API wrappers for R, Julia, and many other programming languages. Itβs free and can be used in commercial applications and products. The library includes functions to plot standard charts and maps, as well as to perform faceting and animations with a single function call. With Plotly Express you can make interactive graphics online but you can also save them offline.
Plotly Express is appropriate for quickly generating exploratory plots. Also, the chart can be quickly styled by using pre-defined themes or templates. According to Plotly main website βTheming generally refers to the process of defining default styles for visual elements. Themes in plotly are implemented using objects called templates. Templates are slightly more general than traditional themes because in addition to defining default styles, templates can pre-populate a figure with visual elements like annotations, shapes, images, and more.β [1].
The built-in themes can be viewed through the following statement:
There are 11 templates: ggplot2, seaborn, plotly, plotly_white, plotly_dark, simple_white, gridon, xgridoff, ygridoff, presentation, and none. The ggplot2 theme is inspired by the R data visualization package ggplot2, whilst the seaborn theme is inspired by the Python data visualization library Seaborn. plotly, plotly_white, and plotly_dark are original plotly.express themes. As indicated above, plotly is the default template, while plotly_dark is inspired by the JupyterLabβs dark theme. The following three themes are related to the presence or absence of grids: gridon, xgridoff, ygridoff. simple_white is a minimalist template for a clear and uncluttered chart. The presentation theme increases the size of fonts, markers, and line widths so that they can be viewed from a greater distance. This theme can be combined with any other (See Fig. 6).
Each one of the above themes can be used as the template argument of any plotly.express function. So, a smart strategy is to iteratively test with the 11 themes until you find the one that best fits your storytelling.
A histogram is a graphical representation of the distribution of a dataset. Although its appearance is similar to that of a standard bar graph, instead of making comparisons between different items or categories or showing trends over time, a histogram is a plot that lets you show the underlying frequency distribution or the probability distribution of a single continuous numerical variable.
Histograms are two-dimensional plots with two axes; the vertical axis is a frequency axis whilst the horizontal axis is divided into a range of numeric values (intervals or bins) or time intervals. The frequency of each bin is shown by the area of vertical rectangular bars. Each bar covers a range of continuous numeric values of the variable under study. The vertical axis shows frequency values derived from counts for each bin.
Storytelling: a histogram is an appropriate graph for the initial exploration of a continuous variable. Through a set of vertical bars, it shows how the numerical values ββof that variable are distributed. The histogram allows us to calculate the probability of representation of any value of the continuous variable under study, which is of great importance if we want to make inferences and estimate population values ββfrom the results of our sample.
We worked with a dataset downloaded from Kaggle [2]. The dataset consists of 10,000 bank customers mentioning their age, salary, marital status, credit card limit, credit card category, education level, and additional features. The bank manager wants to know the age distribution of his customers. The following code allows us to answer his questions.
First, we import plotly.express as px, and the pandas library as pd. We load our dataset as a pandas dataframe (df) and select the column Customer_Age as the numerical variable whose frequency distribution we want to know. Draw the figure with px.histogram using plotly, the default template. Finally, we export our chart as a static PNG format.
PE allows you to choose the number of bins. Even though there are no strictly defined rules for the size and number of intervals, you must try out a few different numbers of bins. Always keep in mind that: few intervals do not allow us to elucidate the fine structure of the data distribution; many intervals give importance to the sampling error.
import pandas as pdimport plotly.express as pxpath = 'your path'df = pd.read_csv(path + 'CreditCardCustomersCols.csv', index_col = False, header = 0, sep = ';', engine='python')fig1 = px.histogram(df, x="Customer_Age", nbins = 10)fig1.write_image(path + "fighist1.png")fig1.show()
Fig. 1 shows the age distribution of the bank customers in five-year bins. Clearly, there are very few Centennials and few Millennials. The generation cohorts of the customers are represented by Baby Boomers and Gen X.
In Fig.2 we changed the theme to ggplot2, and update the chart with update.layout: set the title; the name of the x-axis and the name of the y-axis; set the figure dimensions with width and height.
fig2 = px.histogram(df, x="Customer_Age", nbins = 10, template = 'ggplot2')fig2.update_layout(title = "Histogram of Customers' Age ", xaxis_title = 'Customer Age', yaxis_title = 'Standard Count', width = 1600, height = 1400)fig2.write_image(path + "fighist2.png")fig2.show()
By default, PE shows in the vertical axis frequencies (counts) of the data that fall into each bin. You can change this mode using the histnorm argument. This argument can take the following values: percent, probability, density, or probability density.
In Fig.3 we changed the theme to plotly_dark and the mode of representation from the standard count of samples to the percent one using the histnorm argument.
In Fig. 4 we changed the theme to simple_white and the mode toprobabilty.
fig3 = px.histogram(df, x="Customer_Age", nbins = 10, template = 'plotly_dark', histnorm = 'percent')fig3.update_layout(title = "Histogram of Customers' Age ",xaxis_title = 'Customer Age', yaxis_title = 'Percent Count', width = 1600, height = 1400)fig3.write_image(path + "fighist3.png")fig3.show()fig4 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = βsimple_whiteβ, histnorm = βprobabilityβ)fig4.update_layout(title = βHistogram of Customersβ Age β,xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig4.write_image(path + βfighist4.pngβ)fig4.show()
In Fig. 5 we removed the x gridlines using the xgridoff template. Probability Density was selected as the mode of representation. In Fig. 6 we returned to the probability mode and changed the theme to simple_white+presentation. Clearly, there is an increase in the size of fonts, markers, and line widths.
fig5 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = xgridoffβ, histnorm = βprobability densityβ)fig5.update_layout(title = βHistogram of Customersβ Age β, xaxis_title = βCustomer Ageβ, yaxis_title = βProbability Densityβ, width = 1600, height = 1400)fig5.write_image(path + βfighist5.pngβ)fig5.show()fig6 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = βsimple_white+presentationβ, histnorm = βprobabilityβ)fig6.update_layout(title = βHistogram of Customersβ Age β, xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig6.write_image(path + βfighist6.pngβ)fig6.show()
Overlapping histograms are used to compare the frequency distribution of a continuous variable in two or more categories. Even though the PE website indicates that you can draw several histograms for the different values of one column using the argument color, I did not get a proper chart. So, I filtered the dataframe for the two different values of the categorical variable βGenderβ, use twice the px.histogram function, and βmergeβ both figures with the add_trace method. As the px.histogram function does not have a text attribute, we used the argument color only for labeling purposes. We used different themes to be able to identify each figure and the barmode = βoverlayβ argument to get the overlapping. Figure 7 shows that there is no difference in the distribution of customers according to their gender.
df7a = df[df[βGenderβ] == βMβ]df7b = df[df[βGenderβ] == βFβ]fig7a = px.histogram(df7a, x=βCustomer_Ageβ, nbins = 10, template=βseabornβ, barmode = βoverlayβ, color = βGenderβ)fig7b = px.histogram(df7b, x=βCustomer_Ageβ, nbins = 10, template = βggplot2β, opacity = 0.25, color = βGenderβ)fig7a.update_layout(title = βHistogram of Customersβ Age & Genderβ,xaxis_title = βCustomer Ageβ, yaxis_title = βStandard Countβ, width = 1600, height = 1400)fig7a.add_trace(fig7b.data[0])fig7a.write_image(path + βfighist7.pngβ)fig7a.show()
Fig. 8 shows overlapping histograms for the categorical variable Marital_Status according to the Married, Single, or Divorced condition. We used three different templates and the color argument to be able to identify each figure. The barmode and the opacity level were indicated with update_layout and update_traces respectively.
df8a = df[df[βMarital_Statusβ] == βMarriedβ]df8b = df[df[βMarital_Statusβ] == βSingleβ]df8c = df[df[βMarital_Statusβ] == βDivorcedβ]fig8a = px.histogram(df8a, x=βCustomer_Ageβ, nbins = 10, template = βseabornβ, color = βMarital_Statusβ )fig8b = px.histogram(df8b, x=βCustomer_Ageβ, nbins = 10, template = βggplot2β, color = βMarital_Statusβ)fig8c = px.histogram(df8c, x=βCustomer_Ageβ, nbins = 10, template = βplotly_darkβ, color = βMarital_Statusβ)fig8a.update_layout(title = βHistogram of Customersβ Age & Marital Statusβ,xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig8a.add_trace(fig8b.data[0])fig8a.add_trace(fig8c.data[0])fig8a.update_layout(barmode=βoverlayβ)fig8a.update_traces(opacity = 0.75)fig8a.write_image(path + βfighist8.pngβ)fig8a.show()
You can see (even on the PE website) categorical histograms and also date histograms.
Categorical histograms refer to counts from categories of a discrete variable. I do not consider that they can be defined as histograms, but rather as bar charts (BC). Remember that standard bar charts are used to make numerical comparisons amongst categories whilst histograms are used to show the frequency distribution of a numerical variable. Besides, there are no βgapsβ or spaces between the bars of a histogram, but it is mandatory to leave some space between the bars on a BC to clearly indicate that it refers to discrete (mutually exclusive) groups.
Something similar happens with date histograms: bins created as date ranges are equivalent to an average value for a specific year, so a bar chart or a line chart are more appropriate than a histogram to show the trend over time.
PE allows rotating the histogram so counts are in the horizontal axis while intervals or bins of the numerical variable are in the vertical axis. I do not find any technical reason for such an arrangement and it should be avoided because it is contrary to all existing histogram definitions.
Last but not least, using the histnorm argument with density or probability density values does not translate into density plots. Density plots attempt to show the probability density function of the data set through a continuous curve. With that goal in mind, density plots apply a statistical procedure (kernel density estimation) with the idea of smoothing the rectangular bars that characterize the histogram. As a result, a smooth curve is obtained that allows better visualization of the shape of the distribution (Fig. 9).
Plotly Express is a user-friendly data visualization tool that includes 11 pre-defined themes or templates to speed up work and avoid delays.
You can draw a histogram with a single line of code.
As histograms are considered to be some of the most commonly used charts, you must be very clear about when should histograms be used and which are the differences between them and bar charts. | [
{
"code": null,
"e": 706,
"s": 171,
"text": "Plotly Express (PE) is a high-level wrapper for Plotly.py fully compatible with the rest of the Plotly ecosystem. Based on the JavaScript library D3.js., it also has API wrappers for R, Julia, and many other programming languages. Itβs free and can be used in commercial applications and products. The library includes functions to plot standard charts and maps, as well as to perform faceting and animations with a single function call. With Plotly Express you can make interactive graphics online but you can also save them offline."
},
{
"code": null,
"e": 1260,
"s": 706,
"text": "Plotly Express is appropriate for quickly generating exploratory plots. Also, the chart can be quickly styled by using pre-defined themes or templates. According to Plotly main website βTheming generally refers to the process of defining default styles for visual elements. Themes in plotly are implemented using objects called templates. Templates are slightly more general than traditional themes because in addition to defining default styles, templates can pre-populate a figure with visual elements like annotations, shapes, images, and more.β [1]."
},
{
"code": null,
"e": 1327,
"s": 1260,
"text": "The built-in themes can be viewed through the following statement:"
},
{
"code": null,
"e": 2182,
"s": 1327,
"text": "There are 11 templates: ggplot2, seaborn, plotly, plotly_white, plotly_dark, simple_white, gridon, xgridoff, ygridoff, presentation, and none. The ggplot2 theme is inspired by the R data visualization package ggplot2, whilst the seaborn theme is inspired by the Python data visualization library Seaborn. plotly, plotly_white, and plotly_dark are original plotly.express themes. As indicated above, plotly is the default template, while plotly_dark is inspired by the JupyterLabβs dark theme. The following three themes are related to the presence or absence of grids: gridon, xgridoff, ygridoff. simple_white is a minimalist template for a clear and uncluttered chart. The presentation theme increases the size of fonts, markers, and line widths so that they can be viewed from a greater distance. This theme can be combined with any other (See Fig. 6)."
},
{
"code": null,
"e": 2400,
"s": 2182,
"text": "Each one of the above themes can be used as the template argument of any plotly.express function. So, a smart strategy is to iteratively test with the 11 themes until you find the one that best fits your storytelling."
},
{
"code": null,
"e": 2795,
"s": 2400,
"text": "A histogram is a graphical representation of the distribution of a dataset. Although its appearance is similar to that of a standard bar graph, instead of making comparisons between different items or categories or showing trends over time, a histogram is a plot that lets you show the underlying frequency distribution or the probability distribution of a single continuous numerical variable."
},
{
"code": null,
"e": 3227,
"s": 2795,
"text": "Histograms are two-dimensional plots with two axes; the vertical axis is a frequency axis whilst the horizontal axis is divided into a range of numeric values (intervals or bins) or time intervals. The frequency of each bin is shown by the area of vertical rectangular bars. Each bar covers a range of continuous numeric values of the variable under study. The vertical axis shows frequency values derived from counts for each bin."
},
{
"code": null,
"e": 3681,
"s": 3227,
"text": "Storytelling: a histogram is an appropriate graph for the initial exploration of a continuous variable. Through a set of vertical bars, it shows how the numerical values ββof that variable are distributed. The histogram allows us to calculate the probability of representation of any value of the continuous variable under study, which is of great importance if we want to make inferences and estimate population values ββfrom the results of our sample."
},
{
"code": null,
"e": 4033,
"s": 3681,
"text": "We worked with a dataset downloaded from Kaggle [2]. The dataset consists of 10,000 bank customers mentioning their age, salary, marital status, credit card limit, credit card category, education level, and additional features. The bank manager wants to know the age distribution of his customers. The following code allows us to answer his questions."
},
{
"code": null,
"e": 4379,
"s": 4033,
"text": "First, we import plotly.express as px, and the pandas library as pd. We load our dataset as a pandas dataframe (df) and select the column Customer_Age as the numerical variable whose frequency distribution we want to know. Draw the figure with px.histogram using plotly, the default template. Finally, we export our chart as a static PNG format."
},
{
"code": null,
"e": 4727,
"s": 4379,
"text": "PE allows you to choose the number of bins. Even though there are no strictly defined rules for the size and number of intervals, you must try out a few different numbers of bins. Always keep in mind that: few intervals do not allow us to elucidate the fine structure of the data distribution; many intervals give importance to the sampling error."
},
{
"code": null,
"e": 5010,
"s": 4727,
"text": "import pandas as pdimport plotly.express as pxpath = 'your path'df = pd.read_csv(path + 'CreditCardCustomersCols.csv', index_col = False, header = 0, sep = ';', engine='python')fig1 = px.histogram(df, x=\"Customer_Age\", nbins = 10)fig1.write_image(path + \"fighist1.png\")fig1.show()"
},
{
"code": null,
"e": 5229,
"s": 5010,
"text": "Fig. 1 shows the age distribution of the bank customers in five-year bins. Clearly, there are very few Centennials and few Millennials. The generation cohorts of the customers are represented by Baby Boomers and Gen X."
},
{
"code": null,
"e": 5427,
"s": 5229,
"text": "In Fig.2 we changed the theme to ggplot2, and update the chart with update.layout: set the title; the name of the x-axis and the name of the y-axis; set the figure dimensions with width and height."
},
{
"code": null,
"e": 5707,
"s": 5427,
"text": "fig2 = px.histogram(df, x=\"Customer_Age\", nbins = 10, template = 'ggplot2')fig2.update_layout(title = \"Histogram of Customers' Age \", xaxis_title = 'Customer Age', yaxis_title = 'Standard Count', width = 1600, height = 1400)fig2.write_image(path + \"fighist2.png\")fig2.show()"
},
{
"code": null,
"e": 5961,
"s": 5707,
"text": "By default, PE shows in the vertical axis frequencies (counts) of the data that fall into each bin. You can change this mode using the histnorm argument. This argument can take the following values: percent, probability, density, or probability density."
},
{
"code": null,
"e": 6120,
"s": 5961,
"text": "In Fig.3 we changed the theme to plotly_dark and the mode of representation from the standard count of samples to the percent one using the histnorm argument."
},
{
"code": null,
"e": 6194,
"s": 6120,
"text": "In Fig. 4 we changed the theme to simple_white and the mode toprobabilty."
},
{
"code": null,
"e": 6795,
"s": 6194,
"text": "fig3 = px.histogram(df, x=\"Customer_Age\", nbins = 10, template = 'plotly_dark', histnorm = 'percent')fig3.update_layout(title = \"Histogram of Customers' Age \",xaxis_title = 'Customer Age', yaxis_title = 'Percent Count', width = 1600, height = 1400)fig3.write_image(path + \"fighist3.png\")fig3.show()fig4 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = βsimple_whiteβ, histnorm = βprobabilityβ)fig4.update_layout(title = βHistogram of Customersβ Age β,xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig4.write_image(path + βfighist4.pngβ)fig4.show()"
},
{
"code": null,
"e": 7101,
"s": 6795,
"text": "In Fig. 5 we removed the x gridlines using the xgridoff template. Probability Density was selected as the mode of representation. In Fig. 6 we returned to the probability mode and changed the theme to simple_white+presentation. Clearly, there is an increase in the size of fonts, markers, and line widths."
},
{
"code": null,
"e": 7731,
"s": 7101,
"text": "fig5 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = xgridoffβ, histnorm = βprobability densityβ)fig5.update_layout(title = βHistogram of Customersβ Age β, xaxis_title = βCustomer Ageβ, yaxis_title = βProbability Densityβ, width = 1600, height = 1400)fig5.write_image(path + βfighist5.pngβ)fig5.show()fig6 = px.histogram(df, x=βCustomer_Ageβ, nbins = 10, template = βsimple_white+presentationβ, histnorm = βprobabilityβ)fig6.update_layout(title = βHistogram of Customersβ Age β, xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig6.write_image(path + βfighist6.pngβ)fig6.show()"
},
{
"code": null,
"e": 8547,
"s": 7731,
"text": "Overlapping histograms are used to compare the frequency distribution of a continuous variable in two or more categories. Even though the PE website indicates that you can draw several histograms for the different values of one column using the argument color, I did not get a proper chart. So, I filtered the dataframe for the two different values of the categorical variable βGenderβ, use twice the px.histogram function, and βmergeβ both figures with the add_trace method. As the px.histogram function does not have a text attribute, we used the argument color only for labeling purposes. We used different themes to be able to identify each figure and the barmode = βoverlayβ argument to get the overlapping. Figure 7 shows that there is no difference in the distribution of customers according to their gender."
},
{
"code": null,
"e": 9074,
"s": 8547,
"text": "df7a = df[df[βGenderβ] == βMβ]df7b = df[df[βGenderβ] == βFβ]fig7a = px.histogram(df7a, x=βCustomer_Ageβ, nbins = 10, template=βseabornβ, barmode = βoverlayβ, color = βGenderβ)fig7b = px.histogram(df7b, x=βCustomer_Ageβ, nbins = 10, template = βggplot2β, opacity = 0.25, color = βGenderβ)fig7a.update_layout(title = βHistogram of Customersβ Age & Genderβ,xaxis_title = βCustomer Ageβ, yaxis_title = βStandard Countβ, width = 1600, height = 1400)fig7a.add_trace(fig7b.data[0])fig7a.write_image(path + βfighist7.pngβ)fig7a.show()"
},
{
"code": null,
"e": 9404,
"s": 9074,
"text": "Fig. 8 shows overlapping histograms for the categorical variable Marital_Status according to the Married, Single, or Divorced condition. We used three different templates and the color argument to be able to identify each figure. The barmode and the opacity level were indicated with update_layout and update_traces respectively."
},
{
"code": null,
"e": 10202,
"s": 9404,
"text": "df8a = df[df[βMarital_Statusβ] == βMarriedβ]df8b = df[df[βMarital_Statusβ] == βSingleβ]df8c = df[df[βMarital_Statusβ] == βDivorcedβ]fig8a = px.histogram(df8a, x=βCustomer_Ageβ, nbins = 10, template = βseabornβ, color = βMarital_Statusβ )fig8b = px.histogram(df8b, x=βCustomer_Ageβ, nbins = 10, template = βggplot2β, color = βMarital_Statusβ)fig8c = px.histogram(df8c, x=βCustomer_Ageβ, nbins = 10, template = βplotly_darkβ, color = βMarital_Statusβ)fig8a.update_layout(title = βHistogram of Customersβ Age & Marital Statusβ,xaxis_title = βCustomer Ageβ, yaxis_title = βProbability β, width = 1600, height = 1400)fig8a.add_trace(fig8b.data[0])fig8a.add_trace(fig8c.data[0])fig8a.update_layout(barmode=βoverlayβ)fig8a.update_traces(opacity = 0.75)fig8a.write_image(path + βfighist8.pngβ)fig8a.show()"
},
{
"code": null,
"e": 10288,
"s": 10202,
"text": "You can see (even on the PE website) categorical histograms and also date histograms."
},
{
"code": null,
"e": 10848,
"s": 10288,
"text": "Categorical histograms refer to counts from categories of a discrete variable. I do not consider that they can be defined as histograms, but rather as bar charts (BC). Remember that standard bar charts are used to make numerical comparisons amongst categories whilst histograms are used to show the frequency distribution of a numerical variable. Besides, there are no βgapsβ or spaces between the bars of a histogram, but it is mandatory to leave some space between the bars on a BC to clearly indicate that it refers to discrete (mutually exclusive) groups."
},
{
"code": null,
"e": 11078,
"s": 10848,
"text": "Something similar happens with date histograms: bins created as date ranges are equivalent to an average value for a specific year, so a bar chart or a line chart are more appropriate than a histogram to show the trend over time."
},
{
"code": null,
"e": 11370,
"s": 11078,
"text": "PE allows rotating the histogram so counts are in the horizontal axis while intervals or bins of the numerical variable are in the vertical axis. I do not find any technical reason for such an arrangement and it should be avoided because it is contrary to all existing histogram definitions."
},
{
"code": null,
"e": 11900,
"s": 11370,
"text": "Last but not least, using the histnorm argument with density or probability density values does not translate into density plots. Density plots attempt to show the probability density function of the data set through a continuous curve. With that goal in mind, density plots apply a statistical procedure (kernel density estimation) with the idea of smoothing the rectangular bars that characterize the histogram. As a result, a smooth curve is obtained that allows better visualization of the shape of the distribution (Fig. 9)."
},
{
"code": null,
"e": 12042,
"s": 11900,
"text": "Plotly Express is a user-friendly data visualization tool that includes 11 pre-defined themes or templates to speed up work and avoid delays."
},
{
"code": null,
"e": 12095,
"s": 12042,
"text": "You can draw a histogram with a single line of code."
}
] |
awk - Unix, Linux Command | awk - Finds and Replaces text, database sort/validate/index
awk command searches files for text containing a pattern. When a line or text matches, awk performs a specific action on that line/text. The Program statement tells awk what operation to do; Program statement consists of a series of "rules" where each rule specifies one pattern to search for, and one action to perform when a particular pattern is found. A regular expression enclosed in slashes (/) is an awk pattern to match every input record whose text belongs to that set.
To return the second item($2) from each line of the output from an ls - l listing.
$ ls -l | awk '{print $2}'
13
3
17
7
To return the second item($2) from each line of the output from an ls - l listing.
$ ls -l | awk '{print $2}'
13
3
17
7
To print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in sample.txt.
First create a sample.txt file
Sample Line 1
Sample Line 2
Sample Line 3
$ awk '{print NR "- " $1 }' sample.txt
1 - Sample
2 - Sample
3 - Sample
To print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in sample.txt.
First create a sample.txt file
Sample Line 1
Sample Line 2
Sample Line 3
$ awk '{print NR "- " $1 }' sample.txt
1 - Sample
2 - Sample
3 - Sample
To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt.
$ awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line
To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt.
$ awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line
To print non-empty line from a file.
$ awk 'NF > 0' sample.txt
To print non-empty line from a file.
$ awk 'NF > 0' sample.txt
To print the length of the longest input line.
$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
13
To print the length of the longest input line.
$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
13
To print seven random numbers from zero to 100, inclusive.
$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24
29
85
15
59
19
81
To print seven random numbers from zero to 100, inclusive.
$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24
29
85
15
59
19
81
To count the lines in a file
$ awk 'END { print NR }' sample.txt
3
To count the lines in a file
$ awk 'END { print NR }' sample.txt
3
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": 10637,
"s": 10577,
"text": "awk - Finds and Replaces text, database sort/validate/index"
},
{
"code": null,
"e": 11116,
"s": 10637,
"text": "awk command searches files for text containing a pattern. When a line or text matches, awk performs a specific action on that line/text. The Program statement tells awk what operation to do; Program statement consists of a series of \"rules\" where each rule specifies one pattern to search for, and one action to perform when a particular pattern is found. A regular expression enclosed in slashes (/) is an awk pattern to match every input record whose text belongs to that set."
},
{
"code": null,
"e": 11238,
"s": 11116,
"text": "To return the second item($2) from each line of the output from an ls - l listing.\n$ ls -l | awk '{print $2}'\n13\n3\n17\n7\n\n"
},
{
"code": null,
"e": 11321,
"s": 11238,
"text": "To return the second item($2) from each line of the output from an ls - l listing."
},
{
"code": null,
"e": 11359,
"s": 11321,
"text": "$ ls -l | awk '{print $2}'\n13\n3\n17\n7\n"
},
{
"code": null,
"e": 11625,
"s": 11359,
"text": "To print the Row Number (NR), then a dash and space (\"- \") and then the first item ($1) from each line in sample.txt.\nFirst create a sample.txt file\nSample Line 1\nSample Line 2\nSample Line 3\n\n$ awk '{print NR \"- \" $1 }' sample.txt\n1 - Sample\n2 - Sample\n3 - Sample\n\n"
},
{
"code": null,
"e": 11743,
"s": 11625,
"text": "To print the Row Number (NR), then a dash and space (\"- \") and then the first item ($1) from each line in sample.txt."
},
{
"code": null,
"e": 11774,
"s": 11743,
"text": "First create a sample.txt file"
},
{
"code": null,
"e": 11817,
"s": 11774,
"text": "Sample Line 1\nSample Line 2\nSample Line 3\n"
},
{
"code": null,
"e": 11890,
"s": 11817,
"text": "$ awk '{print NR \"- \" $1 }' sample.txt\n1 - Sample\n2 - Sample\n3 - Sample\n"
},
{
"code": null,
"e": 12065,
"s": 11890,
"text": "To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt.\n$ awk '{print $1, $(NF-1) }' sample.txt\nSample Line\nSample Line\nSample Line\n\n"
},
{
"code": null,
"e": 12162,
"s": 12065,
"text": "To print the first item ($1) and then the second last item $(NF-1) from each line in sample.txt."
},
{
"code": null,
"e": 12239,
"s": 12162,
"text": "$ awk '{print $1, $(NF-1) }' sample.txt\nSample Line\nSample Line\nSample Line\n"
},
{
"code": null,
"e": 12304,
"s": 12239,
"text": "To print non-empty line from a file.\n$ awk 'NF > 0' sample.txt\n\n"
},
{
"code": null,
"e": 12341,
"s": 12304,
"text": "To print non-empty line from a file."
},
{
"code": null,
"e": 12368,
"s": 12341,
"text": "$ awk 'NF > 0' sample.txt\n"
},
{
"code": null,
"e": 12500,
"s": 12368,
"text": "To print the length of the longest input line.\n$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt\n13\n\n"
},
{
"code": null,
"e": 12547,
"s": 12500,
"text": "To print the length of the longest input line."
},
{
"code": null,
"e": 12631,
"s": 12547,
"text": "$ awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt\n13\n"
},
{
"code": null,
"e": 12781,
"s": 12631,
"text": "To print seven random numbers from zero to 100, inclusive.\n$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'\n24\n29\n85\n15\n59\n19\n81\n\n"
},
{
"code": null,
"e": 12840,
"s": 12781,
"text": "To print seven random numbers from zero to 100, inclusive."
},
{
"code": null,
"e": 12930,
"s": 12840,
"text": "$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'\n24\n29\n85\n15\n59\n19\n81\n"
},
{
"code": null,
"e": 12999,
"s": 12930,
"text": "To count the lines in a file\n$ awk 'END { print NR }' sample.txt\n3\n\n"
},
{
"code": null,
"e": 13028,
"s": 12999,
"text": "To count the lines in a file"
},
{
"code": null,
"e": 13067,
"s": 13028,
"text": "$ awk 'END { print NR }' sample.txt\n3\n"
},
{
"code": null,
"e": 13102,
"s": 13067,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 13130,
"s": 13102,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13164,
"s": 13130,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13181,
"s": 13164,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13214,
"s": 13181,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13225,
"s": 13214,
"text": " Pradeep D"
},
{
"code": null,
"e": 13260,
"s": 13225,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13276,
"s": 13260,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 13309,
"s": 13276,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13321,
"s": 13309,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 13353,
"s": 13321,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13361,
"s": 13353,
"text": " Uplatz"
},
{
"code": null,
"e": 13368,
"s": 13361,
"text": " Print"
},
{
"code": null,
"e": 13379,
"s": 13368,
"text": " Add Notes"
}
] |
PHP Object Inheritance | Inheritance is an important principle of object oriented programming methodology. Using this principle, relation between two classes can be defined. PHP supports inheritance in its object model.
PHP uses extends keyword to establish relationship between two classes.
class B extends A
where A is the base class (also called parent called) and B is called a subclass or child class. Child class inherits public and protected methods of parent class. Child class may redefine or override any of inherited methods. If not, inherited methods will retain their functionality as defined in parent class, when used with object of child class.
Definition of parent class must precede child class definition. In this case, definition of A class should appear before definition of class B in the script.
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?>
If autoloading is enabled, definition of parent class is obtained by loading the class script.
Following code shows that child class inherits public and protected members of parent class
Live Demo
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class\n" ;
}
private function privatemethod(){
echo "This is private method of parent class\n" ;
}
}
class childclass extends parentclass{
public function childmethod(){
$this->protectedmethod();
//$this->privatemethod(); //this will produce error
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>
This will produce following result. β
This is public method of parent class
This is protected method of parent class
PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'
If a method inherited from parent class is redefined in child class, new definition overrides earlier functionality. In following example, publicmethod is defined again in child class
Live Demo
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class\n" ;
}
private function privatemethod(){
echo "This is private method of parent class\n" ;
}
}
class childclass extends parentclass{
public function publicmethod(){
echo "public method of parent class is overridden in child class\n" ;
}
}
$obj=new childclass();
$obj->publicmethod();
?>
This will produce following result. β
public method of parent class is overridden in child class
PHP doesn't support multiple inheritance. Hence a class can not extend two or more classes. However, it supports heirarchical inheritance as follows:
Live Demo
<?php
class A{
function test(){
echo "method in A class";
}
}
class B extends A{
//
}
class C extends B{
//
}
$obj=new C();
$obj->test();
?>
This will show following result
method in A class | [
{
"code": null,
"e": 1257,
"s": 1062,
"text": "Inheritance is an important principle of object oriented programming methodology. Using this principle, relation between two classes can be defined. PHP supports inheritance in its object model."
},
{
"code": null,
"e": 1329,
"s": 1257,
"text": "PHP uses extends keyword to establish relationship between two classes."
},
{
"code": null,
"e": 1347,
"s": 1329,
"text": "class B extends A"
},
{
"code": null,
"e": 1698,
"s": 1347,
"text": "where A is the base class (also called parent called) and B is called a subclass or child class. Child class inherits public and protected methods of parent class. Child class may redefine or override any of inherited methods. If not, inherited methods will retain their functionality as defined in parent class, when used with object of child class."
},
{
"code": null,
"e": 1856,
"s": 1698,
"text": "Definition of parent class must precede child class definition. In this case, definition of A class should appear before definition of class B in the script."
},
{
"code": null,
"e": 1991,
"s": 1856,
"text": "<?php\nclass A{\n //properties, constants and methods of class A\n}\nclass B extends A{\n //public and protected methods inherited\n}\n?>"
},
{
"code": null,
"e": 2086,
"s": 1991,
"text": "If autoloading is enabled, definition of parent class is obtained by loading the class script."
},
{
"code": null,
"e": 2178,
"s": 2086,
"text": "Following code shows that child class inherits public and protected members of parent class"
},
{
"code": null,
"e": 2189,
"s": 2178,
"text": " Live Demo"
},
{
"code": null,
"e": 2751,
"s": 2189,
"text": "<?php\nclass parentclass{\n public function publicmethod(){\n echo \"This is public method of parent class\\n\" ;\n }\n protected function protectedmethod(){\n echo \"This is protected method of parent class\\n\" ;\n }\n private function privatemethod(){\n echo \"This is private method of parent class\\n\" ;\n }\n}\nclass childclass extends parentclass{\n public function childmethod(){\n $this->protectedmethod();\n //$this->privatemethod(); //this will produce error\n }\n}\n$obj=new childclass();\n$obj->publicmethod();\n$obj->childmethod();\n?>"
},
{
"code": null,
"e": 2789,
"s": 2751,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 2979,
"s": 2789,
"text": "This is public method of parent class\nThis is protected method of parent class\nPHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'"
},
{
"code": null,
"e": 3163,
"s": 2979,
"text": "If a method inherited from parent class is redefined in child class, new definition overrides earlier functionality. In following example, publicmethod is defined again in child class"
},
{
"code": null,
"e": 3174,
"s": 3163,
"text": " Live Demo"
},
{
"code": null,
"e": 3675,
"s": 3174,
"text": "<?php\nclass parentclass{\npublic function publicmethod(){\n echo \"This is public method of parent class\\n\" ;\n}\nprotected function protectedmethod(){\n echo \"This is protected method of parent class\\n\" ;\n}\nprivate function privatemethod(){\n echo \"This is private method of parent class\\n\" ;\n}\n}\nclass childclass extends parentclass{\n public function publicmethod(){\n echo \"public method of parent class is overridden in child class\\n\" ;\n }\n}\n$obj=new childclass();\n$obj->publicmethod();\n?>"
},
{
"code": null,
"e": 3713,
"s": 3675,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 3772,
"s": 3713,
"text": "public method of parent class is overridden in child class"
},
{
"code": null,
"e": 3922,
"s": 3772,
"text": "PHP doesn't support multiple inheritance. Hence a class can not extend two or more classes. However, it supports heirarchical inheritance as follows:"
},
{
"code": null,
"e": 3933,
"s": 3922,
"text": " Live Demo"
},
{
"code": null,
"e": 4092,
"s": 3933,
"text": "<?php\nclass A{\n function test(){\n echo \"method in A class\";\n }\n}\nclass B extends A{\n //\n}\nclass C extends B{\n //\n}\n$obj=new C();\n$obj->test();\n?>"
},
{
"code": null,
"e": 4124,
"s": 4092,
"text": "This will show following result"
},
{
"code": null,
"e": 4142,
"s": 4124,
"text": "method in A class"
}
] |
Python | Extract specific keys from dictionary - GeeksforGeeks | 25 Mar, 2022
We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container. Letβs discuss certain ways in which this can be performed. Method #1 : Using dictionary comprehension + items() This problem can be performed by reconstruction using the keys extracted through items function that wish to be filtered and dictionary function makes the desired dictionary.
Python3
# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dictionary comprehension + items() # initializing dictionarytest_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint("The original dictionary : " + str(test_dict)) # Using dictionary comprehension + items()# Extracting specific keys from dictionaryres = {key: test_dict[key] for key in test_dict.keys() & {'akshat', 'nikhil'}} # print resultprint("The filtered dictionary is : " + str(res))
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
Method #2 : Using dict() The dict function can be used to perform this task by converting the logic performed using list comprehension into a dictionary.
Python3
C++
# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dict() # initializing dictionarytest_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint("The original dictionary : " + str(test_dict)) # Using dict()# Extracting specific keys from dictionaryres = dict((k, test_dict[k]) for k in ['nikhil', 'akshat'] if k in test_dict) # print resultprint("The filtered dictionary is : " + str(res))
#include <iostream>using namespace std; int main() { cout<<"GFG!"; return 0;}
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
rkbhola5
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 24500,
"s": 24472,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 25005,
"s": 24500,
"text": "We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container. Letβs discuss certain ways in which this can be performed. Method #1 : Using dictionary comprehension + items() This problem can be performed by reconstruction using the keys extracted through items function that wish to be filtered and dictionary function makes the desired dictionary. "
},
{
"code": null,
"e": 25013,
"s": 25005,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dictionary comprehension + items() # initializing dictionarytest_dict = {'nikhil' : 1, \"akash\" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint(\"The original dictionary : \" + str(test_dict)) # Using dictionary comprehension + items()# Extracting specific keys from dictionaryres = {key: test_dict[key] for key in test_dict.keys() & {'akshat', 'nikhil'}} # print resultprint(\"The filtered dictionary is : \" + str(res))",
"e": 25555,
"s": 25013,
"text": null
},
{
"code": null,
"e": 25690,
"s": 25555,
"text": "The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}\nThe filtered dictionary is : {'akshat': 3, 'nikhil': 1}"
},
{
"code": null,
"e": 25847,
"s": 25690,
"text": " Method #2 : Using dict() The dict function can be used to perform this task by converting the logic performed using list comprehension into a dictionary. "
},
{
"code": null,
"e": 25855,
"s": 25847,
"text": "Python3"
},
{
"code": null,
"e": 25859,
"s": 25855,
"text": "C++"
},
{
"code": "# Python3 code to demonstrate# Extracting specific keys from dictionary# Using dict() # initializing dictionarytest_dict = {'nikhil' : 1, \"akash\" : 2, 'akshat' : 3, 'manjeet' : 4} # printing original listprint(\"The original dictionary : \" + str(test_dict)) # Using dict()# Extracting specific keys from dictionaryres = dict((k, test_dict[k]) for k in ['nikhil', 'akshat'] if k in test_dict) # print resultprint(\"The filtered dictionary is : \" + str(res))",
"e": 26353,
"s": 25859,
"text": null
},
{
"code": "#include <iostream>using namespace std; int main() { cout<<\"GFG!\"; return 0;}",
"e": 26438,
"s": 26353,
"text": null
},
{
"code": null,
"e": 26573,
"s": 26438,
"text": "The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}\nThe filtered dictionary is : {'akshat': 3, 'nikhil': 1}"
},
{
"code": null,
"e": 26582,
"s": 26573,
"text": "rkbhola5"
},
{
"code": null,
"e": 26609,
"s": 26582,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26616,
"s": 26609,
"text": "Python"
},
{
"code": null,
"e": 26632,
"s": 26616,
"text": "Python Programs"
},
{
"code": null,
"e": 26730,
"s": 26632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26739,
"s": 26730,
"text": "Comments"
},
{
"code": null,
"e": 26752,
"s": 26739,
"text": "Old Comments"
},
{
"code": null,
"e": 26770,
"s": 26752,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26792,
"s": 26770,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26824,
"s": 26792,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26866,
"s": 26824,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26892,
"s": 26866,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26914,
"s": 26892,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26960,
"s": 26914,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27017,
"s": 26960,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 27055,
"s": 27017,
"text": "Python | Convert a list to dictionary"
}
] |
How to set cookies in ReactJS? | In this chapter, we are going to see how to set, remove and retrieve cookies in a React application.
Cookies are the data stored in the form of key-value pairs that are used to store information about the user on their computer by the websites that the users browse and use it to verify them.
To set or remove the cookies, we are going to use a third-party dependency of react-cookie.
npm install react-cookie
Or,
yarn add react-cookie
Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager.
In this example, we will build a React application that takes the username and password from the user and stores it as a cookie in the userβs computer.
Firstly, wrap the index.js or the root app component of your application with the CookiesProvider component from the react-cookie package.
After that use the useCookies hook provided by it which has a syntax of β
const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
Cookies: Javascript object with all of the userβs cookies.
Cookies: Javascript object with all of the userβs cookies.
setCookie: Function to set the cookies.
setCookie: Function to set the cookies.
removeCookie: Function to remove the cookies.
removeCookie: Function to remove the cookies.
index.jsx
import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
document.getElementById('root')
);
App.jsx
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';
const App = () => {
const [name, setName] = useState('');
const [pwd, setPwd] = useState('');
const [cookies, setCookie] = useCookies(['user']);
const handle = () => {
setCookie('Name', name, { path: '/' });
setCookie('Password', pwd, { path: '/' });
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="name"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>
<button onClick={handle}>Set Cookie</button>
</div>
</div>
);
};
export default App;
In the above example, when the Set-Cookie button is clicked then the handle function is executed which will set the cookies for the user. The path:'/' signifies that the cookie is available for all the pages of the website.
This will produce the following result.
After the cookies have been set, we can access them by writing cookies.{cookies key name}
App.jsx
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';
const App = () => {
const [name, setName] = useState('');
const [pwd, setPwd] = useState('');
const [cookies, setCookie] = useCookies(['user']);
const handle = () => {
setCookie('Name', name, { path: '/' });
setCookie('Password', pwd, { path: '/' });
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="Password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>
<button onClick={handle}>Set Cookie</button>{' '}
</div>
<br />
{cookies.Name && (
<div>
Name: <p>{cookies.Name}</p>
</div>
)}
{cookies.Password && (
<div>
Password: <p>{cookies.Password}</p>
</div>
)}
</div>
);
};
export default App;
In the above example, when the Set Cookie button and the cookies are set, the value of these cookies will be displayed accordingly.
This will produce the following result. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this chapter, we are going to see how to set, remove and retrieve cookies in a React application."
},
{
"code": null,
"e": 1355,
"s": 1163,
"text": "Cookies are the data stored in the form of key-value pairs that are used to store information about the user on their computer by the websites that the users browse and use it to verify them."
},
{
"code": null,
"e": 1447,
"s": 1355,
"text": "To set or remove the cookies, we are going to use a third-party dependency of react-cookie."
},
{
"code": null,
"e": 1472,
"s": 1447,
"text": "npm install react-cookie"
},
{
"code": null,
"e": 1476,
"s": 1472,
"text": "Or,"
},
{
"code": null,
"e": 1498,
"s": 1476,
"text": "yarn add react-cookie"
},
{
"code": null,
"e": 1631,
"s": 1498,
"text": "Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager."
},
{
"code": null,
"e": 1783,
"s": 1631,
"text": "In this example, we will build a React application that takes the username and password from the user and stores it as a cookie in the userβs computer."
},
{
"code": null,
"e": 1922,
"s": 1783,
"text": "Firstly, wrap the index.js or the root app component of your application with the CookiesProvider component from the react-cookie package."
},
{
"code": null,
"e": 1996,
"s": 1922,
"text": "After that use the useCookies hook provided by it which has a syntax of β"
},
{
"code": null,
"e": 2068,
"s": 1996,
"text": "const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);"
},
{
"code": null,
"e": 2127,
"s": 2068,
"text": "Cookies: Javascript object with all of the userβs cookies."
},
{
"code": null,
"e": 2186,
"s": 2127,
"text": "Cookies: Javascript object with all of the userβs cookies."
},
{
"code": null,
"e": 2226,
"s": 2186,
"text": "setCookie: Function to set the cookies."
},
{
"code": null,
"e": 2266,
"s": 2226,
"text": "setCookie: Function to set the cookies."
},
{
"code": null,
"e": 2312,
"s": 2266,
"text": "removeCookie: Function to remove the cookies."
},
{
"code": null,
"e": 2358,
"s": 2312,
"text": "removeCookie: Function to remove the cookies."
},
{
"code": null,
"e": 2368,
"s": 2358,
"text": "index.jsx"
},
{
"code": null,
"e": 2616,
"s": 2368,
"text": "import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { CookiesProvider } from \"react-cookie\";\nimport App from \"./App\";\n\nReactDOM.render(\n <CookiesProvider>\n <App />\n </CookiesProvider>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 2624,
"s": 2616,
"text": "App.jsx"
},
{
"code": null,
"e": 3488,
"s": 2624,
"text": "import React, { useState } from 'react';\nimport { useCookies } from 'react-cookie';\n\nconst App = () => {\n const [name, setName] = useState('');\n const [pwd, setPwd] = useState('');\n const [cookies, setCookie] = useCookies(['user']);\n\n const handle = () => {\n setCookie('Name', name, { path: '/' });\n setCookie('Password', pwd, { path: '/' });\n };\n return (\n <div className=\"App\">\n <h1>Name of the user:</h1>\n <input\n placeholder=\"name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n />\n <h1>Password of the user:</h1>\n <input\n type=\"password\"\n placeholder=\"name\"\n value={pwd}\n onChange={(e) => setPwd(e.target.value)}\n />\n <div>\n <button onClick={handle}>Set Cookie</button>\n </div>\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 3712,
"s": 3488,
"text": "In the above example, when the Set-Cookie button is clicked then the handle function is executed which will set the cookies for the user. The path:'/' signifies that the cookie is available for all the pages of the website."
},
{
"code": null,
"e": 3752,
"s": 3712,
"text": "This will produce the following result."
},
{
"code": null,
"e": 3842,
"s": 3752,
"text": "After the cookies have been set, we can access them by writing cookies.{cookies key name}"
},
{
"code": null,
"e": 3850,
"s": 3842,
"text": "App.jsx"
},
{
"code": null,
"e": 4940,
"s": 3850,
"text": "import React, { useState } from 'react';\nimport { useCookies } from 'react-cookie';\n\nconst App = () => {\n const [name, setName] = useState('');\n const [pwd, setPwd] = useState('');\n const [cookies, setCookie] = useCookies(['user']);\n\n const handle = () => {\n setCookie('Name', name, { path: '/' });\n setCookie('Password', pwd, { path: '/' });\n };\n return (\n <div className=\"App\">\n <h1>Name of the user:</h1>\n <input\n placeholder=\"Name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n />\n <h1>Password of the user:</h1>\n <input\n type=\"password\"\n placeholder=\"Password\"\n value={pwd}\n onChange={(e) => setPwd(e.target.value)}\n />\n <div>\n <button onClick={handle}>Set Cookie</button>{' '}\n </div>\n <br />\n {cookies.Name && (\n <div>\n Name: <p>{cookies.Name}</p>\n </div>\n )}\n {cookies.Password && (\n <div>\n Password: <p>{cookies.Password}</p>\n </div>\n )}\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 5072,
"s": 4940,
"text": "In the above example, when the Set Cookie button and the cookies are set, the value of these cookies will be displayed accordingly."
},
{
"code": null,
"e": 5112,
"s": 5072,
"text": "This will produce the following result."
}
] |
R - Poisson Regression | Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers. For example, the count of number of births or number of wins in a football match series. Also the values of the response variables follow a Poisson distribution.
The general mathematical equation for Poisson regression is β
log(y) = a + b1x1 + b2x2 + bnxn.....
Following is the description of the parameters used β
y is the response variable.
y is the response variable.
a and b are the numeric coefficients.
a and b are the numeric coefficients.
x is the predictor variable.
x is the predictor variable.
The function used to create the Poisson regression model is the glm() function.
The basic syntax for glm() function in Poisson regression is β
glm(formula,data,family)
Following is the description of the parameters used in above functions β
formula is the symbol presenting the relationship between the variables.
formula is the symbol presenting the relationship between the variables.
data is the data set giving the values of these variables.
data is the data set giving the values of these variables.
family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression.
family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression.
We have the in-built data set "warpbreaks" which describes the effect of wool type (A or B) and tension (low, medium or high) on the number of warp breaks per loom. Let's consider "breaks" as the response variable which is a count of number of breaks. The wool "type" and "tension" are taken as predictor variables.
Input Data
input <- warpbreaks
print(head(input))
When we execute the above code, it produces the following result β
breaks wool tension
1 26 A L
2 30 A L
3 54 A L
4 25 A L
5 70 A L
6 52 A L
output <-glm(formula = breaks ~ wool+tension, data = warpbreaks,
family = poisson)
print(summary(output))
When we execute the above code, it produces the following result β
Call:
glm(formula = breaks ~ wool + tension, family = poisson, data = warpbreaks)
Deviance Residuals:
Min 1Q Median 3Q Max
-3.6871 -1.6503 -0.4269 1.1902 4.2616
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 3.69196 0.04541 81.302 < 2e-16 ***
woolB -0.20599 0.05157 -3.994 6.49e-05 ***
tensionM -0.32132 0.06027 -5.332 9.73e-08 ***
tensionH -0.51849 0.06396 -8.107 5.21e-16 ***
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
(Dispersion parameter for poisson family taken to be 1)
Null deviance: 297.37 on 53 degrees of freedom
Residual deviance: 210.39 on 50 degrees of freedom
AIC: 493.06
Number of Fisher Scoring iterations: 4
In the summary we look for the p-value in the last column to be less than 0.05 to consider an impact of the predictor variable on the response variable. As seen the wooltype B having tension type M and H have impact on the count of breaks.
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2694,
"s": 2402,
"text": "Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers. For example, the count of number of births or number of wins in a football match series. Also the values of the response variables follow a Poisson distribution."
},
{
"code": null,
"e": 2756,
"s": 2694,
"text": "The general mathematical equation for Poisson regression is β"
},
{
"code": null,
"e": 2794,
"s": 2756,
"text": "log(y) = a + b1x1 + b2x2 + bnxn.....\n"
},
{
"code": null,
"e": 2848,
"s": 2794,
"text": "Following is the description of the parameters used β"
},
{
"code": null,
"e": 2876,
"s": 2848,
"text": "y is the response variable."
},
{
"code": null,
"e": 2904,
"s": 2876,
"text": "y is the response variable."
},
{
"code": null,
"e": 2942,
"s": 2904,
"text": "a and b are the numeric coefficients."
},
{
"code": null,
"e": 2980,
"s": 2942,
"text": "a and b are the numeric coefficients."
},
{
"code": null,
"e": 3009,
"s": 2980,
"text": "x is the predictor variable."
},
{
"code": null,
"e": 3038,
"s": 3009,
"text": "x is the predictor variable."
},
{
"code": null,
"e": 3118,
"s": 3038,
"text": "The function used to create the Poisson regression model is the glm() function."
},
{
"code": null,
"e": 3181,
"s": 3118,
"text": "The basic syntax for glm() function in Poisson regression is β"
},
{
"code": null,
"e": 3207,
"s": 3181,
"text": "glm(formula,data,family)\n"
},
{
"code": null,
"e": 3280,
"s": 3207,
"text": "Following is the description of the parameters used in above functions β"
},
{
"code": null,
"e": 3353,
"s": 3280,
"text": "formula is the symbol presenting the relationship between the variables."
},
{
"code": null,
"e": 3426,
"s": 3353,
"text": "formula is the symbol presenting the relationship between the variables."
},
{
"code": null,
"e": 3485,
"s": 3426,
"text": "data is the data set giving the values of these variables."
},
{
"code": null,
"e": 3544,
"s": 3485,
"text": "data is the data set giving the values of these variables."
},
{
"code": null,
"e": 3649,
"s": 3544,
"text": "family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression."
},
{
"code": null,
"e": 3754,
"s": 3649,
"text": "family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression."
},
{
"code": null,
"e": 4070,
"s": 3754,
"text": "We have the in-built data set \"warpbreaks\" which describes the effect of wool type (A or B) and tension (low, medium or high) on the number of warp breaks per loom. Let's consider \"breaks\" as the response variable which is a count of number of breaks. The wool \"type\" and \"tension\" are taken as predictor variables."
},
{
"code": null,
"e": 4081,
"s": 4070,
"text": "Input Data"
},
{
"code": null,
"e": 4120,
"s": 4081,
"text": "input <- warpbreaks\nprint(head(input))"
},
{
"code": null,
"e": 4187,
"s": 4120,
"text": "When we execute the above code, it produces the following result β"
},
{
"code": null,
"e": 4355,
"s": 4187,
"text": " breaks wool tension\n1 26 A L\n2 30 A L\n3 54 A L\n4 25 A L\n5 70 A L\n6 52 A L\n"
},
{
"code": null,
"e": 4464,
"s": 4355,
"text": "output <-glm(formula = breaks ~ wool+tension, data = warpbreaks,\n family = poisson)\nprint(summary(output))"
},
{
"code": null,
"e": 4531,
"s": 4464,
"text": "When we execute the above code, it produces the following result β"
},
{
"code": null,
"e": 5297,
"s": 4531,
"text": "Call:\nglm(formula = breaks ~ wool + tension, family = poisson, data = warpbreaks)\n\nDeviance Residuals: \n Min 1Q Median 3Q Max \n -3.6871 -1.6503 -0.4269 1.1902 4.2616 \n\nCoefficients:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 3.69196 0.04541 81.302 < 2e-16 ***\nwoolB -0.20599 0.05157 -3.994 6.49e-05 ***\ntensionM -0.32132 0.06027 -5.332 9.73e-08 ***\ntensionH -0.51849 0.06396 -8.107 5.21e-16 ***\n---\nSignif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1\n\n(Dispersion parameter for poisson family taken to be 1)\n\n Null deviance: 297.37 on 53 degrees of freedom\nResidual deviance: 210.39 on 50 degrees of freedom\nAIC: 493.06\n\nNumber of Fisher Scoring iterations: 4\n"
},
{
"code": null,
"e": 5537,
"s": 5297,
"text": "In the summary we look for the p-value in the last column to be less than 0.05 to consider an impact of the predictor variable on the response variable. As seen the wooltype B having tension type M and H have impact on the count of breaks."
},
{
"code": null,
"e": 5570,
"s": 5537,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5585,
"s": 5570,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5620,
"s": 5585,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5635,
"s": 5620,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5670,
"s": 5635,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5685,
"s": 5670,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5718,
"s": 5685,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5732,
"s": 5718,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5767,
"s": 5732,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5782,
"s": 5767,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5817,
"s": 5782,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5831,
"s": 5817,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5838,
"s": 5831,
"text": " Print"
},
{
"code": null,
"e": 5849,
"s": 5838,
"text": " Add Notes"
}
] |
Theano - Quick Guide | Have you developed Machine Learning models in Python? Then, obviously you know the intricacies in developing these models. The development is typically a slow process taking hours and days of computational power.
The Machine Learning model development requires lot of mathematical computations. These generally require arithmetic computations especially large matrices of multiple dimensions. These days we use Neural Networks rather than the traditional statistical techniques for developing Machine Learning applications. The Neural Networks need to be trained over a huge amount of data. The training is done in batches of data of reasonable size. Thus, the learning process is iterative. Thus, if the computations are not done efficiently, training the network can take several hours or even days. Thus, the optimization of the executable code is highly desired. And that is what exactly Theano provides.
Theano is a Python library that lets you define mathematical expressions used in Machine Learning, optimize these expressions and evaluate those very efficiently by decisively using GPUs in critical areas. It can rival typical full C-implementations in most of the cases.
Theano was written at the LISA lab with the intention of providing rapid development of efficient machine learning algorithms. It is released under a BSD license.
In this tutorial, you will learn to use Theano library.
Theano can be installed on Windows, MacOS, and Linux. The installation in all the cases is trivial. Before you install Theano, you must install its dependencies. The following is the list of dependencies β
Python
NumPy β Required
SciPy β Required only for Sparse Matrix and special functions
BLAS β Provides standard building blocks for performing basic vector and matrix operations
The optional packages that you may choose to install depending on your needs are β
nose: To run Theanoβs test-suite
Sphinx β For building documentation
Graphiz and pydot β To handle graphics and images
NVIDIA CUDA drivers β Required for GPU code generation/execution
libgpuarray β Required for GPU/CPU code generation on CUDA and OpenCL devices
We shall discuss the steps to install Theano in MacOS.
To install Theano and its dependencies, you use pip from the command line as follows. These are the minimal dependencies that we are going to need in this tutorial.
$ pip install Theano
$ pip install numpy
$ pip install scipy
$ pip install pydot
You also need to install OSx command line developer tool using the following command β
$ xcode-select --install
You will see the following screen. Click on the Install button to install the tool.
On successful installation, you will see the success message on the console.
After the installation completes successfully, open a new notebook in the Anaconda Jupyter. In the code cell, enter the following Python script β
import theano
from theano import tensor
a = tensor.dscalar()
b = tensor.dscalar()
c = a + b
f = theano.function([a,b], c)
d = f(1.5, 2.5)
print (d)
Execute the script and you should see the following output β
4.0
The screenshot of the execution is shown below for your quick reference β
If you get the above output, your Theano installation is successful. If not, follow the debug instructions on Theano download page to fix the issues.
Now that you have successfully installed Theano, let us first try to understand what is Theano? Theano is a Python library. It lets you define, optimize, and evaluate mathematical expressions, especially the ones which are used in Machine Learning Model development. Theano itself does not contain any pre-defined ML models; it just facilitates its development. It is especially useful while dealing with multi-dimensional arrays. It seamlessly integrates with NumPy, which is a fundamental and widely used package for scientific computations in Python.
Theano facilitates defining mathematical expressions used in ML development. Such expressions generally involve Matrix Arithmetic, Differentiation, Gradient Computation, and so on.
Theano first builds the entire Computational Graph for your model. It then compiles it into highly efficient code by applying several optimization techniques on the graph. The compiled code is injected into Theano runtime by a special operation called function available in Theano. We execute this function repetitively to train a neural network. The training time is substantially reduced as compared to using pure Python coding or even a full C implementation.
We shall now understand the process of Theano development. Let us begin with how to define a mathematical expression in Theano.
Let us begin our journey of Theano by defining and evaluating a trivial expression in Theano. Consider the following trivial expression that adds two scalars β
c = a + b
Where a, b are variables and c is the expression output. In Theano, defining and evaluating even this trivial expression is tricky.
Let us understand the steps to evaluate the above expression.
First, we need to import Theano library in our program, which we do using the following statement β
from theano import *
Rather than importing the individual packages, we have used * in the above statement to include all packages from the Theano library.
Next, we will declare a variable called a using the following statement β
a = tensor.dscalar()
The dscalar method declares a decimal scalar variable. The execution of the above statement creates a variable called a in your program code. Likewise, we will create variable b using the following statement β
b = tensor.dscalar()
Next, we will define our expression that operates on these two variables a and b.
c = a + b
In Theano, the execution of the above statement does not perform the scalar addition of the two variables a and b.
To evaluate the above expression, we need to define a function in Theano as follows β
f = theano.function([a,b], c)
The function function takes two arguments, the first argument is an input to the function and the second one is its output. The above declaration states that the first argument is of type array consisting of two elements a and b. The output is a scalar unit called c. This function will be referenced with the variable name f in our further code.
The call to the function f is made using the following statement β
d = f(3.5, 5.5)
The input to the function is an array consisting of two scalars: 3.5 and 5.5. The output of execution is assigned to the scalar variable d. To print the contents of d, we will use the print statement β
print (d)
The execution would cause the value of d to be printed on the console, which is 9.0 in this case.
The complete program listing is given here for your quick reference β
from theano import *
a = tensor.dscalar()
b = tensor.dscalar()
c = a + b
f = theano.function([a,b], c)
d = f(3.5, 5.5)
print (d)
Execute the above code and you will see the output as 9.0. The screen shot is shown here β
Now, let us discuss a slightly more complex example that computes the multiplication of two matrices.
We will compute a dot product of two matrices. The first matrix is of dimension 2 x 3 and the second one is of dimension 3 x 2. The matrices that we used as input and their product are expressed here β
To write a Theano expression for the above, we first declare two variables to represent our matrices as follows β
a = tensor.dmatrix()
b = tensor.dmatrix()
The dmatrix is the Type of matrices for doubles. Note that we do not specify the matrix size anywhere. Thus, these variables can represent matrices of any dimension.
To compute the dot product, we used the built-in function called dot as follows β
c = tensor.dot(a,b)
The output of multiplication is assigned to a matrix variable called c.
Next, we define a function as in the earlier example to evaluate the expression.
f = theano.function([a,b], c)
Note that the input to the function are two variables a and b which are of matrix type. The function output is assigned to variable c which would automatically be of matrix type.
We now invoke the function using the following statement β
d = f([[0, -1, 2], [4, 11, 2]], [[3, -1],[1,2], [6,1]])
The two variables in the above statement are NumPy arrays. You may explicitly define NumPy arrays as shown here β
f(numpy.array([[0, -1, 2], [4, 11, 2]]),
numpy.array([[3, -1],[1,2], [6,1]]))
After d is computed we print its value β
print (d)
You will see the following output on the output β
[[11. 0.]
[25. 20.]]
The complete program listing is given here:
from theano import *
a = tensor.dmatrix()
b = tensor.dmatrix()
c = tensor.dot(a,b)
f = theano.function([a,b], c)
d = f([[0, -1, 2],[4, 11, 2]], [[3, -1],[1,2],[6,1]])
print (d)
The screenshot of the program execution is shown here β
From the above two examples, you may have noticed that in Theano we create an expression which is eventually evaluated using the Theano function. Theano uses advanced optimization techniques to optimize the execution of an expression. To visualize the computation graph, Theano provides a printing package in its library.
To see the computation graph for our scalar addition program, use the printing library as follows β
theano.printing.pydotprint(f, outfile="scalar_addition.png", var_with_name_simple=True)
When you execute this statement, a file called scalar_addition.png will be created on your machine. The saved computation graph is displayed here for your quick reference β
The complete program listing to generate the above image is given below β
from theano import *
a = tensor.dscalar()
b = tensor.dscalar()
c = a + b
f = theano.function([a,b], c)
theano.printing.pydotprint(f, outfile="scalar_addition.png", var_with_name_simple=True)
Now, try creating the computation graph for our matrix multiplier. The complete listing for generating this graph is given below β
from theano import *
a = tensor.dmatrix()
b = tensor.dmatrix()
c = tensor.dot(a,b)
f = theano.function([a,b], c)
theano.printing.pydotprint(f, outfile="matrix_dot_product.png", var_with_name_simple=True)
The generated graph is shown here β
In larger expressions, the computational graphs could be very complex. One such graph taken from Theano documentation is shown here β
To understand the working of Theano, it is important to first know the significance of these computational graphs. With this understanding, we shall know the importance of Theano.
By looking at the complexity of the computational graphs, you will now be able to understand the purpose behind developing Theano. A typical compiler would provide local optimizations in the program as it never looks at the entire computation as a single unit.
Theano implements very advanced optimization techniques to optimize the full computational graph. It combines the aspects of Algebra with aspects of an optimizing compiler. A part of the graph may be compiled into C-language code. For repeated calculations, the evaluation speed is critical and Theano meets this purpose by generating a very efficient code.
Now, that you have understood the basics of Theano, let us begin with the different data types available to you for creating your expressions. The following table gives you a partial list of data types defined in Theano.
bscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4, btensor5, btensor6, btensor7
wscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4, wtensor5, wtensor6, wtensor7
iscalar, ivector, imatrix, irow, icol, itensor3, itensor4, itensor5, itensor6, itensor7
lscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4, ltensor5, ltensor6, ltensor7
fscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4, ftensor5, ftensor6, ftensor7
dscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4, dtensor5, dtensor6, dtensor7
cscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4, ctensor5, ctensor6, ctensor7
The above list is not exhaustive and the reader is referred to the tensor creation document for a complete list.
I will now give you a few examples of how to create variables of various kinds of data in Theano.
To construct a scalar variable you would use the syntax β
x = theano.tensor.scalar ('x')
x = 5.0
print (x)
5.0
To create a one dimensional array, use the following declaration β
f = theano.tensor.vector
f = (2.0, 5.0, 3.0)
print (f)f = theano.tensor.vector
f = (2.0, 5.0, 3.0)
print (f)
print (f[0])
print (f[2])
(2.0, 5.0, 3.0)
2.0
3.0
If you do f[3] it would generate an index out of range error as shown here β
print f([3])
IndexError Traceback (most recent call last)
<ipython-input-13-2a9c2a643c3a> in <module>
4 print (f[0])
5 print (f[2])
----> 6 print (f[3])
IndexError: tuple index out of range
To declare a two-dimensional array you would use the following code snippet β
m = theano.tensor.matrix
m = ([2,3], [4,5], [2,4])
print (m[0])
print (m[1][0])
[2, 3]
4
To declare a 5-dimensional array, use the following syntax β
m5 = theano.tensor.tensor5
m5 = ([0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14])
print (m5[1])
print (m5[2][3])
[5, 6, 7, 8, 9]
13
You may declare a 3-dimensional array by using the data type tensor3 in place of tensor5, a 4-dimensional array using the data type tensor4, and so on up to tensor7.
Sometimes, you may want to create variables of the same type in a single declaration. You can do so by using the following syntax β
from theano.tensor import * x, y, z = dmatrices('x', 'y', 'z')
x = ([1,2],[3,4],[5,6])
y = ([7,8],[9,10],[11,12])
z = ([13,14],[15,16],[17,18])
print (x[2])
print (y[1])
print (z[0])
[5, 6]
[9, 10]
[13, 14]
In the previous chapter, while discussing the data types, we created and used Theano variables. To reiterate, we would use the following syntax to create a variable in Theano β
x = theano.tensor.fvector('x')
In this statement, we have created a variable x of type vector containing 32-bit floats. We are also naming it as x. The names are generally useful for debugging.
To declare a vector of 32-bit integers, you would use the following syntax β
i32 = theano.tensor.ivector
Here, we do not specify a name for the variable.
To declare a three-dimensional vector consisting of 64-bit floats, you would use the following declaration β
f64 = theano.tensor.dtensor3
The various types of constructors along with their data types are listed in the table below β
You may use a generic vector constructor and specify the data type explicitly as follows β
x = theano.tensor.vector ('x', dtype=int32)
In the next chapter, we will learn how to create shared variables.
Many a times, you would need to create variables which are shared between different functions and also between multiple calls to the same function. To cite an example, while training a neural network you create weights vector for assigning a weight to each feature under consideration. This vector is modified on every iteration during the network training. Thus, it has to be globally accessible across the multiple calls to the same function. So we create a shared variable for this purpose. Typically, Theano moves such shared variables to the GPU, provided one is available. This speeds up the computation.
You create a shared variable you use the following syntax β
import numpy
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')
Here the NumPy array consisting of four floating point numbers is created. To set/get the W value you would use the following code snippet β
import numpy
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')
print ("Original: ", W.get_value())
print ("Setting new values (0.5, 0.2, 0.4, 0.2)")
W.set_value([0.5, 0.2, 0.4, 0.2])
print ("After modifications:", W.get_value())
Original: [0.1 0.25 0.15 0.3 ]
Setting new values (0.5, 0.2, 0.4, 0.2)
After modifications: [0.5 0.2 0.4 0.2]
Theano function acts like a hook for interacting with the symbolic graph. A symbolic graph is compiled into a highly efficient execution code. It achieves this by restructuring mathematical equations to make them faster. It compiles some parts of the expression into C language code. It moves some tensors to the GPU, and so on.
The efficient compiled code is now given as an input to the Theano function. When you execute the Theano function, it assigns the result of computation to the variables specified by us. The type of optimization may be specified as FAST_COMPILE or FAST_RUN. This is specified in the environment variable THEANO_FLAGS.
A Theano function is declared using the following syntax β
f = theano.function ([x], y)
The first parameter [x] is the list of input variables and the second parameter y is the list of output variables.
Having now understood the basics of Theano, let us begin Theano coding with a trivial example.
Theano is quite useful in training neural networks where we have to repeatedly calculate cost, and gradients to achieve an optimum. On large datasets, this becomes computationally intensive. Theano does this efficiently due to its internal optimizations of the computational graph that we have seen earlier.
We shall now learn how to use Theano library to train a network. We will take a simple case where we start with a four feature dataset. We compute the sum of these features after applying a certain weight (importance) to each feature.
The goal of the training is to modify the weights assigned to each feature so that the sum reaches a target value of 100.
sum = f1 * w1 + f2 * w2 + f3 * w3 + f4 * w4
Where f1, f2, ... are the feature values and w1, w2, ... are the weights.
Let me quantize the example for a better understanding of the problem statement. We will assume an initial value of 1.0 for each feature and we will take w1 equals 0.1, w2 equals 0.25, w3 equals 0.15, and w4 equals 0.3. There is no definite logic in assigning the weight values, it is just our intuition. Thus, the initial sum is as follows β
sum = 1.0 * 0.1 + 1.0 * 0.25 + 1.0 * 0.15 + 1.0 * 0.3
Which sums to 0.8. Now, we will keep modifying the weight assignment so that this sum approaches 100. The current resultant value of 0.8 is far away from our desired target value of 100. In Machine Learning terms, we define cost as the difference between the target value minus the current output value, typically squared to blow up the error. We reduce this cost in each iteration by calculating the gradients and updating our weights vector.
Let us see how this entire logic is implemented in Theano.
We first declare our input vector x as follows β
x = tensor.fvector('x')
Where x is a single dimensional array of float values.
We define a scalar target variable as given below β
target = tensor.fscalar('target')
Next, we create a weights tensor W with the initial values as discussed above β
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')
We now calculate the output using the following expression β
y = (x * W).sum()
Note that in the above statement x and W are the vectors and not simple scalar variables. We now calculate the error (cost) with the following expression β
cost = tensor.sqr(target - y)
The cost is the difference between the target value and the current output, squared.
To calculate the gradient which tells us how far we are from the target, we use the built-in grad method as follows β
gradients = tensor.grad(cost, [W])
We now update the weights vector by taking a learning rate of 0.1 as follows β
W_updated = W - (0.1 * gradients[0])
Next, we need to update our weights vector using the above values. We do this in the following statement β
updates = [(W, W_updated)]
Lastly, we define a function in Theano to compute the sum.
f = function([x, target], y, updates=updates)
To invoke the above function a certain number of times, we create a for loop as follows β
for i in range(10):
output = f([1.0, 1.0, 1.0, 1.0], 100.0)
As said earlier, the input to the function is a vector containing the initial values for the four features - we assign the value of 1.0 to each feature without any specific reason. You may assign different values of your choice and check if the function ultimately converges. We will print the values of the weight vector and the corresponding output in each iteration. It is shown in the below code β
print ("iteration: ", i)
print ("Modified Weights: ", W.get_value())
print ("Output: ", output)
The complete program listing is reproduced here for your quick reference β
from theano import *
import numpy
x = tensor.fvector('x')
target = tensor.fscalar('target')
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')
print ("Weights: ", W.get_value())
y = (x * W).sum()
cost = tensor.sqr(target - y)
gradients = tensor.grad(cost, [W])
W_updated = W - (0.1 * gradients[0])
updates = [(W, W_updated)]
f = function([x, target], y, updates=updates)
for i in range(10):
output = f([1.0, 1.0, 1.0, 1.0], 100.0)
print ("iteration: ", i)
print ("Modified Weights: ", W.get_value())
print ("Output: ", output)
When you run the program you will see the following output β
Weights: [0.1 0.25 0.15 0.3 ]
iteration: 0
Modified Weights: [19.94 20.09 19.99 20.14]
Output: 0.8
iteration: 1
Modified Weights: [23.908 24.058 23.958 24.108]
Output: 80.16000000000001
iteration: 2
Modified Weights: [24.7016 24.8516 24.7516 24.9016]
Output: 96.03200000000001
iteration: 3
Modified Weights: [24.86032 25.01032 24.91032 25.06032]
Output: 99.2064
iteration: 4
Modified Weights: [24.892064 25.042064 24.942064 25.092064]
Output: 99.84128
iteration: 5
Modified Weights: [24.8984128 25.0484128 24.9484128 25.0984128]
Output: 99.968256
iteration: 6
Modified Weights: [24.89968256 25.04968256 24.94968256 25.09968256]
Output: 99.9936512
iteration: 7
Modified Weights: [24.89993651 25.04993651 24.94993651 25.09993651]
Output: 99.99873024
iteration: 8
Modified Weights: [24.8999873 25.0499873 24.9499873 25.0999873]
Output: 99.99974604799999
iteration: 9
Modified Weights: [24.89999746 25.04999746 24.94999746 25.09999746]
Output: 99.99994920960002
Observe that after four iterations, the output is 99.96 and after five iterations, it is 99.99, which is close to our desired target of 100.0.
Depending on the desired accuracy, you may safely conclude that the network is trained in 4 to 5 iterations. After the training completes, look up the weights vector, which after 5 iterations takes the following values β
iteration: 5
Modified Weights: [24.8984128 25.0484128 24.9484128 25.0984128]
You may now use these values in your network for deploying the model.
The Machine Learning model building involves intensive and repetitive computations involving tensors. These require intensive computing resources. As a regular compiler would provide the optimizations at the local level, it does not generally produce a fast execution code.
Theano first builds a computational graph for the entire computation. As the whole picture of computation is available as a single image during compilation, several optimization techniques can be applied during pre-compilation and thatβs what exactly Theano does. It restructures the computational graph, partly converts it into C, moves shared variables to GPU, and so on to generate a very fast executable code. The compiled code is then executed by a Theano function which just acts as a hook for injecting the compiled code into the runtime. Theano has proved its credentials and is widely accepted in both academics and industry.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2082,
"s": 1869,
"text": "Have you developed Machine Learning models in Python? Then, obviously you know the intricacies in developing these models. The development is typically a slow process taking hours and days of computational power."
},
{
"code": null,
"e": 2778,
"s": 2082,
"text": "The Machine Learning model development requires lot of mathematical computations. These generally require arithmetic computations especially large matrices of multiple dimensions. These days we use Neural Networks rather than the traditional statistical techniques for developing Machine Learning applications. The Neural Networks need to be trained over a huge amount of data. The training is done in batches of data of reasonable size. Thus, the learning process is iterative. Thus, if the computations are not done efficiently, training the network can take several hours or even days. Thus, the optimization of the executable code is highly desired. And that is what exactly Theano provides."
},
{
"code": null,
"e": 3050,
"s": 2778,
"text": "Theano is a Python library that lets you define mathematical expressions used in Machine Learning, optimize these expressions and evaluate those very efficiently by decisively using GPUs in critical areas. It can rival typical full C-implementations in most of the cases."
},
{
"code": null,
"e": 3213,
"s": 3050,
"text": "Theano was written at the LISA lab with the intention of providing rapid development of efficient machine learning algorithms. It is released under a BSD license."
},
{
"code": null,
"e": 3269,
"s": 3213,
"text": "In this tutorial, you will learn to use Theano library."
},
{
"code": null,
"e": 3475,
"s": 3269,
"text": "Theano can be installed on Windows, MacOS, and Linux. The installation in all the cases is trivial. Before you install Theano, you must install its dependencies. The following is the list of dependencies β"
},
{
"code": null,
"e": 3482,
"s": 3475,
"text": "Python"
},
{
"code": null,
"e": 3499,
"s": 3482,
"text": "NumPy β Required"
},
{
"code": null,
"e": 3561,
"s": 3499,
"text": "SciPy β Required only for Sparse Matrix and special functions"
},
{
"code": null,
"e": 3652,
"s": 3561,
"text": "BLAS β Provides standard building blocks for performing basic vector and matrix operations"
},
{
"code": null,
"e": 3735,
"s": 3652,
"text": "The optional packages that you may choose to install depending on your needs are β"
},
{
"code": null,
"e": 3768,
"s": 3735,
"text": "nose: To run Theanoβs test-suite"
},
{
"code": null,
"e": 3804,
"s": 3768,
"text": "Sphinx β For building documentation"
},
{
"code": null,
"e": 3854,
"s": 3804,
"text": "Graphiz and pydot β To handle graphics and images"
},
{
"code": null,
"e": 3919,
"s": 3854,
"text": "NVIDIA CUDA drivers β Required for GPU code generation/execution"
},
{
"code": null,
"e": 3997,
"s": 3919,
"text": "libgpuarray β Required for GPU/CPU code generation on CUDA and OpenCL devices"
},
{
"code": null,
"e": 4052,
"s": 3997,
"text": "We shall discuss the steps to install Theano in MacOS."
},
{
"code": null,
"e": 4217,
"s": 4052,
"text": "To install Theano and its dependencies, you use pip from the command line as follows. These are the minimal dependencies that we are going to need in this tutorial."
},
{
"code": null,
"e": 4299,
"s": 4217,
"text": "$ pip install Theano\n$ pip install numpy\n$ pip install scipy\n$ pip install pydot\n"
},
{
"code": null,
"e": 4386,
"s": 4299,
"text": "You also need to install OSx command line developer tool using the following command β"
},
{
"code": null,
"e": 4412,
"s": 4386,
"text": "$ xcode-select --install\n"
},
{
"code": null,
"e": 4496,
"s": 4412,
"text": "You will see the following screen. Click on the Install button to install the tool."
},
{
"code": null,
"e": 4573,
"s": 4496,
"text": "On successful installation, you will see the success message on the console."
},
{
"code": null,
"e": 4719,
"s": 4573,
"text": "After the installation completes successfully, open a new notebook in the Anaconda Jupyter. In the code cell, enter the following Python script β"
},
{
"code": null,
"e": 4867,
"s": 4719,
"text": "import theano\nfrom theano import tensor\na = tensor.dscalar()\nb = tensor.dscalar()\nc = a + b\nf = theano.function([a,b], c)\nd = f(1.5, 2.5)\nprint (d)"
},
{
"code": null,
"e": 4928,
"s": 4867,
"text": "Execute the script and you should see the following output β"
},
{
"code": null,
"e": 4933,
"s": 4928,
"text": "4.0\n"
},
{
"code": null,
"e": 5007,
"s": 4933,
"text": "The screenshot of the execution is shown below for your quick reference β"
},
{
"code": null,
"e": 5157,
"s": 5007,
"text": "If you get the above output, your Theano installation is successful. If not, follow the debug instructions on Theano download page to fix the issues."
},
{
"code": null,
"e": 5711,
"s": 5157,
"text": "Now that you have successfully installed Theano, let us first try to understand what is Theano? Theano is a Python library. It lets you define, optimize, and evaluate mathematical expressions, especially the ones which are used in Machine Learning Model development. Theano itself does not contain any pre-defined ML models; it just facilitates its development. It is especially useful while dealing with multi-dimensional arrays. It seamlessly integrates with NumPy, which is a fundamental and widely used package for scientific computations in Python."
},
{
"code": null,
"e": 5892,
"s": 5711,
"text": "Theano facilitates defining mathematical expressions used in ML development. Such expressions generally involve Matrix Arithmetic, Differentiation, Gradient Computation, and so on."
},
{
"code": null,
"e": 6355,
"s": 5892,
"text": "Theano first builds the entire Computational Graph for your model. It then compiles it into highly efficient code by applying several optimization techniques on the graph. The compiled code is injected into Theano runtime by a special operation called function available in Theano. We execute this function repetitively to train a neural network. The training time is substantially reduced as compared to using pure Python coding or even a full C implementation."
},
{
"code": null,
"e": 6483,
"s": 6355,
"text": "We shall now understand the process of Theano development. Let us begin with how to define a mathematical expression in Theano."
},
{
"code": null,
"e": 6643,
"s": 6483,
"text": "Let us begin our journey of Theano by defining and evaluating a trivial expression in Theano. Consider the following trivial expression that adds two scalars β"
},
{
"code": null,
"e": 6653,
"s": 6643,
"text": "c = a + b"
},
{
"code": null,
"e": 6785,
"s": 6653,
"text": "Where a, b are variables and c is the expression output. In Theano, defining and evaluating even this trivial expression is tricky."
},
{
"code": null,
"e": 6847,
"s": 6785,
"text": "Let us understand the steps to evaluate the above expression."
},
{
"code": null,
"e": 6947,
"s": 6847,
"text": "First, we need to import Theano library in our program, which we do using the following statement β"
},
{
"code": null,
"e": 6969,
"s": 6947,
"text": "from theano import *\n"
},
{
"code": null,
"e": 7103,
"s": 6969,
"text": "Rather than importing the individual packages, we have used * in the above statement to include all packages from the Theano library."
},
{
"code": null,
"e": 7177,
"s": 7103,
"text": "Next, we will declare a variable called a using the following statement β"
},
{
"code": null,
"e": 7199,
"s": 7177,
"text": "a = tensor.dscalar()\n"
},
{
"code": null,
"e": 7409,
"s": 7199,
"text": "The dscalar method declares a decimal scalar variable. The execution of the above statement creates a variable called a in your program code. Likewise, we will create variable b using the following statement β"
},
{
"code": null,
"e": 7431,
"s": 7409,
"text": "b = tensor.dscalar()\n"
},
{
"code": null,
"e": 7513,
"s": 7431,
"text": "Next, we will define our expression that operates on these two variables a and b."
},
{
"code": null,
"e": 7523,
"s": 7513,
"text": "c = a + b"
},
{
"code": null,
"e": 7638,
"s": 7523,
"text": "In Theano, the execution of the above statement does not perform the scalar addition of the two variables a and b."
},
{
"code": null,
"e": 7724,
"s": 7638,
"text": "To evaluate the above expression, we need to define a function in Theano as follows β"
},
{
"code": null,
"e": 7755,
"s": 7724,
"text": "f = theano.function([a,b], c)\n"
},
{
"code": null,
"e": 8102,
"s": 7755,
"text": "The function function takes two arguments, the first argument is an input to the function and the second one is its output. The above declaration states that the first argument is of type array consisting of two elements a and b. The output is a scalar unit called c. This function will be referenced with the variable name f in our further code."
},
{
"code": null,
"e": 8169,
"s": 8102,
"text": "The call to the function f is made using the following statement β"
},
{
"code": null,
"e": 8185,
"s": 8169,
"text": "d = f(3.5, 5.5)"
},
{
"code": null,
"e": 8387,
"s": 8185,
"text": "The input to the function is an array consisting of two scalars: 3.5 and 5.5. The output of execution is assigned to the scalar variable d. To print the contents of d, we will use the print statement β"
},
{
"code": null,
"e": 8398,
"s": 8387,
"text": "print (d)\n"
},
{
"code": null,
"e": 8496,
"s": 8398,
"text": "The execution would cause the value of d to be printed on the console, which is 9.0 in this case."
},
{
"code": null,
"e": 8566,
"s": 8496,
"text": "The complete program listing is given here for your quick reference β"
},
{
"code": null,
"e": 8695,
"s": 8566,
"text": "from theano import *\na = tensor.dscalar()\nb = tensor.dscalar()\nc = a + b\nf = theano.function([a,b], c)\nd = f(3.5, 5.5)\nprint (d)"
},
{
"code": null,
"e": 8786,
"s": 8695,
"text": "Execute the above code and you will see the output as 9.0. The screen shot is shown here β"
},
{
"code": null,
"e": 8888,
"s": 8786,
"text": "Now, let us discuss a slightly more complex example that computes the multiplication of two matrices."
},
{
"code": null,
"e": 9090,
"s": 8888,
"text": "We will compute a dot product of two matrices. The first matrix is of dimension 2 x 3 and the second one is of dimension 3 x 2. The matrices that we used as input and their product are expressed here β"
},
{
"code": null,
"e": 9204,
"s": 9090,
"text": "To write a Theano expression for the above, we first declare two variables to represent our matrices as follows β"
},
{
"code": null,
"e": 9247,
"s": 9204,
"text": "a = tensor.dmatrix()\nb = tensor.dmatrix()\n"
},
{
"code": null,
"e": 9413,
"s": 9247,
"text": "The dmatrix is the Type of matrices for doubles. Note that we do not specify the matrix size anywhere. Thus, these variables can represent matrices of any dimension."
},
{
"code": null,
"e": 9495,
"s": 9413,
"text": "To compute the dot product, we used the built-in function called dot as follows β"
},
{
"code": null,
"e": 9516,
"s": 9495,
"text": "c = tensor.dot(a,b)\n"
},
{
"code": null,
"e": 9588,
"s": 9516,
"text": "The output of multiplication is assigned to a matrix variable called c."
},
{
"code": null,
"e": 9669,
"s": 9588,
"text": "Next, we define a function as in the earlier example to evaluate the expression."
},
{
"code": null,
"e": 9700,
"s": 9669,
"text": "f = theano.function([a,b], c)\n"
},
{
"code": null,
"e": 9879,
"s": 9700,
"text": "Note that the input to the function are two variables a and b which are of matrix type. The function output is assigned to variable c which would automatically be of matrix type."
},
{
"code": null,
"e": 9938,
"s": 9879,
"text": "We now invoke the function using the following statement β"
},
{
"code": null,
"e": 9995,
"s": 9938,
"text": "d = f([[0, -1, 2], [4, 11, 2]], [[3, -1],[1,2], [6,1]])\n"
},
{
"code": null,
"e": 10109,
"s": 9995,
"text": "The two variables in the above statement are NumPy arrays. You may explicitly define NumPy arrays as shown here β"
},
{
"code": null,
"e": 10188,
"s": 10109,
"text": "f(numpy.array([[0, -1, 2], [4, 11, 2]]),\nnumpy.array([[3, -1],[1,2], [6,1]]))\n"
},
{
"code": null,
"e": 10229,
"s": 10188,
"text": "After d is computed we print its value β"
},
{
"code": null,
"e": 10240,
"s": 10229,
"text": "print (d)\n"
},
{
"code": null,
"e": 10290,
"s": 10240,
"text": "You will see the following output on the output β"
},
{
"code": null,
"e": 10312,
"s": 10290,
"text": "[[11. 0.]\n[25. 20.]]\n"
},
{
"code": null,
"e": 10534,
"s": 10312,
"text": "The complete program listing is given here:\nfrom theano import *\na = tensor.dmatrix()\nb = tensor.dmatrix()\nc = tensor.dot(a,b)\nf = theano.function([a,b], c)\nd = f([[0, -1, 2],[4, 11, 2]], [[3, -1],[1,2],[6,1]])\nprint (d)\n"
},
{
"code": null,
"e": 10590,
"s": 10534,
"text": "The screenshot of the program execution is shown here β"
},
{
"code": null,
"e": 10912,
"s": 10590,
"text": "From the above two examples, you may have noticed that in Theano we create an expression which is eventually evaluated using the Theano function. Theano uses advanced optimization techniques to optimize the execution of an expression. To visualize the computation graph, Theano provides a printing package in its library."
},
{
"code": null,
"e": 11012,
"s": 10912,
"text": "To see the computation graph for our scalar addition program, use the printing library as follows β"
},
{
"code": null,
"e": 11101,
"s": 11012,
"text": "theano.printing.pydotprint(f, outfile=\"scalar_addition.png\", var_with_name_simple=True)\n"
},
{
"code": null,
"e": 11274,
"s": 11101,
"text": "When you execute this statement, a file called scalar_addition.png will be created on your machine. The saved computation graph is displayed here for your quick reference β"
},
{
"code": null,
"e": 11348,
"s": 11274,
"text": "The complete program listing to generate the above image is given below β"
},
{
"code": null,
"e": 11539,
"s": 11348,
"text": "from theano import *\na = tensor.dscalar()\nb = tensor.dscalar()\nc = a + b\nf = theano.function([a,b], c)\ntheano.printing.pydotprint(f, outfile=\"scalar_addition.png\", var_with_name_simple=True)"
},
{
"code": null,
"e": 11670,
"s": 11539,
"text": "Now, try creating the computation graph for our matrix multiplier. The complete listing for generating this graph is given below β"
},
{
"code": null,
"e": 11874,
"s": 11670,
"text": "from theano import *\na = tensor.dmatrix()\nb = tensor.dmatrix()\nc = tensor.dot(a,b)\nf = theano.function([a,b], c)\ntheano.printing.pydotprint(f, outfile=\"matrix_dot_product.png\", var_with_name_simple=True)"
},
{
"code": null,
"e": 11910,
"s": 11874,
"text": "The generated graph is shown here β"
},
{
"code": null,
"e": 12044,
"s": 11910,
"text": "In larger expressions, the computational graphs could be very complex. One such graph taken from Theano documentation is shown here β"
},
{
"code": null,
"e": 12224,
"s": 12044,
"text": "To understand the working of Theano, it is important to first know the significance of these computational graphs. With this understanding, we shall know the importance of Theano."
},
{
"code": null,
"e": 12485,
"s": 12224,
"text": "By looking at the complexity of the computational graphs, you will now be able to understand the purpose behind developing Theano. A typical compiler would provide local optimizations in the program as it never looks at the entire computation as a single unit."
},
{
"code": null,
"e": 12843,
"s": 12485,
"text": "Theano implements very advanced optimization techniques to optimize the full computational graph. It combines the aspects of Algebra with aspects of an optimizing compiler. A part of the graph may be compiled into C-language code. For repeated calculations, the evaluation speed is critical and Theano meets this purpose by generating a very efficient code."
},
{
"code": null,
"e": 13064,
"s": 12843,
"text": "Now, that you have understood the basics of Theano, let us begin with the different data types available to you for creating your expressions. The following table gives you a partial list of data types defined in Theano."
},
{
"code": null,
"e": 13152,
"s": 13064,
"text": "bscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4, btensor5, btensor6, btensor7"
},
{
"code": null,
"e": 13240,
"s": 13152,
"text": "wscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4, wtensor5, wtensor6, wtensor7"
},
{
"code": null,
"e": 13328,
"s": 13240,
"text": "iscalar, ivector, imatrix, irow, icol, itensor3, itensor4, itensor5, itensor6, itensor7"
},
{
"code": null,
"e": 13416,
"s": 13328,
"text": "lscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4, ltensor5, ltensor6, ltensor7"
},
{
"code": null,
"e": 13504,
"s": 13416,
"text": "fscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4, ftensor5, ftensor6, ftensor7"
},
{
"code": null,
"e": 13592,
"s": 13504,
"text": "dscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4, dtensor5, dtensor6, dtensor7"
},
{
"code": null,
"e": 13680,
"s": 13592,
"text": "cscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4, ctensor5, ctensor6, ctensor7"
},
{
"code": null,
"e": 13793,
"s": 13680,
"text": "The above list is not exhaustive and the reader is referred to the tensor creation document for a complete list."
},
{
"code": null,
"e": 13891,
"s": 13793,
"text": "I will now give you a few examples of how to create variables of various kinds of data in Theano."
},
{
"code": null,
"e": 13949,
"s": 13891,
"text": "To construct a scalar variable you would use the syntax β"
},
{
"code": null,
"e": 13998,
"s": 13949,
"text": "x = theano.tensor.scalar ('x')\nx = 5.0\nprint (x)"
},
{
"code": null,
"e": 14003,
"s": 13998,
"text": "5.0\n"
},
{
"code": null,
"e": 14070,
"s": 14003,
"text": "To create a one dimensional array, use the following declaration β"
},
{
"code": null,
"e": 14205,
"s": 14070,
"text": "f = theano.tensor.vector\nf = (2.0, 5.0, 3.0)\nprint (f)f = theano.tensor.vector\nf = (2.0, 5.0, 3.0)\nprint (f)\nprint (f[0])\nprint (f[2])"
},
{
"code": null,
"e": 14230,
"s": 14205,
"text": "(2.0, 5.0, 3.0)\n2.0\n3.0\n"
},
{
"code": null,
"e": 14307,
"s": 14230,
"text": "If you do f[3] it would generate an index out of range error as shown here β"
},
{
"code": null,
"e": 14321,
"s": 14307,
"text": "print f([3])\n"
},
{
"code": null,
"e": 14530,
"s": 14321,
"text": "IndexError Traceback (most recent call last)\n<ipython-input-13-2a9c2a643c3a> in <module>\n 4 print (f[0])\n 5 print (f[2])\n----> 6 print (f[3])\nIndexError: tuple index out of range\n"
},
{
"code": null,
"e": 14608,
"s": 14530,
"text": "To declare a two-dimensional array you would use the following code snippet β"
},
{
"code": null,
"e": 14688,
"s": 14608,
"text": "m = theano.tensor.matrix\nm = ([2,3], [4,5], [2,4])\nprint (m[0])\nprint (m[1][0])"
},
{
"code": null,
"e": 14698,
"s": 14688,
"text": "[2, 3]\n4\n"
},
{
"code": null,
"e": 14759,
"s": 14698,
"text": "To declare a 5-dimensional array, use the following syntax β"
},
{
"code": null,
"e": 14867,
"s": 14759,
"text": "m5 = theano.tensor.tensor5\nm5 = ([0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14])\nprint (m5[1])\nprint (m5[2][3])"
},
{
"code": null,
"e": 14887,
"s": 14867,
"text": "[5, 6, 7, 8, 9]\n13\n"
},
{
"code": null,
"e": 15053,
"s": 14887,
"text": "You may declare a 3-dimensional array by using the data type tensor3 in place of tensor5, a 4-dimensional array using the data type tensor4, and so on up to tensor7."
},
{
"code": null,
"e": 15185,
"s": 15053,
"text": "Sometimes, you may want to create variables of the same type in a single declaration. You can do so by using the following syntax β"
},
{
"code": null,
"e": 15374,
"s": 15185,
"text": "from theano.tensor import * x, y, z = dmatrices('x', 'y', 'z') \nx = ([1,2],[3,4],[5,6]) \ny = ([7,8],[9,10],[11,12]) \nz = ([13,14],[15,16],[17,18]) \nprint (x[2]) \nprint (y[1]) \nprint (z[0])"
},
{
"code": null,
"e": 15401,
"s": 15374,
"text": "[5, 6] \n[9, 10] \n[13, 14]\n"
},
{
"code": null,
"e": 15578,
"s": 15401,
"text": "In the previous chapter, while discussing the data types, we created and used Theano variables. To reiterate, we would use the following syntax to create a variable in Theano β"
},
{
"code": null,
"e": 15610,
"s": 15578,
"text": "x = theano.tensor.fvector('x')\n"
},
{
"code": null,
"e": 15773,
"s": 15610,
"text": "In this statement, we have created a variable x of type vector containing 32-bit floats. We are also naming it as x. The names are generally useful for debugging."
},
{
"code": null,
"e": 15850,
"s": 15773,
"text": "To declare a vector of 32-bit integers, you would use the following syntax β"
},
{
"code": null,
"e": 15879,
"s": 15850,
"text": "i32 = theano.tensor.ivector\n"
},
{
"code": null,
"e": 15928,
"s": 15879,
"text": "Here, we do not specify a name for the variable."
},
{
"code": null,
"e": 16037,
"s": 15928,
"text": "To declare a three-dimensional vector consisting of 64-bit floats, you would use the following declaration β"
},
{
"code": null,
"e": 16067,
"s": 16037,
"text": "f64 = theano.tensor.dtensor3\n"
},
{
"code": null,
"e": 16161,
"s": 16067,
"text": "The various types of constructors along with their data types are listed in the table below β"
},
{
"code": null,
"e": 16252,
"s": 16161,
"text": "You may use a generic vector constructor and specify the data type explicitly as follows β"
},
{
"code": null,
"e": 16297,
"s": 16252,
"text": "x = theano.tensor.vector ('x', dtype=int32)\n"
},
{
"code": null,
"e": 16364,
"s": 16297,
"text": "In the next chapter, we will learn how to create shared variables."
},
{
"code": null,
"e": 16975,
"s": 16364,
"text": "Many a times, you would need to create variables which are shared between different functions and also between multiple calls to the same function. To cite an example, while training a neural network you create weights vector for assigning a weight to each feature under consideration. This vector is modified on every iteration during the network training. Thus, it has to be globally accessible across the multiple calls to the same function. So we create a shared variable for this purpose. Typically, Theano moves such shared variables to the GPU, provided one is available. This speeds up the computation."
},
{
"code": null,
"e": 17035,
"s": 16975,
"text": "You create a shared variable you use the following syntax β"
},
{
"code": null,
"e": 17111,
"s": 17035,
"text": "import numpy\nW = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')\n"
},
{
"code": null,
"e": 17252,
"s": 17111,
"text": "Here the NumPy array consisting of four floating point numbers is created. To set/get the W value you would use the following code snippet β"
},
{
"code": null,
"e": 17493,
"s": 17252,
"text": "import numpy\nW = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')\nprint (\"Original: \", W.get_value())\nprint (\"Setting new values (0.5, 0.2, 0.4, 0.2)\")\nW.set_value([0.5, 0.2, 0.4, 0.2])\nprint (\"After modifications:\", W.get_value())"
},
{
"code": null,
"e": 17604,
"s": 17493,
"text": "Original: [0.1 0.25 0.15 0.3 ]\nSetting new values (0.5, 0.2, 0.4, 0.2)\nAfter modifications: [0.5 0.2 0.4 0.2]\n"
},
{
"code": null,
"e": 17933,
"s": 17604,
"text": "Theano function acts like a hook for interacting with the symbolic graph. A symbolic graph is compiled into a highly efficient execution code. It achieves this by restructuring mathematical equations to make them faster. It compiles some parts of the expression into C language code. It moves some tensors to the GPU, and so on."
},
{
"code": null,
"e": 18250,
"s": 17933,
"text": "The efficient compiled code is now given as an input to the Theano function. When you execute the Theano function, it assigns the result of computation to the variables specified by us. The type of optimization may be specified as FAST_COMPILE or FAST_RUN. This is specified in the environment variable THEANO_FLAGS."
},
{
"code": null,
"e": 18309,
"s": 18250,
"text": "A Theano function is declared using the following syntax β"
},
{
"code": null,
"e": 18339,
"s": 18309,
"text": "f = theano.function ([x], y)\n"
},
{
"code": null,
"e": 18454,
"s": 18339,
"text": "The first parameter [x] is the list of input variables and the second parameter y is the list of output variables."
},
{
"code": null,
"e": 18549,
"s": 18454,
"text": "Having now understood the basics of Theano, let us begin Theano coding with a trivial example."
},
{
"code": null,
"e": 18857,
"s": 18549,
"text": "Theano is quite useful in training neural networks where we have to repeatedly calculate cost, and gradients to achieve an optimum. On large datasets, this becomes computationally intensive. Theano does this efficiently due to its internal optimizations of the computational graph that we have seen earlier."
},
{
"code": null,
"e": 19092,
"s": 18857,
"text": "We shall now learn how to use Theano library to train a network. We will take a simple case where we start with a four feature dataset. We compute the sum of these features after applying a certain weight (importance) to each feature."
},
{
"code": null,
"e": 19214,
"s": 19092,
"text": "The goal of the training is to modify the weights assigned to each feature so that the sum reaches a target value of 100."
},
{
"code": null,
"e": 19259,
"s": 19214,
"text": "sum = f1 * w1 + f2 * w2 + f3 * w3 + f4 * w4\n"
},
{
"code": null,
"e": 19333,
"s": 19259,
"text": "Where f1, f2, ... are the feature values and w1, w2, ... are the weights."
},
{
"code": null,
"e": 19676,
"s": 19333,
"text": "Let me quantize the example for a better understanding of the problem statement. We will assume an initial value of 1.0 for each feature and we will take w1 equals 0.1, w2 equals 0.25, w3 equals 0.15, and w4 equals 0.3. There is no definite logic in assigning the weight values, it is just our intuition. Thus, the initial sum is as follows β"
},
{
"code": null,
"e": 19731,
"s": 19676,
"text": "sum = 1.0 * 0.1 + 1.0 * 0.25 + 1.0 * 0.15 + 1.0 * 0.3\n"
},
{
"code": null,
"e": 20175,
"s": 19731,
"text": "Which sums to 0.8. Now, we will keep modifying the weight assignment so that this sum approaches 100. The current resultant value of 0.8 is far away from our desired target value of 100. In Machine Learning terms, we define cost as the difference between the target value minus the current output value, typically squared to blow up the error. We reduce this cost in each iteration by calculating the gradients and updating our weights vector."
},
{
"code": null,
"e": 20234,
"s": 20175,
"text": "Let us see how this entire logic is implemented in Theano."
},
{
"code": null,
"e": 20283,
"s": 20234,
"text": "We first declare our input vector x as follows β"
},
{
"code": null,
"e": 20308,
"s": 20283,
"text": "x = tensor.fvector('x')\n"
},
{
"code": null,
"e": 20363,
"s": 20308,
"text": "Where x is a single dimensional array of float values."
},
{
"code": null,
"e": 20415,
"s": 20363,
"text": "We define a scalar target variable as given below β"
},
{
"code": null,
"e": 20450,
"s": 20415,
"text": "target = tensor.fscalar('target')\n"
},
{
"code": null,
"e": 20530,
"s": 20450,
"text": "Next, we create a weights tensor W with the initial values as discussed above β"
},
{
"code": null,
"e": 20593,
"s": 20530,
"text": "W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')\n"
},
{
"code": null,
"e": 20654,
"s": 20593,
"text": "We now calculate the output using the following expression β"
},
{
"code": null,
"e": 20673,
"s": 20654,
"text": "y = (x * W).sum()\n"
},
{
"code": null,
"e": 20829,
"s": 20673,
"text": "Note that in the above statement x and W are the vectors and not simple scalar variables. We now calculate the error (cost) with the following expression β"
},
{
"code": null,
"e": 20860,
"s": 20829,
"text": "cost = tensor.sqr(target - y)\n"
},
{
"code": null,
"e": 20945,
"s": 20860,
"text": "The cost is the difference between the target value and the current output, squared."
},
{
"code": null,
"e": 21063,
"s": 20945,
"text": "To calculate the gradient which tells us how far we are from the target, we use the built-in grad method as follows β"
},
{
"code": null,
"e": 21099,
"s": 21063,
"text": "gradients = tensor.grad(cost, [W])\n"
},
{
"code": null,
"e": 21178,
"s": 21099,
"text": "We now update the weights vector by taking a learning rate of 0.1 as follows β"
},
{
"code": null,
"e": 21216,
"s": 21178,
"text": "W_updated = W - (0.1 * gradients[0])\n"
},
{
"code": null,
"e": 21323,
"s": 21216,
"text": "Next, we need to update our weights vector using the above values. We do this in the following statement β"
},
{
"code": null,
"e": 21351,
"s": 21323,
"text": "updates = [(W, W_updated)]\n"
},
{
"code": null,
"e": 21410,
"s": 21351,
"text": "Lastly, we define a function in Theano to compute the sum."
},
{
"code": null,
"e": 21457,
"s": 21410,
"text": "f = function([x, target], y, updates=updates)\n"
},
{
"code": null,
"e": 21547,
"s": 21457,
"text": "To invoke the above function a certain number of times, we create a for loop as follows β"
},
{
"code": null,
"e": 21608,
"s": 21547,
"text": "for i in range(10):\noutput = f([1.0, 1.0, 1.0, 1.0], 100.0)\n"
},
{
"code": null,
"e": 22010,
"s": 21608,
"text": "As said earlier, the input to the function is a vector containing the initial values for the four features - we assign the value of 1.0 to each feature without any specific reason. You may assign different values of your choice and check if the function ultimately converges. We will print the values of the weight vector and the corresponding output in each iteration. It is shown in the below code β"
},
{
"code": null,
"e": 22107,
"s": 22010,
"text": "print (\"iteration: \", i)\nprint (\"Modified Weights: \", W.get_value())\nprint (\"Output: \", output)\n"
},
{
"code": null,
"e": 22182,
"s": 22107,
"text": "The complete program listing is reproduced here for your quick reference β"
},
{
"code": null,
"e": 22736,
"s": 22182,
"text": "from theano import *\nimport numpy\n\nx = tensor.fvector('x')\ntarget = tensor.fscalar('target')\n\nW = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')\nprint (\"Weights: \", W.get_value())\n\ny = (x * W).sum()\ncost = tensor.sqr(target - y)\ngradients = tensor.grad(cost, [W])\nW_updated = W - (0.1 * gradients[0])\nupdates = [(W, W_updated)]\n\nf = function([x, target], y, updates=updates)\nfor i in range(10):\n output = f([1.0, 1.0, 1.0, 1.0], 100.0)\n print (\"iteration: \", i)\n print (\"Modified Weights: \", W.get_value())\n print (\"Output: \", output)"
},
{
"code": null,
"e": 22797,
"s": 22736,
"text": "When you run the program you will see the following output β"
},
{
"code": null,
"e": 23756,
"s": 22797,
"text": "Weights: [0.1 0.25 0.15 0.3 ]\niteration: 0\nModified Weights: [19.94 20.09 19.99 20.14]\nOutput: 0.8\niteration: 1\nModified Weights: [23.908 24.058 23.958 24.108]\nOutput: 80.16000000000001\niteration: 2\nModified Weights: [24.7016 24.8516 24.7516 24.9016]\nOutput: 96.03200000000001\niteration: 3\nModified Weights: [24.86032 25.01032 24.91032 25.06032]\nOutput: 99.2064\niteration: 4\nModified Weights: [24.892064 25.042064 24.942064 25.092064]\nOutput: 99.84128\niteration: 5\nModified Weights: [24.8984128 25.0484128 24.9484128 25.0984128]\nOutput: 99.968256\niteration: 6\nModified Weights: [24.89968256 25.04968256 24.94968256 25.09968256]\nOutput: 99.9936512\niteration: 7\nModified Weights: [24.89993651 25.04993651 24.94993651 25.09993651]\nOutput: 99.99873024\niteration: 8\nModified Weights: [24.8999873 25.0499873 24.9499873 25.0999873]\nOutput: 99.99974604799999\niteration: 9\nModified Weights: [24.89999746 25.04999746 24.94999746 25.09999746]\nOutput: 99.99994920960002\n"
},
{
"code": null,
"e": 23899,
"s": 23756,
"text": "Observe that after four iterations, the output is 99.96 and after five iterations, it is 99.99, which is close to our desired target of 100.0."
},
{
"code": null,
"e": 24120,
"s": 23899,
"text": "Depending on the desired accuracy, you may safely conclude that the network is trained in 4 to 5 iterations. After the training completes, look up the weights vector, which after 5 iterations takes the following values β"
},
{
"code": null,
"e": 24198,
"s": 24120,
"text": "iteration: 5\nModified Weights: [24.8984128 25.0484128 24.9484128 25.0984128]\n"
},
{
"code": null,
"e": 24268,
"s": 24198,
"text": "You may now use these values in your network for deploying the model."
},
{
"code": null,
"e": 24542,
"s": 24268,
"text": "The Machine Learning model building involves intensive and repetitive computations involving tensors. These require intensive computing resources. As a regular compiler would provide the optimizations at the local level, it does not generally produce a fast execution code."
},
{
"code": null,
"e": 25177,
"s": 24542,
"text": "Theano first builds a computational graph for the entire computation. As the whole picture of computation is available as a single image during compilation, several optimization techniques can be applied during pre-compilation and thatβs what exactly Theano does. It restructures the computational graph, partly converts it into C, moves shared variables to GPU, and so on to generate a very fast executable code. The compiled code is then executed by a Theano function which just acts as a hook for injecting the compiled code into the runtime. Theano has proved its credentials and is widely accepted in both academics and industry."
},
{
"code": null,
"e": 25184,
"s": 25177,
"text": " Print"
},
{
"code": null,
"e": 25195,
"s": 25184,
"text": " Add Notes"
}
] |
Apache HttpClient - Closing Connection | If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself. This chapter explains how to close the connections manually.
While closing HTTP connections manually follow the steps given below β
The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface.
Using this method, create an HttpClient object as shown below β
CloseableHttpClient httpClient = HttpClients.createDefault();
Start a try-finally block, write the remaining code in the programs in the try block and close the CloseableHttpClient object in the finally block.
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//Remaining code . . . . . . . . . . . . . . .
}finally{
httpClient.close();
}
The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI.
Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI.
HttpGet httpGet = new HttpGet("http://www.tutorialspoint.com/");
The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object.
Execute the request using the given method β
HttpResponse httpResponse = httpclient.execute(httpGet);
Start another try-finally block (nested within the previous try-finally), write the remaining code in the programs in this try block and close the HttpResponse object in the finally block.
CloseableHttpClient httpclient = HttpClients.createDefault();
try{
. . . . . . .
. . . . . . .
CloseableHttpResponse httpresponse = httpclient.execute(httpget);
try{
. . . . . . .
. . . . . . .
}finally{
httpresponse.close();
}
}finally{
httpclient.close();
}
Whenever you create/obtain objects such as request, response stream, etc., start a try finally block in the next line, write the remaining code within the try and close the respective object in the finally block as demonstrated in the following program β
import java.util.Scanner;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class CloseConnectionExample {
public static void main(String args[])throws Exception{
//Create an HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
try{
//Create an HttpGet object
HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/");
//Execute the Get request
CloseableHttpResponse httpresponse = httpclient.execute(httpget);
try{
Scanner sc = new Scanner(httpresponse.getEntity().getContent());
while(sc.hasNext()) {
System.out.println(sc.nextLine());
}
}finally{
httpresponse.close();
}
}finally{
httpclient.close();
}
}
}
On executing the above program, the following output is generated β
<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-232293-17');
</script>
</body>
</html>
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2027,
"s": 1827,
"text": "If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself. This chapter explains how to close the connections manually."
},
{
"code": null,
"e": 2098,
"s": 2027,
"text": "While closing HTTP connections manually follow the steps given below β"
},
{
"code": null,
"e": 2264,
"s": 2098,
"text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface."
},
{
"code": null,
"e": 2328,
"s": 2264,
"text": "Using this method, create an HttpClient object as shown below β"
},
{
"code": null,
"e": 2391,
"s": 2328,
"text": "CloseableHttpClient httpClient = HttpClients.createDefault();\n"
},
{
"code": null,
"e": 2539,
"s": 2391,
"text": "Start a try-finally block, write the remaining code in the programs in the try block and close the CloseableHttpClient object in the finally block."
},
{
"code": null,
"e": 2691,
"s": 2539,
"text": "CloseableHttpClient httpClient = HttpClients.createDefault();\ntry{\n //Remaining code . . . . . . . . . . . . . . .\n}finally{\n httpClient.close();\n}"
},
{
"code": null,
"e": 2806,
"s": 2691,
"text": "The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI."
},
{
"code": null,
"e": 2909,
"s": 2806,
"text": "Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI."
},
{
"code": null,
"e": 2975,
"s": 2909,
"text": "HttpGet httpGet = new HttpGet(\"http://www.tutorialspoint.com/\");\n"
},
{
"code": null,
"e": 3154,
"s": 2975,
"text": "The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object."
},
{
"code": null,
"e": 3199,
"s": 3154,
"text": "Execute the request using the given method β"
},
{
"code": null,
"e": 3257,
"s": 3199,
"text": "HttpResponse httpResponse = httpclient.execute(httpGet);\n"
},
{
"code": null,
"e": 3446,
"s": 3257,
"text": "Start another try-finally block (nested within the previous try-finally), write the remaining code in the programs in this try block and close the HttpResponse object in the finally block."
},
{
"code": null,
"e": 3745,
"s": 3446,
"text": "CloseableHttpClient httpclient = HttpClients.createDefault();\ntry{\n . . . . . . .\n . . . . . . .\n CloseableHttpResponse httpresponse = httpclient.execute(httpget);\n try{\n . . . . . . .\n . . . . . . .\n }finally{\n httpresponse.close();\n }\n}finally{\n httpclient.close();\n}"
},
{
"code": null,
"e": 4000,
"s": 3745,
"text": "Whenever you create/obtain objects such as request, response stream, etc., start a try finally block in the next line, write the remaining code within the try and close the respective object in the finally block as demonstrated in the following program β"
},
{
"code": null,
"e": 4993,
"s": 4000,
"text": "import java.util.Scanner;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class CloseConnectionExample {\n \n public static void main(String args[])throws Exception{\n \n //Create an HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n try{\n //Create an HttpGet object\n HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n\n //Execute the Get request\n CloseableHttpResponse httpresponse = httpclient.execute(httpget);\n\n try{\n Scanner sc = new Scanner(httpresponse.getEntity().getContent());\n while(sc.hasNext()) {\n System.out.println(sc.nextLine());\n }\n }finally{\n httpresponse.close();\n }\n }finally{\n httpclient.close();\n }\n }\n}"
},
{
"code": null,
"e": 5061,
"s": 4993,
"text": "On executing the above program, the following output is generated β"
},
{
"code": null,
"e": 6195,
"s": 5061,
"text": "<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!-->\n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" content = \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href = \"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . \n<script>\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag() {dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'UA-232293-17');\n</script>\n</body>\n</html>\n"
},
{
"code": null,
"e": 6230,
"s": 6195,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6249,
"s": 6230,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6284,
"s": 6249,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6305,
"s": 6284,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6338,
"s": 6305,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6351,
"s": 6338,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6386,
"s": 6351,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6404,
"s": 6386,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6437,
"s": 6404,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6455,
"s": 6437,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6488,
"s": 6455,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6506,
"s": 6488,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6513,
"s": 6506,
"text": " Print"
},
{
"code": null,
"e": 6524,
"s": 6513,
"text": " Add Notes"
}
] |
How I Created an Interactive, Scrolling Visualisation with D3.js, and how you can too | by Cuthbert Chow | Towards Data Science | cuthchow.github.io
Visualisation
Code (Github Repo)
The web is littered with stunning examples of scrolling and interactive visualisations, often built using D3. If youβve ever read such feature pieces from Bloomberg or the New York Times, Iβm sure you know what Iβm talking about. Some of my favourite examples of this form are:
Shirley Wuβs exemplary visualisation of very line in Hamilton, built with D3 and React. In fact, all of her work is excellent.
The New York Timeβs piece of how the economy has been reshaped by the recession, told in 255 different charts.
This absolutely mind-boggling piece, visualising the inner mechanics of Machine Learning, created by the folks over at R2D3.
This quirky visualisation, breaking down the amount of water which we consume on a daily basis
Another article from the NYTimes, illustrating the treacherous climb up El Capitanβs dawn wall
And so many more.
Seriously, every single one of these projects is worth checking out and learning from. They are amazing.
Thereβs something satisfying about the way in which the visual elements comport themselves after each scroll event, bending to your control. Often times, I have a huge smile on my face as I scroll up and down the page, watching all the shapes and colours fly around. Itβs a sensation reminiscent of discovering the secrets held by the data on your own, which is what I believe makes these presentations so convincing. It also provides a much more commanding narrative flow, which would otherwise be lacking in more static pieces. Browsing through these articles, it may appear that such visualisations would be extremely complicated to produce on your own, and you may assume they are best left to the editors and writers of top-shelf publications. But Iβm here to help dispel this notion: Anyone can make one, including you!
After reading through a bunch of online resources (I will leave a list of these at the end of the article), I decided to take a stab at creating one myself. As Iβve mentioned before, the best way of learning a new tool, technique, skill or ability is to put it to use, before you even know if youβre capable of doing that thing. And so that is exactly what I did over the course of a week.
(This article will assume you have some basic familiarity with D3.js and how it works)
After browsing through a series of datasets, I settled on one which I found hosted on Kaggle, which originally came from the analytics blog Fivethirtyeight (if youβre looking for cool datasets, check out googleβs dataset search tool). It was a (slightly outdated) dataset about college majors around the United States. It had information on the number enrolled in each college major, as well as the median, 75th percentile and 25th percentile salaries from those students. Interestingly, it also provided information on the male/female representation for each major, which I thought would be a good point of focus for the piece.
With the dataset decided, I started exploring the data using Python and Pandas in Jupyter notebooks, looking for any interesting trends or points I would want to emphasise in a visualisation. I also made rough, crude approximations of the graphs I would want to show in the final product.
My general conception of the visualisation was that the college majors would each be represented by a bubble. The bubbles would then change form and colour based on the type of data I was trying to highlight (ie gender discrepancies, median salary, category grouping etc.). When the bubbles would be grouped in by specific attributes, I wanted to achieve this through a D3 force simulation, so that the bubbles would appear to be gravitating towards an unseen force.
After some exploration, I knew that I wanted to focus on the impact that gender distribution within a major has on the median salary of its graduates. I would strongly suggest that you take a deep dive into your data before starting any of the visualisation process, because you want to have some semblance of the interactions you have in mind before actually sitting down to code the final product.
If you want a really quick way of observing relationships between variables, the python visualisation package seaborn has a βpairplot()β method to help you do just this, which creates a matrix of scatterplots between all of the variables in the dataframe passed to it.
#Plotting a scatter matriximport seaborn as snsfactors = df[['Total', 'Major_category', 'ShareWomen', 'Sample_size', 'Employed', 'Unemployed', 'Median']]sns.pairplot(factors)
Now we have a solid idea of the things we want to include, we are ready to start creating.
This is (obviously) the most important part of every scroller you build. But conveniently, itβs also the most reusable part, meaning that after you build it once, you should be good to go.
In fact, Iβve created a template version of the scroller functionality, which you can find right here. (credits again to Jim Vallandingham, as much of the code used was sourced from his original article. In fact, he wrote a similar article on creating a scroller, with an emphasis on the scrolling mechanics, so you should read that first. In this article, I will focus on the elements which I found confusing, and put a greater emphasis on the part of actually creating the visualisation).
The entire visualisation should be contained within a single HTML page. Within the page, there is a div which contains all the elements, and within that div, there are two separate divs for the text and the visualisation.
Within the βsectionsβ div are a bunch of section elements, each with the class βstepβ. Each one of these sections should contain a distinct section of text, and correspond to one phase or part of the visualisation. It is when the user moves between sections that the visualisation will be updated,
<div id="graphic"> <div id="sections"> <section class="step"></section> <section class="step"></section> </div> <div id="vis"> </div></div>
You can size and position these elements as you wish, so long as you keep the #vis element fixed on the page (using display: fixed), so it doesnβt move as the user scrolls. You can also tweak the height of each .step element based on how much text you want to include per section.
Here is the code which handles the scroll events. Iβve added comments to clarify certain parts.
function scroller(){ let container = d3.select('body') let dispatch = d3.dispatch('active', 'progress'); let sections = d3.selectAll('.step') let sectionPositions let currentIndex = -1 let containerStart = 0;// Binds the position function to the scroll event, and the resize function to the resize event. What these functions do are detailed below. function scroll(){ d3.select(window) .on('scroll.scroller', position) .on('resize.scroller', resize) resize(); let timer = d3.timer(function() { position(); timer.stop(); }); }//The resize function determines where each of the .step elements are on the page, relative to the top of the first element. It saves all of the co-ordinates of these elements in an array called sectionPositions function resize(){ sectionPositions = []; let startPos; sections.each(function(d, i) { let top = this.getBoundingClientRect().top; if (i === 0 ){ startPos = top; } sectionPositions.push(top - startPos) }); }//The position function determines where the user is on the page (using window.pageYOffset), and uses that to determine which section of text should currently be in view. It then uses D3βs dispatching tools to signal the 'progress' event, which will be used in the main script, passing along the current section index so that the script knows which stage of the animation/visualisation should be showing. function position() { let pos = window.pageYOffset - 300 - containerStart; let sectionIndex = d3.bisect(sectionPositions, pos); sectionIndex = Math.min(sections.size()-1, sectionIndex); if (currentIndex !== sectionIndex){ dispatch.call('active', this, sectionIndex); currentIndex = sectionIndex; } let prevIndex = Math.max(sectionIndex - 1, 0); let prevTop = sectionPositions[prevIndex] let progress = (pos - prevTop) / (sectionPositions[sectionIndex] - prevTop); dispatch.call('progress', this, currentIndex, progress) }//The code here adds an event listener to the dispatcher. scroll.container = function(value) { if (arguments.legth === 0){ return container } container = value return scroll } scroll.on = function(action, callback){ dispatch.on(action, callback) }; return scroll;}
All of the above code is saved in a separate script file. We then create a main script file, which is responsible for updating the visualisation every time the viewer changes sections.
let scroll = scroller().container(d3.select('#graphic'))scroll()let lastIndex, activeIndex = 0//This is where most of the magic happens. Every time the user scrolls, we receive a new index. First, we find all the irrelevant sections, and reduce their opacity. scroll.on('active', function(index){ d3.selectAll('.step') .transition().duration(500) .style('opacity', function (d, i) {return i === index ? 1 : 0.1;});//Next, we selection from a range of activationFunctions (which we create), based on the index of the current section. activeIndex = index let sign = (activeIndex - lastIndex) < 0 ? -1 : 1; let scrolledSections = d3.range(lastIndex + sign, activeIndex + sign, sign); scrolledSections.forEach(i => { activationFunctions[i](); }) lastIndex = activeIndex;})//I placed all the functions in an array. Each function corresponds to a different change in the visualisation. One may change the graph into a scatter plot, and another may initiate a force simulation.let activationFunctions = [ draw1, draw2, draw3, draw4, draw5, draw6, draw7, draw8]
With the generic components of the scroller sorted out, what you do from here is going to vary greatly based on the type of visualisation you are hoping to construct. Nonetheless, I can hopefully offer some broad brush advice that may come in handy, and which I wish I had been aware of sooner in the process.
The essential idea is that all the elements that you need for the visualisation should be created when the page loads. I created a function called drawInitial(), and invoked it once the data was loaded in. This involves creating all the scales, axes, shapes, for simulations and other elements which you will need in the visualisation.
Once they are all created, you can simply set their opacity attribute to 0 to ensure that they donβt show up until required by the visualisation. Make sure each set of features (ie a set of axes for a particular chart, or a detail callout) has associated class or ID names, so that you can reference those specific features when required.
I found it useful to create a cleaning function, which would be invoked at each step. I would pass in the chart type which I was trying to create, and the function would remove (or hide, rather) all the elements which were extraneous to that chart, thus saving me from having to write a lot of duplicated code. This is what part of the function looks like:
function clean(chartType){ let svg = d3.select('#vis').select('svg') if (chartType !== "isScatter") { svg.select('.scatter-x').transition().attr('opacity', 0) svg.select('.scatter-y').transition().attr('opacity', 0) } if (chartType !== "isMultiples"){ svg.selectAll('.lab-text').transition().attr('opacity', 0) svg.selectAll('.cat-rect').transition().attr('opacity', 0)...
As I mentioned, I would be using force simulations to group the circle elements in several of the phases. The key thing to remember is to βreheatβ the force simulation every time you bring it back into use. Force simulations in D3 have an alpha value, which is a cooling parameter that gradually decrements over time, and reduce how much the force impact the nodes. You should reset the alpha back to a certain value every time you restart the force, to make sure it has enough βenergyβ to get to the desired state. You can also tweak the alpha decay rate to affect how quickly the simulation settles down to an equilibrium state.
This part is key: Always use transitions when changing the state of the visualisation, even if that change is something you want to be instantaneous. By utilising D3βs transition feature (even if the duration is 0), you allow the changes to be interrupted. This means that if the user is scrolling through the sections quickly, one transition can be overridden by a subsequent one, avoiding the case where you are left with an awkward, invalid state.
SVG elements are ordered based on when they were appended to the parent element. Think of it like throwing paint on a canvas: the last layer of paint is the one thatβs visible on top. You could reorder elements by removing them from their parent element, and then appending them again to the very end. Alternatively, you could make use of D3βs .raise() and .lower() methods, which conveniently do this exact process for you when given a selection of elements.
Colours are an indispensable component of good data visualisation. For parts of my project, I was trying to encode with colour 16 different categories of college majors. This led to an elaborate process for selecting colours, as I wanted to avoid any two hues which were too similar and thus easily confused.
I highly recommend using Color Hunt in building your palettes. Itβs a website where other creatives have constructed and shared their own palettes, and it allows you to easily copy the hex-codes of the hues which you want, and to save your own palettes as well for future use.
Hopefully, this has demystified at least part of the process of making a scrolling visualisation. Itβs honestly much easier than it looks, and so definitely go find an interesting dataset and try it out for yourself!
Jim Vallandingham: article on scrollers, blog
Shirley Wuβs work, as well as her YouTube channel and Twitch streams
Mike Bostock, blocks, article on how to scroll | [
{
"code": null,
"e": 191,
"s": 172,
"text": "cuthchow.github.io"
},
{
"code": null,
"e": 205,
"s": 191,
"text": "Visualisation"
},
{
"code": null,
"e": 224,
"s": 205,
"text": "Code (Github Repo)"
},
{
"code": null,
"e": 502,
"s": 224,
"text": "The web is littered with stunning examples of scrolling and interactive visualisations, often built using D3. If youβve ever read such feature pieces from Bloomberg or the New York Times, Iβm sure you know what Iβm talking about. Some of my favourite examples of this form are:"
},
{
"code": null,
"e": 629,
"s": 502,
"text": "Shirley Wuβs exemplary visualisation of very line in Hamilton, built with D3 and React. In fact, all of her work is excellent."
},
{
"code": null,
"e": 740,
"s": 629,
"text": "The New York Timeβs piece of how the economy has been reshaped by the recession, told in 255 different charts."
},
{
"code": null,
"e": 865,
"s": 740,
"text": "This absolutely mind-boggling piece, visualising the inner mechanics of Machine Learning, created by the folks over at R2D3."
},
{
"code": null,
"e": 960,
"s": 865,
"text": "This quirky visualisation, breaking down the amount of water which we consume on a daily basis"
},
{
"code": null,
"e": 1055,
"s": 960,
"text": "Another article from the NYTimes, illustrating the treacherous climb up El Capitanβs dawn wall"
},
{
"code": null,
"e": 1073,
"s": 1055,
"text": "And so many more."
},
{
"code": null,
"e": 1178,
"s": 1073,
"text": "Seriously, every single one of these projects is worth checking out and learning from. They are amazing."
},
{
"code": null,
"e": 2004,
"s": 1178,
"text": "Thereβs something satisfying about the way in which the visual elements comport themselves after each scroll event, bending to your control. Often times, I have a huge smile on my face as I scroll up and down the page, watching all the shapes and colours fly around. Itβs a sensation reminiscent of discovering the secrets held by the data on your own, which is what I believe makes these presentations so convincing. It also provides a much more commanding narrative flow, which would otherwise be lacking in more static pieces. Browsing through these articles, it may appear that such visualisations would be extremely complicated to produce on your own, and you may assume they are best left to the editors and writers of top-shelf publications. But Iβm here to help dispel this notion: Anyone can make one, including you!"
},
{
"code": null,
"e": 2394,
"s": 2004,
"text": "After reading through a bunch of online resources (I will leave a list of these at the end of the article), I decided to take a stab at creating one myself. As Iβve mentioned before, the best way of learning a new tool, technique, skill or ability is to put it to use, before you even know if youβre capable of doing that thing. And so that is exactly what I did over the course of a week."
},
{
"code": null,
"e": 2481,
"s": 2394,
"text": "(This article will assume you have some basic familiarity with D3.js and how it works)"
},
{
"code": null,
"e": 3110,
"s": 2481,
"text": "After browsing through a series of datasets, I settled on one which I found hosted on Kaggle, which originally came from the analytics blog Fivethirtyeight (if youβre looking for cool datasets, check out googleβs dataset search tool). It was a (slightly outdated) dataset about college majors around the United States. It had information on the number enrolled in each college major, as well as the median, 75th percentile and 25th percentile salaries from those students. Interestingly, it also provided information on the male/female representation for each major, which I thought would be a good point of focus for the piece."
},
{
"code": null,
"e": 3399,
"s": 3110,
"text": "With the dataset decided, I started exploring the data using Python and Pandas in Jupyter notebooks, looking for any interesting trends or points I would want to emphasise in a visualisation. I also made rough, crude approximations of the graphs I would want to show in the final product."
},
{
"code": null,
"e": 3866,
"s": 3399,
"text": "My general conception of the visualisation was that the college majors would each be represented by a bubble. The bubbles would then change form and colour based on the type of data I was trying to highlight (ie gender discrepancies, median salary, category grouping etc.). When the bubbles would be grouped in by specific attributes, I wanted to achieve this through a D3 force simulation, so that the bubbles would appear to be gravitating towards an unseen force."
},
{
"code": null,
"e": 4266,
"s": 3866,
"text": "After some exploration, I knew that I wanted to focus on the impact that gender distribution within a major has on the median salary of its graduates. I would strongly suggest that you take a deep dive into your data before starting any of the visualisation process, because you want to have some semblance of the interactions you have in mind before actually sitting down to code the final product."
},
{
"code": null,
"e": 4535,
"s": 4266,
"text": "If you want a really quick way of observing relationships between variables, the python visualisation package seaborn has a βpairplot()β method to help you do just this, which creates a matrix of scatterplots between all of the variables in the dataframe passed to it."
},
{
"code": null,
"e": 4710,
"s": 4535,
"text": "#Plotting a scatter matriximport seaborn as snsfactors = df[['Total', 'Major_category', 'ShareWomen', 'Sample_size', 'Employed', 'Unemployed', 'Median']]sns.pairplot(factors)"
},
{
"code": null,
"e": 4801,
"s": 4710,
"text": "Now we have a solid idea of the things we want to include, we are ready to start creating."
},
{
"code": null,
"e": 4990,
"s": 4801,
"text": "This is (obviously) the most important part of every scroller you build. But conveniently, itβs also the most reusable part, meaning that after you build it once, you should be good to go."
},
{
"code": null,
"e": 5481,
"s": 4990,
"text": "In fact, Iβve created a template version of the scroller functionality, which you can find right here. (credits again to Jim Vallandingham, as much of the code used was sourced from his original article. In fact, he wrote a similar article on creating a scroller, with an emphasis on the scrolling mechanics, so you should read that first. In this article, I will focus on the elements which I found confusing, and put a greater emphasis on the part of actually creating the visualisation)."
},
{
"code": null,
"e": 5703,
"s": 5481,
"text": "The entire visualisation should be contained within a single HTML page. Within the page, there is a div which contains all the elements, and within that div, there are two separate divs for the text and the visualisation."
},
{
"code": null,
"e": 6001,
"s": 5703,
"text": "Within the βsectionsβ div are a bunch of section elements, each with the class βstepβ. Each one of these sections should contain a distinct section of text, and correspond to one phase or part of the visualisation. It is when the user moves between sections that the visualisation will be updated,"
},
{
"code": null,
"e": 6169,
"s": 6001,
"text": "<div id=\"graphic\"> <div id=\"sections\"> <section class=\"step\"></section> <section class=\"step\"></section> </div> <div id=\"vis\"> </div></div>"
},
{
"code": null,
"e": 6450,
"s": 6169,
"text": "You can size and position these elements as you wish, so long as you keep the #vis element fixed on the page (using display: fixed), so it doesnβt move as the user scrolls. You can also tweak the height of each .step element based on how much text you want to include per section."
},
{
"code": null,
"e": 6546,
"s": 6450,
"text": "Here is the code which handles the scroll events. Iβve added comments to clarify certain parts."
},
{
"code": null,
"e": 8832,
"s": 6546,
"text": "function scroller(){ let container = d3.select('body') let dispatch = d3.dispatch('active', 'progress'); let sections = d3.selectAll('.step') let sectionPositions let currentIndex = -1 let containerStart = 0;// Binds the position function to the scroll event, and the resize function to the resize event. What these functions do are detailed below. function scroll(){ d3.select(window) .on('scroll.scroller', position) .on('resize.scroller', resize) resize(); let timer = d3.timer(function() { position(); timer.stop(); }); }//The resize function determines where each of the .step elements are on the page, relative to the top of the first element. It saves all of the co-ordinates of these elements in an array called sectionPositions function resize(){ sectionPositions = []; let startPos; sections.each(function(d, i) { let top = this.getBoundingClientRect().top; if (i === 0 ){ startPos = top; } sectionPositions.push(top - startPos) }); }//The position function determines where the user is on the page (using window.pageYOffset), and uses that to determine which section of text should currently be in view. It then uses D3βs dispatching tools to signal the 'progress' event, which will be used in the main script, passing along the current section index so that the script knows which stage of the animation/visualisation should be showing. function position() { let pos = window.pageYOffset - 300 - containerStart; let sectionIndex = d3.bisect(sectionPositions, pos); sectionIndex = Math.min(sections.size()-1, sectionIndex); if (currentIndex !== sectionIndex){ dispatch.call('active', this, sectionIndex); currentIndex = sectionIndex; } let prevIndex = Math.max(sectionIndex - 1, 0); let prevTop = sectionPositions[prevIndex] let progress = (pos - prevTop) / (sectionPositions[sectionIndex] - prevTop); dispatch.call('progress', this, currentIndex, progress) }//The code here adds an event listener to the dispatcher. scroll.container = function(value) { if (arguments.legth === 0){ return container } container = value return scroll } scroll.on = function(action, callback){ dispatch.on(action, callback) }; return scroll;}"
},
{
"code": null,
"e": 9017,
"s": 8832,
"text": "All of the above code is saved in a separate script file. We then create a main script file, which is responsible for updating the visualisation every time the viewer changes sections."
},
{
"code": null,
"e": 10096,
"s": 9017,
"text": "let scroll = scroller().container(d3.select('#graphic'))scroll()let lastIndex, activeIndex = 0//This is where most of the magic happens. Every time the user scrolls, we receive a new index. First, we find all the irrelevant sections, and reduce their opacity. scroll.on('active', function(index){ d3.selectAll('.step') .transition().duration(500) .style('opacity', function (d, i) {return i === index ? 1 : 0.1;});//Next, we selection from a range of activationFunctions (which we create), based on the index of the current section. activeIndex = index let sign = (activeIndex - lastIndex) < 0 ? -1 : 1; let scrolledSections = d3.range(lastIndex + sign, activeIndex + sign, sign); scrolledSections.forEach(i => { activationFunctions[i](); }) lastIndex = activeIndex;})//I placed all the functions in an array. Each function corresponds to a different change in the visualisation. One may change the graph into a scatter plot, and another may initiate a force simulation.let activationFunctions = [ draw1, draw2, draw3, draw4, draw5, draw6, draw7, draw8]"
},
{
"code": null,
"e": 10406,
"s": 10096,
"text": "With the generic components of the scroller sorted out, what you do from here is going to vary greatly based on the type of visualisation you are hoping to construct. Nonetheless, I can hopefully offer some broad brush advice that may come in handy, and which I wish I had been aware of sooner in the process."
},
{
"code": null,
"e": 10742,
"s": 10406,
"text": "The essential idea is that all the elements that you need for the visualisation should be created when the page loads. I created a function called drawInitial(), and invoked it once the data was loaded in. This involves creating all the scales, axes, shapes, for simulations and other elements which you will need in the visualisation."
},
{
"code": null,
"e": 11081,
"s": 10742,
"text": "Once they are all created, you can simply set their opacity attribute to 0 to ensure that they donβt show up until required by the visualisation. Make sure each set of features (ie a set of axes for a particular chart, or a detail callout) has associated class or ID names, so that you can reference those specific features when required."
},
{
"code": null,
"e": 11438,
"s": 11081,
"text": "I found it useful to create a cleaning function, which would be invoked at each step. I would pass in the chart type which I was trying to create, and the function would remove (or hide, rather) all the elements which were extraneous to that chart, thus saving me from having to write a lot of duplicated code. This is what part of the function looks like:"
},
{
"code": null,
"e": 11843,
"s": 11438,
"text": "function clean(chartType){ let svg = d3.select('#vis').select('svg') if (chartType !== \"isScatter\") { svg.select('.scatter-x').transition().attr('opacity', 0) svg.select('.scatter-y').transition().attr('opacity', 0) } if (chartType !== \"isMultiples\"){ svg.selectAll('.lab-text').transition().attr('opacity', 0) svg.selectAll('.cat-rect').transition().attr('opacity', 0)..."
},
{
"code": null,
"e": 12474,
"s": 11843,
"text": "As I mentioned, I would be using force simulations to group the circle elements in several of the phases. The key thing to remember is to βreheatβ the force simulation every time you bring it back into use. Force simulations in D3 have an alpha value, which is a cooling parameter that gradually decrements over time, and reduce how much the force impact the nodes. You should reset the alpha back to a certain value every time you restart the force, to make sure it has enough βenergyβ to get to the desired state. You can also tweak the alpha decay rate to affect how quickly the simulation settles down to an equilibrium state."
},
{
"code": null,
"e": 12925,
"s": 12474,
"text": "This part is key: Always use transitions when changing the state of the visualisation, even if that change is something you want to be instantaneous. By utilising D3βs transition feature (even if the duration is 0), you allow the changes to be interrupted. This means that if the user is scrolling through the sections quickly, one transition can be overridden by a subsequent one, avoiding the case where you are left with an awkward, invalid state."
},
{
"code": null,
"e": 13385,
"s": 12925,
"text": "SVG elements are ordered based on when they were appended to the parent element. Think of it like throwing paint on a canvas: the last layer of paint is the one thatβs visible on top. You could reorder elements by removing them from their parent element, and then appending them again to the very end. Alternatively, you could make use of D3βs .raise() and .lower() methods, which conveniently do this exact process for you when given a selection of elements."
},
{
"code": null,
"e": 13694,
"s": 13385,
"text": "Colours are an indispensable component of good data visualisation. For parts of my project, I was trying to encode with colour 16 different categories of college majors. This led to an elaborate process for selecting colours, as I wanted to avoid any two hues which were too similar and thus easily confused."
},
{
"code": null,
"e": 13971,
"s": 13694,
"text": "I highly recommend using Color Hunt in building your palettes. Itβs a website where other creatives have constructed and shared their own palettes, and it allows you to easily copy the hex-codes of the hues which you want, and to save your own palettes as well for future use."
},
{
"code": null,
"e": 14188,
"s": 13971,
"text": "Hopefully, this has demystified at least part of the process of making a scrolling visualisation. Itβs honestly much easier than it looks, and so definitely go find an interesting dataset and try it out for yourself!"
},
{
"code": null,
"e": 14234,
"s": 14188,
"text": "Jim Vallandingham: article on scrollers, blog"
},
{
"code": null,
"e": 14303,
"s": 14234,
"text": "Shirley Wuβs work, as well as her YouTube channel and Twitch streams"
}
] |
W3.CSS Templates | We have created some responsive W3.CSS website templates for you to use.
You are free to modify, save, share, and use them in all your projects.
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": 73,
"s": 0,
"text": "We have created some responsive W3.CSS website templates for you to use."
},
{
"code": null,
"e": 145,
"s": 73,
"text": "You are free to modify, save, share, and use them in all your projects."
},
{
"code": null,
"e": 178,
"s": 145,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 220,
"s": 178,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 327,
"s": 220,
"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": 346,
"s": 327,
"text": "[email protected]"
}
] |
Difference between border ridge and groove styles in CSS - GeeksforGeeks | 26 May, 2021
The CSS border-style sets the style of an elementβs four borders.
This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border-style is assigned with a separate value.
This property is a shorthand for the following CSS properties:
border-bottom-style
border-left-style
border-right-style
border-top-style
/* Keyword values */
border-style: groove;
border-style: ridge;
/* top and bottom | left and right */
border-style: dotted solid;
/* top | left and right | bottom */
border-style: hidden double dashed;
/* top | right | bottom | left */
border-style: none solid dotted dashed;
/* Global values */
border-style: inherit;
border-style: initial;
border-style: unset;
Ridge border style:
It is a border-style property of CSS. It displays a border with an extruded appearance. It is the opposite of the groove border style. The effect depends on the border-color value. It appears as if it is coming out of the canvas. Border shadow position in ridge is from top left. It reverses the color values in a way that makes the element appear raised.
Syntax:
border-style: ridge;
Example:
HTML
<!DOCTYPE html><html> <style> h1.ridge { border-width: 20px; border-style: ridge; border-color: #CC63FF } </style> <body> <h1 class="ridge">Ridge border style</h1> <p> <strong>Note</strong> This effect depend on the border-color value. </p> </body></html>
Output:
Groove border-style:
It is a border-style property of CSS. It displays a border with a carved appearance. It is the opposite of the ridge style. The effect depends on the border-color value. It appears as if it is carved in the canvas. (This is typically achieved by creating a βshadowβ from two colors that are slightly lighter and darker than the border color). Border shadow position in ridge is from the bottom right. It adds a bevel based on the color value in a way that makes the element appear pressed into the document.
Syntax:
border-style: groove;
Example:
HTML
<!DOCTYPE html><html> <style> h1.groove { border-width: 10px; border-style: groove; border-color: #CC63FF } </style> <body> <h1 class="groove">Groove border style</h1> <p> <strong>Note</strong> This effect depend on the border-color value. </p> </body></html>
Output:
Conclusions:
When we look carefully at both the results we will find that in groove border style, the top and left margin of the inner border is light. The right and bottom margin of the inner border is dark and in ridge border-style, itβs just the opposite.
Groove is a 3D effect that gives the impression that the border is carved into the canvas. Ridge is a 3D effect that has the opposite effect of groove, in which the border appears to protrude from the canvas.
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 25442,
"s": 25376,
"text": "The CSS border-style sets the style of an elementβs four borders."
},
{
"code": null,
"e": 25753,
"s": 25442,
"text": "This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border-style is assigned with a separate value."
},
{
"code": null,
"e": 25816,
"s": 25753,
"text": "This property is a shorthand for the following CSS properties:"
},
{
"code": null,
"e": 25836,
"s": 25816,
"text": "border-bottom-style"
},
{
"code": null,
"e": 25854,
"s": 25836,
"text": "border-left-style"
},
{
"code": null,
"e": 25873,
"s": 25854,
"text": "border-right-style"
},
{
"code": null,
"e": 25890,
"s": 25873,
"text": "border-top-style"
},
{
"code": null,
"e": 26257,
"s": 25890,
"text": "/* Keyword values */\nborder-style: groove;\nborder-style: ridge;\n\n/* top and bottom | left and right */\nborder-style: dotted solid;\n\n/* top | left and right | bottom */\nborder-style: hidden double dashed;\n\n/* top | right | bottom | left */\nborder-style: none solid dotted dashed;\n\n/* Global values */\nborder-style: inherit;\nborder-style: initial;\nborder-style: unset;"
},
{
"code": null,
"e": 26277,
"s": 26257,
"text": "Ridge border style:"
},
{
"code": null,
"e": 26633,
"s": 26277,
"text": "It is a border-style property of CSS. It displays a border with an extruded appearance. It is the opposite of the groove border style. The effect depends on the border-color value. It appears as if it is coming out of the canvas. Border shadow position in ridge is from top left. It reverses the color values in a way that makes the element appear raised."
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Syntax:"
},
{
"code": null,
"e": 26663,
"s": 26641,
"text": "border-style: ridge; "
},
{
"code": null,
"e": 26672,
"s": 26663,
"text": "Example:"
},
{
"code": null,
"e": 26677,
"s": 26672,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style> h1.ridge { border-width: 20px; border-style: ridge; border-color: #CC63FF } </style> <body> <h1 class=\"ridge\">Ridge border style</h1> <p> <strong>Note</strong> This effect depend on the border-color value. </p> </body></html>",
"e": 26976,
"s": 26677,
"text": null
},
{
"code": null,
"e": 26984,
"s": 26976,
"text": "Output:"
},
{
"code": null,
"e": 27005,
"s": 26984,
"text": "Groove border-style:"
},
{
"code": null,
"e": 27514,
"s": 27005,
"text": "It is a border-style property of CSS. It displays a border with a carved appearance. It is the opposite of the ridge style. The effect depends on the border-color value. It appears as if it is carved in the canvas. (This is typically achieved by creating a βshadowβ from two colors that are slightly lighter and darker than the border color). Border shadow position in ridge is from the bottom right. It adds a bevel based on the color value in a way that makes the element appear pressed into the document."
},
{
"code": null,
"e": 27522,
"s": 27514,
"text": "Syntax:"
},
{
"code": null,
"e": 27544,
"s": 27522,
"text": "border-style: groove;"
},
{
"code": null,
"e": 27553,
"s": 27544,
"text": "Example:"
},
{
"code": null,
"e": 27558,
"s": 27553,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style> h1.groove { border-width: 10px; border-style: groove; border-color: #CC63FF } </style> <body> <h1 class=\"groove\">Groove border style</h1> <p> <strong>Note</strong> This effect depend on the border-color value. </p> </body></html>",
"e": 27857,
"s": 27558,
"text": null
},
{
"code": null,
"e": 27865,
"s": 27857,
"text": "Output:"
},
{
"code": null,
"e": 27878,
"s": 27865,
"text": "Conclusions:"
},
{
"code": null,
"e": 28124,
"s": 27878,
"text": "When we look carefully at both the results we will find that in groove border style, the top and left margin of the inner border is light. The right and bottom margin of the inner border is dark and in ridge border-style, itβs just the opposite."
},
{
"code": null,
"e": 28333,
"s": 28124,
"text": "Groove is a 3D effect that gives the impression that the border is carved into the canvas. Ridge is a 3D effect that has the opposite effect of groove, in which the border appears to protrude from the canvas."
},
{
"code": null,
"e": 28348,
"s": 28333,
"text": "CSS-Properties"
},
{
"code": null,
"e": 28362,
"s": 28348,
"text": "CSS-Questions"
},
{
"code": null,
"e": 28369,
"s": 28362,
"text": "Picked"
},
{
"code": null,
"e": 28373,
"s": 28369,
"text": "CSS"
},
{
"code": null,
"e": 28390,
"s": 28373,
"text": "Web Technologies"
},
{
"code": null,
"e": 28488,
"s": 28390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28525,
"s": 28488,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28554,
"s": 28525,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28593,
"s": 28554,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28635,
"s": 28593,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28682,
"s": 28635,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 28724,
"s": 28682,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28757,
"s": 28724,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28800,
"s": 28757,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28845,
"s": 28800,
"text": "Convert a string to an integer in JavaScript"
}
] |
How can we implement a JSON array using Streaming API in Java? | The JsonGenerator interface can be used to write the JSON data to an output source in a streaming way. We can create or implement a JSON array using the writeStartArray() method of JsonGenerator, this method writes the JSON name/start array character pair within the current object context. The writeStartObject() method writes the JSON start object character, and valid only in an array context and the writeEnd() method writes the end of the current context.
JsonGenerator writeStartArray(String name)
import java.io.*;
import javax.json.*;
import javax.json.stream.*;
public class JsonGeneratorTest {
public static void main(String[] args) throws Exception {
StringWriter writer = new StringWriter();
JsonGenerator jsonGen = Json.createGenerator(writer);
jsonGen.writeStartObject()
.write("name", "Adithya")
.write("designation", "Python Developer")
.write("company", "TutorialsPoint")
.writeStartArray("personal details")
.writeStartObject()
.write("email", "[email protected]")
.writeEnd()
.writeStartObject()
.write("contact", "9959927000")
.writeEnd() // end of object
.writeEnd() // end of an array
.writeEnd(); // end of main object
jsonGen.close();
System.out.println(writer.toString());
}
}
{"name":"Adithya","designation":"Python Developer","company":"TutorialsPoint","personal details":[{"email":"[email protected]"},{"contact":"9959927000"}]} | [
{
"code": null,
"e": 1523,
"s": 1062,
"text": "The JsonGenerator interface can be used to write the JSON data to an output source in a streaming way. We can create or implement a JSON array using the writeStartArray() method of JsonGenerator, this method writes the JSON name/start array character pair within the current object context. The writeStartObject() method writes the JSON start object character, and valid only in an array context and the writeEnd() method writes the end of the current context."
},
{
"code": null,
"e": 1566,
"s": 1523,
"text": "JsonGenerator writeStartArray(String name)"
},
{
"code": null,
"e": 2458,
"s": 1566,
"text": "import java.io.*;\nimport javax.json.*;\nimport javax.json.stream.*;\npublic class JsonGeneratorTest {\n public static void main(String[] args) throws Exception {\n StringWriter writer = new StringWriter();\n JsonGenerator jsonGen = Json.createGenerator(writer);\n jsonGen.writeStartObject()\n .write(\"name\", \"Adithya\")\n .write(\"designation\", \"Python Developer\")\n .write(\"company\", \"TutorialsPoint\")\n .writeStartArray(\"personal details\")\n .writeStartObject()\n .write(\"email\", \"[email protected]\")\n .writeEnd()\n .writeStartObject()\n .write(\"contact\", \"9959927000\")\n .writeEnd() // end of object\n .writeEnd() // end of an array\n .writeEnd(); // end of main object\n jsonGen.close();\n System.out.println(writer.toString());\n }\n}"
},
{
"code": null,
"e": 2613,
"s": 2458,
"text": "{\"name\":\"Adithya\",\"designation\":\"Python Developer\",\"company\":\"TutorialsPoint\",\"personal details\":[{\"email\":\"[email protected]\"},{\"contact\":\"9959927000\"}]}"
}
] |
Java - The IdentityHashMap Class | This class implements AbstractMap. It is similar to HashMap except that it uses reference equality when comparing the elements.
This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects.
This class is designed for use only in rare cases wherein reference-equality semantics are required. This class provides constant-time performance for the basic operations (get and put), assuming the system identity hash function (System.identityHashCode(Object)) disperses elements properly among the buckets.
This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold.
Following is the list of the constructors supported by the IdentityHashMap.
IdentityHashMap()
This constructor constructs a new, empty identity hash map with a default expected maximum size (21).
IdentityHashMap(int expectedMaxSize)
This constructor constructs a new, empty IdentityHashMap with the specified expected maximum size.
IdentityHashMap(Map m)
This constructor constructs a new identity hash map containing the keys-value mappings in the specified map.
Apart from the methods inherited from its parent classes, IdentityHashMap defines following methods β
void clear()
Removes all mappings from this map.
Object clone()
Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.
boolean containsKey(Object key)
Tests whether the specified object reference is a key in this identity hash map.
boolean containsValue(Object value)
Tests whether the specified object reference is a value in this identity hash map.
Set entrySet()
Returns a set view of the mappings contained in this map.
boolean equals(Object o)
Compares the specified object with this map for equality.
Object get(Object key)
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key.
int hashCode()
Returns the hash code value for this map.
boolean isEmpty()
Returns true if this identity hash map contains no key-value mappings.
Set keySet()
Returns an identity-based set view of the keys contained in this map.
Object put(Object key, Object value)
Associates the specified value with the specified key in this identity hash map.
void putAll(Map t)
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
Object remove(Object key)
Removes the mapping for this key from this map if present.
int size()
Returns the number of key-value mappings in this identity hash map.
Collection values()
Returns a collection view of the values contained in this map.
The following program illustrates several of the methods supported by this collection β
import java.util.*;
public class IdentityHashMapDemo {
public static void main(String args[]) {
// Create a hash map
IdentityHashMap ihm = new IdentityHashMap();
// Put elements to the map
ihm.put("Zara", new Double(3434.34));
ihm.put("Mahnaz", new Double(123.22));
ihm.put("Ayan", new Double(1378.00));
ihm.put("Daisy", new Double(99.22));
ihm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = ihm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)ihm.get("Zara")).doubleValue();
ihm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + ihm.get("Zara"));
}
}
This will produce the following result β
Ayan: 1378.0
Qadir: -19.08
Mahnaz: 123.22
Daisy: 99.22
Zara: 3434.34
Zara's new balance: 4434.34
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2505,
"s": 2377,
"text": "This class implements AbstractMap. It is similar to HashMap except that it uses reference equality when comparing the elements."
},
{
"code": null,
"e": 2726,
"s": 2505,
"text": "This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects."
},
{
"code": null,
"e": 3037,
"s": 2726,
"text": "This class is designed for use only in rare cases wherein reference-equality semantics are required. This class provides constant-time performance for the basic operations (get and put), assuming the system identity hash function (System.identityHashCode(Object)) disperses elements properly among the buckets."
},
{
"code": null,
"e": 3236,
"s": 3037,
"text": "This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold."
},
{
"code": null,
"e": 3312,
"s": 3236,
"text": "Following is the list of the constructors supported by the IdentityHashMap."
},
{
"code": null,
"e": 3330,
"s": 3312,
"text": "IdentityHashMap()"
},
{
"code": null,
"e": 3432,
"s": 3330,
"text": "This constructor constructs a new, empty identity hash map with a default expected maximum size (21)."
},
{
"code": null,
"e": 3469,
"s": 3432,
"text": "IdentityHashMap(int expectedMaxSize)"
},
{
"code": null,
"e": 3568,
"s": 3469,
"text": "This constructor constructs a new, empty IdentityHashMap with the specified expected maximum size."
},
{
"code": null,
"e": 3591,
"s": 3568,
"text": "IdentityHashMap(Map m)"
},
{
"code": null,
"e": 3700,
"s": 3591,
"text": "This constructor constructs a new identity hash map containing the keys-value mappings in the specified map."
},
{
"code": null,
"e": 3802,
"s": 3700,
"text": "Apart from the methods inherited from its parent classes, IdentityHashMap defines following methods β"
},
{
"code": null,
"e": 3815,
"s": 3802,
"text": "void clear()"
},
{
"code": null,
"e": 3851,
"s": 3815,
"text": "Removes all mappings from this map."
},
{
"code": null,
"e": 3866,
"s": 3851,
"text": "Object clone()"
},
{
"code": null,
"e": 3963,
"s": 3866,
"text": "Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned."
},
{
"code": null,
"e": 3995,
"s": 3963,
"text": "boolean containsKey(Object key)"
},
{
"code": null,
"e": 4076,
"s": 3995,
"text": "Tests whether the specified object reference is a key in this identity hash map."
},
{
"code": null,
"e": 4112,
"s": 4076,
"text": "boolean containsValue(Object value)"
},
{
"code": null,
"e": 4195,
"s": 4112,
"text": "Tests whether the specified object reference is a value in this identity hash map."
},
{
"code": null,
"e": 4210,
"s": 4195,
"text": "Set entrySet()"
},
{
"code": null,
"e": 4268,
"s": 4210,
"text": "Returns a set view of the mappings contained in this map."
},
{
"code": null,
"e": 4293,
"s": 4268,
"text": "boolean equals(Object o)"
},
{
"code": null,
"e": 4351,
"s": 4293,
"text": "Compares the specified object with this map for equality."
},
{
"code": null,
"e": 4374,
"s": 4351,
"text": "Object get(Object key)"
},
{
"code": null,
"e": 4509,
"s": 4374,
"text": "Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key."
},
{
"code": null,
"e": 4524,
"s": 4509,
"text": "int hashCode()"
},
{
"code": null,
"e": 4566,
"s": 4524,
"text": "Returns the hash code value for this map."
},
{
"code": null,
"e": 4584,
"s": 4566,
"text": "boolean isEmpty()"
},
{
"code": null,
"e": 4655,
"s": 4584,
"text": "Returns true if this identity hash map contains no key-value mappings."
},
{
"code": null,
"e": 4668,
"s": 4655,
"text": "Set keySet()"
},
{
"code": null,
"e": 4738,
"s": 4668,
"text": "Returns an identity-based set view of the keys contained in this map."
},
{
"code": null,
"e": 4775,
"s": 4738,
"text": "Object put(Object key, Object value)"
},
{
"code": null,
"e": 4856,
"s": 4775,
"text": "Associates the specified value with the specified key in this identity hash map."
},
{
"code": null,
"e": 4875,
"s": 4856,
"text": "void putAll(Map t)"
},
{
"code": null,
"e": 5049,
"s": 4875,
"text": "Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map."
},
{
"code": null,
"e": 5075,
"s": 5049,
"text": "Object remove(Object key)"
},
{
"code": null,
"e": 5134,
"s": 5075,
"text": "Removes the mapping for this key from this map if present."
},
{
"code": null,
"e": 5145,
"s": 5134,
"text": "int size()"
},
{
"code": null,
"e": 5213,
"s": 5145,
"text": "Returns the number of key-value mappings in this identity hash map."
},
{
"code": null,
"e": 5233,
"s": 5213,
"text": "Collection values()"
},
{
"code": null,
"e": 5296,
"s": 5233,
"text": "Returns a collection view of the values contained in this map."
},
{
"code": null,
"e": 5384,
"s": 5296,
"text": "The following program illustrates several of the methods supported by this collection β"
},
{
"code": null,
"e": 6428,
"s": 5384,
"text": "import java.util.*;\npublic class IdentityHashMapDemo {\n\n public static void main(String args[]) {\n // Create a hash map\n IdentityHashMap ihm = new IdentityHashMap();\n \n // Put elements to the map\n ihm.put(\"Zara\", new Double(3434.34));\n ihm.put(\"Mahnaz\", new Double(123.22));\n ihm.put(\"Ayan\", new Double(1378.00));\n ihm.put(\"Daisy\", new Double(99.22));\n ihm.put(\"Qadir\", new Double(-19.08));\n \n // Get a set of the entries\n Set set = ihm.entrySet();\n \n // Get an iterator\n Iterator i = set.iterator();\n \n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n \n // Deposit 1000 into Zara's account\n double balance = ((Double)ihm.get(\"Zara\")).doubleValue();\n ihm.put(\"Zara\", new Double(balance + 1000));\n System.out.println(\"Zara's new balance: \" + ihm.get(\"Zara\"));\n }\n}"
},
{
"code": null,
"e": 6469,
"s": 6428,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 6568,
"s": 6469,
"text": "Ayan: 1378.0\nQadir: -19.08\nMahnaz: 123.22\nDaisy: 99.22\nZara: 3434.34\n\nZara's new balance: 4434.34\n"
},
{
"code": null,
"e": 6601,
"s": 6568,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6617,
"s": 6601,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6650,
"s": 6617,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6666,
"s": 6650,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6701,
"s": 6666,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6715,
"s": 6701,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6749,
"s": 6715,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6763,
"s": 6749,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6800,
"s": 6763,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6815,
"s": 6800,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6848,
"s": 6815,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6867,
"s": 6848,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6874,
"s": 6867,
"text": " Print"
},
{
"code": null,
"e": 6885,
"s": 6874,
"text": " Add Notes"
}
] |
MariaDB - Temporary Tables | Some operations can benefit from temporary tables due to speed or disposable data. The life of a temporary table ends at the termination of a session whether you employ them from the command prompt, with a PHP script, or through a client program. It also does not appear in the system in a typical fashion. The SHOW TABLES command will not reveal a list containing temporary tables.
The TEMPORARY keyword within a CREATE TABLE statement spawns a temporary table. Review an example given below β
mysql>CREATE TEMPORARY TABLE order (
item_name VARCHAR(50) NOT NULL
, price DECIMAL(7,2) NOT NULL DEFAULT 0.00
, quantity INT UNSIGNED NOT NULL DEFAULT 0
);
In creating a temporary table, you can clone existing tables, meaning all their general characteristics, with the LIKE clause. The CREATE TABLE statement used to spawn the temporary table will not commit transactions as a result of the TEMPORARY keyword.
Though temporary tables stand apart from non-temporary and drop at the end of a session, they may have certain conflicts β
They sometimes conflict with ghost temporary tables from expired sessions.
They sometimes conflict with ghost temporary tables from expired sessions.
They sometimes conflict with shadow names of non-temporary tables.
They sometimes conflict with shadow names of non-temporary tables.
Note β Temporary tables are permitted to have the same name as an existing non-temporary table because MariaDB views it as a difference reference.
MariaDB requires granting privileges to users for creating temporary tables. Utilize a GRANT statement to give this privilege to non-admin users.
GRANT CREATE TEMPORARY TABLES ON orders TO 'machine122'@'localhost';
Though temporary tables are essentially removed at the end of sessions, you have the option to delete them. Dropping a temporary table requires the use of the TEMPORARY keyword, and best practices suggest dropping temporary tables before any non-temporary.
mysql> DROP TABLE order;
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2745,
"s": 2362,
"text": "Some operations can benefit from temporary tables due to speed or disposable data. The life of a temporary table ends at the termination of a session whether you employ them from the command prompt, with a PHP script, or through a client program. It also does not appear in the system in a typical fashion. The SHOW TABLES command will not reveal a list containing temporary tables."
},
{
"code": null,
"e": 2857,
"s": 2745,
"text": "The TEMPORARY keyword within a CREATE TABLE statement spawns a temporary table. Review an example given below β"
},
{
"code": null,
"e": 3024,
"s": 2857,
"text": "mysql>CREATE TEMPORARY TABLE order (\n item_name VARCHAR(50) NOT NULL\n , price DECIMAL(7,2) NOT NULL DEFAULT 0.00\n , quantity INT UNSIGNED NOT NULL DEFAULT 0\n);\n"
},
{
"code": null,
"e": 3279,
"s": 3024,
"text": "In creating a temporary table, you can clone existing tables, meaning all their general characteristics, with the LIKE clause. The CREATE TABLE statement used to spawn the temporary table will not commit transactions as a result of the TEMPORARY keyword."
},
{
"code": null,
"e": 3402,
"s": 3279,
"text": "Though temporary tables stand apart from non-temporary and drop at the end of a session, they may have certain conflicts β"
},
{
"code": null,
"e": 3477,
"s": 3402,
"text": "They sometimes conflict with ghost temporary tables from expired sessions."
},
{
"code": null,
"e": 3552,
"s": 3477,
"text": "They sometimes conflict with ghost temporary tables from expired sessions."
},
{
"code": null,
"e": 3619,
"s": 3552,
"text": "They sometimes conflict with shadow names of non-temporary tables."
},
{
"code": null,
"e": 3686,
"s": 3619,
"text": "They sometimes conflict with shadow names of non-temporary tables."
},
{
"code": null,
"e": 3833,
"s": 3686,
"text": "Note β Temporary tables are permitted to have the same name as an existing non-temporary table because MariaDB views it as a difference reference."
},
{
"code": null,
"e": 3979,
"s": 3833,
"text": "MariaDB requires granting privileges to users for creating temporary tables. Utilize a GRANT statement to give this privilege to non-admin users."
},
{
"code": null,
"e": 4049,
"s": 3979,
"text": "GRANT CREATE TEMPORARY TABLES ON orders TO 'machine122'@'localhost';\n"
},
{
"code": null,
"e": 4306,
"s": 4049,
"text": "Though temporary tables are essentially removed at the end of sessions, you have the option to delete them. Dropping a temporary table requires the use of the TEMPORARY keyword, and best practices suggest dropping temporary tables before any non-temporary."
},
{
"code": null,
"e": 4332,
"s": 4306,
"text": "mysql> DROP TABLE order;\n"
},
{
"code": null,
"e": 4339,
"s": 4332,
"text": " Print"
},
{
"code": null,
"e": 4350,
"s": 4339,
"text": " Add Notes"
}
] |
Interfaces in Java | An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
An interface is similar to a class in the following ways β
An interface can contain any number of methods.
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
The byte code of an interface appears in a .class file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.
However, an interface is different from a class in several ways, including β
You cannot instantiate an interface.
You cannot instantiate an interface.
An interface does not contain any constructors.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
An interface can extend multiple interfaces.
The interface keyword is used to declare an interface. Here is a simple example to declare an interface β
Following is an example of an interface β
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations\
}
Interfaces have the following properties β
An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.
An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.
Methods in an interface are implicitly public.
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
This will produce the following result β
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed β
Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
An implementation class itself can be abstract and if so, interface methods need not be implemented.
An implementation class itself can be abstract and if so, interface methods need not be implemented.
When implementation interfaces, there are several rules β
A class can implement more than one interface at a time.
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, in a similar way as a class can extend another class.
An interface can extend another interface, in a similar way as a class can extend another class.
An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as β
public interface Hockey extends Sports, Event
The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as β
package java.util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces β
Creates a common parent β As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class β This situation is where the term, tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism. | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface."
},
{
"code": null,
"e": 1445,
"s": 1259,
"text": "Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods."
},
{
"code": null,
"e": 1623,
"s": 1445,
"text": "Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements."
},
{
"code": null,
"e": 1749,
"s": 1623,
"text": "Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class."
},
{
"code": null,
"e": 1808,
"s": 1749,
"text": "An interface is similar to a class in the following ways β"
},
{
"code": null,
"e": 1856,
"s": 1808,
"text": "An interface can contain any number of methods."
},
{
"code": null,
"e": 1904,
"s": 1856,
"text": "An interface can contain any number of methods."
},
{
"code": null,
"e": 2024,
"s": 1904,
"text": "An interface is written in a file with a .java extension, with the name of the interface matching the name of the file."
},
{
"code": null,
"e": 2144,
"s": 2024,
"text": "An interface is written in a file with a .java extension, with the name of the interface matching the name of the file."
},
{
"code": null,
"e": 2200,
"s": 2144,
"text": "The byte code of an interface appears in a .class file."
},
{
"code": null,
"e": 2256,
"s": 2200,
"text": "The byte code of an interface appears in a .class file."
},
{
"code": null,
"e": 2389,
"s": 2256,
"text": "Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name."
},
{
"code": null,
"e": 2522,
"s": 2389,
"text": "Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name."
},
{
"code": null,
"e": 2599,
"s": 2522,
"text": "However, an interface is different from a class in several ways, including β"
},
{
"code": null,
"e": 2636,
"s": 2599,
"text": "You cannot instantiate an interface."
},
{
"code": null,
"e": 2673,
"s": 2636,
"text": "You cannot instantiate an interface."
},
{
"code": null,
"e": 2721,
"s": 2673,
"text": "An interface does not contain any constructors."
},
{
"code": null,
"e": 2769,
"s": 2721,
"text": "An interface does not contain any constructors."
},
{
"code": null,
"e": 2818,
"s": 2769,
"text": "All of the methods in an interface are abstract."
},
{
"code": null,
"e": 2867,
"s": 2818,
"text": "All of the methods in an interface are abstract."
},
{
"code": null,
"e": 3000,
"s": 2867,
"text": "An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final."
},
{
"code": null,
"e": 3133,
"s": 3000,
"text": "An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final."
},
{
"code": null,
"e": 3204,
"s": 3133,
"text": "An interface is not extended by a class; it is implemented by a class."
},
{
"code": null,
"e": 3275,
"s": 3204,
"text": "An interface is not extended by a class; it is implemented by a class."
},
{
"code": null,
"e": 3320,
"s": 3275,
"text": "An interface can extend multiple interfaces."
},
{
"code": null,
"e": 3365,
"s": 3320,
"text": "An interface can extend multiple interfaces."
},
{
"code": null,
"e": 3471,
"s": 3365,
"text": "The interface keyword is used to declare an interface. Here is a simple example to declare an interface β"
},
{
"code": null,
"e": 3513,
"s": 3471,
"text": "Following is an example of an interface β"
},
{
"code": null,
"e": 3736,
"s": 3513,
"text": "/* File name : NameOfInterface.java */\nimport java.lang.*;\n// Any number of import statements\n\npublic interface NameOfInterface {\n // Any number of final, static fields\n // Any number of abstract method declarations\\\n}"
},
{
"code": null,
"e": 3779,
"s": 3736,
"text": "Interfaces have the following properties β"
},
{
"code": null,
"e": 3890,
"s": 3779,
"text": "An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface."
},
{
"code": null,
"e": 4001,
"s": 3890,
"text": "An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface."
},
{
"code": null,
"e": 4097,
"s": 4001,
"text": "Each method in an interface is also implicitly abstract, so the abstract keyword is not needed."
},
{
"code": null,
"e": 4193,
"s": 4097,
"text": "Each method in an interface is also implicitly abstract, so the abstract keyword is not needed."
},
{
"code": null,
"e": 4240,
"s": 4193,
"text": "Methods in an interface are implicitly public."
},
{
"code": null,
"e": 4287,
"s": 4240,
"text": "Methods in an interface are implicitly public."
},
{
"code": null,
"e": 4385,
"s": 4287,
"text": "/* File name : Animal.java */\ninterface Animal {\n public void eat();\n public void travel();\n}"
},
{
"code": null,
"e": 4641,
"s": 4385,
"text": "When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract."
},
{
"code": null,
"e": 4810,
"s": 4641,
"text": "A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration."
},
{
"code": null,
"e": 5203,
"s": 4810,
"text": "/* File name : MammalInt.java */\npublic class MammalInt implements Animal {\n\n public void eat() {\n System.out.println(\"Mammal eats\");\n }\n\n public void travel() {\n System.out.println(\"Mammal travels\");\n }\n\n public int noOfLegs() {\n return 0;\n }\n\n public static void main(String args[]) {\n MammalInt m = new MammalInt();\n m.eat();\n m.travel();\n }\n}"
},
{
"code": null,
"e": 5244,
"s": 5203,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 5271,
"s": 5244,
"text": "Mammal eats\nMammal travels"
},
{
"code": null,
"e": 5359,
"s": 5271,
"text": "When overriding methods defined in interfaces, there are several rules to be followed β"
},
{
"code": null,
"e": 5537,
"s": 5359,
"text": "Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method."
},
{
"code": null,
"e": 5715,
"s": 5537,
"text": "Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method."
},
{
"code": null,
"e": 5839,
"s": 5715,
"text": "The signature of the interface method and the same return type or subtype should be maintained when overriding the methods."
},
{
"code": null,
"e": 5963,
"s": 5839,
"text": "The signature of the interface method and the same return type or subtype should be maintained when overriding the methods."
},
{
"code": null,
"e": 6064,
"s": 5963,
"text": "An implementation class itself can be abstract and if so, interface methods need not be implemented."
},
{
"code": null,
"e": 6165,
"s": 6064,
"text": "An implementation class itself can be abstract and if so, interface methods need not be implemented."
},
{
"code": null,
"e": 6223,
"s": 6165,
"text": "When implementation interfaces, there are several rules β"
},
{
"code": null,
"e": 6280,
"s": 6223,
"text": "A class can implement more than one interface at a time."
},
{
"code": null,
"e": 6337,
"s": 6280,
"text": "A class can implement more than one interface at a time."
},
{
"code": null,
"e": 6403,
"s": 6337,
"text": "A class can extend only one class, but implement many interfaces."
},
{
"code": null,
"e": 6469,
"s": 6403,
"text": "A class can extend only one class, but implement many interfaces."
},
{
"code": null,
"e": 6566,
"s": 6469,
"text": "An interface can extend another interface, in a similar way as a class can extend another class."
},
{
"code": null,
"e": 6663,
"s": 6566,
"text": "An interface can extend another interface, in a similar way as a class can extend another class."
},
{
"code": null,
"e": 6882,
"s": 6663,
"text": "An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface."
},
{
"code": null,
"e": 6960,
"s": 6882,
"text": "The following Sports interface is extended by Hockey and Football interfaces."
},
{
"code": null,
"e": 7522,
"s": 6960,
"text": "// Filename: Sports.java\npublic interface Sports {\n public void setHomeTeam(String name);\n public void setVisitingTeam(String name);\n}\n\n// Filename: Football.java\npublic interface Football extends Sports {\n public void homeTeamScored(int points);\n public void visitingTeamScored(int points);\n public void endOfQuarter(int quarter);\n}\n\n// Filename: Hockey.java\npublic interface Hockey extends Sports {\n public void homeGoalScored();\n public void visitingGoalScored();\n public void endOfPeriod(int period);\n public void overtimePeriod(int ot);\n}"
},
{
"code": null,
"e": 7792,
"s": 7522,
"text": "The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports."
},
{
"code": null,
"e": 7973,
"s": 7792,
"text": "A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface."
},
{
"code": null,
"e": 8073,
"s": 7973,
"text": "The extends keyword is used once, and the parent interfaces are declared in a comma-separated list."
},
{
"code": null,
"e": 8168,
"s": 8073,
"text": "For example, if the Hockey interface extended both Sports and Event, it would be declared as β"
},
{
"code": null,
"e": 8214,
"s": 8168,
"text": "public interface Hockey extends Sports, Event"
},
{
"code": null,
"e": 8448,
"s": 8214,
"text": "The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as β"
},
{
"code": null,
"e": 8501,
"s": 8448,
"text": "package java.util;\npublic interface EventListener\n{}"
},
{
"code": null,
"e": 8635,
"s": 8501,
"text": "An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces β"
},
{
"code": null,
"e": 9002,
"s": 8635,
"text": "Creates a common parent β As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario."
},
{
"code": null,
"e": 9269,
"s": 9002,
"text": "Adds a data type to a class β This situation is where the term, tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism."
}
] |
How to sum time in MySQL by converting into seconds? | To convert time to seconds, use the TIME_TO_SEC() method. Let us first create a table β
mysql> create table DemoTable
-> (
-> ArrivalTime time
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable values('04:10:00');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('05:20:50');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('06:40:10');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
+-------------+
| ArrivalTime |
+-------------+
| 04:10:00 |
| 05:20:50 |
| 06:40:10 |
+-------------+
3 rows in set (0.00 sec)
Following is the query to calculate the sum of time in MySQL β
mysql> select SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) from DemoTable;
+-------------------------------------------------+
| SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) |
+-------------------------------------------------+
| 16:11:00 |
+-------------------------------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To convert time to seconds, use the TIME_TO_SEC() method. Let us first create a table β"
},
{
"code": null,
"e": 1257,
"s": 1150,
"text": "mysql> create table DemoTable\n -> (\n -> ArrivalTime time\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1313,
"s": 1257,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1570,
"s": 1313,
"text": "mysql> insert into DemoTable values('04:10:00');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable values('05:20:50');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('06:40:10');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1630,
"s": 1570,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1661,
"s": 1630,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1798,
"s": 1661,
"text": "+-------------+\n| ArrivalTime |\n+-------------+\n| 04:10:00 |\n| 05:20:50 |\n| 06:40:10 |\n+-------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1861,
"s": 1798,
"text": "Following is the query to calculate the sum of time in MySQL β"
},
{
"code": null,
"e": 1939,
"s": 1861,
"text": "mysql> select SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) from DemoTable;"
},
{
"code": null,
"e": 2223,
"s": 1939,
"text": "+-------------------------------------------------+\n| SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) |\n+-------------------------------------------------+\n| 16:11:00 |\n+-------------------------------------------------+\n1 row in set (0.00 sec)"
}
] |
Output of python program | Set 12(Lists and Tuples) - GeeksforGeeks | 11 Mar, 2022
Prerequisite: List and Tuples Note: Output of all these programs is tested on Python3
1) What is the output of the following program?
PYTHON
L1 = []L1.append([1, [2, 3], 4])L1.extend([7, 8, 9])print(L1[0][1][1] + L1[2])
a) Type Error: can only concatenate list (not βintβ) to list b) 12 c) 11 d) 38
Ans: (c)
Explanation: In the print(), indexing is used. L1[0] denotes [1, [2, 3], 4], L1[0][1] denotes [2, 3],
L1[0][1][1] = 3 and L1[2] = 8. Thus, the two integers are added, 3 + 8 = 11 and output comes as 11.
2) What is the output of the following program?
PYTHON
L1 = [1, 1.33, 'GFG', 0, 'NO', None, 'G', True]val1, val2 = 0, ''for x in L1: if(type(x) == int or type(x) == float): val1 += x else if(type(x) == str): val2 += x else: breakprint(val1, val2)
a) 2 GFGNO b) 2.33 GFGNOG c) 2.33 GFGNONoneGTrue d) 2.33 GFGNO
Ans: (d)
Explanation: val1 will only have integer and floating values val1 = 1 + 1.33 + 0 = 2.33 and val2 will have string
values val2 ='GFG' + 'NO' = 'GFGNO'. String 'G' will not be part of val2 as the for loop will break at None,
thus 'G' will not be added to val2.
3) What is the output of the following program?
Python3
L1 = [1, 2, 3, 4]L2 = L1L3 = L1.copy()L4 = L3L1[0] = [5]print(L1, L2, L3, L4)
a) [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] b) [[5], 2, 3, 4] [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] c) [5, 2, 3, 4] [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] d) [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
Ans: (d)
Explanation: L2 is the reference pointing to the same object as L1,
while L3 and L4 are single recursive Copy(Shallow Copy) of List L1.
L1[0] = [5], implies that at index 0, list [5] will be present and not integer value 5.
4) What is the output of the following program?
PYTHON
import sysL1 = tuple()print(sys.getsizeof(L1), end = " ")L1 = (1, 2)print(sys.getsizeof(L1), end = " ")L1 = (1, 3, (4, 5))print(sys.getsizeof(L1), end = " ")L1 = (1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3))print(sys.getsizeof(L1))
a) 0 2 3 10 b) 32 34 35 42 c) 48 64 72 128 d) 48 144 192 480
Ans: (c)
Explanation: An Empty Tuple has 48 Bytes as Overhead size and each additional element requires 8 Bytes.
(1, 2) Size: 48 + 2 * 8 = 64
(1, 3, (4, 5)) Size: 48 + 3 * 8 = 72
(1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3)) Size: 48 + 10 * 8 = 128
5) What is the output of the following program?
PYTHON
T1 = (1)T2 = (3, 4)T1 += 5print(T1)print(T1 + T2)
a) TypeError b) (1, 5, 3, 4) c) 1 TypeError d) 6 TypeError
Ans: (d)
Explanation: T1 is an integer while T2 is tuple. Thus T1 will become 1 + 5 = 6. But an integer and tuple cannot be added, it will throw TypeError.
This article is contributed by Piyush Doorwar. 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.
ManasChhabra2
RajuKumar19
aryan521970
aliabbas4k12
simmytarika5
python-list
Python-Output
python-tuple
Program Output
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12 | [
{
"code": null,
"e": 25863,
"s": 25835,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 25949,
"s": 25863,
"text": "Prerequisite: List and Tuples Note: Output of all these programs is tested on Python3"
},
{
"code": null,
"e": 25998,
"s": 25949,
"text": "1) What is the output of the following program? "
},
{
"code": null,
"e": 26005,
"s": 25998,
"text": "PYTHON"
},
{
"code": "L1 = []L1.append([1, [2, 3], 4])L1.extend([7, 8, 9])print(L1[0][1][1] + L1[2])",
"e": 26084,
"s": 26005,
"text": null
},
{
"code": null,
"e": 26164,
"s": 26084,
"text": "a) Type Error: can only concatenate list (not βintβ) to list b) 12 c) 11 d) 38 "
},
{
"code": null,
"e": 26377,
"s": 26164,
"text": "Ans: (c) \nExplanation: In the print(), indexing is used. L1[0] denotes [1, [2, 3], 4], L1[0][1] denotes [2, 3], \nL1[0][1][1] = 3 and L1[2] = 8. Thus, the two integers are added, 3 + 8 = 11 and output comes as 11."
},
{
"code": null,
"e": 26426,
"s": 26377,
"text": "2) What is the output of the following program? "
},
{
"code": null,
"e": 26433,
"s": 26426,
"text": "PYTHON"
},
{
"code": "L1 = [1, 1.33, 'GFG', 0, 'NO', None, 'G', True]val1, val2 = 0, ''for x in L1: if(type(x) == int or type(x) == float): val1 += x else if(type(x) == str): val2 += x else: breakprint(val1, val2)",
"e": 26655,
"s": 26433,
"text": null
},
{
"code": null,
"e": 26719,
"s": 26655,
"text": "a) 2 GFGNO b) 2.33 GFGNOG c) 2.33 GFGNONoneGTrue d) 2.33 GFGNO "
},
{
"code": null,
"e": 27014,
"s": 26719,
"text": "Ans: (d) \nExplanation: val1 will only have integer and floating values val1 = 1 + 1.33 + 0 = 2.33 and val2 will have string\n values val2 ='GFG' + 'NO' = 'GFGNO'. String 'G' will not be part of val2 as the for loop will break at None,\n thus 'G' will not be added to val2."
},
{
"code": null,
"e": 27063,
"s": 27014,
"text": "3) What is the output of the following program? "
},
{
"code": null,
"e": 27071,
"s": 27063,
"text": "Python3"
},
{
"code": "L1 = [1, 2, 3, 4]L2 = L1L3 = L1.copy()L4 = L3L1[0] = [5]print(L1, L2, L3, L4)",
"e": 27149,
"s": 27071,
"text": null
},
{
"code": null,
"e": 27380,
"s": 27149,
"text": "a) [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] b) [[5], 2, 3, 4] [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] c) [5, 2, 3, 4] [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] d) [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] "
},
{
"code": null,
"e": 27640,
"s": 27380,
"text": "Ans: (d) \nExplanation: L2 is the reference pointing to the same object as L1,\n while L3 and L4 are single recursive Copy(Shallow Copy) of List L1.\n L1[0] = [5], implies that at index 0, list [5] will be present and not integer value 5."
},
{
"code": null,
"e": 27690,
"s": 27640,
"text": "4) What is the output of the following program? "
},
{
"code": null,
"e": 27697,
"s": 27690,
"text": "PYTHON"
},
{
"code": "import sysL1 = tuple()print(sys.getsizeof(L1), end = \" \")L1 = (1, 2)print(sys.getsizeof(L1), end = \" \")L1 = (1, 3, (4, 5))print(sys.getsizeof(L1), end = \" \")L1 = (1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3))print(sys.getsizeof(L1))",
"e": 27932,
"s": 27697,
"text": null
},
{
"code": null,
"e": 27994,
"s": 27932,
"text": "a) 0 2 3 10 b) 32 34 35 42 c) 48 64 72 128 d) 48 144 192 480 "
},
{
"code": null,
"e": 28251,
"s": 27994,
"text": "Ans: (c) \nExplanation: An Empty Tuple has 48 Bytes as Overhead size and each additional element requires 8 Bytes. \n(1, 2) Size: 48 + 2 * 8 = 64 \n(1, 3, (4, 5)) Size: 48 + 3 * 8 = 72 \n(1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3)) Size: 48 + 10 * 8 = 128 "
},
{
"code": null,
"e": 28301,
"s": 28251,
"text": "5) What is the output of the following program? "
},
{
"code": null,
"e": 28308,
"s": 28301,
"text": "PYTHON"
},
{
"code": "T1 = (1)T2 = (3, 4)T1 += 5print(T1)print(T1 + T2)",
"e": 28358,
"s": 28308,
"text": null
},
{
"code": null,
"e": 28418,
"s": 28358,
"text": "a) TypeError b) (1, 5, 3, 4) c) 1 TypeError d) 6 TypeError "
},
{
"code": null,
"e": 28575,
"s": 28418,
"text": "Ans: (d) \nExplanation: T1 is an integer while T2 is tuple. Thus T1 will become 1 + 5 = 6. But an integer and tuple cannot be added, it will throw TypeError."
},
{
"code": null,
"e": 29003,
"s": 28575,
"text": "This article is contributed by Piyush Doorwar. 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. "
},
{
"code": null,
"e": 29017,
"s": 29003,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 29029,
"s": 29017,
"text": "RajuKumar19"
},
{
"code": null,
"e": 29041,
"s": 29029,
"text": "aryan521970"
},
{
"code": null,
"e": 29054,
"s": 29041,
"text": "aliabbas4k12"
},
{
"code": null,
"e": 29067,
"s": 29054,
"text": "simmytarika5"
},
{
"code": null,
"e": 29079,
"s": 29067,
"text": "python-list"
},
{
"code": null,
"e": 29093,
"s": 29079,
"text": "Python-Output"
},
{
"code": null,
"e": 29106,
"s": 29093,
"text": "python-tuple"
},
{
"code": null,
"e": 29121,
"s": 29106,
"text": "Program Output"
},
{
"code": null,
"e": 29133,
"s": 29121,
"text": "python-list"
},
{
"code": null,
"e": 29231,
"s": 29133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29276,
"s": 29231,
"text": "Output of Java program | Set 18 (Overriding)"
},
{
"code": null,
"e": 29308,
"s": 29276,
"text": "Output of Java Program | Set 11"
},
{
"code": null,
"e": 29355,
"s": 29308,
"text": "Output of Java programs | Set 13 (Collections)"
},
{
"code": null,
"e": 29403,
"s": 29355,
"text": "Output of C++ programs | Set 34 (File Handling)"
},
{
"code": null,
"e": 29444,
"s": 29403,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 29475,
"s": 29444,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 29490,
"s": 29475,
"text": "Runtime Errors"
},
{
"code": null,
"e": 29522,
"s": 29490,
"text": "Output of Java program | Set 28"
},
{
"code": null,
"e": 29553,
"s": 29522,
"text": "Output of Java program | Set 5"
}
] |
Python - Append items at beginning of dictionary - GeeksforGeeks | 01 Aug, 2020
Given a dictionary, append another dictionary at beginning of it.
Input : test_dict = {βGfgβ : 5, βisβ : 3, βbestβ : 10}, updict = {βpre1β : 4}Output : {βpre1β: 4, βGfgβ: 5, βisβ: 3, βbestβ: 10}Explanation : New dictionary updated at front of dictionary.
Input : test_dict = {βGfgβ : 5}, updict = {βpre1β : 4}Output : {βpre1β: 4, βGfgβ: 5}Explanation : New dictionary updated at front of dictionary, βpre1β : 4.
Method #1 : Using update()
This is one of the ways in which this task can be performed. In this, we use update function to update old dictionary after the new one so that new dictionary is appended at beginning.
Python3
# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using update() # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 3, "best" : 10} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing update dictionaryupdict = {"pre1" : 4, "pre2" : 8} # update() on new dictionary to get desired orderupdict.update(test_dict) # printing result print("The required dictionary : " + str(updict))
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}
Method #2 : Using ** operator
This is yet another way in which this task can be performed. In this, we perform packing and unpacking of items into custom made dictionary using ** operator.
Python3
# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using ** operator # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 3, "best" : 10} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing update dictionaryupdict = {"pre1" : 4, "pre2" : 8} # ** operator for packing and unpacking items in orderres = {**updict, **test_dict} # printing result print("The required dictionary : " + str(res))
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 25603,
"s": 25537,
"text": "Given a dictionary, append another dictionary at beginning of it."
},
{
"code": null,
"e": 25792,
"s": 25603,
"text": "Input : test_dict = {βGfgβ : 5, βisβ : 3, βbestβ : 10}, updict = {βpre1β : 4}Output : {βpre1β: 4, βGfgβ: 5, βisβ: 3, βbestβ: 10}Explanation : New dictionary updated at front of dictionary."
},
{
"code": null,
"e": 25949,
"s": 25792,
"text": "Input : test_dict = {βGfgβ : 5}, updict = {βpre1β : 4}Output : {βpre1β: 4, βGfgβ: 5}Explanation : New dictionary updated at front of dictionary, βpre1β : 4."
},
{
"code": null,
"e": 25976,
"s": 25949,
"text": "Method #1 : Using update()"
},
{
"code": null,
"e": 26161,
"s": 25976,
"text": "This is one of the ways in which this task can be performed. In this, we use update function to update old dictionary after the new one so that new dictionary is appended at beginning."
},
{
"code": null,
"e": 26169,
"s": 26161,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using update() # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 3, \"best\" : 10} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing update dictionaryupdict = {\"pre1\" : 4, \"pre2\" : 8} # update() on new dictionary to get desired orderupdict.update(test_dict) # printing result print(\"The required dictionary : \" + str(updict)) ",
"e": 26641,
"s": 26169,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26641,
"text": "The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}\nThe required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}\n"
},
{
"code": null,
"e": 26813,
"s": 26783,
"text": "Method #2 : Using ** operator"
},
{
"code": null,
"e": 26972,
"s": 26813,
"text": "This is yet another way in which this task can be performed. In this, we perform packing and unpacking of items into custom made dictionary using ** operator."
},
{
"code": null,
"e": 26980,
"s": 26972,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append items at beginning of dictionary # Using ** operator # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 3, \"best\" : 10} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing update dictionaryupdict = {\"pre1\" : 4, \"pre2\" : 8} # ** operator for packing and unpacking items in orderres = {**updict, **test_dict} # printing result print(\"The required dictionary : \" + str(res)) ",
"e": 27462,
"s": 26980,
"text": null
},
{
"code": null,
"e": 27604,
"s": 27462,
"text": "The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}\nThe required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}\n"
},
{
"code": null,
"e": 27631,
"s": 27604,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27638,
"s": 27631,
"text": "Python"
},
{
"code": null,
"e": 27654,
"s": 27638,
"text": "Python Programs"
},
{
"code": null,
"e": 27752,
"s": 27654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27784,
"s": 27752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27826,
"s": 27784,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27868,
"s": 27826,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27895,
"s": 27868,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27951,
"s": 27895,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27973,
"s": 27951,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28012,
"s": 27973,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28058,
"s": 28012,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28096,
"s": 28058,
"text": "Python | Convert a list to dictionary"
}
] |
Python - Clearing a tuple - GeeksforGeeks | 11 Jun, 2021
Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Letβs discuss certain ways in which this task can be performed.Method #1 : Using list() + clear() + tuple() The combination of above 3 functions can be used to perform this task. In this, we interconvert the tuple to list, clear it and again convert to tuple using tuple().
Python3
# Python3 code to demonstrate# Clearing a tuple# using list() + tuple() + clear() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # Clearing a tuple# using list() + tuple() + clear()temp = list(test_tup)temp.clear()test_tup = tuple(temp) # print resultprint("The tuple after clearing values : " + str(test_tup))
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()
Method #2 : Reinitialization using tuple() Another straight forward way to perform this task is to reinitialize tuple using tuple() which will return empty tuple.
Python3
# Python3 code to demonstrate# Clearing a tuple# using Reinitialization + tuple() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # Clearing a tuple# using Reinitialization + tuple()test_tup = tuple() # print resultprint("The tuple after clearing values : " + str(test_tup))
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()
adnanirshad158
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25655,
"s": 25627,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 26132,
"s": 25655,
"text": "Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Letβs discuss certain ways in which this task can be performed.Method #1 : Using list() + clear() + tuple() The combination of above 3 functions can be used to perform this task. In this, we interconvert the tuple to list, clear it and again convert to tuple using tuple(). "
},
{
"code": null,
"e": 26140,
"s": 26132,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Clearing a tuple# using list() + tuple() + clear() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Clearing a tuple# using list() + tuple() + clear()temp = list(test_tup)temp.clear()test_tup = tuple(temp) # print resultprint(\"The tuple after clearing values : \" + str(test_tup))",
"e": 26523,
"s": 26140,
"text": null
},
{
"code": null,
"e": 26597,
"s": 26523,
"text": "The original tuple : (1, 5, 3, 6, 8)\nThe tuple after clearing values : ()"
},
{
"code": null,
"e": 26764,
"s": 26599,
"text": " Method #2 : Reinitialization using tuple() Another straight forward way to perform this task is to reinitialize tuple using tuple() which will return empty tuple. "
},
{
"code": null,
"e": 26772,
"s": 26764,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Clearing a tuple# using Reinitialization + tuple() # initializing tupletest_tup = (1, 5, 3, 6, 8) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Clearing a tuple# using Reinitialization + tuple()test_tup = tuple() # print resultprint(\"The tuple after clearing values : \" + str(test_tup))",
"e": 27118,
"s": 26772,
"text": null
},
{
"code": null,
"e": 27192,
"s": 27118,
"text": "The original tuple : (1, 5, 3, 6, 8)\nThe tuple after clearing values : ()"
},
{
"code": null,
"e": 27209,
"s": 27194,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27231,
"s": 27209,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27238,
"s": 27231,
"text": "Python"
},
{
"code": null,
"e": 27254,
"s": 27238,
"text": "Python Programs"
},
{
"code": null,
"e": 27352,
"s": 27254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27370,
"s": 27352,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27405,
"s": 27370,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27437,
"s": 27405,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27459,
"s": 27437,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27501,
"s": 27459,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27544,
"s": 27501,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27566,
"s": 27544,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27612,
"s": 27566,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27650,
"s": 27612,
"text": "Python | Convert a list to dictionary"
}
] |
Bitwise OR of N binary strings - GeeksforGeeks | 14 Jun, 2021
Given an array arr[] of binary strings, the task is to calculate the bitwise OR of all of these strings and print the resultant string.Examples:
Input: arr[] = {β100β, β1001β, β0011β} Output 1111 0100 OR 1001 OR 0011 = 1111Input: arr[] = {β10β, β11β, β1000001β} Output: 1000011
Approach: We can do this by first finding the maximum sized string. We need this since we have to add 0s at the front of the strings whose lengths are less than max size. Then apply OR operation on each bit. For example, if strings are β100β, β001β and β1111β. Here max size is 4, so we have to add 1 zero on first and second string to make their length 4 and then the OR operation can be performed on each of the bits of the numbers resulting in β0100β OR β0001β OR β1111β = β1111β.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 bitwise OR of// all the binary stringsstring strBitwiseOR(string* arr, int n){ string res; int max_size = INT_MIN; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = max(max_size, (int)arr[i].size()); reverse(arr[i].begin(), arr[i].end()); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed string s; for (int j = 0; j < max_size - arr[i].size(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i] - '0'); res += (curr_bit + '0'); } // Reverse the resultant string // to get the final string reverse(res.begin(), res.end()); // Return the final string return res;} // Driver codeint main(){ string arr[] = { "10", "11", "1000001" }; int n = sizeof(arr) / sizeof(arr[0]); cout << strBitwiseOR(arr, n); return 0;}
// Java implementation of the approach class GFG{ // Function to return the bitwise OR of// all the binary stringsstatic String strBitwiseOR(String[] arr, int n){ String res=""; int max_size = Integer.MIN_VALUE; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = Math.max(max_size, (int)arr[i].length()); arr[i] = reverse(arr[i]); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed String s=""; for (int j = 0; j < max_size - arr[i].length(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j].charAt(i) - '0'); res += (char)(curr_bit + '0'); } // Reverse the resultant string // to get the final string res = reverse(res); // Return the final string return res;} static String reverse(String input){ char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray);} // Driver codepublic static void main(String[] args){ String arr[] = { "10", "11", "1000001" }; int n = arr.length; System.out.println(strBitwiseOR(arr, n));}} // This code contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the bitwise OR of# all the binary stringsdef strBitwiseOR(arr, n): res="" max_size = -(2**32) # Get max size and reverse each string # Since we have to perform OR operation # on bits from right to left # Reversing the string will make it easier # to perform operation from left to right for i in range(n): max_size = max(max_size, len(arr[i])) arr[i] = arr[i][::-1] for i in range(n): # Add 0s to the end of strings # if needed s = "" for j in range(max_size - len(arr[i])): s += '0' arr[i] = arr[i] + s # Perform OR operation on each bit for i in range(max_size): curr_bit = 0 for j in range(n): curr_bit = curr_bit | ord(arr[j][i]) res += chr(curr_bit) # Reverse the resultant string # to get the final string res=res[::-1] # Return the final string return res # Driver codearr = ["10", "11", "1000001"]n = len(arr)print(strBitwiseOR(arr, n)) # This code is contributed by shubhamsingh10
// C# implementation of the approachusing System; class GFG{ // Function to return the bitwise OR of// all the binary stringsstatic String strBitwiseOR(String[] arr, int n){ String res=""; int max_size = int.MinValue; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = Math.Max(max_size, (int)arr[i].Length); arr[i] = reverse(arr[i]); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed String s=""; for (int j = 0; j < max_size - arr[i].Length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i] - '0'); res += (char)(curr_bit + '0'); } // Reverse the resultant string // to get the final string res = reverse(res); // Return the final string return res;} static String reverse(String input){ char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join("",temparray);} // Driver codepublic static void Main(String[] args){ String []arr = { "10", "11", "1000001" }; int n = arr.Length; Console.WriteLine(strBitwiseOR(arr, n));}} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript implementation of the approach // Function to return the bitwise OR of// all the binary stringsfunction strBitwiseOR(arr, n){ var res = ""; var max_size = -1000000000; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (var i = 0; i < n; i++) { max_size = Math.max(max_size, arr[i].length); arr[i] = arr[i].split('').reverse().join(''); } for (var i = 0; i < n; i++) { // Add 0s to the end of strings // if needed var s = ""; for (var j = 0; j < max_size - arr[i].length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (var i = 0; i < max_size; i++) { var curr_bit = 0; for (var j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i].charCodeAt(0) - '0'.charCodeAt(0)); res += String.fromCharCode(curr_bit + '0'.charCodeAt(0)); } // Reverse the resultant string // to get the final string res = res.split('').reverse().join(''); // Return the final string return res;} // Driver code var arr = ["10", "11", "1000001"];var n = arr.length;document.write( strBitwiseOR(arr, n)); </script>
1000011
Rajput-Ji
princiraj1992
SHUBHAMSINGH10
rrrtnx
Bitwise-OR
Constructive Algorithms
Greedy Algorithms
Marketing
Reverse
Strings
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26607,
"s": 26579,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 26754,
"s": 26607,
"text": "Given an array arr[] of binary strings, the task is to calculate the bitwise OR of all of these strings and print the resultant string.Examples: "
},
{
"code": null,
"e": 26889,
"s": 26754,
"text": "Input: arr[] = {β100β, β1001β, β0011β} Output 1111 0100 OR 1001 OR 0011 = 1111Input: arr[] = {β10β, β11β, β1000001β} Output: 1000011 "
},
{
"code": null,
"e": 27426,
"s": 26891,
"text": "Approach: We can do this by first finding the maximum sized string. We need this since we have to add 0s at the front of the strings whose lengths are less than max size. Then apply OR operation on each bit. For example, if strings are β100β, β001β and β1111β. Here max size is 4, so we have to add 1 zero on first and second string to make their length 4 and then the OR operation can be performed on each of the bits of the numbers resulting in β0100β OR β0001β OR β1111β = β1111β.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27430,
"s": 27426,
"text": "C++"
},
{
"code": null,
"e": 27435,
"s": 27430,
"text": "Java"
},
{
"code": null,
"e": 27443,
"s": 27435,
"text": "Python3"
},
{
"code": null,
"e": 27446,
"s": 27443,
"text": "C#"
},
{
"code": null,
"e": 27457,
"s": 27446,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the bitwise OR of// all the binary stringsstring strBitwiseOR(string* arr, int n){ string res; int max_size = INT_MIN; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = max(max_size, (int)arr[i].size()); reverse(arr[i].begin(), arr[i].end()); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed string s; for (int j = 0; j < max_size - arr[i].size(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i] - '0'); res += (curr_bit + '0'); } // Reverse the resultant string // to get the final string reverse(res.begin(), res.end()); // Return the final string return res;} // Driver codeint main(){ string arr[] = { \"10\", \"11\", \"1000001\" }; int n = sizeof(arr) / sizeof(arr[0]); cout << strBitwiseOR(arr, n); return 0;}",
"e": 28801,
"s": 27457,
"text": null
},
{
"code": "// Java implementation of the approach class GFG{ // Function to return the bitwise OR of// all the binary stringsstatic String strBitwiseOR(String[] arr, int n){ String res=\"\"; int max_size = Integer.MIN_VALUE; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = Math.max(max_size, (int)arr[i].length()); arr[i] = reverse(arr[i]); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed String s=\"\"; for (int j = 0; j < max_size - arr[i].length(); j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j].charAt(i) - '0'); res += (char)(curr_bit + '0'); } // Reverse the resultant string // to get the final string res = reverse(res); // Return the final string return res;} static String reverse(String input){ char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray);} // Driver codepublic static void main(String[] args){ String arr[] = { \"10\", \"11\", \"1000001\" }; int n = arr.length; System.out.println(strBitwiseOR(arr, n));}} // This code contributed by Rajput-Ji",
"e": 30583,
"s": 28801,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the bitwise OR of# all the binary stringsdef strBitwiseOR(arr, n): res=\"\" max_size = -(2**32) # Get max size and reverse each string # Since we have to perform OR operation # on bits from right to left # Reversing the string will make it easier # to perform operation from left to right for i in range(n): max_size = max(max_size, len(arr[i])) arr[i] = arr[i][::-1] for i in range(n): # Add 0s to the end of strings # if needed s = \"\" for j in range(max_size - len(arr[i])): s += '0' arr[i] = arr[i] + s # Perform OR operation on each bit for i in range(max_size): curr_bit = 0 for j in range(n): curr_bit = curr_bit | ord(arr[j][i]) res += chr(curr_bit) # Reverse the resultant string # to get the final string res=res[::-1] # Return the final string return res # Driver codearr = [\"10\", \"11\", \"1000001\"]n = len(arr)print(strBitwiseOR(arr, n)) # This code is contributed by shubhamsingh10",
"e": 31728,
"s": 30583,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the bitwise OR of// all the binary stringsstatic String strBitwiseOR(String[] arr, int n){ String res=\"\"; int max_size = int.MinValue; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (int i = 0; i < n; i++) { max_size = Math.Max(max_size, (int)arr[i].Length); arr[i] = reverse(arr[i]); } for (int i = 0; i < n; i++) { // Add 0s to the end of strings // if needed String s=\"\"; for (int j = 0; j < max_size - arr[i].Length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (int i = 0; i < max_size; i++) { int curr_bit = 0; for (int j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i] - '0'); res += (char)(curr_bit + '0'); } // Reverse the resultant string // to get the final string res = reverse(res); // Return the final string return res;} static String reverse(String input){ char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join(\"\",temparray);} // Driver codepublic static void Main(String[] args){ String []arr = { \"10\", \"11\", \"1000001\" }; int n = arr.Length; Console.WriteLine(strBitwiseOR(arr, n));}} /* This code contributed by PrinciRaj1992 */",
"e": 33524,
"s": 31728,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the bitwise OR of// all the binary stringsfunction strBitwiseOR(arr, n){ var res = \"\"; var max_size = -1000000000; // Get max size and reverse each string // Since we have to perform OR operation // on bits from right to left // Reversing the string will make it easier // to perform operation from left to right for (var i = 0; i < n; i++) { max_size = Math.max(max_size, arr[i].length); arr[i] = arr[i].split('').reverse().join(''); } for (var i = 0; i < n; i++) { // Add 0s to the end of strings // if needed var s = \"\"; for (var j = 0; j < max_size - arr[i].length; j++) s += '0'; arr[i] = arr[i] + s; } // Perform OR operation on each bit for (var i = 0; i < max_size; i++) { var curr_bit = 0; for (var j = 0; j < n; j++) curr_bit = curr_bit | (arr[j][i].charCodeAt(0) - '0'.charCodeAt(0)); res += String.fromCharCode(curr_bit + '0'.charCodeAt(0)); } // Reverse the resultant string // to get the final string res = res.split('').reverse().join(''); // Return the final string return res;} // Driver code var arr = [\"10\", \"11\", \"1000001\"];var n = arr.length;document.write( strBitwiseOR(arr, n)); </script>",
"e": 34882,
"s": 33524,
"text": null
},
{
"code": null,
"e": 34890,
"s": 34882,
"text": "1000011"
},
{
"code": null,
"e": 34902,
"s": 34892,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34916,
"s": 34902,
"text": "princiraj1992"
},
{
"code": null,
"e": 34931,
"s": 34916,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 34938,
"s": 34931,
"text": "rrrtnx"
},
{
"code": null,
"e": 34949,
"s": 34938,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 34973,
"s": 34949,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 34991,
"s": 34973,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 35001,
"s": 34991,
"text": "Marketing"
},
{
"code": null,
"e": 35009,
"s": 35001,
"text": "Reverse"
},
{
"code": null,
"e": 35017,
"s": 35009,
"text": "Strings"
},
{
"code": null,
"e": 35025,
"s": 35017,
"text": "Strings"
},
{
"code": null,
"e": 35033,
"s": 35025,
"text": "Reverse"
},
{
"code": null,
"e": 35131,
"s": 35033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35206,
"s": 35131,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 35263,
"s": 35206,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 35299,
"s": 35263,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 35346,
"s": 35299,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 35399,
"s": 35346,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 35435,
"s": 35399,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 35473,
"s": 35435,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 35503,
"s": 35473,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 35555,
"s": 35503,
"text": "Check whether two strings are anagram of each other"
}
] |
Python Program to Create a Lap Timer - GeeksforGeeks | 24 May, 2020
In this article, we will make a simple timer to calculate lap-time intervals using Python.
time: This module provides various time-related functions. It is a part of Pythonβs standard library and does not require installation.
Approach:The user needs to press ENTER to complete each lap. The timer keeps counting till CTRL+C is pressed. For each lap we calculate the lap time by subtracting the current time from the total time at the end of the previous lap. The time() function of the time module, returns the current epoch time in milliseconds.
Below is the implementation:
# importing librariesimport time # Timer startsstarttime=time.time()lasttime=starttimelapnum=1 print("Press ENTER to count laps.\nPress CTRL+C to stop") try: while True: # Input for the ENTER key press input() # The current lap-time laptime=round((time.time() - lasttime), 2) # Total time elapsed # since the timer started totaltime=round((time.time() - starttime), 2) # Printing the lap number, # lap-time and total time print("Lap No. "+str(lapnum)) print("Total Time: "+str(totaltime)) print("Lap Time: "+str(laptime)) print("*"*20) # Updating the previous total time # and lap number lasttime=time.time() lapnum+=1 # Stopping when CTRL+C is pressedexcept KeyboardInterrupt: print("Done")
Output:
ENTER to count laps.
Press CTRL+C to stop
Lap No. 1
Total Time: 1.09
Lap Time: 1.09
********************
Lap No. 2
Total Time: 2.66
Lap Time: 1.41
********************
Lap No. 3
Total Time: 5.06
Lap Time: 2.23
********************
Lap No. 4
Total Time: 5.63
Lap Time: 0.4
********************
Done
Python time-module
Python
Python Programs
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 25729,
"s": 25701,
"text": "\n24 May, 2020"
},
{
"code": null,
"e": 25820,
"s": 25729,
"text": "In this article, we will make a simple timer to calculate lap-time intervals using Python."
},
{
"code": null,
"e": 25957,
"s": 25820,
"text": "time: This module provides various time-related functions. It is a part of Pythonβs standard library and does not require installation."
},
{
"code": null,
"e": 26278,
"s": 25957,
"text": "Approach:The user needs to press ENTER to complete each lap. The timer keeps counting till CTRL+C is pressed. For each lap we calculate the lap time by subtracting the current time from the total time at the end of the previous lap. The time() function of the time module, returns the current epoch time in milliseconds."
},
{
"code": null,
"e": 26308,
"s": 26278,
"text": "Below is the implementation: "
},
{
"code": "# importing librariesimport time # Timer startsstarttime=time.time()lasttime=starttimelapnum=1 print(\"Press ENTER to count laps.\\nPress CTRL+C to stop\") try: while True: # Input for the ENTER key press input() # The current lap-time laptime=round((time.time() - lasttime), 2) # Total time elapsed # since the timer started totaltime=round((time.time() - starttime), 2) # Printing the lap number, # lap-time and total time print(\"Lap No. \"+str(lapnum)) print(\"Total Time: \"+str(totaltime)) print(\"Lap Time: \"+str(laptime)) print(\"*\"*20) # Updating the previous total time # and lap number lasttime=time.time() lapnum+=1 # Stopping when CTRL+C is pressedexcept KeyboardInterrupt: print(\"Done\")",
"e": 27203,
"s": 26308,
"text": null
},
{
"code": null,
"e": 27211,
"s": 27203,
"text": "Output:"
},
{
"code": null,
"e": 27514,
"s": 27211,
"text": "ENTER to count laps.\nPress CTRL+C to stop\n\nLap No. 1\nTotal Time: 1.09\nLap Time: 1.09\n********************\n\nLap No. 2\nTotal Time: 2.66\nLap Time: 1.41\n********************\n\nLap No. 3\nTotal Time: 5.06\nLap Time: 2.23\n********************\n\nLap No. 4\nTotal Time: 5.63\nLap Time: 0.4\n********************\nDone\n"
},
{
"code": null,
"e": 27533,
"s": 27514,
"text": "Python time-module"
},
{
"code": null,
"e": 27540,
"s": 27533,
"text": "Python"
},
{
"code": null,
"e": 27556,
"s": 27540,
"text": "Python Programs"
},
{
"code": null,
"e": 27572,
"s": 27556,
"text": "Write From Home"
},
{
"code": null,
"e": 27670,
"s": 27572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27688,
"s": 27670,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27720,
"s": 27688,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27742,
"s": 27720,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27784,
"s": 27742,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27814,
"s": 27784,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27857,
"s": 27814,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27879,
"s": 27857,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27918,
"s": 27879,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27964,
"s": 27918,
"text": "Python | Split string into list of characters"
}
] |
PHP append one array to another - GeeksforGeeks | 03 Nov, 2018
Given two array arr1 and arr2 and the task is to append one array to another array.
Examples:
Input : arr1 = [ 1, 2 ]
arr2 = [ 3, 4 ]
Output : arr1 = [ 1, 2, 3, 4 ]
Input : arr1 = [ "Geeks", "g4g" ]
arr2 = [ "GeeksforGeeks" ]
Output : arr1 = [ "Geeks", "g4g", "GeeksforGeeks" ]
Using array_merge function: This function returns a new array after merging the two arrays.
Example:
<?php$arr1 = array("Geeks", "g4g");$arr2 = array("GeeksforGeeks", "Computer science portal"); // Get the merged array in the first array itself.$arr1 = array_merge($arr1, $arr2); echo "arr1 Contents:"; // Use for each loop to print all the array elements.foreach ($arr1 as $value) { echo $value . "\n";}?>
Output:
arr1 Contents:
Geeks
g4g
GeeksforGeeks
Computer science portal
Using array_push Method: This method pushes the second array element in the first array in-place.
Example:
<?php$arr1 = array(1, 2);$arr2 = array(3, 4); // arr2 elements are being pushed in the arr1.array_push($arr1 , ...$arr2); echo "arr1 = "; // Use for each loop to print all the array elements.foreach ($arr1 as $value) {echo $value . ' ';}?>
Output:
arr1 = 1 2 3 4
Note: Another way to do it is by β + β but it gives fatal warning in the newer versions, hence it is not recommended.
PHP-array
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP? | [
{
"code": null,
"e": 32651,
"s": 32623,
"text": "\n03 Nov, 2018"
},
{
"code": null,
"e": 32735,
"s": 32651,
"text": "Given two array arr1 and arr2 and the task is to append one array to another array."
},
{
"code": null,
"e": 32745,
"s": 32735,
"text": "Examples:"
},
{
"code": null,
"e": 32949,
"s": 32745,
"text": "Input : arr1 = [ 1, 2 ]\n arr2 = [ 3, 4 ]\n\nOutput : arr1 = [ 1, 2, 3, 4 ]\n\nInput : arr1 = [ \"Geeks\", \"g4g\" ]\n arr2 = [ \"GeeksforGeeks\" ]\n\nOutput : arr1 = [ \"Geeks\", \"g4g\", \"GeeksforGeeks\" ]\n"
},
{
"code": null,
"e": 33041,
"s": 32949,
"text": "Using array_merge function: This function returns a new array after merging the two arrays."
},
{
"code": null,
"e": 33050,
"s": 33041,
"text": "Example:"
},
{
"code": "<?php$arr1 = array(\"Geeks\", \"g4g\");$arr2 = array(\"GeeksforGeeks\", \"Computer science portal\"); // Get the merged array in the first array itself.$arr1 = array_merge($arr1, $arr2); echo \"arr1 Contents:\"; // Use for each loop to print all the array elements.foreach ($arr1 as $value) { echo $value . \"\\n\";}?>",
"e": 33363,
"s": 33050,
"text": null
},
{
"code": null,
"e": 33371,
"s": 33363,
"text": "Output:"
},
{
"code": null,
"e": 33434,
"s": 33371,
"text": "arr1 Contents:\nGeeks\ng4g\nGeeksforGeeks\nComputer science portal"
},
{
"code": null,
"e": 33532,
"s": 33434,
"text": "Using array_push Method: This method pushes the second array element in the first array in-place."
},
{
"code": null,
"e": 33541,
"s": 33532,
"text": "Example:"
},
{
"code": "<?php$arr1 = array(1, 2);$arr2 = array(3, 4); // arr2 elements are being pushed in the arr1.array_push($arr1 , ...$arr2); echo \"arr1 = \"; // Use for each loop to print all the array elements.foreach ($arr1 as $value) {echo $value . ' ';}?>",
"e": 33785,
"s": 33541,
"text": null
},
{
"code": null,
"e": 33793,
"s": 33785,
"text": "Output:"
},
{
"code": null,
"e": 33808,
"s": 33793,
"text": "arr1 = 1 2 3 4"
},
{
"code": null,
"e": 33926,
"s": 33808,
"text": "Note: Another way to do it is by β + β but it gives fatal warning in the newer versions, hence it is not recommended."
},
{
"code": null,
"e": 33936,
"s": 33926,
"text": "PHP-array"
},
{
"code": null,
"e": 33943,
"s": 33936,
"text": "Picked"
},
{
"code": null,
"e": 33967,
"s": 33943,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 33971,
"s": 33967,
"text": "PHP"
},
{
"code": null,
"e": 33984,
"s": 33971,
"text": "PHP Programs"
},
{
"code": null,
"e": 34003,
"s": 33984,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34020,
"s": 34003,
"text": "Web Technologies"
},
{
"code": null,
"e": 34024,
"s": 34020,
"text": "PHP"
},
{
"code": null,
"e": 34122,
"s": 34024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34167,
"s": 34122,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34217,
"s": 34167,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34257,
"s": 34217,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34281,
"s": 34257,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 34325,
"s": 34281,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 34370,
"s": 34325,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34420,
"s": 34370,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34460,
"s": 34420,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34504,
"s": 34460,
"text": "How to pop an alert message box using PHP ?"
}
] |
multimap::count() in C++ STL - GeeksforGeeks | 18 Nov, 2020
The multimap::count is a built-in function in C++ STL which returns the number of times a key is present in the multimap container.
Syntax:
multimap_name.count(key)
Parameters: The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returned.
Return Value: The function returns the number of times a key is present in the multimap container.
// C++ function for illustration// multimap::count() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 2, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); // count the number of times // 1 is there in the multimap cout << "1 exists " << mp.count(1) << " times in the multimap\n"; // count the number of times // 2 is there in the multimap cout << "2 exists " << mp.count(2) << " times in the multimap\n"; return 0;}
1 exists 2 times in the multimap
2 exists 3 times in the multimap
arorakashish0911
CPP-Functions
cpp-multimap
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Polymorphism in C++ | [
{
"code": null,
"e": 25733,
"s": 25705,
"text": "\n18 Nov, 2020"
},
{
"code": null,
"e": 25865,
"s": 25733,
"text": "The multimap::count is a built-in function in C++ STL which returns the number of times a key is present in the multimap container."
},
{
"code": null,
"e": 25873,
"s": 25865,
"text": "Syntax:"
},
{
"code": null,
"e": 25899,
"s": 25873,
"text": "multimap_name.count(key)\n"
},
{
"code": null,
"e": 26037,
"s": 25899,
"text": "Parameters: The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returned."
},
{
"code": null,
"e": 26136,
"s": 26037,
"text": "Return Value: The function returns the number of times a key is present in the multimap container."
},
{
"code": "// C++ function for illustration// multimap::count() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 2, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); // count the number of times // 1 is there in the multimap cout << \"1 exists \" << mp.count(1) << \" times in the multimap\\n\"; // count the number of times // 2 is there in the multimap cout << \"2 exists \" << mp.count(2) << \" times in the multimap\\n\"; return 0;}",
"e": 26806,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26873,
"s": 26806,
"text": "1 exists 2 times in the multimap\n2 exists 3 times in the multimap\n"
},
{
"code": null,
"e": 26890,
"s": 26873,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26904,
"s": 26890,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26917,
"s": 26904,
"text": "cpp-multimap"
},
{
"code": null,
"e": 26921,
"s": 26917,
"text": "STL"
},
{
"code": null,
"e": 26925,
"s": 26921,
"text": "C++"
},
{
"code": null,
"e": 26929,
"s": 26925,
"text": "STL"
},
{
"code": null,
"e": 26933,
"s": 26929,
"text": "CPP"
},
{
"code": null,
"e": 27031,
"s": 26933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27050,
"s": 27031,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27074,
"s": 27050,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27098,
"s": 27074,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27125,
"s": 27098,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 27156,
"s": 27125,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27176,
"s": 27156,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27204,
"s": 27176,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27232,
"s": 27204,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27267,
"s": 27232,
"text": "Object Oriented Programming in C++"
}
] |
Sort array of objects by string property value in JavaScript - GeeksforGeeks | 28 Mar, 2019
The array of objects can be sort by using user defined function. This function compares the array of objects by its property. For example, the first example compares the l_name of objects and if l_name is small then it place into left otherwise place it into right position.
Example 1: This example sorts the array of objects by l_name property.
<!DOCTYPE html> <html> <head> <title> Sort array of objects </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="demo2">GFG_Object = [ <br> { "f_name": "Geeks", "l_name": "_1" }, <br><br> { "f_name": "for", "l_name": "_2" }, <br><br> { "f_name": "GFG", "l_name": "_3" } <br>]; </p> <button onClick="fun()"> sort </button> <p id="GFG"></p> <!-- Script to compare the object and sort its content --> <script> function fun() { function compare(a, b) { if (a.l_name < b.l_name) return -1; if (a.l_name > b.l_name) return 1; return 0; } var GFG_Object = [ { f_name: 'Geeks', l_name: '_2' }, { f_name: 'for', l_name: '_1' }, { f_name: 'GFG', l_name: '_3' } ]; GFG_Object.sort(compare); document.getElementById("GFG").innerHTML = JSON.stringify(GFG_Object); } </script> </body> </html>
Output:
Before click on the button:
After click on the button:
Example 2: This example sorts the array of objects by f_name property.
<!DOCTYPE html> <html> <head> <title> Sort array of objects </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="demo2"> GFG_Object = [ <br> { "f_name": "Geeks", "l_name": "_1" }, <br><br> { "f_name": "for", "l_name": "_2" }, <br><br> { "f_name": "GFG", "l_name": "_3" } <br>]; </p> <button onClick="fun()"> sort </button> <p id="GFG"></p> <script> function fun() { function compare(a, b) { if (a.f_name < b.f_name) return -1; if (a.f_name > b.f_name) return 1; return 0; } var GFG_Object = [ { f_name: 'Geeks', l_name: '_2' }, { f_name: 'for', l_name: '_1' }, { f_name: 'GFG', l_name: '_3' } ]; GFG_Object.sort(compare); document.getElementById("GFG").innerHTML = JSON.stringify(GFG_Object); } </script> </body> </html>
Output:
Before click on the button:
After click on the button:
javascript-object
javascript-string
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 25956,
"s": 25681,
"text": "The array of objects can be sort by using user defined function. This function compares the array of objects by its property. For example, the first example compares the l_name of objects and if l_name is small then it place into left otherwise place it into right position."
},
{
"code": null,
"e": 26027,
"s": 25956,
"text": "Example 1: This example sorts the array of objects by l_name property."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Sort array of objects </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"demo2\">GFG_Object = [ <br> { \"f_name\": \"Geeks\", \"l_name\": \"_1\" }, <br><br> { \"f_name\": \"for\", \"l_name\": \"_2\" }, <br><br> { \"f_name\": \"GFG\", \"l_name\": \"_3\" } <br>]; </p> <button onClick=\"fun()\"> sort </button> <p id=\"GFG\"></p> <!-- Script to compare the object and sort its content --> <script> function fun() { function compare(a, b) { if (a.l_name < b.l_name) return -1; if (a.l_name > b.l_name) return 1; return 0; } var GFG_Object = [ { f_name: 'Geeks', l_name: '_2' }, { f_name: 'for', l_name: '_1' }, { f_name: 'GFG', l_name: '_3' } ]; GFG_Object.sort(compare); document.getElementById(\"GFG\").innerHTML = JSON.stringify(GFG_Object); } </script> </body> </html> ",
"e": 27301,
"s": 26027,
"text": null
},
{
"code": null,
"e": 27309,
"s": 27301,
"text": "Output:"
},
{
"code": null,
"e": 27337,
"s": 27309,
"text": "Before click on the button:"
},
{
"code": null,
"e": 27364,
"s": 27337,
"text": "After click on the button:"
},
{
"code": null,
"e": 27435,
"s": 27364,
"text": "Example 2: This example sorts the array of objects by f_name property."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Sort array of objects </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"demo2\"> GFG_Object = [ <br> { \"f_name\": \"Geeks\", \"l_name\": \"_1\" }, <br><br> { \"f_name\": \"for\", \"l_name\": \"_2\" }, <br><br> { \"f_name\": \"GFG\", \"l_name\": \"_3\" } <br>]; </p> <button onClick=\"fun()\"> sort </button> <p id=\"GFG\"></p> <script> function fun() { function compare(a, b) { if (a.f_name < b.f_name) return -1; if (a.f_name > b.f_name) return 1; return 0; } var GFG_Object = [ { f_name: 'Geeks', l_name: '_2' }, { f_name: 'for', l_name: '_1' }, { f_name: 'GFG', l_name: '_3' } ]; GFG_Object.sort(compare); document.getElementById(\"GFG\").innerHTML = JSON.stringify(GFG_Object); } </script> </body> </html> ",
"e": 28631,
"s": 27435,
"text": null
},
{
"code": null,
"e": 28639,
"s": 28631,
"text": "Output:"
},
{
"code": null,
"e": 28667,
"s": 28639,
"text": "Before click on the button:"
},
{
"code": null,
"e": 28694,
"s": 28667,
"text": "After click on the button:"
},
{
"code": null,
"e": 28712,
"s": 28694,
"text": "javascript-object"
},
{
"code": null,
"e": 28730,
"s": 28712,
"text": "javascript-string"
},
{
"code": null,
"e": 28741,
"s": 28730,
"text": "JavaScript"
},
{
"code": null,
"e": 28758,
"s": 28741,
"text": "Web Technologies"
},
{
"code": null,
"e": 28785,
"s": 28758,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28883,
"s": 28785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28923,
"s": 28883,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28968,
"s": 28923,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29029,
"s": 28968,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29101,
"s": 29029,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29153,
"s": 29101,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29193,
"s": 29153,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29226,
"s": 29193,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29271,
"s": 29226,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29314,
"s": 29271,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Static data members in C++ - GeeksforGeeks | 05 Dec, 2021
Static data members are class members that are declared using static keywords. A static member has certain special characteristics. These are:
Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
It is initialized before any object of this class is being created, even before main starts.
It is visible only within the class, but its lifetime is the entire program
Syntax
static data_type data_member_name;
C++
#include <iostream>using namespace std; class A{public: A() { cout << "A's Constructor Called " << endl; }}; class B{ static A a;public: B() { cout << "B's Constructor Called " << endl; }}; int main(){ B b; return 0;}
Output:
B's Constructor Called
The above program calls only Bβs constructor, it doesnβt call Aβs constructor. The reason for this is simple, static members are only declared in a class declaration, not defined. They must be explicitly defined outside the class using the scope resolution operator. If we try to access static member βaβ without an explicit definition of it, we will get a compilation error. For example, the following program fails in the compilation.
C++
#include <iostream>using namespace std; class A{ int x;public: A() { cout << "A's constructor called " << endl; }}; class B{ static A a;public: B() { cout << "B's constructor called " << endl; } static A getA() { return a; }}; int main(){ B b; A a = b.getA(); return 0;}
Output:
Compiler Error: undefined reference to `B::a'
If we add the definition of a the program will work fine and will call Aβs constructor. See the following program.
C++
#include <iostream>using namespace std; class A{ int x;public: A() { cout << "A's constructor called " << endl; }}; class B{ static A a;public: B() { cout << "B's constructor called " << endl; } static A getA() { return a; }}; A B::a; // definition of a int main(){ B b1, b2, b3; A a = b1.getA(); return 0;}
Output:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
Note that the above program calls Bβs constructor 3 times for 3 objects (b1, b2, and b3), but calls Aβs constructor only once. The reason is, static members are shared among all objects. That is why they are also known as class members or class fields. Also, static members can be accessed without any object, see the below program where static member βaβ is accessed without any object.
C++
#include <iostream>using namespace std; class A{ int x;public: A() { cout << "A's constructor called " << endl; }}; class B{ static A a;public: B() { cout << "B's constructor called " << endl; } static A getA() { return a; }}; A B::a; // definition of a int main(){ // static member 'a' is accessed without any object of B A a = B::getA(); return 0;}
Output:
A's constructor called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
pksangra
sidhijain
abhaysasidharan
23603vaibhav2021
msahana
Static Keyword
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
std::string class in C++
fork() in C
Different methods to reverse a string in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25553,
"s": 25525,
"text": "\n05 Dec, 2021"
},
{
"code": null,
"e": 25696,
"s": 25553,
"text": "Static data members are class members that are declared using static keywords. A static member has certain special characteristics. These are:"
},
{
"code": null,
"e": 25845,
"s": 25696,
"text": "Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created."
},
{
"code": null,
"e": 25938,
"s": 25845,
"text": "It is initialized before any object of this class is being created, even before main starts."
},
{
"code": null,
"e": 26014,
"s": 25938,
"text": "It is visible only within the class, but its lifetime is the entire program"
},
{
"code": null,
"e": 26021,
"s": 26014,
"text": "Syntax"
},
{
"code": null,
"e": 26056,
"s": 26021,
"text": "static data_type data_member_name;"
},
{
"code": null,
"e": 26060,
"s": 26056,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A{public: A() { cout << \"A's Constructor Called \" << endl; }}; class B{ static A a;public: B() { cout << \"B's Constructor Called \" << endl; }}; int main(){ B b; return 0;}",
"e": 26294,
"s": 26060,
"text": null
},
{
"code": null,
"e": 26303,
"s": 26294,
"text": "Output: "
},
{
"code": null,
"e": 26326,
"s": 26303,
"text": "B's Constructor Called"
},
{
"code": null,
"e": 26763,
"s": 26326,
"text": "The above program calls only Bβs constructor, it doesnβt call Aβs constructor. The reason for this is simple, static members are only declared in a class declaration, not defined. They must be explicitly defined outside the class using the scope resolution operator. If we try to access static member βaβ without an explicit definition of it, we will get a compilation error. For example, the following program fails in the compilation."
},
{
"code": null,
"e": 26767,
"s": 26763,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A{ int x;public: A() { cout << \"A's constructor called \" << endl; }}; class B{ static A a;public: B() { cout << \"B's constructor called \" << endl; } static A getA() { return a; }}; int main(){ B b; A a = b.getA(); return 0;}",
"e": 27063,
"s": 26767,
"text": null
},
{
"code": null,
"e": 27072,
"s": 27063,
"text": "Output: "
},
{
"code": null,
"e": 27119,
"s": 27072,
"text": "Compiler Error: undefined reference to `B::a' "
},
{
"code": null,
"e": 27234,
"s": 27119,
"text": "If we add the definition of a the program will work fine and will call Aβs constructor. See the following program."
},
{
"code": null,
"e": 27238,
"s": 27234,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A{ int x;public: A() { cout << \"A's constructor called \" << endl; }}; class B{ static A a;public: B() { cout << \"B's constructor called \" << endl; } static A getA() { return a; }}; A B::a; // definition of a int main(){ B b1, b2, b3; A a = b1.getA(); return 0;}",
"e": 27573,
"s": 27238,
"text": null
},
{
"code": null,
"e": 27582,
"s": 27573,
"text": "Output: "
},
{
"code": null,
"e": 27674,
"s": 27582,
"text": "A's constructor called\nB's constructor called\nB's constructor called\nB's constructor called"
},
{
"code": null,
"e": 28062,
"s": 27674,
"text": "Note that the above program calls Bβs constructor 3 times for 3 objects (b1, b2, and b3), but calls Aβs constructor only once. The reason is, static members are shared among all objects. That is why they are also known as class members or class fields. Also, static members can be accessed without any object, see the below program where static member βaβ is accessed without any object."
},
{
"code": null,
"e": 28066,
"s": 28062,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A{ int x;public: A() { cout << \"A's constructor called \" << endl; }}; class B{ static A a;public: B() { cout << \"B's constructor called \" << endl; } static A getA() { return a; }}; A B::a; // definition of a int main(){ // static member 'a' is accessed without any object of B A a = B::getA(); return 0;}",
"e": 28444,
"s": 28066,
"text": null
},
{
"code": null,
"e": 28453,
"s": 28444,
"text": "Output: "
},
{
"code": null,
"e": 28476,
"s": 28453,
"text": "A's constructor called"
},
{
"code": null,
"e": 28601,
"s": 28476,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 28610,
"s": 28601,
"text": "pksangra"
},
{
"code": null,
"e": 28620,
"s": 28610,
"text": "sidhijain"
},
{
"code": null,
"e": 28636,
"s": 28620,
"text": "abhaysasidharan"
},
{
"code": null,
"e": 28653,
"s": 28636,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 28661,
"s": 28653,
"text": "msahana"
},
{
"code": null,
"e": 28676,
"s": 28661,
"text": "Static Keyword"
},
{
"code": null,
"e": 28687,
"s": 28676,
"text": "C Language"
},
{
"code": null,
"e": 28691,
"s": 28687,
"text": "C++"
},
{
"code": null,
"e": 28695,
"s": 28691,
"text": "CPP"
},
{
"code": null,
"e": 28793,
"s": 28695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28810,
"s": 28793,
"text": "Substring in C++"
},
{
"code": null,
"e": 28832,
"s": 28810,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 28857,
"s": 28832,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28869,
"s": 28857,
"text": "fork() in C"
},
{
"code": null,
"e": 28916,
"s": 28869,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 28934,
"s": 28916,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28980,
"s": 28934,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28999,
"s": 28980,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29042,
"s": 28999,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Python - List Words Frequency in String - GeeksforGeeks | 08 Jun, 2021
Given a List of Words, Map frequency of each to occurrence in String.
Input : test_str = βgeeksforgeeks is best for geeks and best for CSβ, count_list = [βbestβ, βgeeksforgeeksβ, βcomputerβ] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input : test_str = βgeeksforgeeks is best for geeks and best for CSβ, count_list = [βbetterβ, βgfgβ, βcomputerβ] Output : [0, 0, 0] Explanation : No word from list present in string.
Method #1 : Using defaultdict() + loop + list comprehension
In this, we compute words frequency using loop + defaultdict() and then use list comprehension to get all the counts corresponding to list of words.
Python3
# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import defaultdict # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequencyres = defaultdict(int)for sub in test_str.split(): res[sub] += 1 # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint("The list words frequency : " + str(res))
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]
Method #2 : Using Counter() + list comprehension
In this, Counter() is used to perform task of computing frequency, post that, list comprehension is used to assign frequency to list words.
Python3
# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import Counter # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequency using Counter()res = Counter(test_str.split()) # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint("The list words frequency : " + str(res))
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]
simranarora5sos
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 25607,
"s": 25537,
"text": "Given a List of Words, Map frequency of each to occurrence in String."
},
{
"code": null,
"e": 26017,
"s": 25607,
"text": "Input : test_str = βgeeksforgeeks is best for geeks and best for CSβ, count_list = [βbestβ, βgeeksforgeeksβ, βcomputerβ] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input : test_str = βgeeksforgeeks is best for geeks and best for CSβ, count_list = [βbetterβ, βgfgβ, βcomputerβ] Output : [0, 0, 0] Explanation : No word from list present in string. "
},
{
"code": null,
"e": 26077,
"s": 26017,
"text": "Method #1 : Using defaultdict() + loop + list comprehension"
},
{
"code": null,
"e": 26226,
"s": 26077,
"text": "In this, we compute words frequency using loop + defaultdict() and then use list comprehension to get all the counts corresponding to list of words."
},
{
"code": null,
"e": 26234,
"s": 26226,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import defaultdict # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequencyres = defaultdict(int)for sub in test_str.split(): res[sub] += 1 # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint(\"The list words frequency : \" + str(res))",
"e": 26853,
"s": 26234,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26853,
"text": "The original string is : geeksforgeeks is best for geeks and best for CS\nThe list words frequency : [2, 1, 0, 0, 2, 1]"
},
{
"code": null,
"e": 27021,
"s": 26972,
"text": "Method #2 : Using Counter() + list comprehension"
},
{
"code": null,
"e": 27161,
"s": 27021,
"text": "In this, Counter() is used to perform task of computing frequency, post that, list comprehension is used to assign frequency to list words."
},
{
"code": null,
"e": 27169,
"s": 27161,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Divide String into Equal K chunks# Using list comprehensionfrom collections import Counter # initializing stringstest_str = 'geeksforgeeks is best for geeks and best for CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing count_listcount_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and'] # computing frequency using Counter()res = Counter(test_str.split()) # assigning to list wordsres = [res[sub] for sub in count_list] # printing resultprint(\"The list words frequency : \" + str(res))",
"e": 27764,
"s": 27169,
"text": null
},
{
"code": null,
"e": 27883,
"s": 27764,
"text": "The original string is : geeksforgeeks is best for geeks and best for CS\nThe list words frequency : [2, 1, 0, 0, 2, 1]"
},
{
"code": null,
"e": 27899,
"s": 27883,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27922,
"s": 27899,
"text": "Python string-programs"
},
{
"code": null,
"e": 27929,
"s": 27922,
"text": "Python"
},
{
"code": null,
"e": 27945,
"s": 27929,
"text": "Python Programs"
},
{
"code": null,
"e": 28043,
"s": 27945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28075,
"s": 28043,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28117,
"s": 28075,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28159,
"s": 28117,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28186,
"s": 28159,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28242,
"s": 28186,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28264,
"s": 28242,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28303,
"s": 28264,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28349,
"s": 28303,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28387,
"s": 28349,
"text": "Python | Convert a list to dictionary"
}
] |
HTTP headers | Alt-Svc - GeeksforGeeks | 10 May, 2020
The HTTP headers Alt-Svc header is a response-type header it has been used to advertise alternative service. Which services can be defined by a protocol/host/port combination.
Syntax:
Alt-Svc: clear
Alt-Svc: <protocol-id>=<alt-authority>; ma=<max-age>; persist=1
Directives: This header accept five directives as mentioned above and described below:
clear: This directive define that all alternative services for that origin to be invalidated.
<protocol-id>: This directive is the ALPN protocol identifier.
<alt-authority>: This directive defines an alternative authority which consists of an optional host override, a colon, and a mandatory port number.
ma=<max-age>: It holds the number that defines seconds for which the alternative service is considered fresh if it is omitted then the default value will be 86400. It is an optional directive.
persist=1: This directive holds the alternative service which cleared on network configuration changes. Use of the persist=1 ensures that the entry is not deleted through such changes.
Example:
Alt-Svc: h2=":425"; ma=2585900; persist=1
Alt-Svc: h2=":425"; ma=2585900; persist=1
Alt-Svc: h2=":485"; ma=592000;
Alt-Svc: h2=":485"; ma=592000;
To check this Alt-Svc in action go to Inspect Element -> Network check the request header for Alt-Svc like below, Alt-Svc is highlighted you can see.
Supported Browsers: The browsers compatible with HTTP headers Alt-Svc are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ? | [
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26345,
"s": 26169,
"text": "The HTTP headers Alt-Svc header is a response-type header it has been used to advertise alternative service. Which services can be defined by a protocol/host/port combination."
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Syntax:"
},
{
"code": null,
"e": 26368,
"s": 26353,
"text": "Alt-Svc: clear"
},
{
"code": null,
"e": 26432,
"s": 26368,
"text": "Alt-Svc: <protocol-id>=<alt-authority>; ma=<max-age>; persist=1"
},
{
"code": null,
"e": 26519,
"s": 26432,
"text": "Directives: This header accept five directives as mentioned above and described below:"
},
{
"code": null,
"e": 26613,
"s": 26519,
"text": "clear: This directive define that all alternative services for that origin to be invalidated."
},
{
"code": null,
"e": 26676,
"s": 26613,
"text": "<protocol-id>: This directive is the ALPN protocol identifier."
},
{
"code": null,
"e": 26824,
"s": 26676,
"text": "<alt-authority>: This directive defines an alternative authority which consists of an optional host override, a colon, and a mandatory port number."
},
{
"code": null,
"e": 27017,
"s": 26824,
"text": "ma=<max-age>: It holds the number that defines seconds for which the alternative service is considered fresh if it is omitted then the default value will be 86400. It is an optional directive."
},
{
"code": null,
"e": 27202,
"s": 27017,
"text": "persist=1: This directive holds the alternative service which cleared on network configuration changes. Use of the persist=1 ensures that the entry is not deleted through such changes."
},
{
"code": null,
"e": 27211,
"s": 27202,
"text": "Example:"
},
{
"code": null,
"e": 27253,
"s": 27211,
"text": "Alt-Svc: h2=\":425\"; ma=2585900; persist=1"
},
{
"code": null,
"e": 27295,
"s": 27253,
"text": "Alt-Svc: h2=\":425\"; ma=2585900; persist=1"
},
{
"code": null,
"e": 27328,
"s": 27295,
"text": "Alt-Svc: h2=\":485\"; ma=592000; \n"
},
{
"code": null,
"e": 27361,
"s": 27328,
"text": "Alt-Svc: h2=\":485\"; ma=592000; \n"
},
{
"code": null,
"e": 27512,
"s": 27361,
"text": "To check this Alt-Svc in action go to Inspect Element -> Network check the request header for Alt-Svc like below, Alt-Svc is highlighted you can see.\n"
},
{
"code": null,
"e": 27603,
"s": 27514,
"text": "Supported Browsers: The browsers compatible with HTTP headers Alt-Svc are listed below:\n"
},
{
"code": null,
"e": 27618,
"s": 27603,
"text": "Google Chrome\n"
},
{
"code": null,
"e": 27637,
"s": 27618,
"text": "Internet Explorer\n"
},
{
"code": null,
"e": 27646,
"s": 27637,
"text": "Firefox\n"
},
{
"code": null,
"e": 27654,
"s": 27646,
"text": "Safari\n"
},
{
"code": null,
"e": 27661,
"s": 27654,
"text": "Opera\n"
},
{
"code": null,
"e": 27676,
"s": 27661,
"text": "\nHTTP-headers\n"
},
{
"code": null,
"e": 27685,
"s": 27676,
"text": "\nPicked\n"
},
{
"code": null,
"e": 27704,
"s": 27685,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 27938,
"s": 27704,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n \n "
},
{
"code": null,
"e": 27978,
"s": 27938,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28023,
"s": 27978,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28066,
"s": 28023,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28127,
"s": 28066,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28200,
"s": 28127,
"text": "Differences between Functional Components and Class Components in React\n"
},
{
"code": null,
"e": 28255,
"s": 28200,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28300,
"s": 28255,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 28341,
"s": 28300,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28365,
"s": 28341,
"text": "REST API (Introduction)"
}
] |
Traverse Linked List from middle to left-right order using recursion - GeeksforGeeks | 09 Jun, 2021
Given a Linked List. The task is to traverse the Linked List from middle to left-right order using recursion.For Example:
If the given Linked List is: 2 -> 5 -> 8 -> 3 -> 7 -> 9 -> 12 -> NULL The Middle to left-right order is : 3, 8, 7, 5, 9, 2, 12
Explanation: Middle of the given linked list is β3β so, we start traversing from middle by printing 3 then left and right of 3, so we print 8, 7 then print left of 8 and right of 7, so we print 5, 9 then print left of 5 and right of 9, so we print 2, 12.Note: If number of node are even in a Linked List then print left right only. For this linked list( contains even number of nodes ) 2 -> 5 -> 8 -> 7 -> 9 -> 12 -> NULL.The output should be 8, 7, 5, 9, 2, 12.Examples:
Input: 20 -> 15 -> 23 -> 13 -> 19 -> 32 -> 16 -> 41 -> 11 -> NULL Output: 19, 13, 32, 23, 16, 15, 41, 20, 11.Input: 12 -> 25 -> 51 -> 16 -> 9 -> 90 -> 7 -> 2 -> NULL Output: 16, 9, 51, 90, 25, 7, 12, 2.
Approach: First, calculate the size of the linked list:
If size is odd: -> Then go to the (n+1)/2 -th node using recursion.
If size is even: -> Then go to the n/2 -th node using recursion.
Now print node data and return next node address, do this procedure unless function call stack empty.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// A C++ program to demonstrate// the printing of Linked List middle// to left right order #include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the end void append(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Used in step 5 Node* last = *head_ref; // Put in the data new_node->data = new_data; // This new node is going to be // the last node, so make next of // it as NULL new_node->next = NULL; // If the Linked List is empty, // then make the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // Else traverse till the last node while (last->next != NULL) last = last->next; // Change the next of last node last->next = new_node; return;} // This function prints contents of// linked list starting from head void printList(Node* node){ while (node != NULL) { cout << " " << node->data; if (node->next != NULL) cout << "->"; node = node->next; }} // Function to get the size of linked listint getSize(Node* head){ if (head == NULL) return 0; return 1 + getSize(head->next);} // Utility function to print the Linked List// from middle to left right orderNode* printMiddleToLeftRightUtil(Node* head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value cout << head->data; // Returns address of next node return head->next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value cout << head->data; cout << " , " << head->next->data; // Returns address of next to next node return head->next->next; } else { // Recursive function call and // store return address Node* ptr = printMiddleToLeftRightUtil( head->next, counter - 1, lSize); // Print head data cout << " , " << head->data; // Print ptr data cout << " , " << ptr->data; // Returns address of next node return ptr->next; }} // Function to print Middle to// Left-right ordervoid printMiddleToLeftRight(Node* head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order cout << "Output : "; printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codeint main(){ // Start with the empty list Node* head = NULL; // Insert 6. So linked list // becomes 6->NULL append(&head, 6); // Insert 6. So linked list // becomes 6->4->NULL append(&head, 4); append(&head, 8); append(&head, 7); append(&head, 9); append(&head, 11); append(&head, 2); // After inserting linked list // becomes 6->4->8->7->9->11->2->NULL cout << "Created Linked list is: "; // Function to display Linked List content printList(head); cout << endl; // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head); return 0;}
// A Java program to demonstrate// the printing of Linked List middle// to left right orderclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endstatic Node append(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Used in step 5 Node last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headstatic void printList(Node node){ while (node != null) { System.out.print( " " + node.data); if (node.next != null) System.out.print("->"); node = node.next; }} // Function to get the size of linked liststatic int getSize(Node head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderstatic Node printMiddleToLeftRightUtil(Node head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value System.out.print( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value System.out.print(head.data); System.out.print( " , " + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address Node ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data System.out.print(" , " + head.data); // Print ptr data System.out.print(" , " + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderstatic void printMiddleToLeftRight(Node head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order System.out.print("Output : "); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Insert 6. So linked list // becomes 6.null head = append(head, 6); // Insert 6. So linked list // becomes 6.4.null head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9); head = append(head, 11); head = append(head, 2); // After inserting linked list // becomes 6.4.8.7.9.11.2.null System.out.print("Created Linked list is: "); // Function to display Linked List content printList(head); System.out.println(); // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head);}} // This code is contributed by Arnab Kundu
# A Python3 program to demonstrate# the printing of Linked List middle# to left right order # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Given a reference (pointer to pointer)# to the head of a list and an int, appends# a new node at the enddef append(head_ref, new_data): # Allocate node new_node = Node(); # Used in step 5 last = head_ref; # Put in the data new_node.data = new_data; # This new node is going to be # the last node, so make next of # it as None new_node.next = None; # If the Linked List is empty, # then make the new node as head if (head_ref == None): head_ref = new_node; return head_ref; # Else traverse till the last node while (last.next != None): last = last.next; # Change the next of last node last.next = new_node; return head_ref; # This function prints contents of# linked list starting from headdef printList(node): while (node != None): print(' ' + str(node.data), end = '') if (node.next != None): print('->', end = '') node = node.next; # Function to get the size of linked listdef getSize(head): if (head == None): return 0; return 1 + getSize(head.next); # Utility function to print the Linked List# from middle to left right orderdef printMiddleToLeftRightUtil(head, counter, lSize): # Base Condition # When size of list is odd if (counter == 1 and lSize % 2 != 0): # Print node value print(head.data, end = '') # Returns address of next node return head.next; # Base Condition # When size of list is even elif (counter == 1): # Print node value # and next node value print(str(head.data) + ' , ' + str(head.next.data), end = '') # Returns address of next to next node return head.next.next; else: # Recursive function call and # store return address ptr = printMiddleToLeftRightUtil(head.next, counter - 1,lSize); # Print head data print(' , ' + str(head.data) + ' , ' + str(ptr.data), end = '') # Returns address of next node return ptr.next; # Function to print Middle to# Left-right orderdef printMiddleToLeftRight(head): # Function call to get the size # Of Linked List listSize = getSize(head); middle = 0; # Store middle when Linked # List size is odd if (listSize % 2 != 0): middle = (listSize + 1) // 2; # Store middle when Linked # List size is even else: middle = listSize // 2; # Utility function call print # Linked List from Middle # to left right order print('Output :', end = ' ') printMiddleToLeftRightUtil(head, middle, listSize); # Driver codeif __name__=='__main__': # Start with the empty list head = None; # Insert 6. So linked list # becomes 6.None head = append(head, 6); # Insert 6. So linked list # becomes 6.4.None head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9) head = append(head, 11); head = append(head, 2) # After inserting linked list # becomes 6.4.8.7.9.11.2.None print("Created Linked list is:", end = ' ') # Function to display Linked List content printList(head); print() # Function call print Linked List from # Middle to left right order printMiddleToLeftRight(head); # This code is contributed by rutvik_56
// A C# program to demonstrate// the printing of Linked List middle// to left right orderusing System; public class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endstatic Node append(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Used in step 5 Node last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headstatic void printList(Node node){ while (node != null) { Console.Write( " " + node.data); if (node.next != null) Console.Write("->"); node = node.next; }} // Function to get the size of linked liststatic int getSize(Node head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderstatic Node printMiddleToLeftRightUtil(Node head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value Console.Write( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value Console.Write(head.data); Console.Write( " , " + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address Node ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data Console.Write(" , " + head.data); // Print ptr data Console.Write(" , " + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderstatic void printMiddleToLeftRight(Node head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order Console.Write("Output : "); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Insert 6. So linked list // becomes 6.null head = append(head, 6); // Insert 6. So linked list // becomes 6.4.null head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9); head = append(head, 11); head = append(head, 2); // After inserting linked list // becomes 6.4.8.7.9.11.2.null Console.Write("Created Linked list is: "); // Function to display Linked List content printList(head); Console.WriteLine(); // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to demonstrate// the printing of Linked List middle// to left right order // Structure of a node of the linked list class Node { constructor() { this.data = 0; this.next = null; }} // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endfunction append( head_ref, new_data){ // Allocate node var new_node = new Node(); // Used in step 5 var last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headfunction printList( node){ while (node != null) { document.write( " " + node.data); if (node.next != null) document.write("->"); node = node.next; }} // Function to get the size of linked listfunction getSize( head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderfunction printMiddleToLeftRightUtil( head, counter, lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value document.write( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value document.write(head.data); document.write( " , " + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address var ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data document.write(" , " + head.data); // Print ptr data document.write(" , " + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderfunction printMiddleToLeftRight( head){ // Function call to get the size // Of Linked List let listSize = getSize(head); let middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = Math.floor((listSize + 1) / 2); } // Store middle when Linked // List size is even else { middle = Math.floor(listSize / 2); } // Utility function call print // Linked List from Middle // to left right order document.write("Output : "); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver Code // Start with the empty listvar head = null; // Insert 6. So linked list// becomes 6.nullhead = append(head, 6); // Insert 6. So linked list// becomes 6.4.nullhead = append(head, 4);head = append(head, 8);head = append(head, 7);head = append(head, 9);head = append(head, 11);head = append(head, 2); // After inserting linked list// becomes 6.4.8.7.9.11.2.nulldocument.write("Created Linked list is: "); // Function to display Linked List contentprintList(head);document.write("</br>"); // Function call print Linked List from// Middle to left right orderprintMiddleToLeftRight(head); </script>
Created Linked list is: 6-> 4-> 8-> 7-> 9-> 11-> 2
Output : 7 , 8 , 9 , 4 , 11 , 6 , 2
andrew1234
Rajput-Ji
rutvik_56
jana_sayantan
Traversal
Linked List
Recursion
Linked List
Recursion
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
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)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction | [
{
"code": null,
"e": 26203,
"s": 26175,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 26327,
"s": 26203,
"text": "Given a Linked List. The task is to traverse the Linked List from middle to left-right order using recursion.For Example: "
},
{
"code": null,
"e": 26456,
"s": 26327,
"text": "If the given Linked List is: 2 -> 5 -> 8 -> 3 -> 7 -> 9 -> 12 -> NULL The Middle to left-right order is : 3, 8, 7, 5, 9, 2, 12 "
},
{
"code": null,
"e": 26929,
"s": 26456,
"text": "Explanation: Middle of the given linked list is β3β so, we start traversing from middle by printing 3 then left and right of 3, so we print 8, 7 then print left of 8 and right of 7, so we print 5, 9 then print left of 5 and right of 9, so we print 2, 12.Note: If number of node are even in a Linked List then print left right only. For this linked list( contains even number of nodes ) 2 -> 5 -> 8 -> 7 -> 9 -> 12 -> NULL.The output should be 8, 7, 5, 9, 2, 12.Examples: "
},
{
"code": null,
"e": 27134,
"s": 26929,
"text": "Input: 20 -> 15 -> 23 -> 13 -> 19 -> 32 -> 16 -> 41 -> 11 -> NULL Output: 19, 13, 32, 23, 16, 15, 41, 20, 11.Input: 12 -> 25 -> 51 -> 16 -> 9 -> 90 -> 7 -> 2 -> NULL Output: 16, 9, 51, 90, 25, 7, 12, 2. "
},
{
"code": null,
"e": 27194,
"s": 27136,
"text": "Approach: First, calculate the size of the linked list: "
},
{
"code": null,
"e": 27262,
"s": 27194,
"text": "If size is odd: -> Then go to the (n+1)/2 -th node using recursion."
},
{
"code": null,
"e": 27328,
"s": 27262,
"text": "If size is even: -> Then go to the n/2 -th node using recursion. "
},
{
"code": null,
"e": 27430,
"s": 27328,
"text": "Now print node data and return next node address, do this procedure unless function call stack empty."
},
{
"code": null,
"e": 27483,
"s": 27430,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27487,
"s": 27483,
"text": "C++"
},
{
"code": null,
"e": 27492,
"s": 27487,
"text": "Java"
},
{
"code": null,
"e": 27500,
"s": 27492,
"text": "Python3"
},
{
"code": null,
"e": 27503,
"s": 27500,
"text": "C#"
},
{
"code": null,
"e": 27514,
"s": 27503,
"text": "Javascript"
},
{
"code": "// A C++ program to demonstrate// the printing of Linked List middle// to left right order #include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the end void append(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Used in step 5 Node* last = *head_ref; // Put in the data new_node->data = new_data; // This new node is going to be // the last node, so make next of // it as NULL new_node->next = NULL; // If the Linked List is empty, // then make the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // Else traverse till the last node while (last->next != NULL) last = last->next; // Change the next of last node last->next = new_node; return;} // This function prints contents of// linked list starting from head void printList(Node* node){ while (node != NULL) { cout << \" \" << node->data; if (node->next != NULL) cout << \"->\"; node = node->next; }} // Function to get the size of linked listint getSize(Node* head){ if (head == NULL) return 0; return 1 + getSize(head->next);} // Utility function to print the Linked List// from middle to left right orderNode* printMiddleToLeftRightUtil(Node* head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value cout << head->data; // Returns address of next node return head->next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value cout << head->data; cout << \" , \" << head->next->data; // Returns address of next to next node return head->next->next; } else { // Recursive function call and // store return address Node* ptr = printMiddleToLeftRightUtil( head->next, counter - 1, lSize); // Print head data cout << \" , \" << head->data; // Print ptr data cout << \" , \" << ptr->data; // Returns address of next node return ptr->next; }} // Function to print Middle to// Left-right ordervoid printMiddleToLeftRight(Node* head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order cout << \"Output : \"; printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codeint main(){ // Start with the empty list Node* head = NULL; // Insert 6. So linked list // becomes 6->NULL append(&head, 6); // Insert 6. So linked list // becomes 6->4->NULL append(&head, 4); append(&head, 8); append(&head, 7); append(&head, 9); append(&head, 11); append(&head, 2); // After inserting linked list // becomes 6->4->8->7->9->11->2->NULL cout << \"Created Linked list is: \"; // Function to display Linked List content printList(head); cout << endl; // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head); return 0;}",
"e": 31253,
"s": 27514,
"text": null
},
{
"code": "// A Java program to demonstrate// the printing of Linked List middle// to left right orderclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endstatic Node append(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Used in step 5 Node last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headstatic void printList(Node node){ while (node != null) { System.out.print( \" \" + node.data); if (node.next != null) System.out.print(\"->\"); node = node.next; }} // Function to get the size of linked liststatic int getSize(Node head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderstatic Node printMiddleToLeftRightUtil(Node head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value System.out.print( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value System.out.print(head.data); System.out.print( \" , \" + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address Node ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data System.out.print(\" , \" + head.data); // Print ptr data System.out.print(\" , \" + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderstatic void printMiddleToLeftRight(Node head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order System.out.print(\"Output : \"); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Insert 6. So linked list // becomes 6.null head = append(head, 6); // Insert 6. So linked list // becomes 6.4.null head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9); head = append(head, 11); head = append(head, 2); // After inserting linked list // becomes 6.4.8.7.9.11.2.null System.out.print(\"Created Linked list is: \"); // Function to display Linked List content printList(head); System.out.println(); // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head);}} // This code is contributed by Arnab Kundu",
"e": 35115,
"s": 31253,
"text": null
},
{
"code": "# A Python3 program to demonstrate# the printing of Linked List middle# to left right order # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Given a reference (pointer to pointer)# to the head of a list and an int, appends# a new node at the enddef append(head_ref, new_data): # Allocate node new_node = Node(); # Used in step 5 last = head_ref; # Put in the data new_node.data = new_data; # This new node is going to be # the last node, so make next of # it as None new_node.next = None; # If the Linked List is empty, # then make the new node as head if (head_ref == None): head_ref = new_node; return head_ref; # Else traverse till the last node while (last.next != None): last = last.next; # Change the next of last node last.next = new_node; return head_ref; # This function prints contents of# linked list starting from headdef printList(node): while (node != None): print(' ' + str(node.data), end = '') if (node.next != None): print('->', end = '') node = node.next; # Function to get the size of linked listdef getSize(head): if (head == None): return 0; return 1 + getSize(head.next); # Utility function to print the Linked List# from middle to left right orderdef printMiddleToLeftRightUtil(head, counter, lSize): # Base Condition # When size of list is odd if (counter == 1 and lSize % 2 != 0): # Print node value print(head.data, end = '') # Returns address of next node return head.next; # Base Condition # When size of list is even elif (counter == 1): # Print node value # and next node value print(str(head.data) + ' , ' + str(head.next.data), end = '') # Returns address of next to next node return head.next.next; else: # Recursive function call and # store return address ptr = printMiddleToLeftRightUtil(head.next, counter - 1,lSize); # Print head data print(' , ' + str(head.data) + ' , ' + str(ptr.data), end = '') # Returns address of next node return ptr.next; # Function to print Middle to# Left-right orderdef printMiddleToLeftRight(head): # Function call to get the size # Of Linked List listSize = getSize(head); middle = 0; # Store middle when Linked # List size is odd if (listSize % 2 != 0): middle = (listSize + 1) // 2; # Store middle when Linked # List size is even else: middle = listSize // 2; # Utility function call print # Linked List from Middle # to left right order print('Output :', end = ' ') printMiddleToLeftRightUtil(head, middle, listSize); # Driver codeif __name__=='__main__': # Start with the empty list head = None; # Insert 6. So linked list # becomes 6.None head = append(head, 6); # Insert 6. So linked list # becomes 6.4.None head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9) head = append(head, 11); head = append(head, 2) # After inserting linked list # becomes 6.4.8.7.9.11.2.None print(\"Created Linked list is:\", end = ' ') # Function to display Linked List content printList(head); print() # Function call print Linked List from # Middle to left right order printMiddleToLeftRight(head); # This code is contributed by rutvik_56",
"e": 38707,
"s": 35115,
"text": null
},
{
"code": "// A C# program to demonstrate// the printing of Linked List middle// to left right orderusing System; public class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endstatic Node append(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Used in step 5 Node last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headstatic void printList(Node node){ while (node != null) { Console.Write( \" \" + node.data); if (node.next != null) Console.Write(\"->\"); node = node.next; }} // Function to get the size of linked liststatic int getSize(Node head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderstatic Node printMiddleToLeftRightUtil(Node head, int counter, int lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value Console.Write( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value Console.Write(head.data); Console.Write( \" , \" + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address Node ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data Console.Write(\" , \" + head.data); // Print ptr data Console.Write(\" , \" + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderstatic void printMiddleToLeftRight(Node head){ // Function call to get the size // Of Linked List int listSize = getSize(head); int middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = (listSize + 1) / 2; } // Store middle when Linked // List size is even else { middle = listSize / 2; } // Utility function call print // Linked List from Middle // to left right order Console.Write(\"Output : \"); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Insert 6. So linked list // becomes 6.null head = append(head, 6); // Insert 6. So linked list // becomes 6.4.null head = append(head, 4); head = append(head, 8); head = append(head, 7); head = append(head, 9); head = append(head, 11); head = append(head, 2); // After inserting linked list // becomes 6.4.8.7.9.11.2.null Console.Write(\"Created Linked list is: \"); // Function to display Linked List content printList(head); Console.WriteLine(); // Function call print Linked List from // Middle to left right order printMiddleToLeftRight(head);}} // This code is contributed by Rajput-Ji",
"e": 42605,
"s": 38707,
"text": null
},
{
"code": "<script> // JavaScript program to demonstrate// the printing of Linked List middle// to left right order // Structure of a node of the linked list class Node { constructor() { this.data = 0; this.next = null; }} // Given a reference (pointer to pointer)// to the head of a list and an int, appends// a new node at the endfunction append( head_ref, new_data){ // Allocate node var new_node = new Node(); // Used in step 5 var last = head_ref; // Put in the data new_node.data = new_data; // This new node is going to be // the last node, so make next of // it as null new_node.next = null; // If the Linked List is empty, // then make the new node as head if (head_ref == null) { head_ref = new_node; return head_ref; } // Else traverse till the last node while (last.next != null) last = last.next; // Change the next of last node last.next = new_node; return head_ref;} // This function prints contents of// linked list starting from headfunction printList( node){ while (node != null) { document.write( \" \" + node.data); if (node.next != null) document.write(\"->\"); node = node.next; }} // Function to get the size of linked listfunction getSize( head){ if (head == null) return 0; return 1 + getSize(head.next);} // Utility function to print the Linked List// from middle to left right orderfunction printMiddleToLeftRightUtil( head, counter, lSize){ // Base Condition // When size of list is odd if (counter == 1 && lSize % 2 != 0) { // Print node value document.write( head.data); // Returns address of next node return head.next; } // Base Condition // When size of list is even else if (counter == 1) { // Print node value // and next node value document.write(head.data); document.write( \" , \" + head.next.data); // Returns address of next to next node return head.next.next; } else { // Recursive function call and // store return address var ptr = printMiddleToLeftRightUtil(head.next, counter - 1, lSize); // Print head data document.write(\" , \" + head.data); // Print ptr data document.write(\" , \" + ptr.data); // Returns address of next node return ptr.next; }} // Function to print Middle to// Left-right orderfunction printMiddleToLeftRight( head){ // Function call to get the size // Of Linked List let listSize = getSize(head); let middle = 0; // Store middle when Linked // List size is odd if (listSize % 2 != 0) { middle = Math.floor((listSize + 1) / 2); } // Store middle when Linked // List size is even else { middle = Math.floor(listSize / 2); } // Utility function call print // Linked List from Middle // to left right order document.write(\"Output : \"); printMiddleToLeftRightUtil(head, middle, listSize);} // Driver Code // Start with the empty listvar head = null; // Insert 6. So linked list// becomes 6.nullhead = append(head, 6); // Insert 6. So linked list// becomes 6.4.nullhead = append(head, 4);head = append(head, 8);head = append(head, 7);head = append(head, 9);head = append(head, 11);head = append(head, 2); // After inserting linked list// becomes 6.4.8.7.9.11.2.nulldocument.write(\"Created Linked list is: \"); // Function to display Linked List contentprintList(head);document.write(\"</br>\"); // Function call print Linked List from// Middle to left right orderprintMiddleToLeftRight(head); </script>",
"e": 46318,
"s": 42605,
"text": null
},
{
"code": null,
"e": 46406,
"s": 46318,
"text": "Created Linked list is: 6-> 4-> 8-> 7-> 9-> 11-> 2\nOutput : 7 , 8 , 9 , 4 , 11 , 6 , 2"
},
{
"code": null,
"e": 46419,
"s": 46408,
"text": "andrew1234"
},
{
"code": null,
"e": 46429,
"s": 46419,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 46439,
"s": 46429,
"text": "rutvik_56"
},
{
"code": null,
"e": 46453,
"s": 46439,
"text": "jana_sayantan"
},
{
"code": null,
"e": 46463,
"s": 46453,
"text": "Traversal"
},
{
"code": null,
"e": 46475,
"s": 46463,
"text": "Linked List"
},
{
"code": null,
"e": 46485,
"s": 46475,
"text": "Recursion"
},
{
"code": null,
"e": 46497,
"s": 46485,
"text": "Linked List"
},
{
"code": null,
"e": 46507,
"s": 46497,
"text": "Recursion"
},
{
"code": null,
"e": 46517,
"s": 46507,
"text": "Traversal"
},
{
"code": null,
"e": 46615,
"s": 46517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46656,
"s": 46615,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 46706,
"s": 46656,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 46765,
"s": 46706,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 46805,
"s": 46765,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 46876,
"s": 46805,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 46936,
"s": 46876,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 47021,
"s": 46936,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 47031,
"s": 47021,
"text": "Recursion"
},
{
"code": null,
"e": 47058,
"s": 47031,
"text": "Program for Tower of Hanoi"
}
] |
Introduction to Chempy in Python - GeeksforGeeks | 19 Aug, 2021
ChemPy is a python package designed mainly to solve problems in analytical, physical and inorganic Chemistry. It is a free, open-source Python toolkit for chemistry, chemical engineering, and materials science applications.
ChemPy includes classes for representing substances, reactions, and systems of reactions. It also includes well-established formulae from physical chemistry, as well as analytic solutions to some differential equations commonly encountered in chemical kinetics.
Its intended audience is primarily researchers and engineers who need to perform modeling work. But since the intermediate representations of, e.g., ODE systems and systems of non-linear equations are available symbolically, ChemPy may also be used in an educational setting.
Installation: ChemPy can be installed by running the following script in the Command Prompt / Terminal:
pip install chempy
Here are some examples of the application of the ChemPy module : Example 1 : Printing a list of elements with their mass.
Python3
# importing the modulefrom chempy.util import periodic # number of elements to be fetchedn = 10 # displaying the informationprint("Atomic No.\tName\t\tSymbol\t\tMass") # fetching the information for# the first 10 elementsfor i in range(1, n + 1): # displaying the atomic number print(i, end = "\t\t") # displaying the name if len(periodic.names[i]) > 7: print(periodic.names[i], end = "\t") else: print(periodic.names[i], end = "\t\t") # displaying the symbol print(periodic.symbols[i], end = "\t\t") # displaying the mass print(periodic.relative_atomic_masses[i])
Output :
Atomic No. Name Symbol Mass
1 Helium He 4.002602
2 Lithium Li 6.94
3 Beryllium Be 9.0121831
4 Boron B 10.81
5 Carbon C 12.011
6 Nitrogen N 14.007
7 Oxygen O 15.999
8 Fluorine F 18.998403163
9 Neon Ne 20.1797
10 Sodium Na 22.98976928
Example 2 : Let us see how to represent chemical reactions in ChemPy. Consider the formation of water. In the reaction, 2 H2 molecules combine with an O2 molecule to form 2 H2 molecules. In ChemPy the reaction will be created using the Reaction() function of the chempy.chemistry module.
Python3
# importing the modulefrom chempy import chemistry # creating the reactionreaction = chemistry.Reaction({'H2': 2, 'O2': 1}, {'H2O': 2}) # displaying the reactionprint(reaction) # displaying the reaction orderprint(reaction.order())
Output :
2 H2 + O2 -> 2 H2O
3
gulshankumarar231
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25620,
"s": 25592,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 25844,
"s": 25620,
"text": "ChemPy is a python package designed mainly to solve problems in analytical, physical and inorganic Chemistry. It is a free, open-source Python toolkit for chemistry, chemical engineering, and materials science applications."
},
{
"code": null,
"e": 26106,
"s": 25844,
"text": "ChemPy includes classes for representing substances, reactions, and systems of reactions. It also includes well-established formulae from physical chemistry, as well as analytic solutions to some differential equations commonly encountered in chemical kinetics."
},
{
"code": null,
"e": 26382,
"s": 26106,
"text": "Its intended audience is primarily researchers and engineers who need to perform modeling work. But since the intermediate representations of, e.g., ODE systems and systems of non-linear equations are available symbolically, ChemPy may also be used in an educational setting."
},
{
"code": null,
"e": 26486,
"s": 26382,
"text": "Installation: ChemPy can be installed by running the following script in the Command Prompt / Terminal:"
},
{
"code": null,
"e": 26505,
"s": 26486,
"text": "pip install chempy"
},
{
"code": null,
"e": 26629,
"s": 26505,
"text": "Here are some examples of the application of the ChemPy module : Example 1 : Printing a list of elements with their mass. "
},
{
"code": null,
"e": 26637,
"s": 26629,
"text": "Python3"
},
{
"code": "# importing the modulefrom chempy.util import periodic # number of elements to be fetchedn = 10 # displaying the informationprint(\"Atomic No.\\tName\\t\\tSymbol\\t\\tMass\") # fetching the information for# the first 10 elementsfor i in range(1, n + 1): # displaying the atomic number print(i, end = \"\\t\\t\") # displaying the name if len(periodic.names[i]) > 7: print(periodic.names[i], end = \"\\t\") else: print(periodic.names[i], end = \"\\t\\t\") # displaying the symbol print(periodic.symbols[i], end = \"\\t\\t\") # displaying the mass print(periodic.relative_atomic_masses[i])",
"e": 27247,
"s": 26637,
"text": null
},
{
"code": null,
"e": 27258,
"s": 27247,
"text": "Output : "
},
{
"code": null,
"e": 27706,
"s": 27258,
"text": "Atomic No. Name Symbol Mass\n1 Helium He 4.002602\n2 Lithium Li 6.94\n3 Beryllium Be 9.0121831\n4 Boron B 10.81\n5 Carbon C 12.011\n6 Nitrogen N 14.007\n7 Oxygen O 15.999\n8 Fluorine F 18.998403163\n9 Neon Ne 20.1797\n10 Sodium Na 22.98976928"
},
{
"code": null,
"e": 27995,
"s": 27706,
"text": "Example 2 : Let us see how to represent chemical reactions in ChemPy. Consider the formation of water. In the reaction, 2 H2 molecules combine with an O2 molecule to form 2 H2 molecules. In ChemPy the reaction will be created using the Reaction() function of the chempy.chemistry module. "
},
{
"code": null,
"e": 28003,
"s": 27995,
"text": "Python3"
},
{
"code": "# importing the modulefrom chempy import chemistry # creating the reactionreaction = chemistry.Reaction({'H2': 2, 'O2': 1}, {'H2O': 2}) # displaying the reactionprint(reaction) # displaying the reaction orderprint(reaction.order())",
"e": 28264,
"s": 28003,
"text": null
},
{
"code": null,
"e": 28275,
"s": 28264,
"text": "Output : "
},
{
"code": null,
"e": 28296,
"s": 28275,
"text": "2 H2 + O2 -> 2 H2O\n3"
},
{
"code": null,
"e": 28316,
"s": 28298,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 28331,
"s": 28316,
"text": "python-modules"
},
{
"code": null,
"e": 28338,
"s": 28331,
"text": "Python"
},
{
"code": null,
"e": 28436,
"s": 28338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28454,
"s": 28436,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28489,
"s": 28454,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28521,
"s": 28489,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28543,
"s": 28521,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28585,
"s": 28543,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28615,
"s": 28585,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28641,
"s": 28615,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28670,
"s": 28641,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28714,
"s": 28670,
"text": "Reading and Writing to text files in Python"
}
] |
Set the rightmost off bit - GeeksforGeeks | 05 Nov, 2021
Write a program that sets the rightmost 0 bit of an integer. Examples :
Input: 12 (00...01100)
Output: 13 (00...01101)
Input: 7 (00...00111)
Output: 15 (00...01111)
If we add 1 to a number, all set bits after rightmost unset (or zero bit) become 0 and the rightmost unset bit becomes 1.
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to set the rightmost unset bit#include<iostream>using namespace std; int setRightmostUnsetBit(int n){ // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } // Driver program to test aboveint main(){ int n = 21; cout << setRightmostUnsetBit(n); return 0;}
//Java program to set the rightmost unset bit public class GFG { static int setRightmostUnsetBit(int n) { // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } //Driver program to test above public static void main(String[] args) { int n = 21; System.out.println(setRightmostUnsetBit(n)); } }
# Python3 program to set the# rightmost unset bit def setRightmostUnsetBit(n) : # If all bits are set if n & (n + 1) == 0 : return n # Set rightmost 0 bit return n | (n+1) # Driver code if __name__ == "__main__" : n = 21 print(setRightmostUnsetBit(n)) # This code is contributed# by ANKITRAI1
// C# program to set the rightmost unset bit using System; public class GFG { static int setRightmostUnsetBit(int n) { // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } //Driver program to test above public static void Main() { int n = 21; Console.WriteLine(setRightmostUnsetBit(n)); } }
<?php// PHP program to set the// rightmost unset bitfunction setRightmostUnsetBit($n){ // If all bits are set if (($n & ($n + 1)) == 0) return $n; // Set rightmost 0 bit return $n | ($n + 1);} // Driver Code$n = 21;echo setRightmostUnsetBit($n); // This code is contributed// by Shivi_Aggarwal?>
<script>// JavaScript program to set the rightmost unset bitfunction setRightmostUnsetBit(n){ // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n + 1); } // Driver program to test above let n = 21; document.write(setRightmostUnsetBit(n)); // This code is contributed by Manoj.</script>
23
Time Complexity: O(1)
Auxiliary Space: O(1)
ankthon
ukasp
Shivi_Aggarwal
tufan_gupta2000
Shubham__Ranjan
mank1083
rohan07
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
How to turn off a particular bit in a number?
Extract 'k' bits from a given position in a number.
Swap two nibbles in a byte
Reverse actual bits of the given number
Write an Efficient Method to Check if a Number is Multiple of 3
Count total bits in a number
Calculate XOR from 1 to n.
Bit Tricks for Competitive Programming
Convert decimal fraction to binary number | [
{
"code": null,
"e": 26253,
"s": 26225,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 26327,
"s": 26253,
"text": "Write a program that sets the rightmost 0 bit of an integer. Examples : "
},
{
"code": null,
"e": 26423,
"s": 26327,
"text": "Input: 12 (00...01100)\nOutput: 13 (00...01101)\n\nInput: 7 (00...00111)\nOutput: 15 (00...01111)"
},
{
"code": null,
"e": 26548,
"s": 26425,
"text": "If we add 1 to a number, all set bits after rightmost unset (or zero bit) become 0 and the rightmost unset bit becomes 1. "
},
{
"code": null,
"e": 26552,
"s": 26548,
"text": "C++"
},
{
"code": null,
"e": 26557,
"s": 26552,
"text": "Java"
},
{
"code": null,
"e": 26566,
"s": 26557,
"text": "Python 3"
},
{
"code": null,
"e": 26569,
"s": 26566,
"text": "C#"
},
{
"code": null,
"e": 26573,
"s": 26569,
"text": "PHP"
},
{
"code": null,
"e": 26584,
"s": 26573,
"text": "Javascript"
},
{
"code": "// CPP program to set the rightmost unset bit#include<iostream>using namespace std; int setRightmostUnsetBit(int n){ // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } // Driver program to test aboveint main(){ int n = 21; cout << setRightmostUnsetBit(n); return 0;}",
"e": 26951,
"s": 26584,
"text": null
},
{
"code": "//Java program to set the rightmost unset bit public class GFG { static int setRightmostUnsetBit(int n) { // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } //Driver program to test above public static void main(String[] args) { int n = 21; System.out.println(setRightmostUnsetBit(n)); } }",
"e": 27374,
"s": 26951,
"text": null
},
{
"code": "# Python3 program to set the# rightmost unset bit def setRightmostUnsetBit(n) : # If all bits are set if n & (n + 1) == 0 : return n # Set rightmost 0 bit return n | (n+1) # Driver code if __name__ == \"__main__\" : n = 21 print(setRightmostUnsetBit(n)) # This code is contributed# by ANKITRAI1",
"e": 27702,
"s": 27374,
"text": null
},
{
"code": "// C# program to set the rightmost unset bit using System; public class GFG { static int setRightmostUnsetBit(int n) { // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n+1); } //Driver program to test above public static void Main() { int n = 21; Console.WriteLine(setRightmostUnsetBit(n)); } }",
"e": 28128,
"s": 27702,
"text": null
},
{
"code": "<?php// PHP program to set the// rightmost unset bitfunction setRightmostUnsetBit($n){ // If all bits are set if (($n & ($n + 1)) == 0) return $n; // Set rightmost 0 bit return $n | ($n + 1);} // Driver Code$n = 21;echo setRightmostUnsetBit($n); // This code is contributed// by Shivi_Aggarwal?>",
"e": 28460,
"s": 28128,
"text": null
},
{
"code": "<script>// JavaScript program to set the rightmost unset bitfunction setRightmostUnsetBit(n){ // If all bits are set if ((n & (n + 1)) == 0) return n; // Set rightmost 0 bit return n | (n + 1); } // Driver program to test above let n = 21; document.write(setRightmostUnsetBit(n)); // This code is contributed by Manoj.</script>",
"e": 28834,
"s": 28460,
"text": null
},
{
"code": null,
"e": 28837,
"s": 28834,
"text": "23"
},
{
"code": null,
"e": 28861,
"s": 28839,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28883,
"s": 28861,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28891,
"s": 28883,
"text": "ankthon"
},
{
"code": null,
"e": 28897,
"s": 28891,
"text": "ukasp"
},
{
"code": null,
"e": 28912,
"s": 28897,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 28928,
"s": 28912,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 28944,
"s": 28928,
"text": "Shubham__Ranjan"
},
{
"code": null,
"e": 28953,
"s": 28944,
"text": "mank1083"
},
{
"code": null,
"e": 28961,
"s": 28953,
"text": "rohan07"
},
{
"code": null,
"e": 28971,
"s": 28961,
"text": "Bit Magic"
},
{
"code": null,
"e": 28981,
"s": 28971,
"text": "Bit Magic"
},
{
"code": null,
"e": 29079,
"s": 28981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29130,
"s": 29079,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29176,
"s": 29130,
"text": "How to turn off a particular bit in a number?"
},
{
"code": null,
"e": 29228,
"s": 29176,
"text": "Extract 'k' bits from a given position in a number."
},
{
"code": null,
"e": 29255,
"s": 29228,
"text": "Swap two nibbles in a byte"
},
{
"code": null,
"e": 29295,
"s": 29255,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 29359,
"s": 29295,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 29388,
"s": 29359,
"text": "Count total bits in a number"
},
{
"code": null,
"e": 29415,
"s": 29388,
"text": "Calculate XOR from 1 to n."
},
{
"code": null,
"e": 29454,
"s": 29415,
"text": "Bit Tricks for Competitive Programming"
}
] |
Python | Difference in keys of two dictionaries - GeeksforGeeks | 12 Feb, 2019
Given two dictionaries dic1 and dic2 which may contain same-keys, find the difference of keys in given dictionaries.
Code #1 : Using set to find keys that are missing.
# Python code to find the difference in# keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}dict2= {'key1':'Geeks', 'key2:':'Portal'} diff = set(dict2) - set(dict1) # Printing difference in# keys in two dictionaryprint(diff)
{'key2:'}
Code #2 : Finding keys in dict2 which are not in dict1.
# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} for key in dict2.keys(): if not key in dict1: # Printing difference in # keys in two dictionary print(key)
key4
key3
Code #3: Finding keys in dict1 which are not in dict2.
# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key12':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} for key in dict1.keys(): if not key in dict2: # Printing difference in # keys in two dictionary print(key)
key12
Code #4 : Finding the same keys in two dictionaries.
# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} print(set(dict1.keys()).intersection(dict2.keys()))
{'key2', 'key1'}
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26173,
"s": 26145,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 26290,
"s": 26173,
"text": "Given two dictionaries dic1 and dic2 which may contain same-keys, find the difference of keys in given dictionaries."
},
{
"code": null,
"e": 26341,
"s": 26290,
"text": "Code #1 : Using set to find keys that are missing."
},
{
"code": "# Python code to find the difference in# keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}dict2= {'key1':'Geeks', 'key2:':'Portal'} diff = set(dict2) - set(dict1) # Printing difference in# keys in two dictionaryprint(diff)",
"e": 26620,
"s": 26341,
"text": null
},
{
"code": null,
"e": 26631,
"s": 26620,
"text": "{'key2:'}\n"
},
{
"code": null,
"e": 26688,
"s": 26631,
"text": " Code #2 : Finding keys in dict2 which are not in dict1."
},
{
"code": "# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} for key in dict2.keys(): if not key in dict1: # Printing difference in # keys in two dictionary print(key)",
"e": 27065,
"s": 26688,
"text": null
},
{
"code": null,
"e": 27076,
"s": 27065,
"text": "key4\nkey3\n"
},
{
"code": null,
"e": 27132,
"s": 27076,
"text": " Code #3: Finding keys in dict1 which are not in dict2."
},
{
"code": "# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key12':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} for key in dict1.keys(): if not key in dict2: # Printing difference in # keys in two dictionary print(key)",
"e": 27518,
"s": 27132,
"text": null
},
{
"code": null,
"e": 27525,
"s": 27518,
"text": "key12\n"
},
{
"code": null,
"e": 27579,
"s": 27525,
"text": " Code #4 : Finding the same keys in two dictionaries."
},
{
"code": "# Python code to find difference in keys in two dictionary # Initialising dictionary dict1= {'key1':'Geeks', 'key2':'For'}dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks', 'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }} print(set(dict1.keys()).intersection(dict2.keys()))",
"e": 27883,
"s": 27579,
"text": null
},
{
"code": null,
"e": 27901,
"s": 27883,
"text": "{'key2', 'key1'}\n"
},
{
"code": null,
"e": 27928,
"s": 27901,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27940,
"s": 27928,
"text": "python-dict"
},
{
"code": null,
"e": 27947,
"s": 27940,
"text": "Python"
},
{
"code": null,
"e": 27963,
"s": 27947,
"text": "Python Programs"
},
{
"code": null,
"e": 27975,
"s": 27963,
"text": "python-dict"
},
{
"code": null,
"e": 28073,
"s": 27975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28091,
"s": 28073,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28126,
"s": 28091,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28158,
"s": 28126,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28180,
"s": 28158,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28222,
"s": 28180,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28265,
"s": 28222,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28287,
"s": 28265,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28326,
"s": 28287,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28372,
"s": 28326,
"text": "Python | Split string into list of characters"
}
] |
Minimize string value | Practice | GeeksforGeeks | Given a string of lowercase alphabets and a number k, the task is to find the minimum value of the string after removal of βkβ characters.
The value of a string is defined as the sum of squares of the count of each distinct character.
For example consider the string βgeeksβ, here frequencies of characters are g -> 1, e -> 2, k -> 1, s -> 1 and value of the string is 12 + 22 + 12 + 12 = 7
Example 1:
Input: S = "abccc", K = 1
Output: 6
Explanation: Remove one 'c', then frequency
will be a -> 1, b -> 1, c -> 2.
12 + 12 + 22 = 6
aΜβ¬βΉExample 2:
Input: S = "aaab", K = 2
Output: 2
Explanation: Remove 2 'a's, then frequency
will be a -> 1, b -> 1.
12 + 12 = 2
Your Task:
You don't need to read input or print anything. Your task is to complete the function minValue() which takes the string s as inputs and returns the answer.
Expected Time Complexity: O(K*log(|S|))
Expected Auxiliary Space: O(constant)
Constraints:
1 β€ K, |S| β€ 104
+2
manishkumar250319992 months ago
int minValue(string S, int K){ unordered_map<char,int>mp; for(int i=0;i<S.length();i++) mp[S[i]]++; vector<int>v; for(auto x:mp) v.push_back(x.second); sort(v.begin(),v.end(),greater<int>()); while(K) { v[0]=v[0]-1; K--; sort(v.begin(),v.end(),greater<int>()); } int count=0; for(auto x:v) { if(x>0) count=count+pow(x,2); } return count; }
+1
badgujarsachin836 months ago
int minValue(string S, int K)
{
if(K>S.size()){
return 0;
}
// Your code goes here
int arr[26]={0};
int sum=0;
for(int i=0;i<S.size();i++){
arr[S[i]-'a']++;
}
int index=0;
while(K--){
int maxa=-1;
for(int i=0;i<26;i++){
if(arr[i]>maxa){
maxa=arr[i];
index=i;
}
}
arr[index]--;
}
for(int i=0;i<26;i++){
arr[i]=arr[i]*arr[i];
sum+=arr[i];
}
return sum;
}
+1
sanjitpaul7 months ago
Very Easy Java solution using the hashing concept
https://ide.geeksforgeeks.org/GiJzcwlyl8
0
VISHAL SHARMA8 months ago
VISHAL SHARMA
https://uploads.disquscdn.c...
0
Arnav Singh1 year ago
Arnav Singh
IN JAVA 0.1s https://uploads.disquscdn.c...
0
Anant Agarwal2 years ago
Anant Agarwal
In C++int minValue(string s, int k){ int cnt[26]; memset(cnt, 0, sizeof(cnt)); int n = s.size(); for(int i = 0; i < n; i++) cnt[int(s[i]) - 97]++; set <pair<int, int="">> mset; for(int i = 0; i < 26; i++) mset.insert({-cnt[i], i}); for(int i = 0; i < min(n, k); i++) { auto it = mset.begin(); int x = (*it).first; int y = (*it).second; mset.erase(*it); mset.insert({x + 1, y}); } int ans = 0; for(auto i : mset) ans += pow(i.first, 2); return ans;}
0
Vivek Sharma2 years ago
Vivek Sharma
Use count sort on alphabets, start removing the numbers in decreasing order. Update the count of the last character removed if few of its instances still exist in sorted string.
0
Saurabh Singh2 years ago
Saurabh Singh
In Java:
class Solution { int minValue(String str,int n) { HashMap<character, integer=""> charMap = new HashMap<>(); /*Frequency*/ for (char c : str.toCharArray()) { charMap.put(c, charMap.getOrDefault(c, 0) + 1); } /*Storing The Freq*/ PriorityQueue<integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder()); for (char c : charMap.keySet()) { maxQueue.add(charMap.get(c)); } /*Minimising the frequency*/ while (n-- > 0) { int top = maxQueue.poll(); if (top == 0){ break; } top--; maxQueue.add(top); } int sum = 0; while (!maxQueue.isEmpty()) { Integer data = maxQueue.poll(); sum += data * data; } return sum; }}
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": 632,
"s": 238,
"text": "Given a string of lowercase alphabets and a number k, the task is to find the minimum value of the string after removal of βkβ characters. \nThe value of a string is defined as the sum of squares of the count of each distinct character.\nFor example consider the string βgeeksβ, here frequencies of characters are g -> 1, e -> 2, k -> 1, s -> 1 and value of the string is 12 + 22 + 12 + 12 = 7\n "
},
{
"code": null,
"e": 643,
"s": 632,
"text": "Example 1:"
},
{
"code": null,
"e": 773,
"s": 643,
"text": "Input: S = \"abccc\", K = 1\nOutput: 6\nExplanation: Remove one 'c', then frequency\nwill be a -> 1, b -> 1, c -> 2.\n12 + 12 + 22 = 6\n"
},
{
"code": null,
"e": 788,
"s": 773,
"text": "aΜβ¬βΉExample 2:"
},
{
"code": null,
"e": 903,
"s": 788,
"text": "Input: S = \"aaab\", K = 2\nOutput: 2\nExplanation: Remove 2 'a's, then frequency\nwill be a -> 1, b -> 1.\n12 + 12 = 2\n"
},
{
"code": null,
"e": 1182,
"s": 903,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function minValue() which takes the string s as inputs and returns the answer.\n\nExpected Time Complexity: O(K*log(|S|))\nExpected Auxiliary Space: O(constant)\n\nConstraints:\n1 β€ K, |S| β€ 104"
},
{
"code": null,
"e": 1185,
"s": 1182,
"text": "+2"
},
{
"code": null,
"e": 1217,
"s": 1185,
"text": "manishkumar250319992 months ago"
},
{
"code": null,
"e": 1670,
"s": 1217,
"text": "int minValue(string S, int K){ unordered_map<char,int>mp; for(int i=0;i<S.length();i++) mp[S[i]]++; vector<int>v; for(auto x:mp) v.push_back(x.second); sort(v.begin(),v.end(),greater<int>()); while(K) { v[0]=v[0]-1; K--; sort(v.begin(),v.end(),greater<int>()); } int count=0; for(auto x:v) { if(x>0) count=count+pow(x,2); } return count; }"
},
{
"code": null,
"e": 1673,
"s": 1670,
"text": "+1"
},
{
"code": null,
"e": 1702,
"s": 1673,
"text": "badgujarsachin836 months ago"
},
{
"code": null,
"e": 2286,
"s": 1702,
"text": "\tint minValue(string S, int K)\n\t{\n\t if(K>S.size()){\n\t return 0;\n\t }\n\t // Your code goes here\n\t int arr[26]={0};\n\t int sum=0;\n\t for(int i=0;i<S.size();i++){\n\t arr[S[i]-'a']++;\n\t }\n\t \n\t int index=0;\n\t while(K--){\n\t int maxa=-1;\n\t for(int i=0;i<26;i++){\n\t if(arr[i]>maxa){\n\t maxa=arr[i];\n\t index=i;\n\t \n\t }\n\t }\n\t arr[index]--;\n\t \n\t }\n\t for(int i=0;i<26;i++){\n\t arr[i]=arr[i]*arr[i];\n\t sum+=arr[i];\n\t }\n\t return sum;\n\t}"
},
{
"code": null,
"e": 2289,
"s": 2286,
"text": "+1"
},
{
"code": null,
"e": 2312,
"s": 2289,
"text": "sanjitpaul7 months ago"
},
{
"code": null,
"e": 2362,
"s": 2312,
"text": "Very Easy Java solution using the hashing concept"
},
{
"code": null,
"e": 2403,
"s": 2362,
"text": "https://ide.geeksforgeeks.org/GiJzcwlyl8"
},
{
"code": null,
"e": 2407,
"s": 2405,
"text": "0"
},
{
"code": null,
"e": 2433,
"s": 2407,
"text": "VISHAL SHARMA8 months ago"
},
{
"code": null,
"e": 2447,
"s": 2433,
"text": "VISHAL SHARMA"
},
{
"code": null,
"e": 2478,
"s": 2447,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2480,
"s": 2478,
"text": "0"
},
{
"code": null,
"e": 2502,
"s": 2480,
"text": "Arnav Singh1 year ago"
},
{
"code": null,
"e": 2514,
"s": 2502,
"text": "Arnav Singh"
},
{
"code": null,
"e": 2559,
"s": 2514,
"text": "IN JAVA 0.1s https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2561,
"s": 2559,
"text": "0"
},
{
"code": null,
"e": 2586,
"s": 2561,
"text": "Anant Agarwal2 years ago"
},
{
"code": null,
"e": 2600,
"s": 2586,
"text": "Anant Agarwal"
},
{
"code": null,
"e": 3142,
"s": 2600,
"text": "In C++int minValue(string s, int k){ int cnt[26]; memset(cnt, 0, sizeof(cnt)); int n = s.size(); for(int i = 0; i < n; i++) cnt[int(s[i]) - 97]++; set <pair<int, int=\"\">> mset; for(int i = 0; i < 26; i++) mset.insert({-cnt[i], i}); for(int i = 0; i < min(n, k); i++) { auto it = mset.begin(); int x = (*it).first; int y = (*it).second; mset.erase(*it); mset.insert({x + 1, y}); } int ans = 0; for(auto i : mset) ans += pow(i.first, 2); return ans;}"
},
{
"code": null,
"e": 3144,
"s": 3142,
"text": "0"
},
{
"code": null,
"e": 3168,
"s": 3144,
"text": "Vivek Sharma2 years ago"
},
{
"code": null,
"e": 3181,
"s": 3168,
"text": "Vivek Sharma"
},
{
"code": null,
"e": 3359,
"s": 3181,
"text": "Use count sort on alphabets, start removing the numbers in decreasing order. Update the count of the last character removed if few of its instances still exist in sorted string."
},
{
"code": null,
"e": 3361,
"s": 3359,
"text": "0"
},
{
"code": null,
"e": 3386,
"s": 3361,
"text": "Saurabh Singh2 years ago"
},
{
"code": null,
"e": 3400,
"s": 3386,
"text": "Saurabh Singh"
},
{
"code": null,
"e": 3409,
"s": 3400,
"text": "In Java:"
},
{
"code": null,
"e": 4248,
"s": 3409,
"text": "class Solution { int minValue(String str,int n) { HashMap<character, integer=\"\"> charMap = new HashMap<>(); /*Frequency*/ for (char c : str.toCharArray()) { charMap.put(c, charMap.getOrDefault(c, 0) + 1); } /*Storing The Freq*/ PriorityQueue<integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder()); for (char c : charMap.keySet()) { maxQueue.add(charMap.get(c)); } /*Minimising the frequency*/ while (n-- > 0) { int top = maxQueue.poll(); if (top == 0){ break; } top--; maxQueue.add(top); } int sum = 0; while (!maxQueue.isEmpty()) { Integer data = maxQueue.poll(); sum += data * data; } return sum; }}"
},
{
"code": null,
"e": 4394,
"s": 4248,
"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": 4430,
"s": 4394,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4440,
"s": 4430,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4450,
"s": 4440,
"text": "\nContest\n"
},
{
"code": null,
"e": 4513,
"s": 4450,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4661,
"s": 4513,
"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": 4869,
"s": 4661,
"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": 4975,
"s": 4869,
"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 remove white spaces from a string using jQuery ? - GeeksforGeeks | 22 Mar, 2021
In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string.
Syntax:
jQuery.trim( str )
Parameters: This method accepts a single parameter string that is to be trimmed.
In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string.
Example:
HTML
<!DOCTYpe html>
<html>
<head>
<title>
How to remove white space from
a string using jQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("h1").css("color", "green");
$("button").click(function () {
$(".str").html("String without whitespaces");
var str = $(".string").text();
var trimStr = $.trim(str);
$(".res-string").html(trimStr);
})
});
</script>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
How to remove white space from
a string using jQuery?
</h3>
<h4>String containing white spaces</h4>
<pre class="string"> GeeksforGeeks </pre>
<button>Trim String</button>
<h4 class="str"></h4>
<pre class="res-string"></pre>
</body>
</html>
Output:
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
HTML
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery? | [
{
"code": null,
"e": 24640,
"s": 24609,
"text": " \n22 Mar, 2021\n"
},
{
"code": null,
"e": 24874,
"s": 24640,
"text": "In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string."
},
{
"code": null,
"e": 24882,
"s": 24874,
"text": "Syntax:"
},
{
"code": null,
"e": 24901,
"s": 24882,
"text": "jQuery.trim( str )"
},
{
"code": null,
"e": 24982,
"s": 24901,
"text": "Parameters: This method accepts a single parameter string that is to be trimmed."
},
{
"code": null,
"e": 25224,
"s": 24982,
"text": "In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string."
},
{
"code": null,
"e": 25233,
"s": 25224,
"text": "Example:"
},
{
"code": null,
"e": 25238,
"s": 25233,
"text": "HTML"
},
{
"code": "\n\n\n\n\n\n\n<!DOCTYpe html> \n<html> \n \n<head> \n <title> \n How to remove white space from \n a string using jQuery? \n </title> \n \n <script src= \n\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> \n </script> \n \n <script> \n $(document).ready(function () { \n $(\"h1\").css(\"color\", \"green\"); \n $(\"button\").click(function () { \n $(\".str\").html(\"String without whitespaces\"); \n var str = $(\".string\").text(); \n var trimStr = $.trim(str); \n $(\".res-string\").html(trimStr); \n }) \n }); \n </script> \n</head> \n \n<body> \n <h1>GeeksforGeeks</h1> \n \n <h3> \n How to remove white space from \n a string using jQuery? \n </h3> \n \n <h4>String containing white spaces</h4> \n <pre class=\"string\"> GeeksforGeeks </pre> \n \n <button>Trim String</button> \n \n <h4 class=\"str\"></h4> \n <pre class=\"res-string\"></pre> \n</body> \n \n</html>\n\n\n\n\n\n",
"e": 26267,
"s": 25248,
"text": null
},
{
"code": null,
"e": 26275,
"s": 26267,
"text": "Output:"
},
{
"code": null,
"e": 26412,
"s": 26275,
"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": 26429,
"s": 26412,
"text": "\nHTML-Questions\n"
},
{
"code": null,
"e": 26441,
"s": 26429,
"text": "\nHTML-Tags\n"
},
{
"code": null,
"e": 26458,
"s": 26441,
"text": "\njQuery-Methods\n"
},
{
"code": null,
"e": 26477,
"s": 26458,
"text": "\njQuery-Questions\n"
},
{
"code": null,
"e": 26484,
"s": 26477,
"text": "\nHTML\n"
},
{
"code": null,
"e": 26493,
"s": 26484,
"text": "\nJQuery\n"
},
{
"code": null,
"e": 26512,
"s": 26493,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26717,
"s": 26512,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26741,
"s": 26717,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26778,
"s": 26741,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26807,
"s": 26778,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26854,
"s": 26807,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 26916,
"s": 26854,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 26962,
"s": 26916,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 26991,
"s": 26962,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27054,
"s": 26991,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27131,
"s": 27054,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
How to Train an mT5 Model for Translation With Simple Transformers | by Thilina Rajapakse | Towards Data Science | mT5 is a multilingual Transformer model pre-trained on a dataset (mC4) containing text from 101 different languages. The architecture of the mT5 model (based on T5) is designed to support any Natural Language Processing task (classification, NER, question answering, etc.) by reframing the required task as a sequence-to-sequence task.
In other words β text goes in, and text comes out. For example, in a classification task, the input to the model can be the text sequence to be classified, and the output from the model will be the class label for the sequence. For translation, this is even more straight forward. The text that goes in is in one language, and the text that comes out is in another.
Considering the multilingual capabilities of mT5 and the suitability of the sequence-to-sequence format for language translation, letβs see how we can fine-tune an mT5 model for machine translation. For this article, weβll be training a translation model to translate between Sinhalese (my native language!) and English. Itβs quite challenging to train good translation models for low-resource languages like Sinhalese because of, well, the low availability of resources (training data). Hopefully, the multilingual pre-training on a huge dataset (which includes Sinhalese, although not a lot of it) will help the mT5 model compensate for inadequate training data in the form of direct Sinhalese-English (and vice versa) sequences.
Weβll be using the Simple Transformers library (built on the Huggingface Transformers library) to train the mT5 model. The training and testing data will be obtained from The Tatoeba Translation Challenge. The graphs and charts are generated from Weights & Biases, which is supported natively in Simple Transformers for experiment tracking and hyperparameter optimization.
Note: You can find all the code in this article in the examples/t5/mt5_translation directory (link) of the Simple Transformers Github repo.
Installing Simple TransformersDownloading a dataset for translationTraining the modelEvaluating the model β Calculating the BLEU scoreWrap up
Installing Simple Transformers
Downloading a dataset for translation
Training the model
Evaluating the model β Calculating the BLEU score
Wrap up
You can find the most up-to-date installation instructions in the Simple Transformers documentation.
1. Install Anaconda or Miniconda Package Manager from here.
2. Create a new virtual environment and install packages.
conda create -n st python pandas tqdm sacrebleuconda activate st
3. If using CUDA:
conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch
else:
conda install pytorch cpuonly -c pytorch
4. Install simple transformers.
pip install simpletransformers
The training and test can be obtained from the Tatoeba Translation Challenge data page. Youβll also find datasets for a whole host of other languages there (including Sindarin, a language spoken by Elves in The Lord of the Rings π).
If you want to try training a translation model for another language, you can download the dataset for that language instead of Sinhalese. All the other steps in this article apply to any language dataset.
If you are too lazy to search for the dataset, hereβs the direct link. π
Download the (compressed) translation dataset and extract the archive.Extract the train.trg.gz and train.src.gz archives (yes, the training data is in archives inside archives).Check whether you have thetrain.trg, train.src, test.trg, test.src files in the data/eng-sin/ directory. (If not, itβs probably easiest to move the files to this location as the code examples will assume that these files can be found here)
Download the (compressed) translation dataset and extract the archive.
Extract the train.trg.gz and train.src.gz archives (yes, the training data is in archives inside archives).
Check whether you have thetrain.trg, train.src, test.trg, test.src files in the data/eng-sin/ directory. (If not, itβs probably easiest to move the files to this location as the code examples will assume that these files can be found here)
Now, letβs build the tsv files that we will use to train and test our mT5 model.
import os
import pandas as pd
def prepare_translation_datasets(data_path):
with open(os.path.join(data_path, "train.trg"), "r", encoding="utf-8") as f:
sinhala_text = f.readlines()
sinhala_text = [text.strip("\n") for text in sinhala_text]
with open(os.path.join(data_path, "train.src"), "r") as f:
english_text = f.readlines()
english_text = [text.strip("\n") for text in english_text]
data = []
for sinhala, english in zip(sinhala_text, english_text):
data.append(["translate sinhala to english", sinhala, english])
data.append(["translate english to sinhala", english, sinhala])
train_df = pd.DataFrame(data, columns=["prefix", "input_text", "target_text"])
with open(os.path.join(data_path, "test.trg"), "r", encoding="utf-8") as f:
sinhala_text = f.readlines()
sinhala_text = [text.strip("\n") for text in sinhala_text]
with open(os.path.join(data_path, "test.src"), "r") as f:
english_text = f.readlines()
english_text = [text.strip("\n") for text in english_text]
data = []
for sinhala, english in zip(sinhala_text, english_text):
data.append(["translate sinhala to english", sinhala, english])
data.append(["translate english to sinhala", english, sinhala])
eval_df = pd.DataFrame(data, columns=["prefix", "input_text", "target_text"])
return train_df, eval_df
train_df, eval_df = prepare_translation_datasets("data/eng-sin")
train_df
2255054 rows Γ 3 columns
train_df.to_csv("data/train.tsv", sep="\t")
eval_df.to_csv("data/eval.tsv", sep="\t")
Running the code above will write the two files, train.tsv and eval.tsv, to the data/ directory.
Once we have the data files, we are ready to start training the model.
First, weβll import the necessary stuff and set up logging.
Next, we set up our training and evaluation data.
Here, we remove the prefix values from the datasets because we expect the model to infer the required task based on the input. If the input is in English, then it should be translated to Sinhalese. If itβs in Sinhalese, then it should be translated to English. The model shouldnβt need a prefix to figure this out after the training!
You can use a prefix value to tell an mT5 (or T5) to perform a specific task. This is quite useful to train a model which can perform multiple tasks, as shown in the article below.
towardsdatascience.com
The amount of GPU memory required to train a Transformer model depends on many different factors (maximum sequence length, number of layers, number of attention heads, size of the hidden dimensions, size of the vocabulary, etc.). Out of these, the maximum sequence length of the model is one of the most significant.
For the self-attention mechanisms used in the mT5 model, the memory requirement grows quadratically with the input sequence length (O(n2) space complexity). I.e., When the sequence length doubles, the memory required quadruples.
Also, mT5 has a much larger vocabulary than T5 (~250,000 tokens to ~32,000 tokens), contributing to mT5 being quite punishing in terms of GPU memory required.
The takeaway from all this is that the number of tokens we can input to the model (the maximum sequence length) comes at a hefty premium. Based on this, itβs wasteful to use even a small number of tokens on the prefix if the model can do without.
Now, letβs get back to training the model!
Here, we specify how we want the model to be set up and initialize the pre-trained mT5 model according to model_args.
Iβm using a maximum sequence length (max_seq_length) of 96 and a train/eval batch sizes of 20. Generally, larger batch sizes mean better GPU utilization, and therefore, shorter training times. As mentioned earlier, longer sequences require more GPU memory, which means smaller batch sizes and longer training times. The maximum sequence length of 96 allows the model to work with reasonably long text (typically a few sentences) while also keeping the training time practical.
Note that you may need to tweak these values to train the model on your own GPU. If you run out of GPU memory (CUDA memory error), try reducing the batch sizes and/or the maximum sequence length.
If you want to try the fine-tuned model, you can find it here on the Huggingface model hub.
Now, to run the training, we just need to call the train_model() method.
As easy as that! The fine-tuned model will be saved to the outputs directory at the end of the training (see docs for more info on model saving).
With these settings, the model took a little over 10 hours to complete the training on an RTX 3090 (24 GB VRAM).
I probably could have gotten away with slightly larger batch sizes (as you can see below), but I didnβt want to run the risk of the training crashing as I was running this overnight!
Playing it safe with a batch size of 20 meant that the GPU was not fully utilized, but, 80%-ish is not bad!
Setting the wandb_project value in model_args tells Simple Transformers to log the training progress to Weights & Biases automatically. You can find all the logged data for this experiment here.
The actual loss values here donβt tell us too much, but the fact that they are decreasing does mean that the model is learning!
In fact, it appears as though the model has not yet converged as the evaluation loss is still decreasing. Training for another epoch or two might very well improve the model performance, but, that would take another 10 or 20 hours!
To try out the fine-tuned model in a web-based GUI (Streamlit app), use the terminal command simple-viewer.
The standard metric used to evaluate and compare machine translation models is the BLEU score, specifically, the BLEU scheme used by the annual Conference on Machine Translation (WMT). The SacreBLEU library can be used to calculate this score.
For more information on the BLEU score, please refer to this paper by Matt Post.
Since The Tatoeba Challenge also provides the BLEU scores for the benchmark translation models, we can easily compare our model to the benchmark model.
Now, letβs load our fine-tuned model and see how it stacks up!
We import the necessary stuff (note the sacrebleu library) and initialize the model just as we did for training, except that we load the fine-tuned model from outputs/ rather than the pre-trained model.
We also set some parameters for generating text (decoding) with the model. Here, the max_length is the maximum length for the output from the model rather than the input.
If youβd like to learn more about the decoding process, please refer to the decoding algorithms section in this article and this excellent notebook by Huggingface.
Next, weβll prepare the data for evaluation.
Here, we load the evaluation data and prepare separate lists of inputs and true translations (for English to Sinhalese and vice versa).
With the model and evaluation data loaded and ready, we can go ahead and do the translations. With Simple Transformers, we just call model.predict() with the input data. Then, we use the sacrebleu tool to calculate the BLEU score.
The sacrebleu library should be installed in your virtual environment if you followed the setup instructions. If not, you can install it with pip install sacrebleu.
Running this gives us the following scores (rounded off):
English to Sinhalese: 10.3
Sinhalese to English: 24.4
Both these scores improve upon the scores posted by the translation model in the Tatoeba Challenge!
The mT5 model does an excellent job of translating between Sinhalese and English, despite the limited training data availability.
mT5 outperforms the scores posted in the Tatoeba Challange. However, it should be noted that the benchmark model in the challenge is trained on several other languages in addition to Sinhalese and English. In addition, the mT5 model requires significantly more compute resources to train and to use. On the other hand, the mT5 model has the potential to improve upon the current scores with more training.
Finally, you can find the fine-tuned model on the Huggingface model hub here. You can use it directly with Simple Transformers as shown below.
from simpletransformers.t5 import T5Modelmodel = T5Model("mt5", "thilina/mt5-sinhalese-english")print(model.predict(["Let's translate!"])) | [
{
"code": null,
"e": 507,
"s": 171,
"text": "mT5 is a multilingual Transformer model pre-trained on a dataset (mC4) containing text from 101 different languages. The architecture of the mT5 model (based on T5) is designed to support any Natural Language Processing task (classification, NER, question answering, etc.) by reframing the required task as a sequence-to-sequence task."
},
{
"code": null,
"e": 873,
"s": 507,
"text": "In other words β text goes in, and text comes out. For example, in a classification task, the input to the model can be the text sequence to be classified, and the output from the model will be the class label for the sequence. For translation, this is even more straight forward. The text that goes in is in one language, and the text that comes out is in another."
},
{
"code": null,
"e": 1605,
"s": 873,
"text": "Considering the multilingual capabilities of mT5 and the suitability of the sequence-to-sequence format for language translation, letβs see how we can fine-tune an mT5 model for machine translation. For this article, weβll be training a translation model to translate between Sinhalese (my native language!) and English. Itβs quite challenging to train good translation models for low-resource languages like Sinhalese because of, well, the low availability of resources (training data). Hopefully, the multilingual pre-training on a huge dataset (which includes Sinhalese, although not a lot of it) will help the mT5 model compensate for inadequate training data in the form of direct Sinhalese-English (and vice versa) sequences."
},
{
"code": null,
"e": 1978,
"s": 1605,
"text": "Weβll be using the Simple Transformers library (built on the Huggingface Transformers library) to train the mT5 model. The training and testing data will be obtained from The Tatoeba Translation Challenge. The graphs and charts are generated from Weights & Biases, which is supported natively in Simple Transformers for experiment tracking and hyperparameter optimization."
},
{
"code": null,
"e": 2118,
"s": 1978,
"text": "Note: You can find all the code in this article in the examples/t5/mt5_translation directory (link) of the Simple Transformers Github repo."
},
{
"code": null,
"e": 2260,
"s": 2118,
"text": "Installing Simple TransformersDownloading a dataset for translationTraining the modelEvaluating the model β Calculating the BLEU scoreWrap up"
},
{
"code": null,
"e": 2291,
"s": 2260,
"text": "Installing Simple Transformers"
},
{
"code": null,
"e": 2329,
"s": 2291,
"text": "Downloading a dataset for translation"
},
{
"code": null,
"e": 2348,
"s": 2329,
"text": "Training the model"
},
{
"code": null,
"e": 2398,
"s": 2348,
"text": "Evaluating the model β Calculating the BLEU score"
},
{
"code": null,
"e": 2406,
"s": 2398,
"text": "Wrap up"
},
{
"code": null,
"e": 2507,
"s": 2406,
"text": "You can find the most up-to-date installation instructions in the Simple Transformers documentation."
},
{
"code": null,
"e": 2567,
"s": 2507,
"text": "1. Install Anaconda or Miniconda Package Manager from here."
},
{
"code": null,
"e": 2625,
"s": 2567,
"text": "2. Create a new virtual environment and install packages."
},
{
"code": null,
"e": 2690,
"s": 2625,
"text": "conda create -n st python pandas tqdm sacrebleuconda activate st"
},
{
"code": null,
"e": 2708,
"s": 2690,
"text": "3. If using CUDA:"
},
{
"code": null,
"e": 2763,
"s": 2708,
"text": "conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch"
},
{
"code": null,
"e": 2769,
"s": 2763,
"text": "else:"
},
{
"code": null,
"e": 2810,
"s": 2769,
"text": "conda install pytorch cpuonly -c pytorch"
},
{
"code": null,
"e": 2842,
"s": 2810,
"text": "4. Install simple transformers."
},
{
"code": null,
"e": 2873,
"s": 2842,
"text": "pip install simpletransformers"
},
{
"code": null,
"e": 3106,
"s": 2873,
"text": "The training and test can be obtained from the Tatoeba Translation Challenge data page. Youβll also find datasets for a whole host of other languages there (including Sindarin, a language spoken by Elves in The Lord of the Rings π)."
},
{
"code": null,
"e": 3312,
"s": 3106,
"text": "If you want to try training a translation model for another language, you can download the dataset for that language instead of Sinhalese. All the other steps in this article apply to any language dataset."
},
{
"code": null,
"e": 3385,
"s": 3312,
"text": "If you are too lazy to search for the dataset, hereβs the direct link. π"
},
{
"code": null,
"e": 3802,
"s": 3385,
"text": "Download the (compressed) translation dataset and extract the archive.Extract the train.trg.gz and train.src.gz archives (yes, the training data is in archives inside archives).Check whether you have thetrain.trg, train.src, test.trg, test.src files in the data/eng-sin/ directory. (If not, itβs probably easiest to move the files to this location as the code examples will assume that these files can be found here)"
},
{
"code": null,
"e": 3873,
"s": 3802,
"text": "Download the (compressed) translation dataset and extract the archive."
},
{
"code": null,
"e": 3981,
"s": 3873,
"text": "Extract the train.trg.gz and train.src.gz archives (yes, the training data is in archives inside archives)."
},
{
"code": null,
"e": 4221,
"s": 3981,
"text": "Check whether you have thetrain.trg, train.src, test.trg, test.src files in the data/eng-sin/ directory. (If not, itβs probably easiest to move the files to this location as the code examples will assume that these files can be found here)"
},
{
"code": null,
"e": 4302,
"s": 4221,
"text": "Now, letβs build the tsv files that we will use to train and test our mT5 model."
},
{
"code": null,
"e": 4333,
"s": 4302,
"text": "import os\nimport pandas as pd\n"
},
{
"code": null,
"e": 5721,
"s": 4333,
"text": "def prepare_translation_datasets(data_path):\n with open(os.path.join(data_path, \"train.trg\"), \"r\", encoding=\"utf-8\") as f:\n sinhala_text = f.readlines()\n sinhala_text = [text.strip(\"\\n\") for text in sinhala_text]\n\n with open(os.path.join(data_path, \"train.src\"), \"r\") as f:\n english_text = f.readlines()\n english_text = [text.strip(\"\\n\") for text in english_text]\n\n data = []\n for sinhala, english in zip(sinhala_text, english_text):\n data.append([\"translate sinhala to english\", sinhala, english])\n data.append([\"translate english to sinhala\", english, sinhala])\n\n train_df = pd.DataFrame(data, columns=[\"prefix\", \"input_text\", \"target_text\"])\n\n with open(os.path.join(data_path, \"test.trg\"), \"r\", encoding=\"utf-8\") as f:\n sinhala_text = f.readlines()\n sinhala_text = [text.strip(\"\\n\") for text in sinhala_text]\n\n with open(os.path.join(data_path, \"test.src\"), \"r\") as f:\n english_text = f.readlines()\n english_text = [text.strip(\"\\n\") for text in english_text]\n\n data = []\n for sinhala, english in zip(sinhala_text, english_text):\n data.append([\"translate sinhala to english\", sinhala, english])\n data.append([\"translate english to sinhala\", english, sinhala])\n\n eval_df = pd.DataFrame(data, columns=[\"prefix\", \"input_text\", \"target_text\"])\n\n return train_df, eval_df\n"
},
{
"code": null,
"e": 5787,
"s": 5721,
"text": "train_df, eval_df = prepare_translation_datasets(\"data/eng-sin\")\n"
},
{
"code": null,
"e": 5797,
"s": 5787,
"text": "train_df\n"
},
{
"code": null,
"e": 5822,
"s": 5797,
"text": "2255054 rows Γ 3 columns"
},
{
"code": null,
"e": 5909,
"s": 5822,
"text": "train_df.to_csv(\"data/train.tsv\", sep=\"\\t\")\neval_df.to_csv(\"data/eval.tsv\", sep=\"\\t\")\n"
},
{
"code": null,
"e": 6006,
"s": 5909,
"text": "Running the code above will write the two files, train.tsv and eval.tsv, to the data/ directory."
},
{
"code": null,
"e": 6077,
"s": 6006,
"text": "Once we have the data files, we are ready to start training the model."
},
{
"code": null,
"e": 6137,
"s": 6077,
"text": "First, weβll import the necessary stuff and set up logging."
},
{
"code": null,
"e": 6187,
"s": 6137,
"text": "Next, we set up our training and evaluation data."
},
{
"code": null,
"e": 6521,
"s": 6187,
"text": "Here, we remove the prefix values from the datasets because we expect the model to infer the required task based on the input. If the input is in English, then it should be translated to Sinhalese. If itβs in Sinhalese, then it should be translated to English. The model shouldnβt need a prefix to figure this out after the training!"
},
{
"code": null,
"e": 6702,
"s": 6521,
"text": "You can use a prefix value to tell an mT5 (or T5) to perform a specific task. This is quite useful to train a model which can perform multiple tasks, as shown in the article below."
},
{
"code": null,
"e": 6725,
"s": 6702,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7042,
"s": 6725,
"text": "The amount of GPU memory required to train a Transformer model depends on many different factors (maximum sequence length, number of layers, number of attention heads, size of the hidden dimensions, size of the vocabulary, etc.). Out of these, the maximum sequence length of the model is one of the most significant."
},
{
"code": null,
"e": 7271,
"s": 7042,
"text": "For the self-attention mechanisms used in the mT5 model, the memory requirement grows quadratically with the input sequence length (O(n2) space complexity). I.e., When the sequence length doubles, the memory required quadruples."
},
{
"code": null,
"e": 7430,
"s": 7271,
"text": "Also, mT5 has a much larger vocabulary than T5 (~250,000 tokens to ~32,000 tokens), contributing to mT5 being quite punishing in terms of GPU memory required."
},
{
"code": null,
"e": 7677,
"s": 7430,
"text": "The takeaway from all this is that the number of tokens we can input to the model (the maximum sequence length) comes at a hefty premium. Based on this, itβs wasteful to use even a small number of tokens on the prefix if the model can do without."
},
{
"code": null,
"e": 7720,
"s": 7677,
"text": "Now, letβs get back to training the model!"
},
{
"code": null,
"e": 7838,
"s": 7720,
"text": "Here, we specify how we want the model to be set up and initialize the pre-trained mT5 model according to model_args."
},
{
"code": null,
"e": 8315,
"s": 7838,
"text": "Iβm using a maximum sequence length (max_seq_length) of 96 and a train/eval batch sizes of 20. Generally, larger batch sizes mean better GPU utilization, and therefore, shorter training times. As mentioned earlier, longer sequences require more GPU memory, which means smaller batch sizes and longer training times. The maximum sequence length of 96 allows the model to work with reasonably long text (typically a few sentences) while also keeping the training time practical."
},
{
"code": null,
"e": 8511,
"s": 8315,
"text": "Note that you may need to tweak these values to train the model on your own GPU. If you run out of GPU memory (CUDA memory error), try reducing the batch sizes and/or the maximum sequence length."
},
{
"code": null,
"e": 8603,
"s": 8511,
"text": "If you want to try the fine-tuned model, you can find it here on the Huggingface model hub."
},
{
"code": null,
"e": 8676,
"s": 8603,
"text": "Now, to run the training, we just need to call the train_model() method."
},
{
"code": null,
"e": 8822,
"s": 8676,
"text": "As easy as that! The fine-tuned model will be saved to the outputs directory at the end of the training (see docs for more info on model saving)."
},
{
"code": null,
"e": 8935,
"s": 8822,
"text": "With these settings, the model took a little over 10 hours to complete the training on an RTX 3090 (24 GB VRAM)."
},
{
"code": null,
"e": 9118,
"s": 8935,
"text": "I probably could have gotten away with slightly larger batch sizes (as you can see below), but I didnβt want to run the risk of the training crashing as I was running this overnight!"
},
{
"code": null,
"e": 9226,
"s": 9118,
"text": "Playing it safe with a batch size of 20 meant that the GPU was not fully utilized, but, 80%-ish is not bad!"
},
{
"code": null,
"e": 9421,
"s": 9226,
"text": "Setting the wandb_project value in model_args tells Simple Transformers to log the training progress to Weights & Biases automatically. You can find all the logged data for this experiment here."
},
{
"code": null,
"e": 9549,
"s": 9421,
"text": "The actual loss values here donβt tell us too much, but the fact that they are decreasing does mean that the model is learning!"
},
{
"code": null,
"e": 9781,
"s": 9549,
"text": "In fact, it appears as though the model has not yet converged as the evaluation loss is still decreasing. Training for another epoch or two might very well improve the model performance, but, that would take another 10 or 20 hours!"
},
{
"code": null,
"e": 9889,
"s": 9781,
"text": "To try out the fine-tuned model in a web-based GUI (Streamlit app), use the terminal command simple-viewer."
},
{
"code": null,
"e": 10133,
"s": 9889,
"text": "The standard metric used to evaluate and compare machine translation models is the BLEU score, specifically, the BLEU scheme used by the annual Conference on Machine Translation (WMT). The SacreBLEU library can be used to calculate this score."
},
{
"code": null,
"e": 10214,
"s": 10133,
"text": "For more information on the BLEU score, please refer to this paper by Matt Post."
},
{
"code": null,
"e": 10366,
"s": 10214,
"text": "Since The Tatoeba Challenge also provides the BLEU scores for the benchmark translation models, we can easily compare our model to the benchmark model."
},
{
"code": null,
"e": 10429,
"s": 10366,
"text": "Now, letβs load our fine-tuned model and see how it stacks up!"
},
{
"code": null,
"e": 10632,
"s": 10429,
"text": "We import the necessary stuff (note the sacrebleu library) and initialize the model just as we did for training, except that we load the fine-tuned model from outputs/ rather than the pre-trained model."
},
{
"code": null,
"e": 10803,
"s": 10632,
"text": "We also set some parameters for generating text (decoding) with the model. Here, the max_length is the maximum length for the output from the model rather than the input."
},
{
"code": null,
"e": 10967,
"s": 10803,
"text": "If youβd like to learn more about the decoding process, please refer to the decoding algorithms section in this article and this excellent notebook by Huggingface."
},
{
"code": null,
"e": 11012,
"s": 10967,
"text": "Next, weβll prepare the data for evaluation."
},
{
"code": null,
"e": 11148,
"s": 11012,
"text": "Here, we load the evaluation data and prepare separate lists of inputs and true translations (for English to Sinhalese and vice versa)."
},
{
"code": null,
"e": 11379,
"s": 11148,
"text": "With the model and evaluation data loaded and ready, we can go ahead and do the translations. With Simple Transformers, we just call model.predict() with the input data. Then, we use the sacrebleu tool to calculate the BLEU score."
},
{
"code": null,
"e": 11544,
"s": 11379,
"text": "The sacrebleu library should be installed in your virtual environment if you followed the setup instructions. If not, you can install it with pip install sacrebleu."
},
{
"code": null,
"e": 11602,
"s": 11544,
"text": "Running this gives us the following scores (rounded off):"
},
{
"code": null,
"e": 11629,
"s": 11602,
"text": "English to Sinhalese: 10.3"
},
{
"code": null,
"e": 11656,
"s": 11629,
"text": "Sinhalese to English: 24.4"
},
{
"code": null,
"e": 11756,
"s": 11656,
"text": "Both these scores improve upon the scores posted by the translation model in the Tatoeba Challenge!"
},
{
"code": null,
"e": 11886,
"s": 11756,
"text": "The mT5 model does an excellent job of translating between Sinhalese and English, despite the limited training data availability."
},
{
"code": null,
"e": 12292,
"s": 11886,
"text": "mT5 outperforms the scores posted in the Tatoeba Challange. However, it should be noted that the benchmark model in the challenge is trained on several other languages in addition to Sinhalese and English. In addition, the mT5 model requires significantly more compute resources to train and to use. On the other hand, the mT5 model has the potential to improve upon the current scores with more training."
},
{
"code": null,
"e": 12435,
"s": 12292,
"text": "Finally, you can find the fine-tuned model on the Huggingface model hub here. You can use it directly with Simple Transformers as shown below."
}
] |
Pointers, smart pointers and shared pointers in C++ | Pointers are used to store the address of variable.
Type *pointer;
Type *pointer;
Pointer = variable name;
pointers are used to store address of variable.
pointers can have a null value assigned.
pointer can be referenced by pass by reference.
a pointer has its own memory address and size on the stack.
Live Demo
#include <iostream>
using namespace std;
int main() {
// A normal integer variable
int a = 7;
// A pointer variable that holds address of a.
int *p = &a;
// Value stored is value of variable "a"
cout<<"Value of Variable : "<<*p<<endl;
// It will print the address of the variable "a"
cout<<"Address of Variable : "<<p<<endl;
// reassign the value.
*p = 6;
cout<<"Value of the variable is now: "<<*p<<endl;
return 0;
}
Value of Variable : 7
Address of Variable : 0x6ffe34
Value of the variable is now: 6
Smart pointer is an abstract data type by using which we can make a normal pointer in such way that it can be used as memory management like file handling, network sockets etc., also it can do many things like automatic destruction, reference counting etc.
Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries.
Live Demo
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
T *p; // Actual pointer
public:
// Constructor
Smartpointer(T *ptr = NULL) {
p = ptr;
}
// Destructor
~Smartpointer() {
delete(p);
}
// Overloading dereferencing operator
T & operator * () {
return *p;
}
// Overloding arrow operator so that members of T can be accessed
// like a pointer
T * operator -> () {
return p;
}
};
int main() {
Smartpointer<int> p(new int());
*p = 26;
cout << "Value is: "<<*p;
return 0;
}
Value is: 26
shared_ptr is one of the form of smart pointer can be implemented by C++ libraries. It is a container of raw pointer and a reference counting (a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources) ownership structure of its contained pointer in cooperation with all copies of the shared_ptr.
An object which is referenced by the contained raw pointer will be destroyed only when the all copy is detroyed of shared_ptr.
Live Demo
#include<iostream>
#include<memory>
using namespace std;
int main() {
shared_ptr<int> ptr(new int(7));
shared_ptr<int> ptr1(new int(6));
cout << ptr << endl;
cout << ptr1 << endl;
// Returns the number of shared_ptr objects
// referring to the same managed object.
cout << ptr.use_count() << endl;
cout << ptr1.use_count() << endl;
// Relinquishes ownership of ptr on the object
// and pointer becomes NULL
ptr.reset();
cout << ptr.get() << endl;
cout << ptr1.use_count() << endl;
cout << ptr1.get() << endl;
return 0;
}
0xe80900
0xe80940
1
1
0
1
0xe80940 | [
{
"code": null,
"e": 1114,
"s": 1062,
"text": "Pointers are used to store the address of variable."
},
{
"code": null,
"e": 1129,
"s": 1114,
"text": "Type *pointer;"
},
{
"code": null,
"e": 1169,
"s": 1129,
"text": "Type *pointer;\nPointer = variable name;"
},
{
"code": null,
"e": 1217,
"s": 1169,
"text": "pointers are used to store address of variable."
},
{
"code": null,
"e": 1258,
"s": 1217,
"text": "pointers can have a null value assigned."
},
{
"code": null,
"e": 1306,
"s": 1258,
"text": "pointer can be referenced by pass by reference."
},
{
"code": null,
"e": 1366,
"s": 1306,
"text": "a pointer has its own memory address and size on the stack."
},
{
"code": null,
"e": 1377,
"s": 1366,
"text": " Live Demo"
},
{
"code": null,
"e": 1831,
"s": 1377,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n // A normal integer variable\n int a = 7;\n // A pointer variable that holds address of a.\n int *p = &a;\n // Value stored is value of variable \"a\"\n cout<<\"Value of Variable : \"<<*p<<endl;\n // It will print the address of the variable \"a\"\n cout<<\"Address of Variable : \"<<p<<endl;\n // reassign the value.\n *p = 6;\n cout<<\"Value of the variable is now: \"<<*p<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 1916,
"s": 1831,
"text": "Value of Variable : 7\nAddress of Variable : 0x6ffe34\nValue of the variable is now: 6"
},
{
"code": null,
"e": 2173,
"s": 1916,
"text": "Smart pointer is an abstract data type by using which we can make a normal pointer in such way that it can be used as memory management like file handling, network sockets etc., also it can do many things like automatic destruction, reference counting etc."
},
{
"code": null,
"e": 2391,
"s": 2173,
"text": "Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries."
},
{
"code": null,
"e": 2402,
"s": 2391,
"text": " Live Demo"
},
{
"code": null,
"e": 3024,
"s": 2402,
"text": "#include<iostream>\nusing namespace std;\n// A generic smart pointer class\ntemplate <class T>\nclass Smartpointer {\n T *p; // Actual pointer\n public:\n // Constructor\n Smartpointer(T *ptr = NULL) {\n p = ptr;\n }\n // Destructor\n ~Smartpointer() {\n delete(p);\n }\n // Overloading dereferencing operator\n T & operator * () {\n return *p;\n }\n // Overloding arrow operator so that members of T can be accessed\n // like a pointer\n T * operator -> () {\n return p;\n }\n};\nint main() {\n Smartpointer<int> p(new int());\n *p = 26;\n cout << \"Value is: \"<<*p;\n return 0;\n}"
},
{
"code": null,
"e": 3037,
"s": 3024,
"text": "Value is: 26"
},
{
"code": null,
"e": 3425,
"s": 3037,
"text": "shared_ptr is one of the form of smart pointer can be implemented by C++ libraries. It is a container of raw pointer and a reference counting (a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources) ownership structure of its contained pointer in cooperation with all copies of the shared_ptr."
},
{
"code": null,
"e": 3552,
"s": 3425,
"text": "An object which is referenced by the contained raw pointer will be destroyed only when the all copy is detroyed of shared_ptr."
},
{
"code": null,
"e": 3563,
"s": 3552,
"text": " Live Demo"
},
{
"code": null,
"e": 4129,
"s": 3563,
"text": "#include<iostream>\n#include<memory>\nusing namespace std;\nint main() {\n shared_ptr<int> ptr(new int(7));\n shared_ptr<int> ptr1(new int(6));\n cout << ptr << endl;\n cout << ptr1 << endl;\n // Returns the number of shared_ptr objects\n // referring to the same managed object.\n cout << ptr.use_count() << endl;\n cout << ptr1.use_count() << endl;\n // Relinquishes ownership of ptr on the object\n // and pointer becomes NULL\n ptr.reset();\n cout << ptr.get() << endl;\n cout << ptr1.use_count() << endl;\n cout << ptr1.get() << endl;\n return 0;\n}"
},
{
"code": null,
"e": 4164,
"s": 4129,
"text": "0xe80900\n0xe80940\n1\n1\n0\n1\n0xe80940"
}
] |
Cat Swarm Optimization - GeeksforGeeks | 21 Aug, 2021
Nature is replete with social compartments to carry out various jobs. Even if the final goal of all persons and collective conduct is survival, for various reasons: hunting, protection, navigation and foraging animals work and interact in groups, herds, schools, colonies and flocks. It is very interesting that creatures find the optimal situations and perform tasks efficiently in groups. It is clear that such optimal and efficient conduct has been evolved throughout the millennia. So we inspire them to fix our issues is fairly logical. This is the main aim of a study field called swarm intelligence (SI). Many algorithms have been proposed in the field of swarm intelligence (SI) e.g. Ant Colony Optimization (ACO), Particle Swarm Optimization (PSO), Grey Wolf Optimizer (GWO) etc.
In this article, we shall discuss the Cat Swarm Optimization technique which is a swarm-based optimization.
Cat Swarm Optimization is clearly inspired by the behaviour of cats in the real world. According to biology, there are about 32 different cat species from lions to cheetahs and from tigers to domestic cats. Even though they live in quite different environments many behavioural attributes are similar. Despite being in most times inactive, cats have a strong curiosity.
Before defining the mathematical model of the algorithm, one must know that there are two different states of being for any cat.
Seeking mode: Cats are inactive in this state i.e. resting, looking around or in a state to move to another location.Tracking mode: Cats are active in this state i.e. they change their current position.
Seeking mode: Cats are inactive in this state i.e. resting, looking around or in a state to move to another location.
Tracking mode: Cats are active in this state i.e. they change their current position.
Letβs define the model of cat swarm optimization. Every cat in a solution space has its own N dimensions dN, velocity for each dimension , a flag that suggests whether the cat is in either of the two modes (seeking or tracking) and finally a fitness value that represents the accommodation of cats to the fitness function.
We desire to find the optimal position for a cat.
Seeking mode: As already mentioned cats in this state are inactive. This mode has four essential factors namely: seeking memory pool (SMP), seeking a range of the selected dimension (SRD), counts of dimension to change (CDC), and self-position considering (SPC).
SMP: Defines the memory for each cat indicating the points pursued by a cat.
SRD: declares the mutative ratio for the selected dimensions.
CDC: How many dimensions will be varied is indicated by this factor.
SPC: Whether the position at which the cat is already placed will be a candidate point for a cat to move to. It is a Boolean value (either true or false).
NOTE: Regardless of the value of SPC the value of SMP is not influenced.
1. If SPC is True Then
j=SMP
Else
j=SMP-1
2. Present position of cat Ck is copied j times.
3. Depending on the value of CDC the value of SRD is either decremented or incremented.
4. Calculate the Fitness value (FV) of all candidate points.
5. If all the FV are not equal, FV are converted to selection probability:
where i ranges in (0,j)
can be set to or depending on the goal of fitness function either
maximize or minimize.
6. Randomly select the candidate points and replace the current position of cat Ck.
Tracing mode: Once a cat is in tracing mode, the cat is assigned with its velocity as .
1. Update the velocites of each cat according to:
where d ranges in [1,N]
c1 is a constant, r1 ranges in [0,1] and and are the position of cat Ck in
dimension d and the position of a cat with the best FV respectively.
2. If Then
Else
CSO algorithm
In order to merge both the modes, we must keep in mind that the cats spend most of the time in seeking mode. Therefore, we define a mixture ratio (MR) that suggests how much of either of the modes to take into account while performing CSO. It is quite evident that we must keep the value of MR very low to account for cats spending the most time in seeking mode.
1. Create M cats.
2. Randomly drop the M cats in N dimensional solution space. Assign the velocities of each cat in
accordance to .
3. Distribute the cats to tracing mode according to MR and rest to seeking mode.
4. Apply the position of the cat into the fitness function and calculate the fitness value FV.
5. Move the cats according to their flag value. If Ck is in tracing mode apply the tracing mode
process to it, if not then apply seeking mode process.
6. Redistribute the cats according to MR.
7. Repeat from step 4 to 6 until termination condition is met.
By applying the CSO we get the which is the position of a cat with the best FV.
This is how the CSO algorithm works.
https://link.springer.com/chapter/10.1007/978-3-540-36668-3_94
surinderdawra388
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Singular Value Decomposition (SVD)
k-nearest neighbor algorithm in Python
Python | Decision Tree Regression using sklearn
DBSCAN Clustering in ML | Density based clustering
Q-Learning in Python | [
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 26379,
"s": 25589,
"text": "Nature is replete with social compartments to carry out various jobs. Even if the final goal of all persons and collective conduct is survival, for various reasons: hunting, protection, navigation and foraging animals work and interact in groups, herds, schools, colonies and flocks. It is very interesting that creatures find the optimal situations and perform tasks efficiently in groups. It is clear that such optimal and efficient conduct has been evolved throughout the millennia. So we inspire them to fix our issues is fairly logical. This is the main aim of a study field called swarm intelligence (SI). Many algorithms have been proposed in the field of swarm intelligence (SI) e.g. Ant Colony Optimization (ACO), Particle Swarm Optimization (PSO), Grey Wolf Optimizer (GWO) etc. "
},
{
"code": null,
"e": 26487,
"s": 26379,
"text": "In this article, we shall discuss the Cat Swarm Optimization technique which is a swarm-based optimization."
},
{
"code": null,
"e": 26857,
"s": 26487,
"text": "Cat Swarm Optimization is clearly inspired by the behaviour of cats in the real world. According to biology, there are about 32 different cat species from lions to cheetahs and from tigers to domestic cats. Even though they live in quite different environments many behavioural attributes are similar. Despite being in most times inactive, cats have a strong curiosity."
},
{
"code": null,
"e": 26986,
"s": 26857,
"text": "Before defining the mathematical model of the algorithm, one must know that there are two different states of being for any cat."
},
{
"code": null,
"e": 27189,
"s": 26986,
"text": "Seeking mode: Cats are inactive in this state i.e. resting, looking around or in a state to move to another location.Tracking mode: Cats are active in this state i.e. they change their current position."
},
{
"code": null,
"e": 27307,
"s": 27189,
"text": "Seeking mode: Cats are inactive in this state i.e. resting, looking around or in a state to move to another location."
},
{
"code": null,
"e": 27393,
"s": 27307,
"text": "Tracking mode: Cats are active in this state i.e. they change their current position."
},
{
"code": null,
"e": 27716,
"s": 27393,
"text": "Letβs define the model of cat swarm optimization. Every cat in a solution space has its own N dimensions dN, velocity for each dimension , a flag that suggests whether the cat is in either of the two modes (seeking or tracking) and finally a fitness value that represents the accommodation of cats to the fitness function."
},
{
"code": null,
"e": 27766,
"s": 27716,
"text": "We desire to find the optimal position for a cat."
},
{
"code": null,
"e": 28029,
"s": 27766,
"text": "Seeking mode: As already mentioned cats in this state are inactive. This mode has four essential factors namely: seeking memory pool (SMP), seeking a range of the selected dimension (SRD), counts of dimension to change (CDC), and self-position considering (SPC)."
},
{
"code": null,
"e": 28106,
"s": 28029,
"text": "SMP: Defines the memory for each cat indicating the points pursued by a cat."
},
{
"code": null,
"e": 28168,
"s": 28106,
"text": "SRD: declares the mutative ratio for the selected dimensions."
},
{
"code": null,
"e": 28237,
"s": 28168,
"text": "CDC: How many dimensions will be varied is indicated by this factor."
},
{
"code": null,
"e": 28392,
"s": 28237,
"text": "SPC: Whether the position at which the cat is already placed will be a candidate point for a cat to move to. It is a Boolean value (either true or false)."
},
{
"code": null,
"e": 28465,
"s": 28392,
"text": "NOTE: Regardless of the value of SPC the value of SMP is not influenced."
},
{
"code": null,
"e": 29022,
"s": 28465,
"text": "1. If SPC is True Then\n j=SMP\n Else\n j=SMP-1\n2. Present position of cat Ck is copied j times.\n3. Depending on the value of CDC the value of SRD is either decremented or incremented.\n4. Calculate the Fitness value (FV) of all candidate points.\n5. If all the FV are not equal, FV are converted to selection probability:\n where i ranges in (0,j)\n\n can be set to or depending on the goal of fitness function either \n\n maximize or minimize.\n\n 6. Randomly select the candidate points and replace the current position of cat Ck."
},
{
"code": null,
"e": 29110,
"s": 29022,
"text": "Tracing mode: Once a cat is in tracing mode, the cat is assigned with its velocity as ."
},
{
"code": null,
"e": 29394,
"s": 29110,
"text": "1. Update the velocites of each cat according to:\n where d ranges in [1,N]\n\n \n\n c1 is a constant, r1 ranges in [0,1] and and are the position of cat Ck in \n\n dimension d and the position of a cat with the best FV respectively.\n\n2. If Then\n\n \n\n Else\n\n "
},
{
"code": null,
"e": 29408,
"s": 29394,
"text": "CSO algorithm"
},
{
"code": null,
"e": 29771,
"s": 29408,
"text": "In order to merge both the modes, we must keep in mind that the cats spend most of the time in seeking mode. Therefore, we define a mixture ratio (MR) that suggests how much of either of the modes to take into account while performing CSO. It is quite evident that we must keep the value of MR very low to account for cats spending the most time in seeking mode."
},
{
"code": null,
"e": 30350,
"s": 29771,
"text": "1. Create M cats.\n2. Randomly drop the M cats in N dimensional solution space. Assign the velocities of each cat in \n accordance to .\n\n3. Distribute the cats to tracing mode according to MR and rest to seeking mode.\n\n4. Apply the position of the cat into the fitness function and calculate the fitness value FV.\n\n5. Move the cats according to their flag value. If Ck is in tracing mode apply the tracing mode \n\n process to it, if not then apply seeking mode process.\n\n6. Redistribute the cats according to MR.\n\n7. Repeat from step 4 to 6 until termination condition is met."
},
{
"code": null,
"e": 30431,
"s": 30350,
"text": "By applying the CSO we get the which is the position of a cat with the best FV."
},
{
"code": null,
"e": 30468,
"s": 30431,
"text": "This is how the CSO algorithm works."
},
{
"code": null,
"e": 30531,
"s": 30468,
"text": "https://link.springer.com/chapter/10.1007/978-3-540-36668-3_94"
},
{
"code": null,
"e": 30548,
"s": 30531,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30565,
"s": 30548,
"text": "Machine Learning"
},
{
"code": null,
"e": 30582,
"s": 30565,
"text": "Machine Learning"
},
{
"code": null,
"e": 30680,
"s": 30582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30713,
"s": 30680,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 30754,
"s": 30713,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 30782,
"s": 30754,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 30818,
"s": 30782,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 30873,
"s": 30818,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 30908,
"s": 30873,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 30947,
"s": 30908,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 30995,
"s": 30947,
"text": "Python | Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 31046,
"s": 30995,
"text": "DBSCAN Clustering in ML | Density based clustering"
}
] |
C++ Program to Compare Binary and Sequential Search | Binary Search and Sequential or Linear Search both are used in computer programming to search an element. The time complexity of Binary Search is O(log(n)) and Sequential Search is O(n).
Begin
Algorithm for Binary Search:
BinarySearch() function with βarrβ the array of data and βnβ the number of values, start and end index, iteration count and element to be searched in the argument list.
Increment iteration counter and compare the item value with the a[mid].
If item < a[mid] choose first half otherwise second half to proceed further.
Return iteration value on successful search.
End
#include<iostream>
using namespace std;
int BinarySearch(int a[], int start, int end, int item, int iter) {
int i, mid;
cout<<"\niteration "<<iter+1;
iter++;
mid = start + (end-start+1)/2;
if(item > a[end] || item < a[start] || mid == end) {
cout<<"\nNot found";
return iter;
} else if(item == a[mid]) {
cout<<"\n item found at "<<mid<<" index.";
return iter;
} else if(item == a[start]) {
cout<<"\n item found at "<<start<<" index.";
return iter;
} else if(item == a[end]) {
cout<<"\n item found at "<<end<<" index.";
return iter;
} else if(item > a[mid])
BinarySearch(a, mid, 9, item, iter);
else
BinarySearch(a, start, mid, item, iter);
}
int LinearSearch(int a[], int n, int item) {
int i;
for(i = 0; i < n; i++) {
cout<<"\niteration "<<i+1;
if(a[i] == item) {
cout<<"\n item found at "<<i<<" index.";
return i+1;
}
}
cout<<"\nNot found";
}
int main() {
int n, i, B, L, a[10]={2, 7, 14, 24, 26, 35, 38, 41, 49, 53};
cout<<"\nEnter the element to be searched: ";
cin>>n;
cout<<"\n\n\t\t\tBinary Search :";
B = BinarySearch(a, 0, 9, n, 0);
cout<<"\n\n\t\t\tLinear Search :";
L = LinearSearch(a, 10, n);
if(L > B)
cout<<"\n\nBinary search is better for this search.";
else if(L < B)
cout<<"\n\nLinear search is better for this search.";
else
cout<<"\n\nBoth are equally efficient for this search.";
return 0;
}
Enter the element to be searched: 7
Binary Search :
iteration 1
iteration 2
iteration 3
iteration 4
item found at 1 index.
Linear Search :
iteration 1
iteration 2
item found at 1 index.
Linear search is better for this search.
Enter the element to be searched: 53
Binary Search :
iteration 1
item found at 9 index.
Linear Search :
iteration 1
iteration 2
iteration 3
iteration 4
iteration 5
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
item found at 9 index.
Binary search is better for this search.
Enter the element to be searched: 1
Binary Search :
iteration 1
Not found
Linear Search :
iteration 1
iteration 2
iteration 3
iteration 4
iteration 5
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
Not found
Binary search is better for this search. | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "Binary Search and Sequential or Linear Search both are used in computer programming to search an element. The time complexity of Binary Search is O(log(n)) and Sequential Search is O(n)."
},
{
"code": null,
"e": 1666,
"s": 1249,
"text": "Begin\n Algorithm for Binary Search:\n BinarySearch() function with βarrβ the array of data and βnβ the number of values, start and end index, iteration count and element to be searched in the argument list.\n Increment iteration counter and compare the item value with the a[mid].\n If item < a[mid] choose first half otherwise second half to proceed further.\n Return iteration value on successful search.\nEnd"
},
{
"code": null,
"e": 3197,
"s": 1666,
"text": "#include<iostream>\nusing namespace std;\nint BinarySearch(int a[], int start, int end, int item, int iter) {\n int i, mid;\n cout<<\"\\niteration \"<<iter+1;\n iter++;\n mid = start + (end-start+1)/2;\n if(item > a[end] || item < a[start] || mid == end) {\n cout<<\"\\nNot found\";\n return iter;\n } else if(item == a[mid]) {\n cout<<\"\\n item found at \"<<mid<<\" index.\";\n return iter;\n } else if(item == a[start]) {\n cout<<\"\\n item found at \"<<start<<\" index.\";\n return iter;\n } else if(item == a[end]) {\n cout<<\"\\n item found at \"<<end<<\" index.\";\n return iter;\n } else if(item > a[mid])\n BinarySearch(a, mid, 9, item, iter);\n else\n BinarySearch(a, start, mid, item, iter);\n }\n int LinearSearch(int a[], int n, int item) {\n int i;\n for(i = 0; i < n; i++) {\n cout<<\"\\niteration \"<<i+1;\n if(a[i] == item) {\n cout<<\"\\n item found at \"<<i<<\" index.\";\n return i+1;\n }\n }\n cout<<\"\\nNot found\";\n}\nint main() {\n int n, i, B, L, a[10]={2, 7, 14, 24, 26, 35, 38, 41, 49, 53};\n cout<<\"\\nEnter the element to be searched: \";\n cin>>n;\n cout<<\"\\n\\n\\t\\t\\tBinary Search :\";\n B = BinarySearch(a, 0, 9, n, 0);\n cout<<\"\\n\\n\\t\\t\\tLinear Search :\";\n L = LinearSearch(a, 10, n);\n if(L > B)\n cout<<\"\\n\\nBinary search is better for this search.\";\n else if(L < B)\n cout<<\"\\n\\nLinear search is better for this search.\";\n else\n cout<<\"\\n\\nBoth are equally efficient for this search.\";\n return 0;\n}"
},
{
"code": null,
"e": 3975,
"s": 3197,
"text": "Enter the element to be searched: 7\nBinary Search :\niteration 1\niteration 2\niteration 3\niteration 4\nitem found at 1 index.\nLinear Search :\niteration 1\niteration 2\nitem found at 1 index.\nLinear search is better for this search.\nEnter the element to be searched: 53\nBinary Search :\niteration 1\nitem found at 9 index.\nLinear Search :\niteration 1\niteration 2\niteration 3\niteration 4\niteration 5\niteration 6\niteration 7\niteration 8\niteration 9\niteration 10\nitem found at 9 index.\nBinary search is better for this search.\nEnter the element to be searched: 1\nBinary Search :\niteration 1\nNot found\nLinear Search :\niteration 1\niteration 2\niteration 3\niteration 4\niteration 5\niteration 6\niteration 7\niteration 8\niteration 9\niteration 10\nNot found\nBinary search is better for this search."
}
] |
Full binary tree | Practice | GeeksforGeeks | Given a Binary Tree. Check whether the Binary tree is a full binary tree or not.
Example 1:
Input:
1
/ \
2 3
/ \
4 5
Output: 1
Explanation: Every node except leaf node
has two children so it is a full tree.
Example 2:
Input:
1
/ \
2 3
/
4
Output: 0
Explanation: Node 2 has only one child
so this is not a full tree.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isFullTree() which takes the root node of the tree as input and returns True if the given Binary Tree is full. Else, it returns False. (The driver code will print 1 if the returned value is true, otherwise 0).
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1<=Number of nodes<=1000
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
imaniket2 months ago
bool isFullTree (struct Node* root)
{
if(!root) return false;
if(!root->left && !root->right) return true;
if(isFullTree(root->left) && isFullTree(root->right)) return true;
else return false;
}
0
mayank20212 months ago
C++bool isFullTree (struct Node* root){
if( !root || (!root->left && !root->right) )return 1;else if((root->left && !root->right) || (!root->left && root->right))return 0;elsereturn isFullTree(root->left) && isFullTree(root->right);}
+1
feyza2 months ago
class GfG
{
boolean isFullTree(Node node)
{
if(node == null) return true;
if(node.left == null && node.right == null) return true;
if(node.left != null && node.right != null)
{
return (isFullTree(node.right) && isFullTree(node.left));
}
return false;
}
}
0
hamidnourashraf2 months ago
def isFullTree(root):
if root is None:
return True
if root.left is None and root.right is None:
return True
if root.left is None and root.right is not None:
return False
if root.left is not None and root.right is None:
return False
return (isFullTree(root.left) and isFullTree(root.right))
+1
shashikantsolanki0423 months ago
C++ Level order traversal Soln.
bool isFullTree (struct Node* root){
queue<Node*>q;
q.push(root);
while(!q.empty()){
Node* top = q.front();
int ctr = 0;
q.pop();
if(top->left){
ctr++;
q.push(top->left);
}
if(top->right){
ctr++;
q.push(top->right);
}
if(ctr == 1){
return false;
}
}
return true;
}
0
bhushan5613 months ago
C++ Solution
bool isFullTree (struct Node* root){//add code here.if(root==NULL)return true;else if(root->left==NULL && root->right==NULL)return true;else if(root->left!=NULL && root->right!=NULL)return isFullTree(root->left) && isFullTree(root->right);else if(root->left || root->right)return false;}
0
ee19b0373 months ago
bool isFullTree (struct Node* root)
{
//add code here
if(!root) return 1;
if(root->left==NULL ^ root->right==NULL) return 0;
return isFullTree(root->left) && isFullTree(root->right);
}
0
amanpandey30073 months ago
bool isFullTree (struct Node* root){ if(!root) return true; if(!root->left and !root->right) return true; if(!root->left or !root->right) return false; bool a=isFullTree(root->left); bool b=isFullTree (root->right); return a and b; }
0
harishk2711994 months ago
void solve(Node* root , int & f){
if(root==NULL) return;
if((root->left and !root->right ) or (!root->left and root->right )) {
f=0;
return ;
}
if(root->left and root->right){
solve(root->left,f);
solve(root->right,f);
}
}
bool isFullTree (struct Node* root)
{
//add code here.
int f=1;
solve(root,f);
return f;
}
0
anjalipatel94314 months ago
bool isFullTree (struct Node* root){//add code here. if(root==NULL || (root->left==NULL && root->right==NULL) ) return 1; if(root->left==NULL && root->right!=NULL) return 0; if(root->left!=NULL && root->right==NULL ) return 0; return isFullTree(root->left) && isFullTree(root->right);}
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": 319,
"s": 238,
"text": "Given a Binary Tree. Check whether the Binary tree is a full binary tree or not."
},
{
"code": null,
"e": 330,
"s": 319,
"text": "Example 1:"
},
{
"code": null,
"e": 490,
"s": 330,
"text": "Input:\n 1\n / \\\n 2 3\n / \\\n 4 5\nOutput: 1\nExplanation: Every node except leaf node\nhas two children so it is a full tree.\n"
},
{
"code": null,
"e": 501,
"s": 490,
"text": "Example 2:"
},
{
"code": null,
"e": 645,
"s": 501,
"text": "Input:\n 1\n / \\\n 2 3\n / \n 4 \nOutput: 0\nExplanation: Node 2 has only one child\nso this is not a full tree."
},
{
"code": null,
"e": 954,
"s": 647,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isFullTree() which takes the root node of the tree as input and returns True if the given Binary Tree is full. Else, it returns False. (The driver code will print 1 if the returned value is true, otherwise 0)."
},
{
"code": null,
"e": 1035,
"s": 954,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 1073,
"s": 1035,
"text": "Constraints:\n1<=Number of nodes<=1000"
},
{
"code": null,
"e": 1382,
"s": 1073,
"text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1384,
"s": 1382,
"text": "0"
},
{
"code": null,
"e": 1405,
"s": 1384,
"text": "imaniket2 months ago"
},
{
"code": null,
"e": 1611,
"s": 1405,
"text": "bool isFullTree (struct Node* root)\n{\n if(!root) return false;\n if(!root->left && !root->right) return true;\n \n if(isFullTree(root->left) && isFullTree(root->right)) return true;\n else return false;\n}"
},
{
"code": null,
"e": 1613,
"s": 1611,
"text": "0"
},
{
"code": null,
"e": 1636,
"s": 1613,
"text": "mayank20212 months ago"
},
{
"code": null,
"e": 1676,
"s": 1636,
"text": "C++bool isFullTree (struct Node* root){"
},
{
"code": null,
"e": 1871,
"s": 1676,
"text": "if( !root || (!root->left && !root->right) )return 1;else if((root->left && !root->right) || (!root->left && root->right))return 0;elsereturn isFullTree(root->left) && isFullTree(root->right);}"
},
{
"code": null,
"e": 1874,
"s": 1871,
"text": "+1"
},
{
"code": null,
"e": 1892,
"s": 1874,
"text": "feyza2 months ago"
},
{
"code": null,
"e": 2238,
"s": 1892,
"text": "class GfG\n{\n\tboolean isFullTree(Node node)\n {\n if(node == null) return true;\n \n if(node.left == null && node.right == null) return true;\n \n if(node.left != null && node.right != null)\n {\n return (isFullTree(node.right) && isFullTree(node.left));\n } \n return false;\n }\n}"
},
{
"code": null,
"e": 2240,
"s": 2238,
"text": "0"
},
{
"code": null,
"e": 2268,
"s": 2240,
"text": "hamidnourashraf2 months ago"
},
{
"code": null,
"e": 2610,
"s": 2268,
"text": "def isFullTree(root):\n if root is None:\n return True\n if root.left is None and root.right is None:\n return True\n if root.left is None and root.right is not None:\n return False\n if root.left is not None and root.right is None:\n return False\n return (isFullTree(root.left) and isFullTree(root.right))"
},
{
"code": null,
"e": 2613,
"s": 2610,
"text": "+1"
},
{
"code": null,
"e": 2646,
"s": 2613,
"text": "shashikantsolanki0423 months ago"
},
{
"code": null,
"e": 2678,
"s": 2646,
"text": "C++ Level order traversal Soln."
},
{
"code": null,
"e": 3097,
"s": 2680,
"text": "bool isFullTree (struct Node* root){\n queue<Node*>q;\n q.push(root);\n while(!q.empty()){\n Node* top = q.front();\n int ctr = 0;\n q.pop();\n if(top->left){\n ctr++;\n q.push(top->left);\n }\n if(top->right){\n ctr++;\n q.push(top->right);\n }\n if(ctr == 1){\n return false;\n }\n }\n return true;\n}"
},
{
"code": null,
"e": 3101,
"s": 3099,
"text": "0"
},
{
"code": null,
"e": 3124,
"s": 3101,
"text": "bhushan5613 months ago"
},
{
"code": null,
"e": 3137,
"s": 3124,
"text": "C++ Solution"
},
{
"code": null,
"e": 3429,
"s": 3139,
"text": "bool isFullTree (struct Node* root){//add code here.if(root==NULL)return true;else if(root->left==NULL && root->right==NULL)return true;else if(root->left!=NULL && root->right!=NULL)return isFullTree(root->left) && isFullTree(root->right);else if(root->left || root->right)return false;} "
},
{
"code": null,
"e": 3431,
"s": 3429,
"text": "0"
},
{
"code": null,
"e": 3452,
"s": 3431,
"text": "ee19b0373 months ago"
},
{
"code": null,
"e": 3654,
"s": 3452,
"text": "bool isFullTree (struct Node* root)\n{\n//add code here\n if(!root) return 1;\n if(root->left==NULL ^ root->right==NULL) return 0;\n return isFullTree(root->left) && isFullTree(root->right);\n \n}"
},
{
"code": null,
"e": 3656,
"s": 3654,
"text": "0"
},
{
"code": null,
"e": 3683,
"s": 3656,
"text": "amanpandey30073 months ago"
},
{
"code": null,
"e": 3937,
"s": 3683,
"text": "bool isFullTree (struct Node* root){ if(!root) return true; if(!root->left and !root->right) return true; if(!root->left or !root->right) return false; bool a=isFullTree(root->left); bool b=isFullTree (root->right); return a and b; }"
},
{
"code": null,
"e": 3939,
"s": 3937,
"text": "0"
},
{
"code": null,
"e": 3965,
"s": 3939,
"text": "harishk2711994 months ago"
},
{
"code": null,
"e": 4372,
"s": 3965,
"text": "void solve(Node* root , int & f){\n if(root==NULL) return;\n if((root->left and !root->right ) or (!root->left and root->right )) {\n f=0;\n return ;\n \n }\n if(root->left and root->right){\n solve(root->left,f);\n solve(root->right,f);\n \n }\n}\nbool isFullTree (struct Node* root)\n{\n//add code here.\n int f=1;\n solve(root,f);\n return f;\n \n \n }"
},
{
"code": null,
"e": 4374,
"s": 4372,
"text": "0"
},
{
"code": null,
"e": 4402,
"s": 4374,
"text": "anjalipatel94314 months ago"
},
{
"code": null,
"e": 4701,
"s": 4402,
"text": "bool isFullTree (struct Node* root){//add code here. if(root==NULL || (root->left==NULL && root->right==NULL) ) return 1; if(root->left==NULL && root->right!=NULL) return 0; if(root->left!=NULL && root->right==NULL ) return 0; return isFullTree(root->left) && isFullTree(root->right);}"
},
{
"code": null,
"e": 4847,
"s": 4701,
"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": 4883,
"s": 4847,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4893,
"s": 4883,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4903,
"s": 4893,
"text": "\nContest\n"
},
{
"code": null,
"e": 4966,
"s": 4903,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5114,
"s": 4966,
"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": 5322,
"s": 5114,
"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": 5428,
"s": 5322,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JavaScript getElementsByClassName() Vs getElementById() Method - GeeksforGeeks | 22 Nov, 2021
In this article, we will learn about the get Element methods in Javascript for manipulating the HTML elements. We will also understand their implementation through the examples.
JavaScript getElementsByClassName() Method: This method returns an object containing all with the specified class name, as a collection of HTML Collection object representing a collection of the nodes. The elements returned can be accessed using its index starting from zero.
Syntax:
document.getElementsByClassName("class_name");
Parameters: The class name of the elements that you want to get.
Return Value: This function returns the HTML Collection object.
Example 1: This example describes the getElementsByClassName() method to find all the HTML element containing the same class name.
HTML
<!DOCTYPE html><html> <head> <style> h1 { color: green; } body { text-align: center; } button { background-color: black; color: white; width: 300px; padding: 10px; margin: 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <button onclick="yellow()" class="black yellow"> Click to change to yellow button </button> <br> <button onclick="green()" class="green"> Click to change to green button </button> <br> </div> <script> function yellow() { document.getElementsByClassName('yellow')[0].style.backgroundColor = 'yellow'; } function green() { var elements = document.getElementsByClassName('green'); for(var i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = 'green'; } } </script></body> </html>
Output:
getElementByClassName() Method
JavaScript getElementById() Method: This method returns the element that has the ID attribute with the specified value. It is the most used HTML DOM method to manipulate, or get info from, an element on your document.
Syntax:
document.getElementById("id_name");
Parameters: This function accepts a single parameter i.e. element ID and it is used to hold the ID of the element.
Return Value: This function returns the ID attributeβs value of the element.
Example 2: This example describes the getElementById() method to specify the id value for which the behavior of the element is changing by applying the style properties.
HTML
<!DOCTYPE html><html> <head> <script> // Function to change the // color of element function color() { var demo = document.getElementById("heading"); demo.style.color = "green"; } </script></head> <body style="text-align:center"> <h1 id="heading">GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <!-- Click on the button to change color --> <input type="button" onclick="color()" value="Click here to change heading color" /></body> </html>
Output: From the output, we can notice that this method modifies the HTML element for the specified id value, on clicking the button.
getElementById() Method
Difference between getElementsByClassName() Vs getElementById() Method:
1.
This method returns an element object that specifies the element for which id property matches with the specified string ie., it returns a single DOM element whose id matches the specific query.
This method returns an array-like object of all child-element that contains all the given class name(s) ie., it will return an HtmlCollection β an array-like structure containing the DOM elements that matched the query, that is needed to iterate through each element in the array to apply the style.
2.
It accepts the id as a parameter value to locate that specific element.
It takes the name which is a string, as a parameter value that represents the class name(s) to match. In the case of multiple class names, it can be separated by whitespace.
3.
It returns a null value if no matching element is found in the document.
It returns a live HTMLCollection, with the possible length as 0 if no matching elements are found in the document.
bhaskargeeksforgeeks
JavaScript-Methods
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 26249,
"s": 26221,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 26427,
"s": 26249,
"text": "In this article, we will learn about the get Element methods in Javascript for manipulating the HTML elements. We will also understand their implementation through the examples."
},
{
"code": null,
"e": 26703,
"s": 26427,
"text": "JavaScript getElementsByClassName() Method: This method returns an object containing all with the specified class name, as a collection of HTML Collection object representing a collection of the nodes. The elements returned can be accessed using its index starting from zero."
},
{
"code": null,
"e": 26711,
"s": 26703,
"text": "Syntax:"
},
{
"code": null,
"e": 26758,
"s": 26711,
"text": "document.getElementsByClassName(\"class_name\");"
},
{
"code": null,
"e": 26823,
"s": 26758,
"text": "Parameters: The class name of the elements that you want to get."
},
{
"code": null,
"e": 26887,
"s": 26823,
"text": "Return Value: This function returns the HTML Collection object."
},
{
"code": null,
"e": 27018,
"s": 26887,
"text": "Example 1: This example describes the getElementsByClassName() method to find all the HTML element containing the same class name."
},
{
"code": null,
"e": 27023,
"s": 27018,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } body { text-align: center; } button { background-color: black; color: white; width: 300px; padding: 10px; margin: 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <button onclick=\"yellow()\" class=\"black yellow\"> Click to change to yellow button </button> <br> <button onclick=\"green()\" class=\"green\"> Click to change to green button </button> <br> </div> <script> function yellow() { document.getElementsByClassName('yellow')[0].style.backgroundColor = 'yellow'; } function green() { var elements = document.getElementsByClassName('green'); for(var i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = 'green'; } } </script></body> </html>",
"e": 28072,
"s": 27023,
"text": null
},
{
"code": null,
"e": 28080,
"s": 28072,
"text": "Output:"
},
{
"code": null,
"e": 28111,
"s": 28080,
"text": "getElementByClassName() Method"
},
{
"code": null,
"e": 28329,
"s": 28111,
"text": "JavaScript getElementById() Method: This method returns the element that has the ID attribute with the specified value. It is the most used HTML DOM method to manipulate, or get info from, an element on your document."
},
{
"code": null,
"e": 28337,
"s": 28329,
"text": "Syntax:"
},
{
"code": null,
"e": 28373,
"s": 28337,
"text": "document.getElementById(\"id_name\");"
},
{
"code": null,
"e": 28488,
"s": 28373,
"text": "Parameters: This function accepts a single parameter i.e. element ID and it is used to hold the ID of the element."
},
{
"code": null,
"e": 28565,
"s": 28488,
"text": "Return Value: This function returns the ID attributeβs value of the element."
},
{
"code": null,
"e": 28735,
"s": 28565,
"text": "Example 2: This example describes the getElementById() method to specify the id value for which the behavior of the element is changing by applying the style properties."
},
{
"code": null,
"e": 28740,
"s": 28735,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script> // Function to change the // color of element function color() { var demo = document.getElementById(\"heading\"); demo.style.color = \"green\"; } </script></head> <body style=\"text-align:center\"> <h1 id=\"heading\">GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <!-- Click on the button to change color --> <input type=\"button\" onclick=\"color()\" value=\"Click here to change heading color\" /></body> </html>",
"e": 29264,
"s": 28740,
"text": null
},
{
"code": null,
"e": 29398,
"s": 29264,
"text": "Output: From the output, we can notice that this method modifies the HTML element for the specified id value, on clicking the button."
},
{
"code": null,
"e": 29422,
"s": 29398,
"text": "getElementById() Method"
},
{
"code": null,
"e": 29494,
"s": 29422,
"text": "Difference between getElementsByClassName() Vs getElementById() Method:"
},
{
"code": null,
"e": 29497,
"s": 29494,
"text": "1."
},
{
"code": null,
"e": 29692,
"s": 29497,
"text": "This method returns an element object that specifies the element for which id property matches with the specified string ie., it returns a single DOM element whose id matches the specific query."
},
{
"code": null,
"e": 29992,
"s": 29692,
"text": "This method returns an array-like object of all child-element that contains all the given class name(s) ie., it will return an HtmlCollection β an array-like structure containing the DOM elements that matched the query, that is needed to iterate through each element in the array to apply the style."
},
{
"code": null,
"e": 29995,
"s": 29992,
"text": "2."
},
{
"code": null,
"e": 30068,
"s": 29995,
"text": "It accepts the id as a parameter value to locate that specific element. "
},
{
"code": null,
"e": 30242,
"s": 30068,
"text": "It takes the name which is a string, as a parameter value that represents the class name(s) to match. In the case of multiple class names, it can be separated by whitespace."
},
{
"code": null,
"e": 30245,
"s": 30242,
"text": "3."
},
{
"code": null,
"e": 30318,
"s": 30245,
"text": "It returns a null value if no matching element is found in the document."
},
{
"code": null,
"e": 30433,
"s": 30318,
"text": "It returns a live HTMLCollection, with the possible length as 0 if no matching elements are found in the document."
},
{
"code": null,
"e": 30454,
"s": 30433,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 30473,
"s": 30454,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 30478,
"s": 30473,
"text": "HTML"
},
{
"code": null,
"e": 30489,
"s": 30478,
"text": "JavaScript"
},
{
"code": null,
"e": 30506,
"s": 30489,
"text": "Web Technologies"
},
{
"code": null,
"e": 30511,
"s": 30506,
"text": "HTML"
},
{
"code": null,
"e": 30609,
"s": 30511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30633,
"s": 30609,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 30674,
"s": 30633,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 30711,
"s": 30674,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30740,
"s": 30711,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30760,
"s": 30740,
"text": "Angular File Upload"
},
{
"code": null,
"e": 30800,
"s": 30760,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30845,
"s": 30800,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30906,
"s": 30845,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30975,
"s": 30906,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
C++ Program for Block swap algorithm for array rotation - GeeksforGeeks | 13 Dec, 2021
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.
Rotation of the above array by 2 will make array
Algorithm :
Initialize A = arr[0..d-1] and B = arr[d..n-1]
1) Do following until size of A is equal to size of B
a) If A is shorter, divide B into Bl and Br such that Br is of same
length as A. Swap A and Br to change ABlBr into BrBlA. Now A
is at its final place, so recur on pieces of B.
b) If A is longer, divide A into Al and Ar such that Al is of same
length as B Swap Al and B to change AlArB into BArAl. Now B
is at its final place, so recur on pieces of A.
2) Finally when A and B are of equal size, block swap them.
Recursive Implementation:
C++
#include <bits/stdc++.h>using namespace std; /*Prototype for utility functions */void printArray(int arr[], int size); void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n) { /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else /* If B is shorter*/ { swap(arr, 0, d, n - d); leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/ } } /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size) { int i; for(i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } /*This function swaps d elements starting at index fi with d elements starting at index si */void swap(int arr[], int fi, int si, int d) { int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } } // Driver Codeint main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); return 0; } // This code is contributed by rathbhupendra
Iterative Implementation: Here is iterative implementation of the same algorithm. Same utility function swap() is used here.
C++
// C++ code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if (d == 0 || d == n) return; i = d; j = n - d; while (i != j) { if (i < j) /*A is shorter*/ { swap(arr, d - i, d + j - i, i); j -= i; } else /*B is shorter*/ { swap(arr, d - i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d - i, d, i);} // This code is contributed by Shivani
Time Complexity: O(n)Please see following posts for other methods of array rotation: https://www.geeksforgeeks.org/array-rotation/ https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
References: http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdfPlease write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm.
Please refer complete article on Block swap algorithm for array rotation for more details!
Arrays
rotation
Arrays
C++
C++ Programs
Arrays
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26148,
"s": 26067,
"text": "Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. "
},
{
"code": null,
"e": 26197,
"s": 26148,
"text": "Rotation of the above array by 2 will make array"
},
{
"code": null,
"e": 26210,
"s": 26197,
"text": "Algorithm : "
},
{
"code": null,
"e": 26766,
"s": 26210,
"text": "Initialize A = arr[0..d-1] and B = arr[d..n-1]\n1) Do following until size of A is equal to size of B\n\n a) If A is shorter, divide B into Bl and Br such that Br is of same \n length as A. Swap A and Br to change ABlBr into BrBlA. Now A\n is at its final place, so recur on pieces of B. \n\n b) If A is longer, divide A into Al and Ar such that Al is of same \n length as B Swap Al and B to change AlArB into BArAl. Now B\n is at its final place, so recur on pieces of A.\n\n2) Finally when A and B are of equal size, block swap them."
},
{
"code": null,
"e": 26792,
"s": 26766,
"text": "Recursive Implementation:"
},
{
"code": null,
"e": 26796,
"s": 26792,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /*Prototype for utility functions */void printArray(int arr[], int size); void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n) { /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else /* If B is shorter*/ { swap(arr, 0, d, n - d); leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/ } } /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size) { int i; for(i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl; } /*This function swaps d elements starting at index fi with d elements starting at index si */void swap(int arr[], int fi, int si, int d) { int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } } // Driver Codeint main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); return 0; } // This code is contributed by rathbhupendra",
"e": 28251,
"s": 26796,
"text": null
},
{
"code": null,
"e": 28376,
"s": 28251,
"text": "Iterative Implementation: Here is iterative implementation of the same algorithm. Same utility function swap() is used here."
},
{
"code": null,
"e": 28380,
"s": 28376,
"text": "C++"
},
{
"code": "// C++ code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if (d == 0 || d == n) return; i = d; j = n - d; while (i != j) { if (i < j) /*A is shorter*/ { swap(arr, d - i, d + j - i, i); j -= i; } else /*B is shorter*/ { swap(arr, d - i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d - i, d, i);} // This code is contributed by Shivani",
"e": 28938,
"s": 28380,
"text": null
},
{
"code": null,
"e": 29156,
"s": 28938,
"text": "Time Complexity: O(n)Please see following posts for other methods of array rotation: https://www.geeksforgeeks.org/array-rotation/ https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/"
},
{
"code": null,
"e": 29368,
"s": 29156,
"text": "References: http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdfPlease write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm."
},
{
"code": null,
"e": 29459,
"s": 29368,
"text": "Please refer complete article on Block swap algorithm for array rotation for more details!"
},
{
"code": null,
"e": 29466,
"s": 29459,
"text": "Arrays"
},
{
"code": null,
"e": 29475,
"s": 29466,
"text": "rotation"
},
{
"code": null,
"e": 29482,
"s": 29475,
"text": "Arrays"
},
{
"code": null,
"e": 29486,
"s": 29482,
"text": "C++"
},
{
"code": null,
"e": 29499,
"s": 29486,
"text": "C++ Programs"
},
{
"code": null,
"e": 29506,
"s": 29499,
"text": "Arrays"
},
{
"code": null,
"e": 29510,
"s": 29506,
"text": "CPP"
},
{
"code": null,
"e": 29608,
"s": 29510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29639,
"s": 29608,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29664,
"s": 29639,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29702,
"s": 29664,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29723,
"s": 29702,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29781,
"s": 29723,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 29799,
"s": 29781,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29818,
"s": 29799,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29864,
"s": 29818,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29907,
"s": 29864,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Named Entity Recognition and Classification with Scikit-Learn | by Susan Li | Towards Data Science | Named Entity Recognition and Classification (NERC) is a process of recognizing information units like names, including person, organization and location names, and numeric expressions including time, date, money and percent expressions from unstructured text. The goal is to develop practical and domain-independent techniques in order to detect named entities with high accuracy automatically.
Last week, we gave an introduction on Named Entity Recognition (NER) in NLTK and SpaCy. Today, we go a step further, β training machine learning models for NER using some of Scikit-Learnβs libraries. Letβs get started!
The data is feature engineered corpus annotated with IOB and POS tags that can be found at Kaggle. We can have a quick peek of first several rows of the data.
Essential info about entities:
geo = Geographical Entity
org = Organization
per = Person
gpe = Geopolitical Entity
tim = Time indicator
art = Artifact
eve = Event
nat = Natural Phenomenon
Insideβoutsideβbeginning (tagging)
The IOB (short for inside, outside, beginning) is a common tagging format for tagging tokens.
I- prefix before a tag indicates that the tag is inside a chunk.
B- prefix before a tag indicates that the tag is the beginning of a chunk.
An O tag indicates that a token belongs to no chunk (outside).
import pandas as pdimport numpy as npfrom sklearn.feature_extraction import DictVectorizerfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.linear_model import Perceptronfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import SGDClassifierfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import classification_report
The entire data set can not be fit into the memory of a single computer, so we select the first 100,000 records, and use Out-of-core learning algorithms to efficiently fetch and process the data.
df = pd.read_csv('ner_dataset.csv', encoding = "ISO-8859-1")df = df[:100000]df.head()
df.isnull().sum()
We notice that there are many NaN values in βSentence #β column, and we fill NaN by preceding values.
df = df.fillna(method='ffill')df['Sentence #'].nunique(), df.Word.nunique(), df.Tag.nunique()
(4544, 10922, 17)
We have 4,544 sentences that contain 10,922 unique words and tagged by 17 tags.
The tags are not evenly distributed.
df.groupby('Tag').size().reset_index(name='counts')
The following code transform the text date to vector using DictVectorizer and then split to train and test sets.
X = df.drop('Tag', axis=1)v = DictVectorizer(sparse=False)X = v.fit_transform(X.to_dict('records'))y = df.Tag.valuesclasses = np.unique(y)classes = classes.tolist()X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=0)X_train.shape, y_train.shape
((67000, 15507), (67000,))
We will try some of the out-of-core algorithms that are designed to process data that is too large to fit into a single computer memory that support partial_fit method.
per = Perceptron(verbose=10, n_jobs=-1, max_iter=5)per.partial_fit(X_train, y_train, classes)
Because tag βOβ (outside) is the most common tag and it will make our results look much better than they actual are. So we remove tag βOβ when we evaluate classification metrics.
new_classes = classes.copy()new_classes.pop()new_classes
print(classification_report(y_pred=per.predict(X_test), y_true=y_test, labels=new_classes))
Linear classifiers with SGD training
sgd = SGDClassifier()sgd.partial_fit(X_train, y_train, classes)
print(classification_report(y_pred=sgd.predict(X_test), y_true=y_test, labels=new_classes))
Naive Bayes classifier for multinomial models
nb = MultinomialNB(alpha=0.01)nb.partial_fit(X_train, y_train, classes)
print(classification_report(y_pred=nb.predict(X_test), y_true=y_test, labels = new_classes))
Passive Aggressive Classifier
pa =PassiveAggressiveClassifier()pa.partial_fit(X_train, y_train, classes)
print(classification_report(y_pred=pa.predict(X_test), y_true=y_test, labels=new_classes))
None of the above classifiers produced satisfying results. It is obvious that it is not going to be easy to classify named entities using regular classifiers.
CRFs is often used for labeling or parsing of sequential data, such as natural language processing and CRFs find applications in POS Tagging, named entity recognition, among others.
We will train a CRF model for named entity recognition using sklearn-crfsuite on our data set.
import sklearn_crfsuitefrom sklearn_crfsuite import scorersfrom sklearn_crfsuite import metricsfrom collections import Counter
The following code is to retrieve sentences with their POS and tags. Thanks Tobias for the tip.
class SentenceGetter(object): def __init__(self, data): self.n_sent = 1 self.data = data self.empty = False agg_func = lambda s: [(w, p, t) for w, p, t in zip(s['Word'].values.tolist(), s['POS'].values.tolist(), s['Tag'].values.tolist())] self.grouped = self.data.groupby('Sentence #').apply(agg_func) self.sentences = [s for s in self.grouped] def get_next(self): try: s = self.grouped['Sentence: {}'.format(self.n_sent)] self.n_sent += 1 return s except: return Nonegetter = SentenceGetter(df)sentences = getter.sentences
Feature Extraction
Next, we extract more features (word parts, simplified POS tags, lower/title/upper flags, features of nearby words) and convert them to sklearn-crfsuite format β each sentence should be converted to a list of dicts. The following code were taken from sklearn-crfsuites official site.
def word2features(sent, i): word = sent[i][0] postag = sent[i][1] features = { 'bias': 1.0, 'word.lower()': word.lower(), 'word[-3:]': word[-3:], 'word[-2:]': word[-2:], 'word.isupper()': word.isupper(), 'word.istitle()': word.istitle(), 'word.isdigit()': word.isdigit(), 'postag': postag, 'postag[:2]': postag[:2], } if i > 0: word1 = sent[i-1][0] postag1 = sent[i-1][1] features.update({ '-1:word.lower()': word1.lower(), '-1:word.istitle()': word1.istitle(), '-1:word.isupper()': word1.isupper(), '-1:postag': postag1, '-1:postag[:2]': postag1[:2], }) else: features['BOS'] = True if i < len(sent)-1: word1 = sent[i+1][0] postag1 = sent[i+1][1] features.update({ '+1:word.lower()': word1.lower(), '+1:word.istitle()': word1.istitle(), '+1:word.isupper()': word1.isupper(), '+1:postag': postag1, '+1:postag[:2]': postag1[:2], }) else: features['EOS'] = Truereturn featuresdef sent2features(sent): return [word2features(sent, i) for i in range(len(sent))]def sent2labels(sent): return [label for token, postag, label in sent]def sent2tokens(sent): return [token for token, postag, label in sent]
Split train and test sets
X = [sent2features(s) for s in sentences]y = [sent2labels(s) for s in sentences]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0)
Train a CRF model
crf = sklearn_crfsuite.CRF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=100, all_possible_transitions=True)crf.fit(X_train, y_train)
Evaluation
y_pred = crf.predict(X_test)print(metrics.flat_classification_report(y_test, y_pred, labels = new_classes))
Way better! We will stick to sklearn-crfsuite and explore more!
What our classifier learned?
def print_transitions(trans_features): for (label_from, label_to), weight in trans_features: print("%-6s -> %-7s %0.6f" % (label_from, label_to, weight))print("Top likely transitions:")print_transitions(Counter(crf.transition_features_).most_common(20))print("\nTop unlikely transitions:")print_transitions(Counter(crf.transition_features_).most_common()[-20:])
Interpretation: It is very likely that the beginning of a geographical entity (B-geo) will be followed by a token inside geographical entity (I-geo), but transitions to inside of an organization name (I-org) from tokens with other labels are penalized hugely.
Check the state features
def print_state_features(state_features): for (attr, label), weight in state_features: print("%0.6f %-8s %s" % (weight, label, attr))print("Top positive:")print_state_features(Counter(crf.state_features_).most_common(30))print("\nTop negative:")print_state_features(Counter(crf.state_features_).most_common()[-30:])
Observations:
1). 5.183603 B-tim word[-3]:day The model learns that if a nearby word was βdayβ then the token is likely a part of a Time indicator.
2). 3.370614 B-per word.lower():president The model learns that token "president" is likely to be at the beginning of a person name.
3). -3.521244 O postag:NNP The model learns that proper nouns are often entities.
4). -3.087828 O word.isdigit() Digits are likely entities.
5). -3.233526 O word.istitle() TitleCased words are likely entities.
ELI5 is a Python package which allows to check weights of sklearn_crfsuite.CRF models.
Inspect model weights
import eli5eli5.show_weights(crf, top=10)
Observations:
It does make sense that I-entity must follow B-entity, such as I-geo follows B-geo, I-org follows B-org, I-per follows B-per, and so on.We can also see that it is not common in this data set to have a person right after an organization name (B-org -> I-per has a large negative weight).The model learned large negative weights for impossible transitions like O -> I-geo, O -> I-org and O -> I-tim, and so on.
It does make sense that I-entity must follow B-entity, such as I-geo follows B-geo, I-org follows B-org, I-per follows B-per, and so on.
We can also see that it is not common in this data set to have a person right after an organization name (B-org -> I-per has a large negative weight).
The model learned large negative weights for impossible transitions like O -> I-geo, O -> I-org and O -> I-tim, and so on.
For easy to read, we can check only a subset of tags.
eli5.show_weights(crf, top=10, targets=['O', 'B-org', 'I-per'])
Or check only some of the features for all tags.
eli5.show_weights(crf, top=10, feature_re='^word\.is', horizontal_layout=False, show=['targets'])
That was it, for now. I enjoyed making my hands dirty on sklearn-crfsuite and ELI5, hope you did too. Source code can be found at Github. Have a great week! | [
{
"code": null,
"e": 567,
"s": 172,
"text": "Named Entity Recognition and Classification (NERC) is a process of recognizing information units like names, including person, organization and location names, and numeric expressions including time, date, money and percent expressions from unstructured text. The goal is to develop practical and domain-independent techniques in order to detect named entities with high accuracy automatically."
},
{
"code": null,
"e": 786,
"s": 567,
"text": "Last week, we gave an introduction on Named Entity Recognition (NER) in NLTK and SpaCy. Today, we go a step further, β training machine learning models for NER using some of Scikit-Learnβs libraries. Letβs get started!"
},
{
"code": null,
"e": 945,
"s": 786,
"text": "The data is feature engineered corpus annotated with IOB and POS tags that can be found at Kaggle. We can have a quick peek of first several rows of the data."
},
{
"code": null,
"e": 976,
"s": 945,
"text": "Essential info about entities:"
},
{
"code": null,
"e": 1002,
"s": 976,
"text": "geo = Geographical Entity"
},
{
"code": null,
"e": 1021,
"s": 1002,
"text": "org = Organization"
},
{
"code": null,
"e": 1034,
"s": 1021,
"text": "per = Person"
},
{
"code": null,
"e": 1060,
"s": 1034,
"text": "gpe = Geopolitical Entity"
},
{
"code": null,
"e": 1081,
"s": 1060,
"text": "tim = Time indicator"
},
{
"code": null,
"e": 1096,
"s": 1081,
"text": "art = Artifact"
},
{
"code": null,
"e": 1108,
"s": 1096,
"text": "eve = Event"
},
{
"code": null,
"e": 1133,
"s": 1108,
"text": "nat = Natural Phenomenon"
},
{
"code": null,
"e": 1168,
"s": 1133,
"text": "Insideβoutsideβbeginning (tagging)"
},
{
"code": null,
"e": 1262,
"s": 1168,
"text": "The IOB (short for inside, outside, beginning) is a common tagging format for tagging tokens."
},
{
"code": null,
"e": 1327,
"s": 1262,
"text": "I- prefix before a tag indicates that the tag is inside a chunk."
},
{
"code": null,
"e": 1402,
"s": 1327,
"text": "B- prefix before a tag indicates that the tag is the beginning of a chunk."
},
{
"code": null,
"e": 1465,
"s": 1402,
"text": "An O tag indicates that a token belongs to no chunk (outside)."
},
{
"code": null,
"e": 1912,
"s": 1465,
"text": "import pandas as pdimport numpy as npfrom sklearn.feature_extraction import DictVectorizerfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.linear_model import Perceptronfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import SGDClassifierfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import classification_report"
},
{
"code": null,
"e": 2108,
"s": 1912,
"text": "The entire data set can not be fit into the memory of a single computer, so we select the first 100,000 records, and use Out-of-core learning algorithms to efficiently fetch and process the data."
},
{
"code": null,
"e": 2194,
"s": 2108,
"text": "df = pd.read_csv('ner_dataset.csv', encoding = \"ISO-8859-1\")df = df[:100000]df.head()"
},
{
"code": null,
"e": 2212,
"s": 2194,
"text": "df.isnull().sum()"
},
{
"code": null,
"e": 2314,
"s": 2212,
"text": "We notice that there are many NaN values in βSentence #β column, and we fill NaN by preceding values."
},
{
"code": null,
"e": 2408,
"s": 2314,
"text": "df = df.fillna(method='ffill')df['Sentence #'].nunique(), df.Word.nunique(), df.Tag.nunique()"
},
{
"code": null,
"e": 2426,
"s": 2408,
"text": "(4544, 10922, 17)"
},
{
"code": null,
"e": 2506,
"s": 2426,
"text": "We have 4,544 sentences that contain 10,922 unique words and tagged by 17 tags."
},
{
"code": null,
"e": 2543,
"s": 2506,
"text": "The tags are not evenly distributed."
},
{
"code": null,
"e": 2595,
"s": 2543,
"text": "df.groupby('Tag').size().reset_index(name='counts')"
},
{
"code": null,
"e": 2708,
"s": 2595,
"text": "The following code transform the text date to vector using DictVectorizer and then split to train and test sets."
},
{
"code": null,
"e": 2992,
"s": 2708,
"text": "X = df.drop('Tag', axis=1)v = DictVectorizer(sparse=False)X = v.fit_transform(X.to_dict('records'))y = df.Tag.valuesclasses = np.unique(y)classes = classes.tolist()X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=0)X_train.shape, y_train.shape"
},
{
"code": null,
"e": 3019,
"s": 2992,
"text": "((67000, 15507), (67000,))"
},
{
"code": null,
"e": 3188,
"s": 3019,
"text": "We will try some of the out-of-core algorithms that are designed to process data that is too large to fit into a single computer memory that support partial_fit method."
},
{
"code": null,
"e": 3282,
"s": 3188,
"text": "per = Perceptron(verbose=10, n_jobs=-1, max_iter=5)per.partial_fit(X_train, y_train, classes)"
},
{
"code": null,
"e": 3461,
"s": 3282,
"text": "Because tag βOβ (outside) is the most common tag and it will make our results look much better than they actual are. So we remove tag βOβ when we evaluate classification metrics."
},
{
"code": null,
"e": 3518,
"s": 3461,
"text": "new_classes = classes.copy()new_classes.pop()new_classes"
},
{
"code": null,
"e": 3610,
"s": 3518,
"text": "print(classification_report(y_pred=per.predict(X_test), y_true=y_test, labels=new_classes))"
},
{
"code": null,
"e": 3647,
"s": 3610,
"text": "Linear classifiers with SGD training"
},
{
"code": null,
"e": 3711,
"s": 3647,
"text": "sgd = SGDClassifier()sgd.partial_fit(X_train, y_train, classes)"
},
{
"code": null,
"e": 3803,
"s": 3711,
"text": "print(classification_report(y_pred=sgd.predict(X_test), y_true=y_test, labels=new_classes))"
},
{
"code": null,
"e": 3849,
"s": 3803,
"text": "Naive Bayes classifier for multinomial models"
},
{
"code": null,
"e": 3921,
"s": 3849,
"text": "nb = MultinomialNB(alpha=0.01)nb.partial_fit(X_train, y_train, classes)"
},
{
"code": null,
"e": 4014,
"s": 3921,
"text": "print(classification_report(y_pred=nb.predict(X_test), y_true=y_test, labels = new_classes))"
},
{
"code": null,
"e": 4044,
"s": 4014,
"text": "Passive Aggressive Classifier"
},
{
"code": null,
"e": 4119,
"s": 4044,
"text": "pa =PassiveAggressiveClassifier()pa.partial_fit(X_train, y_train, classes)"
},
{
"code": null,
"e": 4210,
"s": 4119,
"text": "print(classification_report(y_pred=pa.predict(X_test), y_true=y_test, labels=new_classes))"
},
{
"code": null,
"e": 4369,
"s": 4210,
"text": "None of the above classifiers produced satisfying results. It is obvious that it is not going to be easy to classify named entities using regular classifiers."
},
{
"code": null,
"e": 4551,
"s": 4369,
"text": "CRFs is often used for labeling or parsing of sequential data, such as natural language processing and CRFs find applications in POS Tagging, named entity recognition, among others."
},
{
"code": null,
"e": 4646,
"s": 4551,
"text": "We will train a CRF model for named entity recognition using sklearn-crfsuite on our data set."
},
{
"code": null,
"e": 4773,
"s": 4646,
"text": "import sklearn_crfsuitefrom sklearn_crfsuite import scorersfrom sklearn_crfsuite import metricsfrom collections import Counter"
},
{
"code": null,
"e": 4869,
"s": 4773,
"text": "The following code is to retrieve sentences with their POS and tags. Thanks Tobias for the tip."
},
{
"code": null,
"e": 5631,
"s": 4869,
"text": "class SentenceGetter(object): def __init__(self, data): self.n_sent = 1 self.data = data self.empty = False agg_func = lambda s: [(w, p, t) for w, p, t in zip(s['Word'].values.tolist(), s['POS'].values.tolist(), s['Tag'].values.tolist())] self.grouped = self.data.groupby('Sentence #').apply(agg_func) self.sentences = [s for s in self.grouped] def get_next(self): try: s = self.grouped['Sentence: {}'.format(self.n_sent)] self.n_sent += 1 return s except: return Nonegetter = SentenceGetter(df)sentences = getter.sentences"
},
{
"code": null,
"e": 5650,
"s": 5631,
"text": "Feature Extraction"
},
{
"code": null,
"e": 5934,
"s": 5650,
"text": "Next, we extract more features (word parts, simplified POS tags, lower/title/upper flags, features of nearby words) and convert them to sklearn-crfsuite format β each sentence should be converted to a list of dicts. The following code were taken from sklearn-crfsuites official site."
},
{
"code": null,
"e": 7313,
"s": 5934,
"text": "def word2features(sent, i): word = sent[i][0] postag = sent[i][1] features = { 'bias': 1.0, 'word.lower()': word.lower(), 'word[-3:]': word[-3:], 'word[-2:]': word[-2:], 'word.isupper()': word.isupper(), 'word.istitle()': word.istitle(), 'word.isdigit()': word.isdigit(), 'postag': postag, 'postag[:2]': postag[:2], } if i > 0: word1 = sent[i-1][0] postag1 = sent[i-1][1] features.update({ '-1:word.lower()': word1.lower(), '-1:word.istitle()': word1.istitle(), '-1:word.isupper()': word1.isupper(), '-1:postag': postag1, '-1:postag[:2]': postag1[:2], }) else: features['BOS'] = True if i < len(sent)-1: word1 = sent[i+1][0] postag1 = sent[i+1][1] features.update({ '+1:word.lower()': word1.lower(), '+1:word.istitle()': word1.istitle(), '+1:word.isupper()': word1.isupper(), '+1:postag': postag1, '+1:postag[:2]': postag1[:2], }) else: features['EOS'] = Truereturn featuresdef sent2features(sent): return [word2features(sent, i) for i in range(len(sent))]def sent2labels(sent): return [label for token, postag, label in sent]def sent2tokens(sent): return [token for token, postag, label in sent]"
},
{
"code": null,
"e": 7339,
"s": 7313,
"text": "Split train and test sets"
},
{
"code": null,
"e": 7509,
"s": 7339,
"text": "X = [sent2features(s) for s in sentences]y = [sent2labels(s) for s in sentences]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0)"
},
{
"code": null,
"e": 7527,
"s": 7509,
"text": "Train a CRF model"
},
{
"code": null,
"e": 7681,
"s": 7527,
"text": "crf = sklearn_crfsuite.CRF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=100, all_possible_transitions=True)crf.fit(X_train, y_train)"
},
{
"code": null,
"e": 7692,
"s": 7681,
"text": "Evaluation"
},
{
"code": null,
"e": 7800,
"s": 7692,
"text": "y_pred = crf.predict(X_test)print(metrics.flat_classification_report(y_test, y_pred, labels = new_classes))"
},
{
"code": null,
"e": 7864,
"s": 7800,
"text": "Way better! We will stick to sklearn-crfsuite and explore more!"
},
{
"code": null,
"e": 7893,
"s": 7864,
"text": "What our classifier learned?"
},
{
"code": null,
"e": 8265,
"s": 7893,
"text": "def print_transitions(trans_features): for (label_from, label_to), weight in trans_features: print(\"%-6s -> %-7s %0.6f\" % (label_from, label_to, weight))print(\"Top likely transitions:\")print_transitions(Counter(crf.transition_features_).most_common(20))print(\"\\nTop unlikely transitions:\")print_transitions(Counter(crf.transition_features_).most_common()[-20:])"
},
{
"code": null,
"e": 8525,
"s": 8265,
"text": "Interpretation: It is very likely that the beginning of a geographical entity (B-geo) will be followed by a token inside geographical entity (I-geo), but transitions to inside of an organization name (I-org) from tokens with other labels are penalized hugely."
},
{
"code": null,
"e": 8550,
"s": 8525,
"text": "Check the state features"
},
{
"code": null,
"e": 8876,
"s": 8550,
"text": "def print_state_features(state_features): for (attr, label), weight in state_features: print(\"%0.6f %-8s %s\" % (weight, label, attr))print(\"Top positive:\")print_state_features(Counter(crf.state_features_).most_common(30))print(\"\\nTop negative:\")print_state_features(Counter(crf.state_features_).most_common()[-30:])"
},
{
"code": null,
"e": 8890,
"s": 8876,
"text": "Observations:"
},
{
"code": null,
"e": 9024,
"s": 8890,
"text": "1). 5.183603 B-tim word[-3]:day The model learns that if a nearby word was βdayβ then the token is likely a part of a Time indicator."
},
{
"code": null,
"e": 9157,
"s": 9024,
"text": "2). 3.370614 B-per word.lower():president The model learns that token \"president\" is likely to be at the beginning of a person name."
},
{
"code": null,
"e": 9239,
"s": 9157,
"text": "3). -3.521244 O postag:NNP The model learns that proper nouns are often entities."
},
{
"code": null,
"e": 9298,
"s": 9239,
"text": "4). -3.087828 O word.isdigit() Digits are likely entities."
},
{
"code": null,
"e": 9367,
"s": 9298,
"text": "5). -3.233526 O word.istitle() TitleCased words are likely entities."
},
{
"code": null,
"e": 9454,
"s": 9367,
"text": "ELI5 is a Python package which allows to check weights of sklearn_crfsuite.CRF models."
},
{
"code": null,
"e": 9476,
"s": 9454,
"text": "Inspect model weights"
},
{
"code": null,
"e": 9518,
"s": 9476,
"text": "import eli5eli5.show_weights(crf, top=10)"
},
{
"code": null,
"e": 9532,
"s": 9518,
"text": "Observations:"
},
{
"code": null,
"e": 9941,
"s": 9532,
"text": "It does make sense that I-entity must follow B-entity, such as I-geo follows B-geo, I-org follows B-org, I-per follows B-per, and so on.We can also see that it is not common in this data set to have a person right after an organization name (B-org -> I-per has a large negative weight).The model learned large negative weights for impossible transitions like O -> I-geo, O -> I-org and O -> I-tim, and so on."
},
{
"code": null,
"e": 10078,
"s": 9941,
"text": "It does make sense that I-entity must follow B-entity, such as I-geo follows B-geo, I-org follows B-org, I-per follows B-per, and so on."
},
{
"code": null,
"e": 10229,
"s": 10078,
"text": "We can also see that it is not common in this data set to have a person right after an organization name (B-org -> I-per has a large negative weight)."
},
{
"code": null,
"e": 10352,
"s": 10229,
"text": "The model learned large negative weights for impossible transitions like O -> I-geo, O -> I-org and O -> I-tim, and so on."
},
{
"code": null,
"e": 10406,
"s": 10352,
"text": "For easy to read, we can check only a subset of tags."
},
{
"code": null,
"e": 10470,
"s": 10406,
"text": "eli5.show_weights(crf, top=10, targets=['O', 'B-org', 'I-per'])"
},
{
"code": null,
"e": 10519,
"s": 10470,
"text": "Or check only some of the features for all tags."
},
{
"code": null,
"e": 10634,
"s": 10519,
"text": "eli5.show_weights(crf, top=10, feature_re='^word\\.is', horizontal_layout=False, show=['targets'])"
}
] |
How to use map() to Create Lists in ReactJS ? - GeeksforGeeks | 23 Jul, 2021
An array in JavaScript comes with a plethora of functions to work with. A map() is one such function that is used to create a list of objects by calling a function on each element of the array. In React, we can use the map() function to map a list of values to a list of components.
Letβs see how we can create a list in react using a simple project. The project has a list of fruit names, and we will change them into a list of components rendered in the browser.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app listmapdemo
Step 1: Create a React application using the following command:
npx create-react-app listmapdemo
Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:cd listmapdemo
Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:
cd listmapdemo
Project Structure: It will look like the following.
Project Structure
Example: While creating components using the map, react expects a key prop passed to each component being built. It will still render if the key is not passed, but you will see a warning from React about it in the console. In the App.js file, we have defined a list of fruits which is then mapped to a list of divs.
App.js
import React from "react" function App() { // Declared an array of items const fruits = [ 'Apple', 'Mango', 'Banana', 'GFG' ]; // Some styling for the items const styles = { backgroundColor: 'white', width: '50px', marginBottom: '10px', padding: '10px', color: 'green', boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px', }; return <> { /* This maps each array item to a div adds the style declared above and return it */ fruits.map(fruit => <div key={fruit} style={styles}>{fruit}</div>) } </>;} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: We declared a list of fruits that will be used to render divs. The styles object contains CSS styles for each item, it simply adds some margin, padding and some shadow. Finally, the App function returns a list of divs that are returned by calling map() on the fruits array. We added the styles object to the style attribute of each div.
kapoorsagar226
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26622,
"s": 26594,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 26905,
"s": 26622,
"text": "An array in JavaScript comes with a plethora of functions to work with. A map() is one such function that is used to create a list of objects by calling a function on each element of the array. In React, we can use the map() function to map a list of values to a list of components."
},
{
"code": null,
"e": 27087,
"s": 26905,
"text": "Letβs see how we can create a list in react using a simple project. The project has a list of fruit names, and we will change them into a list of components rendered in the browser."
},
{
"code": null,
"e": 27137,
"s": 27087,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27234,
"s": 27137,
"text": "Step 1: Create a React application using the following command:npx create-react-app listmapdemo "
},
{
"code": null,
"e": 27298,
"s": 27234,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27331,
"s": 27298,
"text": "npx create-react-app listmapdemo"
},
{
"code": null,
"e": 27448,
"s": 27333,
"text": "Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:cd listmapdemo"
},
{
"code": null,
"e": 27549,
"s": 27448,
"text": "Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:"
},
{
"code": null,
"e": 27564,
"s": 27549,
"text": "cd listmapdemo"
},
{
"code": null,
"e": 27616,
"s": 27564,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27634,
"s": 27616,
"text": "Project Structure"
},
{
"code": null,
"e": 27950,
"s": 27634,
"text": "Example: While creating components using the map, react expects a key prop passed to each component being built. It will still render if the key is not passed, but you will see a warning from React about it in the console. In the App.js file, we have defined a list of fruits which is then mapped to a list of divs."
},
{
"code": null,
"e": 27957,
"s": 27950,
"text": "App.js"
},
{
"code": "import React from \"react\" function App() { // Declared an array of items const fruits = [ 'Apple', 'Mango', 'Banana', 'GFG' ]; // Some styling for the items const styles = { backgroundColor: 'white', width: '50px', marginBottom: '10px', padding: '10px', color: 'green', boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px', }; return <> { /* This maps each array item to a div adds the style declared above and return it */ fruits.map(fruit => <div key={fruit} style={styles}>{fruit}</div>) } </>;} export default App;",
"e": 28544,
"s": 27957,
"text": null
},
{
"code": null,
"e": 28657,
"s": 28544,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28667,
"s": 28657,
"text": "npm start"
},
{
"code": null,
"e": 28766,
"s": 28667,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29116,
"s": 28766,
"text": "Explanation: We declared a list of fruits that will be used to render divs. The styles object contains CSS styles for each item, it simply adds some margin, padding and some shadow. Finally, the App function returns a list of divs that are returned by calling map() on the fruits array. We added the styles object to the style attribute of each div."
},
{
"code": null,
"e": 29131,
"s": 29116,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 29138,
"s": 29131,
"text": "Picked"
},
{
"code": null,
"e": 29154,
"s": 29138,
"text": "React-Questions"
},
{
"code": null,
"e": 29162,
"s": 29154,
"text": "ReactJS"
},
{
"code": null,
"e": 29179,
"s": 29162,
"text": "Web Technologies"
},
{
"code": null,
"e": 29277,
"s": 29179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29304,
"s": 29277,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29342,
"s": 29304,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29384,
"s": 29342,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29419,
"s": 29384,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29477,
"s": 29419,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29517,
"s": 29477,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29550,
"s": 29517,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29595,
"s": 29550,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29645,
"s": 29595,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PyQt5 QListWidget β Setting Selection Behaviour - GeeksforGeeks | 06 Aug, 2020
In this article we will see how we can set the selection behavior of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Selection behavior describes how user can select the item, it can be row or it can be column or it can be single item.
In order to do this we will use setSelectionBehavior method with the list widget object.
Syntax : list_widget.setSelectionBehavior(behaviour)
Argument : It takes behaviour object as argument
Return : It returns None
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 title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("PyQt5 Geeks for Geeks") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting selection behaviour list_widget.setSelectionBehavior(QAbstractItemView.SelectItems) # setting word wrap property list_widget.setWordWrap(True) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 26077,
"s": 25665,
"text": "In this article we will see how we can set the selection behavior of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Selection behavior describes how user can select the item, it can be row or it can be column or it can be single item."
},
{
"code": null,
"e": 26166,
"s": 26077,
"text": "In order to do this we will use setSelectionBehavior method with the list widget object."
},
{
"code": null,
"e": 26219,
"s": 26166,
"text": "Syntax : list_widget.setSelectionBehavior(behaviour)"
},
{
"code": null,
"e": 26268,
"s": 26219,
"text": "Argument : It takes behaviour object as argument"
},
{
"code": null,
"e": 26293,
"s": 26268,
"text": "Return : It returns None"
},
{
"code": null,
"e": 26321,
"s": 26293,
"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 title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"PyQt5 Geeks for Geeks\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting selection behaviour list_widget.setSelectionBehavior(QAbstractItemView.SelectItems) # setting word wrap property list_widget.setWordWrap(True) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27859,
"s": 26321,
"text": null
},
{
"code": null,
"e": 27868,
"s": 27859,
"text": "Output :"
},
{
"code": null,
"e": 27892,
"s": 27868,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 27903,
"s": 27892,
"text": "Python-gui"
},
{
"code": null,
"e": 27915,
"s": 27903,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27922,
"s": 27915,
"text": "Python"
},
{
"code": null,
"e": 28020,
"s": 27922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28052,
"s": 28020,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28094,
"s": 28052,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28136,
"s": 28094,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28192,
"s": 28136,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28219,
"s": 28192,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28250,
"s": 28219,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28279,
"s": 28250,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28301,
"s": 28279,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28340,
"s": 28301,
"text": "Python | Get unique values from a list"
}
] |
Preorder to Postorder | Practice | GeeksforGeeks | Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.
In Pre-Order traversal, the root node is visited before the left child and right child nodes.
Post-order traversal is one of the multiple methods to traverse a tree.
Example 1:
Input:
N = 5
arr[] = {40,30,35,80,100}
Output: 35 30 100 80 40
Explanation: PreOrder: 40 30 35 80 100
InOrder: 30 35 40 80 100
Therefore, the BST will be:
40
/ \
30 80
\ \
35 100
Hence, the postOrder traversal will
be: 35 30 100 80 40
Example 2:
Input:
N = 8
arr[] = {40,30,32,35,80,90,100,120}
Output: 35 32 30 120 100 90 80 40
Your Task:
You need to complete the given function and return the root of the tree. The driver code will then use this root to print the post order traversal.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 103
1 <= arr[i] <= 104
+2
shubhamxthakur2 weeks ago
Recursive C++ solution (No extra space except recursive call stack)
Node* construct(int arr[], int l, int h){
if(l>h) return NULL;
Node* root = newNode(arr[l]);
int i=l+1;
while(arr[i]<arr[l] && i<=h) i++;
root->left = construct(arr, l+1, i-1);
root->right = construct(arr, i, h);
return root;
}
Node* post_order(int pre[], int n)
{
if(n==0) return NULL;
return construct(pre, 0, n-1);
}
-1
sangamchoudhary72 months ago
Node* solve(int pre[],int &i,int ub,int n){
if(i >= n or pre[i] >= ub) return NULL;
Node* root = newNode(pre[i++]);
root->left = solve(pre,i,root->data,n);
root->right = solve(pre,i,ub,n);
return root;
}
Node* post_order(int pre[], int n){
int i=0;
return solve(pre,i,INT_MAX,n);
}
+1
aditya202 months ago
Solution using Stack ( time - O ( n ) and Space O ( height of tree ) )
if(size == 0)
return NULL;
if(size == 1){
Node *re = newNode(pre[0]);
return re;
}
// // changing the array into node tree
// // Node *P = newNode(pre[0]);
vector<Node*> v;
for(int i=0;i<size;i++){
Node *temp = newNode(pre[i]);
v.push_back(temp);
}
stack<Node*> S;
Node *P = v[0];
S.push(P);
Node *re = P;
for(int i = 1;i < size ; i++){
while(!S.empty() && S.top()->data < v[i]->data){
P = S.top();
S.pop();
}
if(P->data < v[i]->data){
P->right = v[i];
}else{
P->left = v[i];
}
S.push(v[i]);
P = S.top();
}
return re;
+4
srivasaurabh792 months ago
Striver Approach
int i = 0;
Node* build(int pre[] , int n , int mxval)
{
if(i == n || pre[i] > mxval)
{
return NULL;
}
Node* root = newNode(pre[i++]);
root->left = build(pre , n , root->data);
root->right = build(pre , n , mxval);
return root;
}
Node* post_order(int pre[], int size)
{
i = 0;
return build(pre , size , INT_MAX);
}
+1
spsahilpandey3 months ago
Node* solve(int a[],int l,int r){ if(l>r) return NULL; Node *temp=newNode(a[l]); if(l==r) return temp; int p=l+1; while(p<=r && a[p]<a[l]) p++; temp->left=solve(a,l+1,p-1); temp->right=solve(a,p,r);}// vector<int> res;// void post(Node* root){// if(!root) return;// post(root->left);// post(root->right);// res.push_back(root->data);// }Node* post_order(int pre[], int size){ //code here return solve(pre,0,size-1); }
-1
shashikantg3 months ago
Node * treemaker(int * pre,int size, int& idx, int minR, int maxR){
if(idx==size || pre[idx]<minR || pre[idx]>maxR)
return NULL;
int curr=pre[idx++];
Node * root=newNode(curr);
root->left=treemaker(pre, size, idx, minR, curr);
root->right=treemaker(pre, size, idx, curr, maxR);
return root;
}
Node* post_order(int pre[], int size)
{
int idx=0;
return treemaker(pre, size, idx, INT_MIN, INT_MAX);
}
-1
vishalpandey100220003 months ago
public static Node post_order(int pre[], int size) { //Your code here Node root=null; for (int i=0;i<size;i++){ root=preo(root,pre[i]); } return root;}private static Node preo(Node root, int i) { if (root==null){ return new Node(i); } if (root.data>i){ root.left=preo(root.left,i); } else{ root.right=preo(root.right,i); } return root; }
-1
siddhant073 months ago
Node* makeTree(Node *root, int x){
if(root == NULL){
return newNode(x);
}
if(x < root->data){
root->left = makeTree(root->left, x);
}
else{
root->right = makeTree(root->right, x);
}
return root;
}
Node* post_order(int pre[], int size)
{
Node *root = NULL;
for(int i = 0; i < size; i++){
root = makeTree(root, pre[i]);
}
return root;
}
0
abhixhek053 months ago
Node* func(int arr[], int l, int r){
if(l<=r){
Node *root = newNode(arr[l]);
int mid = l+1;
while(mid<=r && arr[mid]<arr[l] ) mid++;
root->left = func(arr,l+1,mid-1);
root->right = func(arr,mid,r);
return root;
}
return NULL;
}
//Function that constructs BST from its preorder traversal.
Node* post_order(int pre[], int size)
{
//code here
return func(pre, 0, size-1);
}
0
absi20cs3 months ago
EASIEST C++ SOLUTION 0.0/1.1
Node* post_order(int pre[], int size){ //code here Node *root=newNode(pre[0]); Node *p,*t; for(int i=1;i<size;i++) { t=root; while(t!=NULL) { p=t; if(pre[i]<t->data) t=t->left; else t=t->right; } if(p->data>pre[i]) p->left=newNode(pre[i]); else p->right=newNode(pre[i]); } return root;}
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": 510,
"s": 226,
"text": "Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.\nIn Pre-Order traversal, the root node is visited before the left child and right child nodes.\nPost-order traversal is one of the multiple methods to traverse a tree."
},
{
"code": null,
"e": 521,
"s": 510,
"text": "Example 1:"
},
{
"code": null,
"e": 839,
"s": 521,
"text": "Input:\nN = 5\narr[] = {40,30,35,80,100}\nOutput: 35 30 100 80 40\nExplanation: PreOrder: 40 30 35 80 100\nInOrder: 30 35 40 80 100\nTherefore, the BST will be:\n 40\n / \\\n 30 80\n \\ \\ \n 35 100\nHence, the postOrder traversal will\nbe: 35 30 100 80 40"
},
{
"code": null,
"e": 850,
"s": 839,
"text": "Example 2:"
},
{
"code": null,
"e": 934,
"s": 850,
"text": "Input:\nN = 8\narr[] = {40,30,32,35,80,90,100,120}\nOutput: 35 32 30 120 100 90 80 40"
},
{
"code": null,
"e": 1093,
"s": 934,
"text": "Your Task:\nYou need to complete the given function and return the root of the tree. The driver code will then use this root to print the post order traversal."
},
{
"code": null,
"e": 1157,
"s": 1093,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1203,
"s": 1157,
"text": "Constraints:\n1 <= N <= 103\n1 <= arr[i] <= 104"
},
{
"code": null,
"e": 1206,
"s": 1203,
"text": "+2"
},
{
"code": null,
"e": 1232,
"s": 1206,
"text": "shubhamxthakur2 weeks ago"
},
{
"code": null,
"e": 1300,
"s": 1232,
"text": "Recursive C++ solution (No extra space except recursive call stack)"
},
{
"code": null,
"e": 1659,
"s": 1302,
"text": "Node* construct(int arr[], int l, int h){\n if(l>h) return NULL;\n Node* root = newNode(arr[l]);\n int i=l+1;\n while(arr[i]<arr[l] && i<=h) i++;\n root->left = construct(arr, l+1, i-1);\n root->right = construct(arr, i, h);\n return root;\n}\n\nNode* post_order(int pre[], int n)\n{\n if(n==0) return NULL;\n return construct(pre, 0, n-1);\n}"
},
{
"code": null,
"e": 1662,
"s": 1659,
"text": "-1"
},
{
"code": null,
"e": 1691,
"s": 1662,
"text": "sangamchoudhary72 months ago"
},
{
"code": null,
"e": 2017,
"s": 1691,
"text": "Node* solve(int pre[],int &i,int ub,int n){\n if(i >= n or pre[i] >= ub) return NULL;\n \n Node* root = newNode(pre[i++]);\n \n root->left = solve(pre,i,root->data,n);\n root->right = solve(pre,i,ub,n);\n \n return root;\n}\n\nNode* post_order(int pre[], int n){\n int i=0;\n return solve(pre,i,INT_MAX,n);\n}"
},
{
"code": null,
"e": 2020,
"s": 2017,
"text": "+1"
},
{
"code": null,
"e": 2041,
"s": 2020,
"text": "aditya202 months ago"
},
{
"code": null,
"e": 2868,
"s": 2041,
"text": "Solution using Stack ( time - O ( n ) and Space O ( height of tree ) )\n\n if(size == 0)\n return NULL;\n if(size == 1){\n Node *re = newNode(pre[0]);\n return re;\n }\n // // changing the array into node tree\n // // Node *P = newNode(pre[0]);\n vector<Node*> v;\n for(int i=0;i<size;i++){\n Node *temp = newNode(pre[i]);\n v.push_back(temp);\n }\n stack<Node*> S;\n Node *P = v[0];\n S.push(P);\n Node *re = P;\n for(int i = 1;i < size ; i++){\n \n while(!S.empty() && S.top()->data < v[i]->data){\n P = S.top();\n S.pop();\n }\n if(P->data < v[i]->data){\n \n P->right = v[i];\n \n }else{\n \n P->left = v[i];\n \n }\n S.push(v[i]);\n P = S.top();\n }\n return re;"
},
{
"code": null,
"e": 2871,
"s": 2868,
"text": "+4"
},
{
"code": null,
"e": 2898,
"s": 2871,
"text": "srivasaurabh792 months ago"
},
{
"code": null,
"e": 2916,
"s": 2898,
"text": "Striver Approach "
},
{
"code": null,
"e": 3274,
"s": 2918,
"text": "int i = 0;\nNode* build(int pre[] , int n , int mxval)\n{\n if(i == n || pre[i] > mxval)\n {\n return NULL;\n }\n \n Node* root = newNode(pre[i++]);\n \n root->left = build(pre , n , root->data);\n root->right = build(pre , n , mxval);\n return root;\n}\nNode* post_order(int pre[], int size)\n{\n i = 0;\n return build(pre , size , INT_MAX);\n}"
},
{
"code": null,
"e": 3277,
"s": 3274,
"text": "+1"
},
{
"code": null,
"e": 3303,
"s": 3277,
"text": "spsahilpandey3 months ago"
},
{
"code": null,
"e": 3757,
"s": 3303,
"text": "Node* solve(int a[],int l,int r){ if(l>r) return NULL; Node *temp=newNode(a[l]); if(l==r) return temp; int p=l+1; while(p<=r && a[p]<a[l]) p++; temp->left=solve(a,l+1,p-1); temp->right=solve(a,p,r);}// vector<int> res;// void post(Node* root){// if(!root) return;// post(root->left);// post(root->right);// res.push_back(root->data);// }Node* post_order(int pre[], int size){ //code here return solve(pre,0,size-1); }"
},
{
"code": null,
"e": 3760,
"s": 3757,
"text": "-1"
},
{
"code": null,
"e": 3784,
"s": 3760,
"text": "shashikantg3 months ago"
},
{
"code": null,
"e": 4219,
"s": 3784,
"text": "Node * treemaker(int * pre,int size, int& idx, int minR, int maxR){\n if(idx==size || pre[idx]<minR || pre[idx]>maxR)\n return NULL;\n int curr=pre[idx++];\n Node * root=newNode(curr);\n root->left=treemaker(pre, size, idx, minR, curr);\n root->right=treemaker(pre, size, idx, curr, maxR);\n return root;\n}\n\nNode* post_order(int pre[], int size)\n{\n int idx=0;\n return treemaker(pre, size, idx, INT_MIN, INT_MAX);\n}"
},
{
"code": null,
"e": 4222,
"s": 4219,
"text": "-1"
},
{
"code": null,
"e": 4255,
"s": 4222,
"text": "vishalpandey100220003 months ago"
},
{
"code": null,
"e": 4700,
"s": 4255,
"text": "public static Node post_order(int pre[], int size) { //Your code here Node root=null; for (int i=0;i<size;i++){ root=preo(root,pre[i]); } return root;}private static Node preo(Node root, int i) { if (root==null){ return new Node(i); } if (root.data>i){ root.left=preo(root.left,i); } else{ root.right=preo(root.right,i); } return root; } "
},
{
"code": null,
"e": 4703,
"s": 4700,
"text": "-1"
},
{
"code": null,
"e": 4726,
"s": 4703,
"text": "siddhant073 months ago"
},
{
"code": null,
"e": 5139,
"s": 4726,
"text": "Node* makeTree(Node *root, int x){\n if(root == NULL){\n return newNode(x);\n }\n if(x < root->data){\n root->left = makeTree(root->left, x);\n }\n else{\n root->right = makeTree(root->right, x);\n }\n return root;\n}\n\n\nNode* post_order(int pre[], int size)\n{\n Node *root = NULL;\n for(int i = 0; i < size; i++){\n root = makeTree(root, pre[i]);\n }\n return root;\n}"
},
{
"code": null,
"e": 5141,
"s": 5139,
"text": "0"
},
{
"code": null,
"e": 5164,
"s": 5141,
"text": "abhixhek053 months ago"
},
{
"code": null,
"e": 5637,
"s": 5164,
"text": "\nNode* func(int arr[], int l, int r){\n\n if(l<=r){\n Node *root = newNode(arr[l]);\n int mid = l+1;\n \n while(mid<=r && arr[mid]<arr[l] ) mid++;\n \n root->left = func(arr,l+1,mid-1);\n root->right = func(arr,mid,r);\n \n return root;\n }\n \n return NULL;\n \n}\n\n//Function that constructs BST from its preorder traversal.\nNode* post_order(int pre[], int size)\n{\n //code here\n return func(pre, 0, size-1);\n \n}"
},
{
"code": null,
"e": 5639,
"s": 5637,
"text": "0"
},
{
"code": null,
"e": 5660,
"s": 5639,
"text": "absi20cs3 months ago"
},
{
"code": null,
"e": 5689,
"s": 5660,
"text": "EASIEST C++ SOLUTION 0.0/1.1"
},
{
"code": null,
"e": 6143,
"s": 5689,
"text": "Node* post_order(int pre[], int size){ //code here Node *root=newNode(pre[0]); Node *p,*t; for(int i=1;i<size;i++) { t=root; while(t!=NULL) { p=t; if(pre[i]<t->data) t=t->left; else t=t->right; } if(p->data>pre[i]) p->left=newNode(pre[i]); else p->right=newNode(pre[i]); } return root;}"
},
{
"code": null,
"e": 6289,
"s": 6143,
"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": 6325,
"s": 6289,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6335,
"s": 6325,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6345,
"s": 6335,
"text": "\nContest\n"
},
{
"code": null,
"e": 6408,
"s": 6345,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6556,
"s": 6408,
"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": 6764,
"s": 6556,
"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": 6870,
"s": 6764,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Iterative Preorder Traversal of an N-ary Tree - GeeksforGeeks | 05 May, 2021
Given a K-ary Tree. The task is to write an iterative program to perform the preorder traversal of the given n-ary tree.
Examples:
Input: 3-Array Tree
1
/ | \
/ | \
2 3 4
/ \ / | \
5 6 7 8 9
/ / | \
10 11 12 13
Output: 1 2 5 10 6 11 12 13 3 4 7 8 9
Input: 3-Array Tree
1
/ | \
/ | \
2 3 4
/ \ / | \
5 6 7 8 9
Output: 1 2 5 6 3 4 7 8 9
Preorder Traversal of an N-ary Tree is similar to the preorder traversal of Binary Search Tree or Binary Tree with the only difference that is, all the child nodes of a parent are traversed from left to right in a sequence.Iterative Preorder Traversal of Binary Tree.
Cases to handle during traversal: Two Cases have been taken care of in this Iterative Preorder Traversal Algorithm:
Pop the top node from the stack β Top from the stack and insert it into visited list of nodes.Push all of the child nodes of Top into the stack from right to left as the traversal from the stack will be carried out in a reverse order. As a result, correct preorder traversal is achieved.
Pop the top node from the stack β Top from the stack and insert it into visited list of nodes.
Push all of the child nodes of Top into the stack from right to left as the traversal from the stack will be carried out in a reverse order. As a result, correct preorder traversal is achieved.
Note: In the below python implementation, a βdequeueβ is used to implement the stack instead of a list because of its efficient append and pop operations.
Below is the implementation of the above approach:
C++
Python3
// C++ program for Iterative Preorder// Traversal of N-ary Tree.// Preorder{ Root, print children// from left to right.#include <bits/stdc++.h>using namespace std; // Node Structure of K-ary Treeclass NewNode {public: int key; // All children are stored in a list vector<NewNode*> child; NewNode(int val) : key(val) { }}; // Utility function to print the// preorder of the given K-Ary Treevoid preorderTraversal(NewNode* root){ stack<NewNode*> Stack; // 'Preorder'-> contains all the // visited nodes vector<int> Preorder; Stack.push(root); while (!Stack.empty()) { NewNode* temp = Stack.top(); Stack.pop(); // store the key in preorder vector(visited list) Preorder.push_back(temp->key); // Push all of the child nodes of temp into // the stack from right to left. for (int i = temp->child.size() - 1; i >= 0; i--) { Stack.push(temp->child[i]); } } for (auto i : Preorder) { cout << i << " "; } cout << endl;} // Driver Codeint main(){ // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ / \ 7 8 9 5 6 / / | \ 10 11 12 13 */ NewNode* root = new NewNode(1); root->child.push_back(new NewNode(2)); root->child.push_back(new NewNode(3)); root->child.push_back(new NewNode(4)); root->child[0]->child.push_back(new NewNode(5)); root->child[0]->child[0]->child.push_back( new NewNode(10)); root->child[0]->child.push_back(new NewNode(6)); root->child[0]->child[1]->child.push_back( new NewNode(11)); root->child[0]->child[1]->child.push_back( new NewNode(12)); root->child[0]->child[1]->child.push_back( new NewNode(13)); root->child[2]->child.push_back(new NewNode(7)); root->child[2]->child.push_back(new NewNode(8)); root->child[2]->child.push_back(new NewNode(9)); preorderTraversal(root);} // This code is contributed by sarangiswastika5
# Python3 program for Iterative Preorder# Traversal of N-ary Tree.# Preorder: Root, print children# from left to right. from collections import deque # Node Structure of K-ary Treeclass NewNode(): def __init__(self, val): self.key = val # all children are stored in a list self.child =[] # Utility function to print the# preorder of the given K-Ary Treedef preorderTraversal(root): Stack = deque([]) # 'Preorder'-> contains all the # visited nodes. Preorder =[] Preorder.append(root.key) Stack.append(root) while len(Stack)>0: # 'Flag' checks whether all the child # nodes have been visited. flag = 0 # CASE 1- If Top of the stack is a leaf # node then remove it from the stack: if len((Stack[len(Stack)-1]).child)== 0: X = Stack.pop() # CASE 2- If Top of the stack is # Parent with children: else: Par = Stack[len(Stack)-1] # a)As soon as an unvisited child is # found(left to right sequence), # Push it to Stack and Store it in # Auxillary List(Marked Visited) # Start Again from Case-1, to explore # this newly visited child for i in range(0, len(Par.child)): if Par.child[i].key not in Preorder: flag = 1 Stack.append(Par.child[i]) Preorder.append(Par.child[i].key) break; # b)If all Child nodes from left to right # of a Parent have been visited # then remove the parent from the stack. if flag == 0: Stack.pop() print(Preorder) # Execution Start From hereif __name__=='__main__':# input nodes ''' 1 / | \ / | \ 2 3 4 / \ / | \ / \ 7 8 9 5 6 / / | \ 10 11 12 13 ''' root = NewNode(1)root.child.append(NewNode(2))root.child.append(NewNode(3))root.child.append(NewNode(4)) root.child[0].child.append(NewNode(5)) root.child[0].child[0].child.append(NewNode(10)) root.child[0].child.append(NewNode(6)) root.child[0].child[1].child.append(NewNode(11))root.child[0].child[1].child.append(NewNode(12))root.child[0].child[1].child.append(NewNode(13)) root.child[2].child.append(NewNode(7))root.child[2].child.append(NewNode(8))root.child[2].child.append(NewNode(9)) preorderTraversal(root)
[1, 2, 5, 10, 6, 11, 12, 13, 3, 4, 7, 8, 9]
shikharrai
sanjeev2552
sarangiswastika5
n-ary-tree
Preorder Traversal
Advanced Data Structure
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Red-Black Tree | Set 2 (Insert)
Decision Tree Introduction with example
Disjoint Set Data Structures
AVL Tree | Set 2 (Deletion)
Binary Tree | Set 1 (Introduction)
Binary Tree | Set 3 (Types of Binary Tree)
Decision Tree
Binary Tree | Set 2 (Properties)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree | [
{
"code": null,
"e": 25034,
"s": 25006,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25155,
"s": 25034,
"text": "Given a K-ary Tree. The task is to write an iterative program to perform the preorder traversal of the given n-ary tree."
},
{
"code": null,
"e": 25167,
"s": 25155,
"text": "Examples: "
},
{
"code": null,
"e": 25632,
"s": 25167,
"text": "Input: 3-Array Tree \n 1\n / | \\\n / | \\\n 2 3 4\n / \\ / | \\\n 5 6 7 8 9\n / / | \\ \n 10 11 12 13\n\nOutput: 1 2 5 10 6 11 12 13 3 4 7 8 9\n\nInput: 3-Array Tree\n 1\n / | \\\n / | \\\n 2 3 4\n / \\ / | \\\n 5 6 7 8 9\n\nOutput: 1 2 5 6 3 4 7 8 9"
},
{
"code": null,
"e": 25900,
"s": 25632,
"text": "Preorder Traversal of an N-ary Tree is similar to the preorder traversal of Binary Search Tree or Binary Tree with the only difference that is, all the child nodes of a parent are traversed from left to right in a sequence.Iterative Preorder Traversal of Binary Tree."
},
{
"code": null,
"e": 26017,
"s": 25900,
"text": "Cases to handle during traversal: Two Cases have been taken care of in this Iterative Preorder Traversal Algorithm: "
},
{
"code": null,
"e": 26305,
"s": 26017,
"text": "Pop the top node from the stack β Top from the stack and insert it into visited list of nodes.Push all of the child nodes of Top into the stack from right to left as the traversal from the stack will be carried out in a reverse order. As a result, correct preorder traversal is achieved."
},
{
"code": null,
"e": 26400,
"s": 26305,
"text": "Pop the top node from the stack β Top from the stack and insert it into visited list of nodes."
},
{
"code": null,
"e": 26594,
"s": 26400,
"text": "Push all of the child nodes of Top into the stack from right to left as the traversal from the stack will be carried out in a reverse order. As a result, correct preorder traversal is achieved."
},
{
"code": null,
"e": 26749,
"s": 26594,
"text": "Note: In the below python implementation, a βdequeueβ is used to implement the stack instead of a list because of its efficient append and pop operations."
},
{
"code": null,
"e": 26802,
"s": 26749,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26806,
"s": 26802,
"text": "C++"
},
{
"code": null,
"e": 26814,
"s": 26806,
"text": "Python3"
},
{
"code": "// C++ program for Iterative Preorder// Traversal of N-ary Tree.// Preorder{ Root, print children// from left to right.#include <bits/stdc++.h>using namespace std; // Node Structure of K-ary Treeclass NewNode {public: int key; // All children are stored in a list vector<NewNode*> child; NewNode(int val) : key(val) { }}; // Utility function to print the// preorder of the given K-Ary Treevoid preorderTraversal(NewNode* root){ stack<NewNode*> Stack; // 'Preorder'-> contains all the // visited nodes vector<int> Preorder; Stack.push(root); while (!Stack.empty()) { NewNode* temp = Stack.top(); Stack.pop(); // store the key in preorder vector(visited list) Preorder.push_back(temp->key); // Push all of the child nodes of temp into // the stack from right to left. for (int i = temp->child.size() - 1; i >= 0; i--) { Stack.push(temp->child[i]); } } for (auto i : Preorder) { cout << i << \" \"; } cout << endl;} // Driver Codeint main(){ // input nodes /* 1 / | \\ / | \\ 2 3 4 / \\ / | \\ / \\ 7 8 9 5 6 / / | \\ 10 11 12 13 */ NewNode* root = new NewNode(1); root->child.push_back(new NewNode(2)); root->child.push_back(new NewNode(3)); root->child.push_back(new NewNode(4)); root->child[0]->child.push_back(new NewNode(5)); root->child[0]->child[0]->child.push_back( new NewNode(10)); root->child[0]->child.push_back(new NewNode(6)); root->child[0]->child[1]->child.push_back( new NewNode(11)); root->child[0]->child[1]->child.push_back( new NewNode(12)); root->child[0]->child[1]->child.push_back( new NewNode(13)); root->child[2]->child.push_back(new NewNode(7)); root->child[2]->child.push_back(new NewNode(8)); root->child[2]->child.push_back(new NewNode(9)); preorderTraversal(root);} // This code is contributed by sarangiswastika5",
"e": 28865,
"s": 26814,
"text": null
},
{
"code": "# Python3 program for Iterative Preorder# Traversal of N-ary Tree.# Preorder: Root, print children# from left to right. from collections import deque # Node Structure of K-ary Treeclass NewNode(): def __init__(self, val): self.key = val # all children are stored in a list self.child =[] # Utility function to print the# preorder of the given K-Ary Treedef preorderTraversal(root): Stack = deque([]) # 'Preorder'-> contains all the # visited nodes. Preorder =[] Preorder.append(root.key) Stack.append(root) while len(Stack)>0: # 'Flag' checks whether all the child # nodes have been visited. flag = 0 # CASE 1- If Top of the stack is a leaf # node then remove it from the stack: if len((Stack[len(Stack)-1]).child)== 0: X = Stack.pop() # CASE 2- If Top of the stack is # Parent with children: else: Par = Stack[len(Stack)-1] # a)As soon as an unvisited child is # found(left to right sequence), # Push it to Stack and Store it in # Auxillary List(Marked Visited) # Start Again from Case-1, to explore # this newly visited child for i in range(0, len(Par.child)): if Par.child[i].key not in Preorder: flag = 1 Stack.append(Par.child[i]) Preorder.append(Par.child[i].key) break; # b)If all Child nodes from left to right # of a Parent have been visited # then remove the parent from the stack. if flag == 0: Stack.pop() print(Preorder) # Execution Start From hereif __name__=='__main__':# input nodes ''' 1 / | \\ / | \\ 2 3 4 / \\ / | \\ / \\ 7 8 9 5 6 / / | \\ 10 11 12 13 ''' root = NewNode(1)root.child.append(NewNode(2))root.child.append(NewNode(3))root.child.append(NewNode(4)) root.child[0].child.append(NewNode(5)) root.child[0].child[0].child.append(NewNode(10)) root.child[0].child.append(NewNode(6)) root.child[0].child[1].child.append(NewNode(11))root.child[0].child[1].child.append(NewNode(12))root.child[0].child[1].child.append(NewNode(13)) root.child[2].child.append(NewNode(7))root.child[2].child.append(NewNode(8))root.child[2].child.append(NewNode(9)) preorderTraversal(root)",
"e": 31407,
"s": 28865,
"text": null
},
{
"code": null,
"e": 31451,
"s": 31407,
"text": "[1, 2, 5, 10, 6, 11, 12, 13, 3, 4, 7, 8, 9]"
},
{
"code": null,
"e": 31464,
"s": 31453,
"text": "shikharrai"
},
{
"code": null,
"e": 31476,
"s": 31464,
"text": "sanjeev2552"
},
{
"code": null,
"e": 31493,
"s": 31476,
"text": "sarangiswastika5"
},
{
"code": null,
"e": 31504,
"s": 31493,
"text": "n-ary-tree"
},
{
"code": null,
"e": 31523,
"s": 31504,
"text": "Preorder Traversal"
},
{
"code": null,
"e": 31547,
"s": 31523,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31552,
"s": 31547,
"text": "Tree"
},
{
"code": null,
"e": 31557,
"s": 31552,
"text": "Tree"
},
{
"code": null,
"e": 31655,
"s": 31557,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31664,
"s": 31655,
"text": "Comments"
},
{
"code": null,
"e": 31677,
"s": 31664,
"text": "Old Comments"
},
{
"code": null,
"e": 31711,
"s": 31677,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 31743,
"s": 31711,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 31783,
"s": 31743,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31812,
"s": 31783,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 31840,
"s": 31812,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 31875,
"s": 31840,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 31918,
"s": 31875,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 31932,
"s": 31918,
"text": "Decision Tree"
},
{
"code": null,
"e": 31965,
"s": 31932,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
Tryit Editor v3.7 | Tryit basic HTML headings | [] |
Groovy - isEmpty() | Returns true if this List contains no elements.
boolean isEmpty()
None
True or false depending on whether the list is empty or not.
Following is an example of the usage of this method β
class Example {
static void main(String[] args) {
def lst = [11, 12, 13, 14];
def emptylst = [];
println(lst.isEmpty());
println(emptylst.isEmpty());
}
}
When we run the above program, we will get the following result β
false
true
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2286,
"s": 2238,
"text": "Returns true if this List contains no elements."
},
{
"code": null,
"e": 2306,
"s": 2286,
"text": "boolean isEmpty() \n"
},
{
"code": null,
"e": 2311,
"s": 2306,
"text": "None"
},
{
"code": null,
"e": 2372,
"s": 2311,
"text": "True or false depending on whether the list is empty or not."
},
{
"code": null,
"e": 2426,
"s": 2372,
"text": "Following is an example of the usage of this method β"
},
{
"code": null,
"e": 2619,
"s": 2426,
"text": "class Example { \n static void main(String[] args) { \n def lst = [11, 12, 13, 14]; \n def emptylst = [];\n\t\t\n println(lst.isEmpty()); \n println(emptylst.isEmpty()); \n } \n}"
},
{
"code": null,
"e": 2685,
"s": 2619,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 2698,
"s": 2685,
"text": "false \ntrue\n"
},
{
"code": null,
"e": 2731,
"s": 2698,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2749,
"s": 2731,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2784,
"s": 2749,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2802,
"s": 2784,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2809,
"s": 2802,
"text": " Print"
},
{
"code": null,
"e": 2820,
"s": 2809,
"text": " Add Notes"
}
] |
How to check android mobile supports magnetometer? | This example demonstrate about How to check android mobile supports magnetometer
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
In the above code, we have taken text view to show magnetometer sensor information.
Step 3 β Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.usage.UsageEvents;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.annotation.RequiresApi;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.LogPrinter;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.logging.LogManager;
import javax.crypto.KeyGenerator;
public class MainActivity extends AppCompatActivity {
TextView textView;
private SensorManager sensorManager;
@SuppressLint({"RestrictedApi", "ClickableViewAccessibility"})
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView actionEvent = findViewById(R.id.actionEvent);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null) {
actionEvent.setText("magnetometer supports");
} else {
actionEvent.setText("no magnetometer supports");
}
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "This example demonstrate about How to check android mobile supports magnetometer"
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1896,
"s": 1337,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:app=\"http://schemas.android.com/apk/res-auto\"\nxmlns:tools=\"http://schemas.android.com/tools\"\nandroid:layout_width=\"match_parent\"\nandroid:gravity=\"center\"\nandroid:layout_height=\"match_parent\"\ntools:context=\".MainActivity\"\nandroid:orientation=\"vertical\">\n<TextView\nandroid:id=\"@+id/actionEvent\"\nandroid:textSize=\"40sp\"\nandroid:layout_marginTop=\"30dp\"\nandroid:layout_width=\"wrap_content\"\nandroid:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1980,
"s": 1896,
"text": "In the above code, we have taken text view to show magnetometer sensor information."
},
{
"code": null,
"e": 2037,
"s": 1980,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3987,
"s": 2037,
"text": "package com.example.myapplication;\nimport android.annotation.SuppressLint;\nimport android.app.KeyguardManager;\nimport android.app.usage.UsageEvents;\nimport android.content.Context;\nimport android.hardware.Sensor;\nimport android.hardware.SensorManager;\nimport android.hardware.fingerprint.FingerprintManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.security.keystore.KeyGenParameterSpec;\nimport android.security.keystore.KeyProperties;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.view.MotionEventCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.util.LogPrinter;\nimport android.view.DragEvent;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.View.OnTouchListener;\nimport android.widget.Switch;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.NoSuchProviderException;\nimport java.util.logging.LogManager;\nimport javax.crypto.KeyGenerator;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n private SensorManager sensorManager;\n @SuppressLint({\"RestrictedApi\", \"ClickableViewAccessibility\"})\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView actionEvent = findViewById(R.id.actionEvent);\n sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);\n sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);\n if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null) {\n actionEvent.setText(\"magnetometer supports\");\n } else {\n actionEvent.setText(\"no magnetometer supports\");\n }\n }\n}"
},
{
"code": null,
"e": 4334,
"s": 3987,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 4376,
"s": 4334,
"text": "Click here to download the project code"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.