title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to check an element has certain CSS style using jQuery ? | 16 Oct, 2019
Given an HTML document containing some CSS property and the task is to check whether an element has a specific CSS style or not with the help of jQuery.
Approach 1: Use css() method to check an element contains certain CSS styles or not.
Example: This example uses css() method to check an element contains certain CSS style or not.
<!DOCTYPE HTML> <html> <head> <title> How to check an element has certain CSS style using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style="color:green"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = "Click on the button to check" + " if H1 has style, color = green."; function GFG_Fun() { if ($("#h1").css("color") == "rgb(0, 128, 0)") { down.innerHTML = "H1 has CSS style, color: green"; } else { down.innerHTML = "H1 has not CSS style, color: green"; } } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2: Use hasClass() method to check an element contains certain CSS styles or not.
Example: This example uses hasClass() method to check an element contains certain CSS style or not.
<!DOCTYPE HTML> <html> <head> <title> How to check an element has certain CSS style using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" class = "color" style = "font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = "Click on the button to check if" + " P[id = GFG_DOWN] has style, color =" + " green using class."; function GFG_Fun() { if ($("#GFG_DOWN").hasClass('color')) { down.innerHTML = "P[id = GFG_DOWN] has CSS style, color: green"; } else { down.innerHTML = "P[id = GFG_DOWN] has not CSS style, color: green"; } } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
CSS-Misc
jQuery-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2019"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "Given an HTML document containing some CSS property and the task is to check whether an element has a specific CSS style or not with the help of jQuery."
},
{
"code": null,
"e": 266,
"s": 181,
"text": "Approach 1: Use css() method to check an element contains certain CSS styles or not."
},
{
"code": null,
"e": 361,
"s": 266,
"text": "Example: This example uses css() method to check an element contains certain CSS style or not."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to check an element has certain CSS style using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = \"Click on the button to check\" + \" if H1 has style, color = green.\"; function GFG_Fun() { if ($(\"#h1\").css(\"color\") == \"rgb(0, 128, 0)\") { down.innerHTML = \"H1 has CSS style, color: green\"; } else { down.innerHTML = \"H1 has not CSS style, color: green\"; } } </script> </body> </html>",
"e": 1543,
"s": 361,
"text": null
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Output:"
},
{
"code": null,
"e": 1582,
"s": 1551,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1612,
"s": 1582,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1702,
"s": 1612,
"text": "Approach 2: Use hasClass() method to check an element contains certain CSS styles or not."
},
{
"code": null,
"e": 1802,
"s": 1702,
"text": "Example: This example uses hasClass() method to check an element contains certain CSS style or not."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to check an element has certain CSS style using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" class = \"color\" style = \"font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = \"Click on the button to check if\" + \" P[id = GFG_DOWN] has style, color =\" + \" green using class.\"; function GFG_Fun() { if ($(\"#GFG_DOWN\").hasClass('color')) { down.innerHTML = \"P[id = GFG_DOWN] has CSS style, color: green\"; } else { down.innerHTML = \"P[id = GFG_DOWN] has not CSS style, color: green\"; } } </script> </body> </html>",
"e": 3087,
"s": 1802,
"text": null
},
{
"code": null,
"e": 3095,
"s": 3087,
"text": "Output:"
},
{
"code": null,
"e": 3126,
"s": 3095,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3156,
"s": 3126,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3165,
"s": 3156,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3177,
"s": 3165,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 3188,
"s": 3177,
"text": "JavaScript"
},
{
"code": null,
"e": 3205,
"s": 3188,
"text": "Web Technologies"
},
{
"code": null,
"e": 3232,
"s": 3205,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3330,
"s": 3232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3391,
"s": 3330,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3431,
"s": 3391,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3472,
"s": 3431,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3514,
"s": 3472,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3536,
"s": 3514,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3569,
"s": 3536,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3631,
"s": 3569,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3692,
"s": 3631,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3742,
"s": 3692,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Stream flatMap() in Java with examples | 12 Mar, 2018
Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Note : Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead.
flatMap() V/s map() :1) map() takes a Stream and transform it to another Stream. It applies a function on each element of Stream and store return value into new Stream. It does not flatten the stream. But flatMap() is the combination of a map and a flat operation i.e, it applies a function to elements as well as flatten them.2) map() is used for transformation only, but flatMap() is used for both transformation and flattening.
Syntax :
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
where, R is the element type of the new stream.
Stream is an interface and T is the type
of stream elements. mapper is a stateless function
which is applied to each element and the function
returns the new stream.
Example 1 : flatMap() function with provided mapping function.
// Java code for Stream flatMap// (Function mapper) to get a stream by// replacing the stream with a mapped// stream by applying the provided mapping function.import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList("5.6", "7.4", "4", "1", "2.3"); // Using Stream flatMap(Function mapper) list.stream().flatMap(num -> Stream.of(num)). forEach(System.out::println); }}
Output :
5.6
7.4
4
1
2.3
Example 2 : flatMap() function with provided operation of mapping string with character at position 2.
// Java code for Stream flatMap// (Function mapper) to get a stream by// replacing the stream with a mapped// stream by applying the provided mapping function.import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList("Geeks", "GFG", "GeeksforGeeks", "gfg"); // Using Stream flatMap(Function mapper) list.stream().flatMap(str -> Stream.of(str.charAt(2))). forEach(System.out::println); }}
Output :
e
G
e
g
As already discussed in the post that flatMap() is the combination of a map and a flat operation i.e, it first applies map function and than flattens the result. Let us consider some examples to understand what exactly flattening a stream is.Example 1 :The list before flattening :
[ [2, 3, 5], [7, 11, 13], [17, 19, 23] ]
The list has 2 levels and consists of 3 small lists. After Flattening, it gets transformed into “one level” structure as shown :
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
Example 2 :The list before flattening :
[ ["G", "E", "E"], ["K", "S", "F"], ["O", "R", "G"], ["E", "E", "K", "S"] ]
The list has 3 levels and consists of 4 small lists. After Flattening, it gets transformed into “one level” structure as shown :
["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"]
In short, we can say that if there is a Stream of List of <<Data Type>> before flattening, then on applying flatMap(), Stream of <<Data Type>> is returned after flattening.Application :
// Java code for Stream flatMap(Function mapper) import java.util.*;import java.util.stream.Collectors; class GFG{ // Driver code public static void main(String[] args) { // Creating a list of Prime Numbers List<Integer> PrimeNumbers = Arrays.asList(5, 7, 11,13); // Creating a list of Odd Numbers List<Integer> OddNumbers = Arrays.asList(1, 3, 5); // Creating a list of Even Numbers List<Integer> EvenNumbers = Arrays.asList(2, 4, 6, 8); List<List<Integer>> listOfListofInts = Arrays.asList(PrimeNumbers, OddNumbers, EvenNumbers); System.out.println("The Structure before flattening is : " + listOfListofInts); // Using flatMap for transformating and flattening. List<Integer> listofInts = listOfListofInts.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList()); System.out.println("The Structure after flattening is : " + listofInts); }}
Output :
The Structure before flattening is : [[5, 7, 11, 13], [1, 3, 5], [2, 4, 6, 8]]
The Structure after flattening is : [5, 7, 11, 13, 1, 3, 5, 2, 4, 6, 8]
Java - util package
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Mar, 2018"
},
{
"code": null,
"e": 505,
"s": 52,
"text": "Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output."
},
{
"code": null,
"e": 657,
"s": 505,
"text": "Note : Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead."
},
{
"code": null,
"e": 1088,
"s": 657,
"text": "flatMap() V/s map() :1) map() takes a Stream and transform it to another Stream. It applies a function on each element of Stream and store return value into new Stream. It does not flatten the stream. But flatMap() is the combination of a map and a flat operation i.e, it applies a function to elements as well as flatten them.2) map() is used for transformation only, but flatMap() is used for both transformation and flattening."
},
{
"code": null,
"e": 1097,
"s": 1088,
"text": "Syntax :"
},
{
"code": null,
"e": 1396,
"s": 1097,
"text": "<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)\n\nwhere, R is the element type of the new stream.\nStream is an interface and T is the type \nof stream elements. mapper is a stateless function \nwhich is applied to each element and the function\nreturns the new stream.\n"
},
{
"code": null,
"e": 1459,
"s": 1396,
"text": "Example 1 : flatMap() function with provided mapping function."
},
{
"code": "// Java code for Stream flatMap// (Function mapper) to get a stream by// replacing the stream with a mapped// stream by applying the provided mapping function.import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList(\"5.6\", \"7.4\", \"4\", \"1\", \"2.3\"); // Using Stream flatMap(Function mapper) list.stream().flatMap(num -> Stream.of(num)). forEach(System.out::println); }}",
"e": 2065,
"s": 1459,
"text": null
},
{
"code": null,
"e": 2074,
"s": 2065,
"text": "Output :"
},
{
"code": null,
"e": 2091,
"s": 2074,
"text": "5.6\n7.4\n4\n1\n2.3\n"
},
{
"code": null,
"e": 2194,
"s": 2091,
"text": "Example 2 : flatMap() function with provided operation of mapping string with character at position 2."
},
{
"code": "// Java code for Stream flatMap// (Function mapper) to get a stream by// replacing the stream with a mapped// stream by applying the provided mapping function.import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"gfg\"); // Using Stream flatMap(Function mapper) list.stream().flatMap(str -> Stream.of(str.charAt(2))). forEach(System.out::println); }}",
"e": 2835,
"s": 2194,
"text": null
},
{
"code": null,
"e": 2844,
"s": 2835,
"text": "Output :"
},
{
"code": null,
"e": 2853,
"s": 2844,
"text": "e\nG\ne\ng\n"
},
{
"code": null,
"e": 3135,
"s": 2853,
"text": "As already discussed in the post that flatMap() is the combination of a map and a flat operation i.e, it first applies map function and than flattens the result. Let us consider some examples to understand what exactly flattening a stream is.Example 1 :The list before flattening :"
},
{
"code": null,
"e": 3177,
"s": 3135,
"text": "[ [2, 3, 5], [7, 11, 13], [17, 19, 23] ]\n"
},
{
"code": null,
"e": 3306,
"s": 3177,
"text": "The list has 2 levels and consists of 3 small lists. After Flattening, it gets transformed into “one level” structure as shown :"
},
{
"code": null,
"e": 3343,
"s": 3306,
"text": "[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ] \n"
},
{
"code": null,
"e": 3383,
"s": 3343,
"text": "Example 2 :The list before flattening :"
},
{
"code": null,
"e": 3460,
"s": 3383,
"text": "[ [\"G\", \"E\", \"E\"], [\"K\", \"S\", \"F\"], [\"O\", \"R\", \"G\"], [\"E\", \"E\", \"K\", \"S\"] ]\n"
},
{
"code": null,
"e": 3589,
"s": 3460,
"text": "The list has 3 levels and consists of 4 small lists. After Flattening, it gets transformed into “one level” structure as shown :"
},
{
"code": null,
"e": 3657,
"s": 3589,
"text": "[\"G\", \"E\", \"E\", \"K\", \"S\", \"F\", \"O\", \"R\", \"G\", \"E\", \"E\", \"K\", \"S\"] \n"
},
{
"code": null,
"e": 3843,
"s": 3657,
"text": "In short, we can say that if there is a Stream of List of <<Data Type>> before flattening, then on applying flatMap(), Stream of <<Data Type>> is returned after flattening.Application :"
},
{
"code": "// Java code for Stream flatMap(Function mapper) import java.util.*;import java.util.stream.Collectors; class GFG{ // Driver code public static void main(String[] args) { // Creating a list of Prime Numbers List<Integer> PrimeNumbers = Arrays.asList(5, 7, 11,13); // Creating a list of Odd Numbers List<Integer> OddNumbers = Arrays.asList(1, 3, 5); // Creating a list of Even Numbers List<Integer> EvenNumbers = Arrays.asList(2, 4, 6, 8); List<List<Integer>> listOfListofInts = Arrays.asList(PrimeNumbers, OddNumbers, EvenNumbers); System.out.println(\"The Structure before flattening is : \" + listOfListofInts); // Using flatMap for transformating and flattening. List<Integer> listofInts = listOfListofInts.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList()); System.out.println(\"The Structure after flattening is : \" + listofInts); }}",
"e": 5022,
"s": 3843,
"text": null
},
{
"code": null,
"e": 5031,
"s": 5022,
"text": "Output :"
},
{
"code": null,
"e": 5183,
"s": 5031,
"text": "The Structure before flattening is : [[5, 7, 11, 13], [1, 3, 5], [2, 4, 6, 8]]\nThe Structure after flattening is : [5, 7, 11, 13, 1, 3, 5, 2, 4, 6, 8]\n"
},
{
"code": null,
"e": 5203,
"s": 5183,
"text": "Java - util package"
},
{
"code": null,
"e": 5215,
"s": 5203,
"text": "java-stream"
},
{
"code": null,
"e": 5220,
"s": 5215,
"text": "Java"
},
{
"code": null,
"e": 5225,
"s": 5220,
"text": "Java"
},
{
"code": null,
"e": 5323,
"s": 5225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5374,
"s": 5323,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5405,
"s": 5374,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5424,
"s": 5405,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5454,
"s": 5424,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5472,
"s": 5454,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5492,
"s": 5472,
"text": "Collections in Java"
},
{
"code": null,
"e": 5524,
"s": 5492,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5544,
"s": 5524,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 5568,
"s": 5544,
"text": "Singleton Class in Java"
}
] |
How to use R8 to Reduce APK Size in Android? | 23 Feb, 2021
If you are building any apps and you want to target this app to a large audience then there are so many factors which you should consider while building your apps. The most important factor while building any application is its size. The size of the app matters a lot. If your app size is very high then users don’t like to download such big apps that require such a huge storage space and data charges. So it is very important to maintain your app size for your users while building any Android application. In this article, we will take a look at reducing app size using R8.
What is R8?
How to use R8 shrinking in your app?
How the shrinking in R8 works?
For enabling R8 in your application you have to use the Android Studio version like 3.4 or higher.
The Gradle version inside your project should have a version of around 3.4.0
R8 is an app shrinking tool that is used to reduce the size of your application. This tool present in Android Studio works with the rules of Proguard. R8 will convert your app’s code into optimized Dalvik code. During this process of conversion R8 will remove the classes and methods which are unused inside our application. Along with this android applications are having so many unused files that we don’t require inside our application so R8 will remove that files and helps in the reduction of app size. The benefit of using R8 is that it will make your app more secure and difficult to reverse engineer. So this will helps us to increase the security of our application.
Optimization of your code: In this process, R8 will actually optimize the code to reduce app size. So in the process of optimization, it will remove the unused classes, methods, and dead code present inside our application.
Identifier Renaming: In this process, R8 will actually rename our class names and variable names. While writing code we use some identifier pattern so that we can understand our code properly. But in this process, R8 will rename all the classes into smaller variable names that will also help to reduce APK size. for example, you have generated a new class named “Constant” for storing some constants which are being used in different parts of our application. R8 will rename that class in any smaller name let’s say “a” or in any other format.
Shrinking: While writing code we create so many methods inside our application. While creating this method some of the methods are not being used inside our application, those methods are called unreachable methods which are not being used anywhere inside our application. So R8 will remove such unreachable methods to reduce the size of APK.
Optimization of 3rd party library: For the implementation of many external features inside our application developers generally prefer to use external libraries inside their application. But while using these libraries this it will install so many files that we don’t require for our app. So R8 will optimize the code for that library and keep only that code that is required in our application and will remove the files which are unused.
Now we will move towards the practical implementation of R8 inside our app.
Implementation of R8 shrinking is a single-step process. First of all, create a New Project with an empty activity inside Android Studio. For creating a new project in Android Studio. Take a look over this link on How to create a new project in Android Studio. After creating this new project. Navigate to the Gradle scripts > build.gradle(:app) and you will get to see the section of buildTypes. Inside this change minifyEnabled from false to true to enable R8. Below is the section where we have to make a change.
buildTypes {
release {
// make change here
minifyEnabled true
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
After changing it true sync your project and R8 is being added inside your application You can now test the APK size by building the APK. You can also test the APK size by adding some external libraries. Test the APK size using R8 and without using R8 you will get to see the difference between the size of APK.
The algorithms which are used by R8 for the reduction of app size will trace for the unused methods and unreachable code in your application and remove those methods. So R8 will start tracing your code from an entry point which we have to declare for any class and from that entry point R8 will starts tracing the code for the unused code. For example, we will take a look at a class which is created below:
Java
/*package whatever //do not write package name here */ import java.io.*; // entry point for R8 class GFG { // Method one is used // inside our main method. private void methodone(){ System.out.println("Method 1 "); } // Method two is not being // used in our main method. private void methodtwo(){ System.out.println("Method 2 "); } // Our main method public static void main (String[] args) { methodone(); }}
Inside the proguard we will ad the below rule to it as:
-keep class GFG {
public static void main (String[] args) {
}
}
In the above example, the proguard will start scanning your application from the main method and inside this method, the methodone() will be called first and after printing method one the tracing will be stopped. Then R8 will look for the unused method inside our application the unused method is methodtwo() which we are not using inside our main method. So R8 will remove that methodtwo() inside our application. and the methodone() will be renamed with some smaller names and align the code properly. After aligning the code will look like the below example.
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { System.out.println("Method 1 "); }}
So inside our application in Android Studio, there are so many files that are to be traced by R8. So for tracing these files and deciding the entry point for each file aapt2 tool is used. Add the below line below to that of the line where you have enabled your proguard.
minifyEnabled true
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’)
But while using this there are some problems with gson files When your code contains some reflection files So it will remove that code but we have to keep that code inside our project. For implementing this add the below line under the minifyEnabled true.
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-gson.pro’, ‘proguard-rules.pro’
So to overcome the issues while Gson in Android adds the line which is shown above in your build.gradle file. So in this way we have implemented the R8 app shrinking inside our application and this will helps to reduce the size of our app.
Android-Misc
Technical Scripter 2020
Android
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Introduction to Android Development
Activity Lifecycle in Android with Demo App
Fragment Lifecycle in Android | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 630,
"s": 52,
"text": "If you are building any apps and you want to target this app to a large audience then there are so many factors which you should consider while building your apps. The most important factor while building any application is its size. The size of the app matters a lot. If your app size is very high then users don’t like to download such big apps that require such a huge storage space and data charges. So it is very important to maintain your app size for your users while building any Android application. In this article, we will take a look at reducing app size using R8. "
},
{
"code": null,
"e": 642,
"s": 630,
"text": "What is R8?"
},
{
"code": null,
"e": 679,
"s": 642,
"text": "How to use R8 shrinking in your app?"
},
{
"code": null,
"e": 710,
"s": 679,
"text": "How the shrinking in R8 works?"
},
{
"code": null,
"e": 809,
"s": 710,
"text": "For enabling R8 in your application you have to use the Android Studio version like 3.4 or higher."
},
{
"code": null,
"e": 886,
"s": 809,
"text": "The Gradle version inside your project should have a version of around 3.4.0"
},
{
"code": null,
"e": 1563,
"s": 886,
"text": "R8 is an app shrinking tool that is used to reduce the size of your application. This tool present in Android Studio works with the rules of Proguard. R8 will convert your app’s code into optimized Dalvik code. During this process of conversion R8 will remove the classes and methods which are unused inside our application. Along with this android applications are having so many unused files that we don’t require inside our application so R8 will remove that files and helps in the reduction of app size. The benefit of using R8 is that it will make your app more secure and difficult to reverse engineer. So this will helps us to increase the security of our application. "
},
{
"code": null,
"e": 1787,
"s": 1563,
"text": "Optimization of your code: In this process, R8 will actually optimize the code to reduce app size. So in the process of optimization, it will remove the unused classes, methods, and dead code present inside our application."
},
{
"code": null,
"e": 2332,
"s": 1787,
"text": "Identifier Renaming: In this process, R8 will actually rename our class names and variable names. While writing code we use some identifier pattern so that we can understand our code properly. But in this process, R8 will rename all the classes into smaller variable names that will also help to reduce APK size. for example, you have generated a new class named “Constant” for storing some constants which are being used in different parts of our application. R8 will rename that class in any smaller name let’s say “a” or in any other format."
},
{
"code": null,
"e": 2675,
"s": 2332,
"text": "Shrinking: While writing code we create so many methods inside our application. While creating this method some of the methods are not being used inside our application, those methods are called unreachable methods which are not being used anywhere inside our application. So R8 will remove such unreachable methods to reduce the size of APK."
},
{
"code": null,
"e": 3114,
"s": 2675,
"text": "Optimization of 3rd party library: For the implementation of many external features inside our application developers generally prefer to use external libraries inside their application. But while using these libraries this it will install so many files that we don’t require for our app. So R8 will optimize the code for that library and keep only that code that is required in our application and will remove the files which are unused."
},
{
"code": null,
"e": 3191,
"s": 3114,
"text": "Now we will move towards the practical implementation of R8 inside our app. "
},
{
"code": null,
"e": 3707,
"s": 3191,
"text": "Implementation of R8 shrinking is a single-step process. First of all, create a New Project with an empty activity inside Android Studio. For creating a new project in Android Studio. Take a look over this link on How to create a new project in Android Studio. After creating this new project. Navigate to the Gradle scripts > build.gradle(:app) and you will get to see the section of buildTypes. Inside this change minifyEnabled from false to true to enable R8. Below is the section where we have to make a change."
},
{
"code": null,
"e": 3720,
"s": 3707,
"text": "buildTypes {"
},
{
"code": null,
"e": 3737,
"s": 3720,
"text": " release {"
},
{
"code": null,
"e": 3768,
"s": 3737,
"text": " // make change here"
},
{
"code": null,
"e": 3798,
"s": 3768,
"text": " minifyEnabled true"
},
{
"code": null,
"e": 3901,
"s": 3798,
"text": " proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’"
},
{
"code": null,
"e": 3914,
"s": 3901,
"text": " }"
},
{
"code": null,
"e": 3919,
"s": 3914,
"text": " }"
},
{
"code": null,
"e": 4232,
"s": 3919,
"text": "After changing it true sync your project and R8 is being added inside your application You can now test the APK size by building the APK. You can also test the APK size by adding some external libraries. Test the APK size using R8 and without using R8 you will get to see the difference between the size of APK. "
},
{
"code": null,
"e": 4641,
"s": 4232,
"text": "The algorithms which are used by R8 for the reduction of app size will trace for the unused methods and unreachable code in your application and remove those methods. So R8 will start tracing your code from an entry point which we have to declare for any class and from that entry point R8 will starts tracing the code for the unused code. For example, we will take a look at a class which is created below: "
},
{
"code": null,
"e": 4646,
"s": 4641,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; // entry point for R8 class GFG { // Method one is used // inside our main method. private void methodone(){ System.out.println(\"Method 1 \"); } // Method two is not being // used in our main method. private void methodtwo(){ System.out.println(\"Method 2 \"); } // Our main method public static void main (String[] args) { methodone(); }}",
"e": 5116,
"s": 4646,
"text": null
},
{
"code": null,
"e": 5173,
"s": 5116,
"text": "Inside the proguard we will ad the below rule to it as: "
},
{
"code": null,
"e": 5191,
"s": 5173,
"text": "-keep class GFG {"
},
{
"code": null,
"e": 5236,
"s": 5191,
"text": " public static void main (String[] args) {"
},
{
"code": null,
"e": 5245,
"s": 5236,
"text": " }"
},
{
"code": null,
"e": 5247,
"s": 5245,
"text": "}"
},
{
"code": null,
"e": 5810,
"s": 5247,
"text": "In the above example, the proguard will start scanning your application from the main method and inside this method, the methodone() will be called first and after printing method one the tracing will be stopped. Then R8 will look for the unused method inside our application the unused method is methodtwo() which we are not using inside our main method. So R8 will remove that methodtwo() inside our application. and the methodone() will be renamed with some smaller names and align the code properly. After aligning the code will look like the below example. "
},
{
"code": null,
"e": 5815,
"s": 5810,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { System.out.println(\"Method 1 \"); }}",
"e": 5997,
"s": 5815,
"text": null
},
{
"code": null,
"e": 6268,
"s": 5997,
"text": "So inside our application in Android Studio, there are so many files that are to be traced by R8. So for tracing these files and deciding the entry point for each file aapt2 tool is used. Add the below line below to that of the line where you have enabled your proguard."
},
{
"code": null,
"e": 6287,
"s": 6268,
"text": "minifyEnabled true"
},
{
"code": null,
"e": 6357,
"s": 6287,
"text": "proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’)"
},
{
"code": null,
"e": 6614,
"s": 6357,
"text": "But while using this there are some problems with gson files When your code contains some reflection files So it will remove that code but we have to keep that code inside our project. For implementing this add the below line under the minifyEnabled true. "
},
{
"code": null,
"e": 6727,
"s": 6614,
"text": "proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-gson.pro’, ‘proguard-rules.pro’"
},
{
"code": null,
"e": 6968,
"s": 6727,
"text": "So to overcome the issues while Gson in Android adds the line which is shown above in your build.gradle file. So in this way we have implemented the R8 app shrinking inside our application and this will helps to reduce the size of our app. "
},
{
"code": null,
"e": 6981,
"s": 6968,
"text": "Android-Misc"
},
{
"code": null,
"e": 7005,
"s": 6981,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 7013,
"s": 7005,
"text": "Android"
},
{
"code": null,
"e": 7032,
"s": 7013,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7040,
"s": 7032,
"text": "Android"
},
{
"code": null,
"e": 7138,
"s": 7040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7207,
"s": 7138,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7239,
"s": 7207,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7278,
"s": 7239,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7327,
"s": 7278,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 7369,
"s": 7327,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7420,
"s": 7369,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 7443,
"s": 7420,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 7479,
"s": 7443,
"text": "Introduction to Android Development"
},
{
"code": null,
"e": 7523,
"s": 7479,
"text": "Activity Lifecycle in Android with Demo App"
}
] |
Throwable initCause() method in Java with Examples | 19 Aug, 2019
The initCause() method of Throwable class is used to initialize the cause of the this Throwable with the specified cause passed as a parameter to initCause(). Actually, the cause is the throwable that caused this throwable Object to get thrown when an exception occurs. This method can be called only once. Generally, This method is called from within the constructor, or immediately after creating the throwable. If the calling Throwable is created by using Throwable(Throwable) or Throwable(String, Throwable), then this method cannot be called even once.
Syntax:
public Throwable initCause?(Throwable cause)
Parameters: This method accepts cause as a parameter which represents the cause of the this Throwable.
Returns: This method returns a reference to this Throwable instance.
Exception: This method throws:
IllegalArgumentException if cause is this throwable.
IllegalStateException if this throwable was created with Throwable(Throwable) or Throwable(String, Throwable), or this method has already been called on this throwable.
Below programs illustrate the initCause method of Throwable class:
Example 1:
// Java program to demonstrate// the initCause() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { System.out.println("Cause : " + e.getCause()); } } // method which throws Exception public static void testException1() throws Exception { // ArrayIndexOutOfBoundsException Exception // This exception will be used as a Cause // of another exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }}
Cause : java.lang.ArrayIndexOutOfBoundsException
Example 2:
// Java program to demonstrate// the initCause() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // add the numbers addPositiveNumbers(2, -1); } catch (Throwable e) { System.out.println("Cause : " + e.getCause()); } } // method which adds two positive number public static void addPositiveNumbers(int a, int b) throws Exception { // if Numbers are Positive // than add or throw Exception if (a < 0 || b < 0) { // create a Exception // when Numbers are not Positive // This exception will be used as a Cause // of another exception Exception ee = new Exception("Numbers are not Positive"); // create a new Exception Exception anotherEXe = new Exception(); // initialize the cause and throw Exception anotherEXe.initCause(ee); throw anotherEXe; } else { System.out.println(a + b); } }}
Cause : java.lang.Exception: Numbers are not Positive
References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#initCause(java.lang.Throwable)
Akanksha_Rai
Java-Exception Handling
Java-Exceptions
Java-Functions
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 586,
"s": 28,
"text": "The initCause() method of Throwable class is used to initialize the cause of the this Throwable with the specified cause passed as a parameter to initCause(). Actually, the cause is the throwable that caused this throwable Object to get thrown when an exception occurs. This method can be called only once. Generally, This method is called from within the constructor, or immediately after creating the throwable. If the calling Throwable is created by using Throwable(Throwable) or Throwable(String, Throwable), then this method cannot be called even once."
},
{
"code": null,
"e": 594,
"s": 586,
"text": "Syntax:"
},
{
"code": null,
"e": 639,
"s": 594,
"text": "public Throwable initCause?(Throwable cause)"
},
{
"code": null,
"e": 742,
"s": 639,
"text": "Parameters: This method accepts cause as a parameter which represents the cause of the this Throwable."
},
{
"code": null,
"e": 811,
"s": 742,
"text": "Returns: This method returns a reference to this Throwable instance."
},
{
"code": null,
"e": 842,
"s": 811,
"text": "Exception: This method throws:"
},
{
"code": null,
"e": 895,
"s": 842,
"text": "IllegalArgumentException if cause is this throwable."
},
{
"code": null,
"e": 1064,
"s": 895,
"text": "IllegalStateException if this throwable was created with Throwable(Throwable) or Throwable(String, Throwable), or this method has already been called on this throwable."
},
{
"code": null,
"e": 1131,
"s": 1064,
"text": "Below programs illustrate the initCause method of Throwable class:"
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// the initCause() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { System.out.println(\"Cause : \" + e.getCause()); } } // method which throws Exception public static void testException1() throws Exception { // ArrayIndexOutOfBoundsException Exception // This exception will be used as a Cause // of another exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }}",
"e": 2034,
"s": 1142,
"text": null
},
{
"code": null,
"e": 2084,
"s": 2034,
"text": "Cause : java.lang.ArrayIndexOutOfBoundsException\n"
},
{
"code": null,
"e": 2095,
"s": 2084,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the initCause() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // add the numbers addPositiveNumbers(2, -1); } catch (Throwable e) { System.out.println(\"Cause : \" + e.getCause()); } } // method which adds two positive number public static void addPositiveNumbers(int a, int b) throws Exception { // if Numbers are Positive // than add or throw Exception if (a < 0 || b < 0) { // create a Exception // when Numbers are not Positive // This exception will be used as a Cause // of another exception Exception ee = new Exception(\"Numbers are not Positive\"); // create a new Exception Exception anotherEXe = new Exception(); // initialize the cause and throw Exception anotherEXe.initCause(ee); throw anotherEXe; } else { System.out.println(a + b); } }}",
"e": 3296,
"s": 2095,
"text": null
},
{
"code": null,
"e": 3351,
"s": 3296,
"text": "Cause : java.lang.Exception: Numbers are not Positive\n"
},
{
"code": null,
"e": 3462,
"s": 3351,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#initCause(java.lang.Throwable)"
},
{
"code": null,
"e": 3475,
"s": 3462,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3499,
"s": 3475,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 3515,
"s": 3499,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 3530,
"s": 3515,
"text": "Java-Functions"
},
{
"code": null,
"e": 3545,
"s": 3530,
"text": "java-Throwable"
},
{
"code": null,
"e": 3550,
"s": 3545,
"text": "Java"
},
{
"code": null,
"e": 3555,
"s": 3550,
"text": "Java"
}
] |
Combine vectors or DataFrames of unequal length in R | 07 Apr, 2021
In this article, we are going to see how to combine vectors or DataFrames of unequal length into one DataFrame in R Programming Language.
Functions Used:
c(“Value1”, “Value2”, “Value3”) : This is a generic function which combines its arguments. The default method combines its arguments(Values) to form a vector.length(vector): Get or set the length of the Vectors, Factors, or any other R Objects.max(...): Returns the maximum of all the values passing inside it’s an argument.rep(x, ...): Replicates the values in x and the second argument can be anything from times, length(), length.out, each.
c(“Value1”, “Value2”, “Value3”) : This is a generic function which combines its arguments. The default method combines its arguments(Values) to form a vector.
length(vector): Get or set the length of the Vectors, Factors, or any other R Objects.
max(...): Returns the maximum of all the values passing inside it’s an argument.
rep(x, ...): Replicates the values in x and the second argument can be anything from times, length(), length.out, each.
Stepwise implementation:
Step 1: Prepare the vectors for dataframe using the c() function. Here we dummy student data and Rollno, Name, Marks, and Age as a vector. As you can see below, we have Name and Age of only first three students. We have not other three’s name and age data. Also, we have not a mark of the last student.
R
Rollno <- c("5", "6", "7", "8", "9", "10")Name <- c("John Doe", "Jane Doe", "Bill Gates")Marks <- c("80", "75", "95", "96", "70", "86")Age <- c("13", "13", "14")
Step 2: As you can see above data, the length of Rollno, Name, Marks, and Age is 6, 3, 5, and 3 respectively. Now, by using the max() function. Inside max() function we get all vector’s length by length() function. We will get the maximum length overall vectors that we created and store this length to the maxlength variable. Also, check the length by print it for testing purposes.
R
Rollno <- c("5", "6", "7", "8", "9", "10") # length = 6Name <- c("John Doe","Jane Doe", "Bill Gates") # length = 3Marks <- c("80", "75", "95", "96", "70") # length = 5Age <- c("13", "13", "14") # length = 3 maxlength = max(length(Rollno), length(Name), length(Marks), length(Age))print(maxlength)
Output:
6
Step 3: Vectors Name and Age have length 3 and Marks have length 5. So, we should replace the remaining black places with NA values. For this, we will use rep() function where the first argument is NA and here we use a length of remaining black places as a second argument. After, fill the black space by NA, we will update the vectors by same c() function.
R
Rollno <- c("5", "6", "7", "8", "9", "10") Name <- c("John Doe","Jane Doe", "Bill Gates") Marks <- c("80", "75", "95", "96", "70") Age <- c("13", "13", "14") maxlength = max(length(Rollno), length(Name), length(Marks), length(Age)) Rollno = c(Rollno, rep(NA, maxlength - length(Rollno))) # fill last three spaces by NA.Name = c(Name, rep(NA, maxlength - length(Name))) # fill last one spaces by NA.Marks = c(Marks, rep(NA, maxlength - length(Marks))) # fill last three spaces by NA.Age = c(Age, rep(NA, maxlength - length(Age)))
Step 4: Now, we will create a DataFrame of updated vectors by using data.frame() function and store it to studentdata variable.
R
Rollno <- c("5", "6", "7", "8", "9", "10") Name <- c("John Doe","Jane Doe", "Bill Gates") Marks <- c("80", "75", "95", "96", "70") Age <- c("13", "13", "14") maxlength = max(length(Rollno), length(Name), length(Marks), length(Age)) Rollno = c(Rollno, rep(NA, maxlength - length(Rollno)))Name = c(Name, rep(NA, maxlength - length(Name)))Marks = c(Marks, rep(NA, maxlength - length(Marks)))Age = c(Age, rep(NA, maxlength - length(Age))) studentdata <- data.frame(Rollno, Name, Marks, Age)display(studentdata)
Output:
‘studentdata’ DataFrame
Picked
R DataFrame-Programs
R Vector-Programs
R-DataFrame
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "In this article, we are going to see how to combine vectors or DataFrames of unequal length into one DataFrame in R Programming Language."
},
{
"code": null,
"e": 182,
"s": 166,
"text": "Functions Used:"
},
{
"code": null,
"e": 626,
"s": 182,
"text": "c(“Value1”, “Value2”, “Value3”) : This is a generic function which combines its arguments. The default method combines its arguments(Values) to form a vector.length(vector): Get or set the length of the Vectors, Factors, or any other R Objects.max(...): Returns the maximum of all the values passing inside it’s an argument.rep(x, ...): Replicates the values in x and the second argument can be anything from times, length(), length.out, each."
},
{
"code": null,
"e": 785,
"s": 626,
"text": "c(“Value1”, “Value2”, “Value3”) : This is a generic function which combines its arguments. The default method combines its arguments(Values) to form a vector."
},
{
"code": null,
"e": 872,
"s": 785,
"text": "length(vector): Get or set the length of the Vectors, Factors, or any other R Objects."
},
{
"code": null,
"e": 953,
"s": 872,
"text": "max(...): Returns the maximum of all the values passing inside it’s an argument."
},
{
"code": null,
"e": 1073,
"s": 953,
"text": "rep(x, ...): Replicates the values in x and the second argument can be anything from times, length(), length.out, each."
},
{
"code": null,
"e": 1098,
"s": 1073,
"text": "Stepwise implementation:"
},
{
"code": null,
"e": 1401,
"s": 1098,
"text": "Step 1: Prepare the vectors for dataframe using the c() function. Here we dummy student data and Rollno, Name, Marks, and Age as a vector. As you can see below, we have Name and Age of only first three students. We have not other three’s name and age data. Also, we have not a mark of the last student."
},
{
"code": null,
"e": 1403,
"s": 1401,
"text": "R"
},
{
"code": "Rollno <- c(\"5\", \"6\", \"7\", \"8\", \"9\", \"10\")Name <- c(\"John Doe\", \"Jane Doe\", \"Bill Gates\")Marks <- c(\"80\", \"75\", \"95\", \"96\", \"70\", \"86\")Age <- c(\"13\", \"13\", \"14\")",
"e": 1565,
"s": 1403,
"text": null
},
{
"code": null,
"e": 1949,
"s": 1565,
"text": "Step 2: As you can see above data, the length of Rollno, Name, Marks, and Age is 6, 3, 5, and 3 respectively. Now, by using the max() function. Inside max() function we get all vector’s length by length() function. We will get the maximum length overall vectors that we created and store this length to the maxlength variable. Also, check the length by print it for testing purposes."
},
{
"code": null,
"e": 1951,
"s": 1949,
"text": "R"
},
{
"code": "Rollno <- c(\"5\", \"6\", \"7\", \"8\", \"9\", \"10\") # length = 6Name <- c(\"John Doe\",\"Jane Doe\", \"Bill Gates\") # length = 3Marks <- c(\"80\", \"75\", \"95\", \"96\", \"70\") # length = 5Age <- c(\"13\", \"13\", \"14\") # length = 3 maxlength = max(length(Rollno), length(Name), length(Marks), length(Age))print(maxlength)",
"e": 2302,
"s": 1951,
"text": null
},
{
"code": null,
"e": 2310,
"s": 2302,
"text": "Output:"
},
{
"code": null,
"e": 2312,
"s": 2310,
"text": "6"
},
{
"code": null,
"e": 2670,
"s": 2312,
"text": "Step 3: Vectors Name and Age have length 3 and Marks have length 5. So, we should replace the remaining black places with NA values. For this, we will use rep() function where the first argument is NA and here we use a length of remaining black places as a second argument. After, fill the black space by NA, we will update the vectors by same c() function."
},
{
"code": null,
"e": 2672,
"s": 2670,
"text": "R"
},
{
"code": "Rollno <- c(\"5\", \"6\", \"7\", \"8\", \"9\", \"10\") Name <- c(\"John Doe\",\"Jane Doe\", \"Bill Gates\") Marks <- c(\"80\", \"75\", \"95\", \"96\", \"70\") Age <- c(\"13\", \"13\", \"14\") maxlength = max(length(Rollno), length(Name), length(Marks), length(Age)) Rollno = c(Rollno, rep(NA, maxlength - length(Rollno))) # fill last three spaces by NA.Name = c(Name, rep(NA, maxlength - length(Name))) # fill last one spaces by NA.Marks = c(Marks, rep(NA, maxlength - length(Marks))) # fill last three spaces by NA.Age = c(Age, rep(NA, maxlength - length(Age)))",
"e": 3261,
"s": 2672,
"text": null
},
{
"code": null,
"e": 3389,
"s": 3261,
"text": "Step 4: Now, we will create a DataFrame of updated vectors by using data.frame() function and store it to studentdata variable."
},
{
"code": null,
"e": 3391,
"s": 3389,
"text": "R"
},
{
"code": "Rollno <- c(\"5\", \"6\", \"7\", \"8\", \"9\", \"10\") Name <- c(\"John Doe\",\"Jane Doe\", \"Bill Gates\") Marks <- c(\"80\", \"75\", \"95\", \"96\", \"70\") Age <- c(\"13\", \"13\", \"14\") maxlength = max(length(Rollno), length(Name), length(Marks), length(Age)) Rollno = c(Rollno, rep(NA, maxlength - length(Rollno)))Name = c(Name, rep(NA, maxlength - length(Name)))Marks = c(Marks, rep(NA, maxlength - length(Marks)))Age = c(Age, rep(NA, maxlength - length(Age))) studentdata <- data.frame(Rollno, Name, Marks, Age)display(studentdata)",
"e": 3955,
"s": 3391,
"text": null
},
{
"code": null,
"e": 3963,
"s": 3955,
"text": "Output:"
},
{
"code": null,
"e": 3987,
"s": 3963,
"text": "‘studentdata’ DataFrame"
},
{
"code": null,
"e": 3994,
"s": 3987,
"text": "Picked"
},
{
"code": null,
"e": 4015,
"s": 3994,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 4033,
"s": 4015,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 4045,
"s": 4033,
"text": "R-DataFrame"
},
{
"code": null,
"e": 4055,
"s": 4045,
"text": "R-Vectors"
},
{
"code": null,
"e": 4066,
"s": 4055,
"text": "R Language"
},
{
"code": null,
"e": 4077,
"s": 4066,
"text": "R Programs"
}
] |
Python | Drawing different shapes on PyGame window | 14 Jan, 2019
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit.
Command to install pygame :
pip install pygame
There are four basic steps to displaying images on the pygame window :
Create a display surface object using display.set_mode() method of pygame.
Completely fill the surface object with white using fill() method of pygame display surface object.
Drawing different shapes onto a surface object using Primitive Drawing Functions of pygame.
Show the display surface object on the pygame window using display.update() method of pygame.
Below is the implementation:
# import pygame module in this programimport pygame # activate the pygame library .# initiate pygame and give permission# to use pygame's functionality.pygame.init() # define the RGB value# for white, green,# blue, black, red# colour respectively.white = (255, 255, 255)green = (0, 255, 0)blue = (0, 0, 128)black = (0, 0, 0)red = (255, 0, 0) # assigning values to X and Y variableX = 400Y = 400 # create the display surface object# of specific dimension..e(X,Y).display_surface = pygame.display.set_mode((X, Y )) # set the pygame window namepygame.display.set_caption('Drawing') # completely fill the surface object # with white colour display_surface.fill(white) # draw a polygon using draw.polygon()# method of pygame.# pygame.draw.polygon(surface, color, pointlist, thickness)# thickness of line parameter is optional.pygame.draw.polygon(display_surface, blue, [(146, 0), (291, 106), (236, 277), (56, 277), (0, 106)]) # draw a line using draw.line()# method of pygame.# pygame.draw.line(surface, color,# start point, end point, thickness) pygame.draw.line(display_surface, green, (60, 300), (120, 300), 4) # draw a circle using draw.circle()# method of pygame.# pygame.draw.circle(surface, color,# center point, radius, thickness) pygame.draw.circle(display_surface, green, (300, 50), 20, 0) # draw a ellipse using draw.ellipse()# method of pygame.# pygame.draw.ellipse(surface, color,# bounding rectangle, thickness) pygame.draw.ellipse(display_surface, black, (300, 250, 40, 80), 1) # draw a rectangle using draw.rect()# method of pygame.# pygame.draw.rect(surface, color,# rectangle tuple, thickness)# thickness of line parameter is optional.pygame.draw.rect(display_surface, black, (150, 300, 100, 50)) # infinite loopwhile True : # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get() : # if event object type is QUIT # then quitting the pygame # and program both. if event.type == pygame.QUIT : # deactivates the pygame library pygame.quit() # quit the program. quit() # Draws the surface object to the screen. pygame.display.update()
Output :
Python-PyGame
python-utility
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jan, 2019"
},
{
"code": null,
"e": 366,
"s": 54,
"text": "Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit."
},
{
"code": null,
"e": 394,
"s": 366,
"text": "Command to install pygame :"
},
{
"code": null,
"e": 414,
"s": 394,
"text": "pip install pygame\n"
},
{
"code": null,
"e": 485,
"s": 414,
"text": "There are four basic steps to displaying images on the pygame window :"
},
{
"code": null,
"e": 560,
"s": 485,
"text": "Create a display surface object using display.set_mode() method of pygame."
},
{
"code": null,
"e": 660,
"s": 560,
"text": "Completely fill the surface object with white using fill() method of pygame display surface object."
},
{
"code": null,
"e": 752,
"s": 660,
"text": "Drawing different shapes onto a surface object using Primitive Drawing Functions of pygame."
},
{
"code": null,
"e": 846,
"s": 752,
"text": "Show the display surface object on the pygame window using display.update() method of pygame."
},
{
"code": null,
"e": 875,
"s": 846,
"text": "Below is the implementation:"
},
{
"code": "# import pygame module in this programimport pygame # activate the pygame library .# initiate pygame and give permission# to use pygame's functionality.pygame.init() # define the RGB value# for white, green,# blue, black, red# colour respectively.white = (255, 255, 255)green = (0, 255, 0)blue = (0, 0, 128)black = (0, 0, 0)red = (255, 0, 0) # assigning values to X and Y variableX = 400Y = 400 # create the display surface object# of specific dimension..e(X,Y).display_surface = pygame.display.set_mode((X, Y )) # set the pygame window namepygame.display.set_caption('Drawing') # completely fill the surface object # with white colour display_surface.fill(white) # draw a polygon using draw.polygon()# method of pygame.# pygame.draw.polygon(surface, color, pointlist, thickness)# thickness of line parameter is optional.pygame.draw.polygon(display_surface, blue, [(146, 0), (291, 106), (236, 277), (56, 277), (0, 106)]) # draw a line using draw.line()# method of pygame.# pygame.draw.line(surface, color,# start point, end point, thickness) pygame.draw.line(display_surface, green, (60, 300), (120, 300), 4) # draw a circle using draw.circle()# method of pygame.# pygame.draw.circle(surface, color,# center point, radius, thickness) pygame.draw.circle(display_surface, green, (300, 50), 20, 0) # draw a ellipse using draw.ellipse()# method of pygame.# pygame.draw.ellipse(surface, color,# bounding rectangle, thickness) pygame.draw.ellipse(display_surface, black, (300, 250, 40, 80), 1) # draw a rectangle using draw.rect()# method of pygame.# pygame.draw.rect(surface, color,# rectangle tuple, thickness)# thickness of line parameter is optional.pygame.draw.rect(display_surface, black, (150, 300, 100, 50)) # infinite loopwhile True : # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get() : # if event object type is QUIT # then quitting the pygame # and program both. if event.type == pygame.QUIT : # deactivates the pygame library pygame.quit() # quit the program. quit() # Draws the surface object to the screen. pygame.display.update() ",
"e": 3231,
"s": 875,
"text": null
},
{
"code": null,
"e": 3240,
"s": 3231,
"text": "Output :"
},
{
"code": null,
"e": 3254,
"s": 3240,
"text": "Python-PyGame"
},
{
"code": null,
"e": 3269,
"s": 3254,
"text": "python-utility"
},
{
"code": null,
"e": 3293,
"s": 3269,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3300,
"s": 3293,
"text": "Python"
},
{
"code": null,
"e": 3319,
"s": 3300,
"text": "Technical Scripter"
}
] |
Python PIL | getpalette() Method | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.getpalette() Returns the image palette as a list.
Syntax: Image.getpalette()
Parameters:image the image used should have L mode.-
Returns: A list of color values [r, g, b, ...], or None if the image has no palette.
Image Used:
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\python.png") # use getpalleteim2 = im.getpalette()print(im2)
Output:
none
Another Example:– Here used another image.
Image Used:
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\lion.png") # use getpalleteim2 = im.getpalette()print(im2)
Output:
[0, 0, 0, 255, 255, 255, 235, 235, 235, 244, 244, 244, 252, 252, 252, 247, 247, 247, 204, 204, 204, 208, 208, 208, 193, 193, 193, 221, 221, 221, 169, 169, 169, 232, 232, 232, 215, 215, 215, 195, 195, 195, 111, 111, 111, 143, 143, 143, 79, 79, 79, 162, 162, 162, 225, 225, 225, 85, 85, 85, 184, 184, 184, 62, 62, 62, 130, 130, 130, 165, 165, 165, 149, 149, 149, 73, 73, 73, 155, 155, 155, 67, 67, 67, 178, 178, 178, 90, 90, 90, 101, 101, 101, 39, 39, 39, 135, 135, 135, 48, 48, 48, 123, 123, 123, 41, 41, 41, 50, 50, 50, 26, 26, 26, 117, 117, 117, 21, 21, 21, 104, 104, 104, 12, 12, 12, 24, 24, 24, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47, 47, 48, 48, 48, 49, 49, 49, 50, 50, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 69, 69, 69, 70, 70, 70, 71, 71, 71, 72, 72, 72, 73, 73, 73, 74, 74, 74, 75, 75, 75, 76, 76, 76, 77, 77, 77, 78, 78, 78, 79, 79, 79, 80, 80, 80, 81, 81, 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 85, 85, 85, 86, 86, 86, 87, 87, 87, 88, 88, 88, 89, 89, 89, 90, 90, 90, 91, 91, 91, 92, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 116, 116, 116, 117, 117, 117, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 122, 122, 122, 123, 123, 123, 124, 124, 124, 125, 125, 125, 126, 126, 126, 127, 127, 127, 128, 128, 128, 129, 129, 129, 130, 130, 130, 131, 131, 131, 132, 132, 132, 133, 133, 133, 134, 134, 134, 135, 135, 135, 136, 136, 136, 137, 137, 137, 138, 138, 138, 139, 139, 139, 140, 140, 140, 141, 141, 141, 142, 142, 142, 143, 143, 143, 144, 144, 144, 145, 145, 145, 146, 146, 146, 147, 147, 147, 148, 148, 148, 149, 149, 149, 150, 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 154, 154, 154, 155, 155, 155, 156, 156, 156, 157, 157, 157, 158, 158, 158, 159, 159, 159, 160, 160, 160, 161, 161, 161, 162, 162, 162, 163, 163, 163, 164, 164, 164, 165, 165, 165, 166, 166, 166, 167, 167, 167, 168, 168, 168, 169, 169, 169, 170, 170, 170, 171, 171, 171, 172, 172, 172, 173, 173, 173, 174, 174, 174, 175, 175, 175, 176, 176, 176, 177, 177, 177, 178, 178, 178, 179, 179, 179, 180, 180, 180, 181, 181, 181, 182, 182, 182, 183, 183, 183, 184, 184, 184, 185, 185, 185, 186, 186, 186, 187, 187, 187, 188, 188, 188, 189, 189, 189, 190, 190, 190, 191, 191, 191, 192, 192, 192, 193, 193, 193, 194, 194, 194, 195, 195, 195, 196, 196, 196, 197, 197, 197, 198, 198, 198, 199, 199, 199, 200, 200, 200, 201, 201, 201, 202, 202, 202, 203, 203, 203, 204, 204, 204, 205, 205, 205, 206, 206, 206, 207, 207, 207, 208, 208, 208, 209, 209, 209, 210, 210, 210, 211, 211, 211, 212, 212, 212, 213, 213, 213, 214, 214, 214, 215, 215, 215, 216, 216, 216, 217, 217, 217, 218, 218, 218, 219, 219, 219, 220, 220, 220, 221, 221, 221, 222, 222, 222, 223, 223, 223, 224, 224, 224, 225, 225, 225, 226, 226, 226, 227, 227, 227, 228, 228, 228, 229, 229, 229, 230, 230, 230, 231, 231, 231, 232, 232, 232, 233, 233, 233, 234, 234, 234, 235, 235, 235, 236, 236, 236, 237, 237, 237, 238, 238, 238, 239, 239, 239, 240, 240, 240, 241, 241, 241, 242, 242, 242, 243, 243, 243, 244, 244, 244, 245, 245, 245, 246, 246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 250, 250, 250, 251, 251, 251, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255]
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 411,
"s": 355,
"text": "Image.getpalette() Returns the image palette as a list."
},
{
"code": null,
"e": 438,
"s": 411,
"text": "Syntax: Image.getpalette()"
},
{
"code": null,
"e": 491,
"s": 438,
"text": "Parameters:image the image used should have L mode.-"
},
{
"code": null,
"e": 576,
"s": 491,
"text": "Returns: A list of color values [r, g, b, ...], or None if the image has no palette."
},
{
"code": null,
"e": 588,
"s": 576,
"text": "Image Used:"
},
{
"code": " # importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\python.png\") # use getpalleteim2 = im.getpalette()print(im2)",
"e": 785,
"s": 588,
"text": null
},
{
"code": null,
"e": 793,
"s": 785,
"text": "Output:"
},
{
"code": null,
"e": 799,
"s": 793,
"text": "none\n"
},
{
"code": null,
"e": 842,
"s": 799,
"text": "Another Example:– Here used another image."
},
{
"code": null,
"e": 854,
"s": 842,
"text": "Image Used:"
},
{
"code": " # importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\lion.png\") # use getpalleteim2 = im.getpalette()print(im2)",
"e": 1049,
"s": 854,
"text": null
},
{
"code": null,
"e": 1057,
"s": 1049,
"text": "Output:"
},
{
"code": null,
"e": 4679,
"s": 1057,
"text": "[0, 0, 0, 255, 255, 255, 235, 235, 235, 244, 244, 244, 252, 252, 252, 247, 247, 247, 204, 204, 204, 208, 208, 208, 193, 193, 193, 221, 221, 221, 169, 169, 169, 232, 232, 232, 215, 215, 215, 195, 195, 195, 111, 111, 111, 143, 143, 143, 79, 79, 79, 162, 162, 162, 225, 225, 225, 85, 85, 85, 184, 184, 184, 62, 62, 62, 130, 130, 130, 165, 165, 165, 149, 149, 149, 73, 73, 73, 155, 155, 155, 67, 67, 67, 178, 178, 178, 90, 90, 90, 101, 101, 101, 39, 39, 39, 135, 135, 135, 48, 48, 48, 123, 123, 123, 41, 41, 41, 50, 50, 50, 26, 26, 26, 117, 117, 117, 21, 21, 21, 104, 104, 104, 12, 12, 12, 24, 24, 24, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47, 47, 48, 48, 48, 49, 49, 49, 50, 50, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 69, 69, 69, 70, 70, 70, 71, 71, 71, 72, 72, 72, 73, 73, 73, 74, 74, 74, 75, 75, 75, 76, 76, 76, 77, 77, 77, 78, 78, 78, 79, 79, 79, 80, 80, 80, 81, 81, 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 85, 85, 85, 86, 86, 86, 87, 87, 87, 88, 88, 88, 89, 89, 89, 90, 90, 90, 91, 91, 91, 92, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 116, 116, 116, 117, 117, 117, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 122, 122, 122, 123, 123, 123, 124, 124, 124, 125, 125, 125, 126, 126, 126, 127, 127, 127, 128, 128, 128, 129, 129, 129, 130, 130, 130, 131, 131, 131, 132, 132, 132, 133, 133, 133, 134, 134, 134, 135, 135, 135, 136, 136, 136, 137, 137, 137, 138, 138, 138, 139, 139, 139, 140, 140, 140, 141, 141, 141, 142, 142, 142, 143, 143, 143, 144, 144, 144, 145, 145, 145, 146, 146, 146, 147, 147, 147, 148, 148, 148, 149, 149, 149, 150, 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 154, 154, 154, 155, 155, 155, 156, 156, 156, 157, 157, 157, 158, 158, 158, 159, 159, 159, 160, 160, 160, 161, 161, 161, 162, 162, 162, 163, 163, 163, 164, 164, 164, 165, 165, 165, 166, 166, 166, 167, 167, 167, 168, 168, 168, 169, 169, 169, 170, 170, 170, 171, 171, 171, 172, 172, 172, 173, 173, 173, 174, 174, 174, 175, 175, 175, 176, 176, 176, 177, 177, 177, 178, 178, 178, 179, 179, 179, 180, 180, 180, 181, 181, 181, 182, 182, 182, 183, 183, 183, 184, 184, 184, 185, 185, 185, 186, 186, 186, 187, 187, 187, 188, 188, 188, 189, 189, 189, 190, 190, 190, 191, 191, 191, 192, 192, 192, 193, 193, 193, 194, 194, 194, 195, 195, 195, 196, 196, 196, 197, 197, 197, 198, 198, 198, 199, 199, 199, 200, 200, 200, 201, 201, 201, 202, 202, 202, 203, 203, 203, 204, 204, 204, 205, 205, 205, 206, 206, 206, 207, 207, 207, 208, 208, 208, 209, 209, 209, 210, 210, 210, 211, 211, 211, 212, 212, 212, 213, 213, 213, 214, 214, 214, 215, 215, 215, 216, 216, 216, 217, 217, 217, 218, 218, 218, 219, 219, 219, 220, 220, 220, 221, 221, 221, 222, 222, 222, 223, 223, 223, 224, 224, 224, 225, 225, 225, 226, 226, 226, 227, 227, 227, 228, 228, 228, 229, 229, 229, 230, 230, 230, 231, 231, 231, 232, 232, 232, 233, 233, 233, 234, 234, 234, 235, 235, 235, 236, 236, 236, 237, 237, 237, 238, 238, 238, 239, 239, 239, 240, 240, 240, 241, 241, 241, 242, 242, 242, 243, 243, 243, 244, 244, 244, 245, 245, 245, 246, 246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 250, 250, 250, 251, 251, 251, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255]"
},
{
"code": null,
"e": 4690,
"s": 4679,
"text": "Python-pil"
},
{
"code": null,
"e": 4697,
"s": 4690,
"text": "Python"
},
{
"code": null,
"e": 4795,
"s": 4697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4825,
"s": 4795,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4875,
"s": 4825,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 4897,
"s": 4875,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4913,
"s": 4897,
"text": "Deque in Python"
},
{
"code": null,
"e": 4929,
"s": 4913,
"text": "Stack in Python"
},
{
"code": null,
"e": 4947,
"s": 4929,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4972,
"s": 4947,
"text": "sum() function in Python"
},
{
"code": null,
"e": 5013,
"s": 4972,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 5055,
"s": 5013,
"text": "Different ways to create Pandas Dataframe"
}
] |
Out Parameter With Examples in C# | 01 Oct, 2021
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values.
Important Points:
It is similar to ref keyword. But the main difference between ref and out keyword is that ref needs that the variable must be initialized before it passed to the method. But out parameter doesn’t require the variables to be initialized before it passed to the method. But before it returns a value to the calling method, the variable must be initialized in the called method.
It is also similar to the in keyword but the in keyword does not allow the method that called to change the argument value but ref allows.
For using out keyword as a parameter both the method definition and calling method must use the out keyword explicitly.
The out parameters are not allowed to use in asynchronous methods.
The out parameters are not allowed to use in iterator methods.
There can be more than one out parameter in a method.
At the time of method call, out parameter can be declared inline. But the inline out parameters can be accessed in the same block of code where it calls.
Method overloading can also be done using out parameters.
Properties cannot be passed as out parameters as these are not variables.
Up to C# 6.0, a user first declares the variable then it can only pass as an out argument. But from C# 7.0, excepting a separate variable declaration, the user can also declare the out variable in the argument list of the method call.
Declaration of out Parameter:
// No need to initialize
// the variable here
data_type variable_name;
Method_Name(out variable_name);
// you can also convert both above two
// lines of codes as follows from
// C# 7.0 onwards
Method_Name(out data_type variable_name);
Here the value of variable_name must be initialized in the called method before it returns a value.
Example:
C#
// C# program to illustrate the// concept of out parameterusing System; class GFG { // Main method static public void Main() { // Declaring variable // without assigning value int i; // Pass variable i to the method // using out keyword Addition(out i); // Display the value i Console.WriteLine("The addition of the value is: {0}", i); } // Method in which out parameter is passed // and this method returns the value of // the passed parameter public static void Addition(out int i) { i = 30; i += i; }}
The addition of the value is: 60
Multiple out Parameters: In C#, a user is allowed to pass multiple out parameters to the method and the method returns multiple values.
Example: In the below code, we declared two value variables without initializing i.e int i, j;. Now we pass these parameters to the Addition method using out keyword like Addition(out i, out j);. The value of these variables is assigned in the method in which they passed.
C#
// C# program to illustrate the// concept of multiple out parameterusing System; class GFG { // Main method static public void Main() { // Declaring variables // without assigning values int i, j; // Pass multiple variable to // the method using out keyword Addition(out i, out j); // Display the value i and j Console.WriteLine("The addition of the value is: {0}", i); Console.WriteLine("The addition of the value is: {0}", j); } // Method in which out parameters // are passed and this method returns // the values of the passed parameters public static void Addition(out int p, out int q) { p = 30; q = 40; p += p; q += q; }}
The addition of the value is: 60
The addition of the value is: 80
Enhancement of Out Parameter in C# 7.0 : In C# 7.0, there are some new features added to the out parameter and the features are:
In C# 7.0, the out parameter can pass without its declaration and initialization which is termed as the In-line declaration of Out parameter or Implicit Type Out Parameter. Its scope is limited to the method body i.e. local scope.
The out parameter is allowed to use var type in the method parameter list.
In out parameter, it is not compulsory that the name of the out parameter is same in both definition and call.
It can also be used in Try Pattern.
Example: Below programs demonstrate the inline declaration of Out parameter. Here the line of code i.e Area(out int length, out int width, out int Rarea); contains the inline declaration of Out parameter as these variables are directly declared inside the method calling. The value of the variables is initialized in the method in which they passed.
Note: You need to require C# 7.0 version to run this example.
Example:
C#
// C# program to illustrate the// concept of out parameterusing System; class GFG{ // Main method static public void Main() { // In-line declaring variables // without assigning values // Passing multiple variable to // the method using out keyword Area(out int length, out int width, out int Rarea); // Display the value length, width, and Rarea System.Console.WriteLine("Length of the rectangle is: "+ length); System.Console.WriteLine("Width of the rectangle is: "+ width); System.Console.WriteLine("Area of the rectangle is: "+ Rarea); Console.ReadLine(); } // Method in which out parameters are passed // and this method returns the values of // the passed parameters public static void Area(out int p, out int q, out int Rarea) { p = 30; q = 40; Rarea = p * q; }}
Output:
Length of the rectangle is : 30
Width of the rectangle is : 40
Area of the rectangle is : 1200
arorakashish0911
akshaysingh98088
surindertarika1234
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Arrays
Extension Method in C#
C# | List Class | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 217,
"s": 54,
"text": "The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values."
},
{
"code": null,
"e": 235,
"s": 217,
"text": "Important Points:"
},
{
"code": null,
"e": 611,
"s": 235,
"text": "It is similar to ref keyword. But the main difference between ref and out keyword is that ref needs that the variable must be initialized before it passed to the method. But out parameter doesn’t require the variables to be initialized before it passed to the method. But before it returns a value to the calling method, the variable must be initialized in the called method."
},
{
"code": null,
"e": 750,
"s": 611,
"text": "It is also similar to the in keyword but the in keyword does not allow the method that called to change the argument value but ref allows."
},
{
"code": null,
"e": 870,
"s": 750,
"text": "For using out keyword as a parameter both the method definition and calling method must use the out keyword explicitly."
},
{
"code": null,
"e": 937,
"s": 870,
"text": "The out parameters are not allowed to use in asynchronous methods."
},
{
"code": null,
"e": 1000,
"s": 937,
"text": "The out parameters are not allowed to use in iterator methods."
},
{
"code": null,
"e": 1054,
"s": 1000,
"text": "There can be more than one out parameter in a method."
},
{
"code": null,
"e": 1208,
"s": 1054,
"text": "At the time of method call, out parameter can be declared inline. But the inline out parameters can be accessed in the same block of code where it calls."
},
{
"code": null,
"e": 1266,
"s": 1208,
"text": "Method overloading can also be done using out parameters."
},
{
"code": null,
"e": 1340,
"s": 1266,
"text": "Properties cannot be passed as out parameters as these are not variables."
},
{
"code": null,
"e": 1575,
"s": 1340,
"text": "Up to C# 6.0, a user first declares the variable then it can only pass as an out argument. But from C# 7.0, excepting a separate variable declaration, the user can also declare the out variable in the argument list of the method call."
},
{
"code": null,
"e": 1607,
"s": 1575,
"text": "Declaration of out Parameter: "
},
{
"code": null,
"e": 1848,
"s": 1607,
"text": "// No need to initialize \n// the variable here\ndata_type variable_name;\n\nMethod_Name(out variable_name);\n\n// you can also convert both above two \n// lines of codes as follows from\n// C# 7.0 onwards\nMethod_Name(out data_type variable_name);"
},
{
"code": null,
"e": 1949,
"s": 1848,
"text": "Here the value of variable_name must be initialized in the called method before it returns a value. "
},
{
"code": null,
"e": 1959,
"s": 1949,
"text": "Example: "
},
{
"code": null,
"e": 1962,
"s": 1959,
"text": "C#"
},
{
"code": "// C# program to illustrate the// concept of out parameterusing System; class GFG { // Main method static public void Main() { // Declaring variable // without assigning value int i; // Pass variable i to the method // using out keyword Addition(out i); // Display the value i Console.WriteLine(\"The addition of the value is: {0}\", i); } // Method in which out parameter is passed // and this method returns the value of // the passed parameter public static void Addition(out int i) { i = 30; i += i; }}",
"e": 2572,
"s": 1962,
"text": null
},
{
"code": null,
"e": 2605,
"s": 2572,
"text": "The addition of the value is: 60"
},
{
"code": null,
"e": 2744,
"s": 2607,
"text": "Multiple out Parameters: In C#, a user is allowed to pass multiple out parameters to the method and the method returns multiple values. "
},
{
"code": null,
"e": 3018,
"s": 2744,
"text": "Example: In the below code, we declared two value variables without initializing i.e int i, j;. Now we pass these parameters to the Addition method using out keyword like Addition(out i, out j);. The value of these variables is assigned in the method in which they passed. "
},
{
"code": null,
"e": 3021,
"s": 3018,
"text": "C#"
},
{
"code": "// C# program to illustrate the// concept of multiple out parameterusing System; class GFG { // Main method static public void Main() { // Declaring variables // without assigning values int i, j; // Pass multiple variable to // the method using out keyword Addition(out i, out j); // Display the value i and j Console.WriteLine(\"The addition of the value is: {0}\", i); Console.WriteLine(\"The addition of the value is: {0}\", j); } // Method in which out parameters // are passed and this method returns // the values of the passed parameters public static void Addition(out int p, out int q) { p = 30; q = 40; p += p; q += q; }}",
"e": 3776,
"s": 3021,
"text": null
},
{
"code": null,
"e": 3842,
"s": 3776,
"text": "The addition of the value is: 60\nThe addition of the value is: 80"
},
{
"code": null,
"e": 3974,
"s": 3844,
"text": "Enhancement of Out Parameter in C# 7.0 : In C# 7.0, there are some new features added to the out parameter and the features are: "
},
{
"code": null,
"e": 4205,
"s": 3974,
"text": "In C# 7.0, the out parameter can pass without its declaration and initialization which is termed as the In-line declaration of Out parameter or Implicit Type Out Parameter. Its scope is limited to the method body i.e. local scope."
},
{
"code": null,
"e": 4280,
"s": 4205,
"text": "The out parameter is allowed to use var type in the method parameter list."
},
{
"code": null,
"e": 4391,
"s": 4280,
"text": "In out parameter, it is not compulsory that the name of the out parameter is same in both definition and call."
},
{
"code": null,
"e": 4427,
"s": 4391,
"text": "It can also be used in Try Pattern."
},
{
"code": null,
"e": 4777,
"s": 4427,
"text": "Example: Below programs demonstrate the inline declaration of Out parameter. Here the line of code i.e Area(out int length, out int width, out int Rarea); contains the inline declaration of Out parameter as these variables are directly declared inside the method calling. The value of the variables is initialized in the method in which they passed."
},
{
"code": null,
"e": 4839,
"s": 4777,
"text": "Note: You need to require C# 7.0 version to run this example."
},
{
"code": null,
"e": 4850,
"s": 4839,
"text": "Example: "
},
{
"code": null,
"e": 4853,
"s": 4850,
"text": "C#"
},
{
"code": "// C# program to illustrate the// concept of out parameterusing System; class GFG{ // Main method static public void Main() { // In-line declaring variables // without assigning values // Passing multiple variable to // the method using out keyword Area(out int length, out int width, out int Rarea); // Display the value length, width, and Rarea System.Console.WriteLine(\"Length of the rectangle is: \"+ length); System.Console.WriteLine(\"Width of the rectangle is: \"+ width); System.Console.WriteLine(\"Area of the rectangle is: \"+ Rarea); Console.ReadLine(); } // Method in which out parameters are passed // and this method returns the values of // the passed parameters public static void Area(out int p, out int q, out int Rarea) { p = 30; q = 40; Rarea = p * q; }}",
"e": 5748,
"s": 4853,
"text": null
},
{
"code": null,
"e": 5757,
"s": 5748,
"text": "Output: "
},
{
"code": null,
"e": 5853,
"s": 5757,
"text": "Length of the rectangle is : 30\nWidth of the rectangle is : 40\nArea of the rectangle is : 1200"
},
{
"code": null,
"e": 5872,
"s": 5855,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5889,
"s": 5872,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 5908,
"s": 5889,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5923,
"s": 5908,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 5926,
"s": 5923,
"text": "C#"
},
{
"code": null,
"e": 6024,
"s": 5926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6067,
"s": 6024,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 6098,
"s": 6067,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 6147,
"s": 6098,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 6162,
"s": 6147,
"text": "C# | Delegates"
},
{
"code": null,
"e": 6178,
"s": 6162,
"text": "C# | Data Types"
},
{
"code": null,
"e": 6218,
"s": 6178,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 6240,
"s": 6218,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 6252,
"s": 6240,
"text": "C# | Arrays"
},
{
"code": null,
"e": 6275,
"s": 6252,
"text": "Extension Method in C#"
}
] |
How to get the outer html of an element using jQuery ? | 02 Jun, 2020
Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element.
Syntax:
document.getElementById("your-element-id").outerHTML)
You can use a variable and initialize it to the above to get the value of the outer HTML element. Below is an example that illustrates how to fetch the outer HTML element of an HTML element and store it in a variable newVar.
Example 1: In this example, it has a div that encloses a paragraph with id = “demo”. When the on-screen button is pressed the JavaScript pushes an alert message on the browser window with the outer HTML of the HTML element with the given id. The myFunction uses the getElementbyId function to fetch the element with the given id and then fetches that elements outerHTML. If an id is given such that there are multiple HTML elements with that id or there are none, then the outerHTML will throw an error as its being called on a null value.
HTML
<!DOCTYPE html><html> <head> </head> <body> <div id="demo"> <p>This is the text inside</p> </div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var newVar = document.getElementById("demo").outerHTML; alert(newVar); } </script> </body></html>
Output:
<div id="demo">
<p>This is the text inside</p>
</div>
Example 2: This example illustrates that the outerHTML DOM displays only the HTML element whose id is given and not its parent
HTML
<!DOCTYPE html><html> <head> </head> <body> <div> <p id="demo">This is the text inside</p> </div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var newVar = document.getElementById("demo").outerHTML; alert(newVar); } </script> </body></html>
Output:
<p id="demo">This is the text inside</p>
JavaScript-Misc
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element."
},
{
"code": null,
"e": 232,
"s": 223,
"text": "Syntax: "
},
{
"code": null,
"e": 287,
"s": 232,
"text": "document.getElementById(\"your-element-id\").outerHTML)\n"
},
{
"code": null,
"e": 512,
"s": 287,
"text": "You can use a variable and initialize it to the above to get the value of the outer HTML element. Below is an example that illustrates how to fetch the outer HTML element of an HTML element and store it in a variable newVar."
},
{
"code": null,
"e": 1053,
"s": 512,
"text": "Example 1: In this example, it has a div that encloses a paragraph with id = “demo”. When the on-screen button is pressed the JavaScript pushes an alert message on the browser window with the outer HTML of the HTML element with the given id. The myFunction uses the getElementbyId function to fetch the element with the given id and then fetches that elements outerHTML. If an id is given such that there are multiple HTML elements with that id or there are none, then the outerHTML will throw an error as its being called on a null value."
},
{
"code": null,
"e": 1058,
"s": 1053,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <div id=\"demo\"> <p>This is the text inside</p> </div> <button onclick=\"myFunction()\">Try it</button> <script> function myFunction() { var newVar = document.getElementById(\"demo\").outerHTML; alert(newVar); } </script> </body></html>",
"e": 1470,
"s": 1058,
"text": null
},
{
"code": null,
"e": 1478,
"s": 1470,
"text": "Output:"
},
{
"code": null,
"e": 1536,
"s": 1478,
"text": "<div id=\"demo\">\n <p>This is the text inside</p>\n</div>"
},
{
"code": null,
"e": 1665,
"s": 1536,
"text": "Example 2: This example illustrates that the outerHTML DOM displays only the HTML element whose id is given and not its parent "
},
{
"code": null,
"e": 1670,
"s": 1665,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <div> <p id=\"demo\">This is the text inside</p> </div> <button onclick=\"myFunction()\">Try it</button> <script> function myFunction() { var newVar = document.getElementById(\"demo\").outerHTML; alert(newVar); } </script> </body></html>",
"e": 2079,
"s": 1670,
"text": null
},
{
"code": null,
"e": 2088,
"s": 2079,
"text": " Output:"
},
{
"code": null,
"e": 2129,
"s": 2088,
"text": "<p id=\"demo\">This is the text inside</p>"
},
{
"code": null,
"e": 2145,
"s": 2129,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2152,
"s": 2145,
"text": "Picked"
},
{
"code": null,
"e": 2159,
"s": 2152,
"text": "JQuery"
},
{
"code": null,
"e": 2176,
"s": 2159,
"text": "Web Technologies"
}
] |
Median of an unsorted array using Quick Select Algorithm | 16 May, 2022
Given an unsorted array arr[] of length N, the task is to find the median of this array. Median of a sorted array of size N is defined as the middle element when n is odd and average of middle two elements when n is even.
Examples:
Input: arr[] = {12, 3, 5, 7, 4, 19, 26} Output: 7 Sorted sequence of given array arr[] = {3, 4, 5, 7, 12, 19, 26} Since the number of elements is odd, the median is 4th element in the sorted sequence of given array arr[], which is 7
Input: arr[] = {12, 3, 5, 7, 4, 26} Output: 6 Since number of elements are even, median is average of 3rd and 4th element in sorted sequence of given array arr[], which means (5 + 7)/2 = 6
Naive Approach:
Sort the array arr[] in increasing order.
If number of elements in arr[] is odd, then median is arr[n/2].
If the number of elements in arr[] is even, median is average of arr[n/2] and arr[n/2+1].
Please refer to this article for the implementation of above approach.
Efficient Approach: using Randomized QuickSelect
Randomly pick pivot element from arr[] and the using the partition step from the quick sort algorithm arrange all the elements smaller than the pivot on its left and the elements greater than it on its right.
If after the previous step, the position of the chosen pivot is the middle of the array then it is the required median of the given array.
If the position is before the middle element then repeat the step for the subarray starting from previous starting index and the chosen pivot as the ending index.
If the position is after the middle element then repeat the step for the subarray starting from the chosen pivot and ending at the previous ending index.
Note that in case of even number of elements, the middle two elements have to be found and their average will be the median of the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// CPP program to find median of// an array #include "bits/stdc++.h"using namespace std; // Utility function to swapping of elementvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Returns the correct position of// pivot elementint Partition(int arr[], int l, int r){ int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { swap(&arr[i], &arr[j]); i++; } j++; } swap(&arr[i], &arr[r]); return i;} // Picks a random pivot element between// l and r and partitions arr[l..r]// around the randomly picked element// using partition()int randomPartition(int arr[], int l, int r){ int n = r - l + 1; int pivot = rand() % n; swap(&arr[l + pivot], &arr[r]); return Partition(arr, l, r);} // Utility function to find medianvoid MedianUtil(int arr[], int l, int r, int k, int& a, int& b){ // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in arr[] if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return; } // If index = k - 1, then we get // a & b as middle element of // arr[] else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return; } // If partitionIndex >= k then // find the index in first half // of the arr[] if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k, a, b); // If partitionIndex <= k then // find the index in second half // of the arr[] else return MedianUtil(arr, partitionIndex + 1, r, k, a, b); } return;} // Function to find Medianvoid findMedian(int arr[], int n){ int ans, a = -1, b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2, a, b); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2, a, b); ans = (a + b) / 2; } // Print the Median of arr[] cout << "Median = " << ans;} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = sizeof(arr) / sizeof(arr[0]); findMedian(arr, n); return 0;}
// JAVA program to find median of// an arrayclass GFG{ static int a, b; // Utility function to swapping of element static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Returns the correct position of // pivot element static int Partition(int arr[], int l, int r) { int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { arr = swap(arr, i, j); i++; } j++; } arr = swap(arr, i, r); return i; } // Picks a random pivot element between // l and r and partitions arr[l..r] // around the randomly picked element // using partition() static int randomPartition(int arr[], int l, int r) { int n = r - l + 1; int pivot = (int) (Math.random() % n); arr = swap(arr, l + pivot, r); return Partition(arr, l, r); } // Utility function to find median static int MedianUtil(int arr[], int l, int r, int k) { // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in arr[] if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return Integer.MIN_VALUE; } // If index = k - 1, then we get // a & b as middle element of // arr[] else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return Integer.MIN_VALUE; } // If partitionIndex >= k then // find the index in first half // of the arr[] if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k); // If partitionIndex <= k then // find the index in second half // of the arr[] else return MedianUtil(arr, partitionIndex + 1, r, k); } return Integer.MIN_VALUE; } // Function to find Median static void findMedian(int arr[], int n) { int ans; a = -1; b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2); ans = (a + b) / 2; } // Print the Median of arr[] System.out.print("Median = " + ans); } // Driver code public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = arr.length; findMedian(arr, n); }} // This code is contributed by 29AjayKumar
# Python3 program to find median of# an arrayimport random a, b = None, None; # Returns the correct position of# pivot elementdef Partition(arr, l, r) : lst = arr[r]; i = l; j = l; while (j < r) : if (arr[j] < lst) : arr[i], arr[j] = arr[j],arr[i]; i += 1; j += 1; arr[i], arr[r] = arr[r],arr[i]; return i; # Picks a random pivot element between# l and r and partitions arr[l..r]# around the randomly picked element# using partition()def randomPartition(arr, l, r) : n = r - l + 1; pivot = random.randrange(1, 100) % n; arr[l + pivot], arr[r] = arr[r], arr[l + pivot]; return Partition(arr, l, r); # Utility function to find mediandef MedianUtil(arr, l, r, k, a1, b1) : global a, b; # if l < r if (l <= r) : # Find the partition index partitionIndex = randomPartition(arr, l, r); # If partition index = k, then # we found the median of odd # number element in arr[] if (partitionIndex == k) : b = arr[partitionIndex]; if (a1 != -1) : return; # If index = k - 1, then we get # a & b as middle element of # arr[] elif (partitionIndex == k - 1) : a = arr[partitionIndex]; if (b1 != -1) : return; # If partitionIndex >= k then # find the index in first half # of the arr[] if (partitionIndex >= k) : return MedianUtil(arr, l, partitionIndex - 1, k, a, b); # If partitionIndex <= k then # find the index in second half # of the arr[] else : return MedianUtil(arr, partitionIndex + 1, r, k, a, b); return; # Function to find Mediandef findMedian(arr, n) : global a; global b; a = -1; b = -1; # If n is odd if (n % 2 == 1) : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = b; # If n is even else : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = (a + b) // 2; # Print the Median of arr[] print("Median = " ,ans); # Driver codearr = [ 12, 3, 5, 7, 4, 19, 26 ];n = len(arr);findMedian(arr, n); # This code is contributed by AnkitRai01
// C# program to find median of// an arrayusing System; class GFG{ static int a, b; // Utility function to swapping of element static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Returns the correct position of // pivot element static int Partition(int []arr, int l, int r) { int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { arr = swap(arr, i, j); i++; } j++; } arr = swap(arr, i, r); return i; } // Picks a random pivot element between // l and r and partitions arr[l..r] // around the randomly picked element // using partition() static int randomPartition(int []arr, int l, int r) { int n = r - l + 1; int pivot = (int) (new Random().Next() % n); arr = swap(arr, l + pivot, r); return Partition(arr, l, r); } // Utility function to find median static int MedianUtil(int []arr, int l, int r, int k) { // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in []arr if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return int.MinValue; } // If index = k - 1, then we get // a & b as middle element of // []arr else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return int.MinValue; } // If partitionIndex >= k then // find the index in first half // of the []arr if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k); // If partitionIndex <= k then // find the index in second half // of the []arr else return MedianUtil(arr, partitionIndex + 1, r, k); } return int.MinValue; } // Function to find Median static void findMedian(int []arr, int n) { int ans; a = -1; b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2); ans = (a + b) / 2; } // Print the Median of []arr Console.Write("Median = " + ans); } // Driver code public static void Main(String[] args) { int []arr = { 12, 3, 5, 7, 4, 19, 26 }; int n = arr.Length; findMedian(arr, n); }} // This code is contributed by PrinciRaj1992
Median = 7
Time Complexity:
Best case analysis: O(1)Average case analysis: O(N)Worst case analysis: O(N2)
Best case analysis: O(1)
Average case analysis: O(N)
Worst case analysis: O(N2)
Auxiliary Space: O(N)Wonder how? Reference: ByStanfordUniversity
ankthon
29AjayKumar
princiraj1992
Hrudwik_Dhulipalla
pankajsharmagfg
anikaseth98
ankita_saini
median-finding
Algorithms
Arrays
Divide and Conquer
Arrays
Divide and Conquer
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 274,
"s": 52,
"text": "Given an unsorted array arr[] of length N, the task is to find the median of this array. Median of a sorted array of size N is defined as the middle element when n is odd and average of middle two elements when n is even."
},
{
"code": null,
"e": 285,
"s": 274,
"text": "Examples: "
},
{
"code": null,
"e": 518,
"s": 285,
"text": "Input: arr[] = {12, 3, 5, 7, 4, 19, 26} Output: 7 Sorted sequence of given array arr[] = {3, 4, 5, 7, 12, 19, 26} Since the number of elements is odd, the median is 4th element in the sorted sequence of given array arr[], which is 7"
},
{
"code": null,
"e": 708,
"s": 518,
"text": "Input: arr[] = {12, 3, 5, 7, 4, 26} Output: 6 Since number of elements are even, median is average of 3rd and 4th element in sorted sequence of given array arr[], which means (5 + 7)/2 = 6 "
},
{
"code": null,
"e": 726,
"s": 708,
"text": "Naive Approach: "
},
{
"code": null,
"e": 768,
"s": 726,
"text": "Sort the array arr[] in increasing order."
},
{
"code": null,
"e": 832,
"s": 768,
"text": "If number of elements in arr[] is odd, then median is arr[n/2]."
},
{
"code": null,
"e": 922,
"s": 832,
"text": "If the number of elements in arr[] is even, median is average of arr[n/2] and arr[n/2+1]."
},
{
"code": null,
"e": 993,
"s": 922,
"text": "Please refer to this article for the implementation of above approach."
},
{
"code": null,
"e": 1044,
"s": 993,
"text": "Efficient Approach: using Randomized QuickSelect "
},
{
"code": null,
"e": 1253,
"s": 1044,
"text": "Randomly pick pivot element from arr[] and the using the partition step from the quick sort algorithm arrange all the elements smaller than the pivot on its left and the elements greater than it on its right."
},
{
"code": null,
"e": 1392,
"s": 1253,
"text": "If after the previous step, the position of the chosen pivot is the middle of the array then it is the required median of the given array."
},
{
"code": null,
"e": 1555,
"s": 1392,
"text": "If the position is before the middle element then repeat the step for the subarray starting from previous starting index and the chosen pivot as the ending index."
},
{
"code": null,
"e": 1709,
"s": 1555,
"text": "If the position is after the middle element then repeat the step for the subarray starting from the chosen pivot and ending at the previous ending index."
},
{
"code": null,
"e": 1847,
"s": 1709,
"text": "Note that in case of even number of elements, the middle two elements have to be found and their average will be the median of the array."
},
{
"code": null,
"e": 1900,
"s": 1847,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1904,
"s": 1900,
"text": "C++"
},
{
"code": null,
"e": 1909,
"s": 1904,
"text": "Java"
},
{
"code": null,
"e": 1917,
"s": 1909,
"text": "Python3"
},
{
"code": null,
"e": 1920,
"s": 1917,
"text": "C#"
},
{
"code": "// CPP program to find median of// an array #include \"bits/stdc++.h\"using namespace std; // Utility function to swapping of elementvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Returns the correct position of// pivot elementint Partition(int arr[], int l, int r){ int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { swap(&arr[i], &arr[j]); i++; } j++; } swap(&arr[i], &arr[r]); return i;} // Picks a random pivot element between// l and r and partitions arr[l..r]// around the randomly picked element// using partition()int randomPartition(int arr[], int l, int r){ int n = r - l + 1; int pivot = rand() % n; swap(&arr[l + pivot], &arr[r]); return Partition(arr, l, r);} // Utility function to find medianvoid MedianUtil(int arr[], int l, int r, int k, int& a, int& b){ // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in arr[] if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return; } // If index = k - 1, then we get // a & b as middle element of // arr[] else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return; } // If partitionIndex >= k then // find the index in first half // of the arr[] if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k, a, b); // If partitionIndex <= k then // find the index in second half // of the arr[] else return MedianUtil(arr, partitionIndex + 1, r, k, a, b); } return;} // Function to find Medianvoid findMedian(int arr[], int n){ int ans, a = -1, b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2, a, b); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2, a, b); ans = (a + b) / 2; } // Print the Median of arr[] cout << \"Median = \" << ans;} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = sizeof(arr) / sizeof(arr[0]); findMedian(arr, n); return 0;}",
"e": 4534,
"s": 1920,
"text": null
},
{
"code": "// JAVA program to find median of// an arrayclass GFG{ static int a, b; // Utility function to swapping of element static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Returns the correct position of // pivot element static int Partition(int arr[], int l, int r) { int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { arr = swap(arr, i, j); i++; } j++; } arr = swap(arr, i, r); return i; } // Picks a random pivot element between // l and r and partitions arr[l..r] // around the randomly picked element // using partition() static int randomPartition(int arr[], int l, int r) { int n = r - l + 1; int pivot = (int) (Math.random() % n); arr = swap(arr, l + pivot, r); return Partition(arr, l, r); } // Utility function to find median static int MedianUtil(int arr[], int l, int r, int k) { // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in arr[] if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return Integer.MIN_VALUE; } // If index = k - 1, then we get // a & b as middle element of // arr[] else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return Integer.MIN_VALUE; } // If partitionIndex >= k then // find the index in first half // of the arr[] if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k); // If partitionIndex <= k then // find the index in second half // of the arr[] else return MedianUtil(arr, partitionIndex + 1, r, k); } return Integer.MIN_VALUE; } // Function to find Median static void findMedian(int arr[], int n) { int ans; a = -1; b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2); ans = (a + b) / 2; } // Print the Median of arr[] System.out.print(\"Median = \" + ans); } // Driver code public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = arr.length; findMedian(arr, n); }} // This code is contributed by 29AjayKumar",
"e": 7514,
"s": 4534,
"text": null
},
{
"code": "# Python3 program to find median of# an arrayimport random a, b = None, None; # Returns the correct position of# pivot elementdef Partition(arr, l, r) : lst = arr[r]; i = l; j = l; while (j < r) : if (arr[j] < lst) : arr[i], arr[j] = arr[j],arr[i]; i += 1; j += 1; arr[i], arr[r] = arr[r],arr[i]; return i; # Picks a random pivot element between# l and r and partitions arr[l..r]# around the randomly picked element# using partition()def randomPartition(arr, l, r) : n = r - l + 1; pivot = random.randrange(1, 100) % n; arr[l + pivot], arr[r] = arr[r], arr[l + pivot]; return Partition(arr, l, r); # Utility function to find mediandef MedianUtil(arr, l, r, k, a1, b1) : global a, b; # if l < r if (l <= r) : # Find the partition index partitionIndex = randomPartition(arr, l, r); # If partition index = k, then # we found the median of odd # number element in arr[] if (partitionIndex == k) : b = arr[partitionIndex]; if (a1 != -1) : return; # If index = k - 1, then we get # a & b as middle element of # arr[] elif (partitionIndex == k - 1) : a = arr[partitionIndex]; if (b1 != -1) : return; # If partitionIndex >= k then # find the index in first half # of the arr[] if (partitionIndex >= k) : return MedianUtil(arr, l, partitionIndex - 1, k, a, b); # If partitionIndex <= k then # find the index in second half # of the arr[] else : return MedianUtil(arr, partitionIndex + 1, r, k, a, b); return; # Function to find Mediandef findMedian(arr, n) : global a; global b; a = -1; b = -1; # If n is odd if (n % 2 == 1) : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = b; # If n is even else : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = (a + b) // 2; # Print the Median of arr[] print(\"Median = \" ,ans); # Driver codearr = [ 12, 3, 5, 7, 4, 19, 26 ];n = len(arr);findMedian(arr, n); # This code is contributed by AnkitRai01",
"e": 9824,
"s": 7514,
"text": null
},
{
"code": "// C# program to find median of// an arrayusing System; class GFG{ static int a, b; // Utility function to swapping of element static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Returns the correct position of // pivot element static int Partition(int []arr, int l, int r) { int lst = arr[r], i = l, j = l; while (j < r) { if (arr[j] < lst) { arr = swap(arr, i, j); i++; } j++; } arr = swap(arr, i, r); return i; } // Picks a random pivot element between // l and r and partitions arr[l..r] // around the randomly picked element // using partition() static int randomPartition(int []arr, int l, int r) { int n = r - l + 1; int pivot = (int) (new Random().Next() % n); arr = swap(arr, l + pivot, r); return Partition(arr, l, r); } // Utility function to find median static int MedianUtil(int []arr, int l, int r, int k) { // if l < r if (l <= r) { // Find the partition index int partitionIndex = randomPartition(arr, l, r); // If partition index = k, then // we found the median of odd // number element in []arr if (partitionIndex == k) { b = arr[partitionIndex]; if (a != -1) return int.MinValue; } // If index = k - 1, then we get // a & b as middle element of // []arr else if (partitionIndex == k - 1) { a = arr[partitionIndex]; if (b != -1) return int.MinValue; } // If partitionIndex >= k then // find the index in first half // of the []arr if (partitionIndex >= k) return MedianUtil(arr, l, partitionIndex - 1, k); // If partitionIndex <= k then // find the index in second half // of the []arr else return MedianUtil(arr, partitionIndex + 1, r, k); } return int.MinValue; } // Function to find Median static void findMedian(int []arr, int n) { int ans; a = -1; b = -1; // If n is odd if (n % 2 == 1) { MedianUtil(arr, 0, n - 1, n / 2); ans = b; } // If n is even else { MedianUtil(arr, 0, n - 1, n / 2); ans = (a + b) / 2; } // Print the Median of []arr Console.Write(\"Median = \" + ans); } // Driver code public static void Main(String[] args) { int []arr = { 12, 3, 5, 7, 4, 19, 26 }; int n = arr.Length; findMedian(arr, n); }} // This code is contributed by PrinciRaj1992",
"e": 12806,
"s": 9824,
"text": null
},
{
"code": null,
"e": 12817,
"s": 12806,
"text": "Median = 7"
},
{
"code": null,
"e": 12837,
"s": 12819,
"text": "Time Complexity: "
},
{
"code": null,
"e": 12915,
"s": 12837,
"text": "Best case analysis: O(1)Average case analysis: O(N)Worst case analysis: O(N2)"
},
{
"code": null,
"e": 12940,
"s": 12915,
"text": "Best case analysis: O(1)"
},
{
"code": null,
"e": 12968,
"s": 12940,
"text": "Average case analysis: O(N)"
},
{
"code": null,
"e": 12995,
"s": 12968,
"text": "Worst case analysis: O(N2)"
},
{
"code": null,
"e": 13061,
"s": 12995,
"text": "Auxiliary Space: O(N)Wonder how? Reference: ByStanfordUniversity "
},
{
"code": null,
"e": 13069,
"s": 13061,
"text": "ankthon"
},
{
"code": null,
"e": 13081,
"s": 13069,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13095,
"s": 13081,
"text": "princiraj1992"
},
{
"code": null,
"e": 13114,
"s": 13095,
"text": "Hrudwik_Dhulipalla"
},
{
"code": null,
"e": 13130,
"s": 13114,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13142,
"s": 13130,
"text": "anikaseth98"
},
{
"code": null,
"e": 13155,
"s": 13142,
"text": "ankita_saini"
},
{
"code": null,
"e": 13170,
"s": 13155,
"text": "median-finding"
},
{
"code": null,
"e": 13181,
"s": 13170,
"text": "Algorithms"
},
{
"code": null,
"e": 13188,
"s": 13181,
"text": "Arrays"
},
{
"code": null,
"e": 13207,
"s": 13188,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 13214,
"s": 13207,
"text": "Arrays"
},
{
"code": null,
"e": 13233,
"s": 13214,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 13244,
"s": 13233,
"text": "Algorithms"
}
] |
Java Program for Bubble Sort | 13 Jun, 2022
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Java
Java
// Java program for implementation of Bubble Sortclass BubbleSort{ void bubbleSort(int arr[]) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { // swap temp and arr[i] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } /* Prints the array */ void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method to test above public static void main(String args[]) { BubbleSort ob = new BubbleSort(); int arr[] = {64, 34, 25, 12, 22, 11, 90}; ob.bubbleSort(arr); System.out.println("Sorted array"); ob.printArray(arr); }}/* This code is contributed by Rajat Mishra */
Time Complexity: O(n2)Auxiliary Space: O(1)
Please refer complete article on Bubble Sort for more details!
amankr0211
BubbleSort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate through List in Java
How to Iterate HashMap in Java?
Merge Sort
QuickSort
Insertion Sort
Selection Sort Algorithm
std::sort() in C++ STL | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 182,
"s": 52,
"text": "Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order."
},
{
"code": null,
"e": 187,
"s": 182,
"text": "Java"
},
{
"code": null,
"e": 192,
"s": 187,
"text": "Java"
},
{
"code": "// Java program for implementation of Bubble Sortclass BubbleSort{ void bubbleSort(int arr[]) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { // swap temp and arr[i] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } /* Prints the array */ void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver method to test above public static void main(String args[]) { BubbleSort ob = new BubbleSort(); int arr[] = {64, 34, 25, 12, 22, 11, 90}; ob.bubbleSort(arr); System.out.println(\"Sorted array\"); ob.printArray(arr); }}/* This code is contributed by Rajat Mishra */",
"e": 1151,
"s": 192,
"text": null
},
{
"code": null,
"e": 1195,
"s": 1151,
"text": "Time Complexity: O(n2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1258,
"s": 1195,
"text": "Please refer complete article on Bubble Sort for more details!"
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": "amankr0211"
},
{
"code": null,
"e": 1280,
"s": 1269,
"text": "BubbleSort"
},
{
"code": null,
"e": 1294,
"s": 1280,
"text": "Java Programs"
},
{
"code": null,
"e": 1302,
"s": 1294,
"text": "Sorting"
},
{
"code": null,
"e": 1310,
"s": 1302,
"text": "Sorting"
},
{
"code": null,
"e": 1408,
"s": 1310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1446,
"s": 1408,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 1503,
"s": 1446,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 1584,
"s": 1503,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 1613,
"s": 1584,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 1645,
"s": 1613,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 1656,
"s": 1645,
"text": "Merge Sort"
},
{
"code": null,
"e": 1666,
"s": 1656,
"text": "QuickSort"
},
{
"code": null,
"e": 1681,
"s": 1666,
"text": "Insertion Sort"
},
{
"code": null,
"e": 1706,
"s": 1681,
"text": "Selection Sort Algorithm"
}
] |
How to use JSONobject to parse JSON in Android? | This example demonstrates how do I use JSONObject to parse JSON in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textStyle="bold"
android:textSize="24sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
public static final String JSON_STRING="{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}";
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
try {
JSONObject emp = (new JSONObject(JSON_STRING)).getJSONObject("Employee");
String empName = emp.getString("Name");
int empSalary = emp.getInt("Salary");
String string = "Employee Name: "+empName+"\n"+"Employee Salary: "+empSalary;
textView.setText(string);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "This example demonstrates how do I use JSONObject to parse JSON in android."
},
{
"code": null,
"e": 1267,
"s": 1138,
"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": 1332,
"s": 1267,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1898,
"s": 1332,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n android:textStyle=\"bold\"\n android:textSize=\"24sp\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1955,
"s": 1898,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2890,
"s": 1955,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport org.json.JSONException;\nimport org.json.JSONObject;\npublic class MainActivity extends AppCompatActivity {\n public static final String JSON_STRING=\"{\\\"Employee\\\":{\\\"Name\\\":\\\"Niyaz\\\",\\\"Salary\\\":56000}}\";\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n try {\n JSONObject emp = (new JSONObject(JSON_STRING)).getJSONObject(\"Employee\");\n String empName = emp.getString(\"Name\");\n int empSalary = emp.getInt(\"Salary\");\n String string = \"Employee Name: \"+empName+\"\\n\"+\"Employee Salary: \"+empSalary;\n textView.setText(string);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2945,
"s": 2890,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3618,
"s": 2945,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3965,
"s": 3618,
"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": 4006,
"s": 3965,
"text": "Click here to download the project code."
}
] |
Sub-Array sum divisible by K | Practice | GeeksforGeeks | You are given an array A of N positive and/or negative integers and a value K. The task is to find the count of all sub-arrays whose sum is divisible by K.
Example 1:
Input: N = 6, K = 5
arr[] = {4, 5, 0, -2, -3, 1}
Output: 7
Explanation: There are 7 sub-arrays whose
is divisible by K {4, 5, 0, -2, -3, 1}, {5},
{5, 0}, {5, 0, -2, -3}, {0}, {0, -2, -3}
and {-2, -3}
Example 2:
Input: N = 6, K = 2
arr[] = {2, 2, 2, 2, 2, 2}
Output: 21
Explanation: All subarray sums are
divisible by 7
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function subCount() that takes array arr, integer N, and integer K as parameters and returns the desired output.
Expected Time Complexity: O(N+K).
Expected Auxiliary Space: O(K).
Constraints:
2 ≤ N ≤ 105
+1
abhishekshrivastav19201 month ago
not easy problem if you have to solve in O(N).
0
rajubugude3 months ago
PYTHON (Prefix Sum + Hash map)
Total Time Taken: 0.8/5.8
class Solution:
def subCount(self,arr, n, k):
# Your code goes here
res = {0:1} #coz len of arr >= 2
summ = 0
count = 0
for i in range(n):
summ += arr[i]
rem = summ % k
# If rem already in 'remMap'.
if(rem in res):
count += res[rem]
res[rem] += 1
else:
res[rem] = 1
return count
+1
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
Execution Time :- 0.7 / 1.7 sec
long long subCount(long long arr[], int n, long long k){ long long int cnt = 0; unordered_map<long long int,int> mp; long long int currSum = 0; mp[0]++; for(int i=0; i<n; i++){ currSum += arr[i]; int rem = currSum % k; if(rem < 0) rem = rem + k; if(mp.find(rem) != mp.end()){ cnt += mp[rem]; } mp[rem]++; } return (cnt);}
0
chessnoobdj3 months ago
C++
long long subCount(long long arr[], int N, long long K)
{
long long pref = 0; // prefix sum
vector<long long> cPref(K); //sum will not exceed K as we are taking modulo at every step
cPref[pref]++; // adding 0 as prefix sum, base case
int answer = 0; // count of number of subarrays whose sum is divisible by K
for(int i=0; i<N; i++) {
pref = (pref + arr[i]) % K; // Here, we take modulo of prefix sum as outlined in the explanation
if(pref < 0) pref += K; // since -1 mod 5 and 4 mod 5 are equivalent, we will keep only positives since we like them :)
answer += cPref[pref]; // if we have already found pref, then increase the answer count
cPref[pref]++; // add pref seen count by 1
}
return answer;
}
0
radheshyamnitj4 months ago
unordered_map<int,int> mp; int ans=0,cursum=0; mp[0]=1; int rem=0; for(int i=0;i<N;i++){ cursum+=arr[i]; rem=cursum%K; if(rem<0){ rem+=K; } if(mp.find(rem)!=mp.end()){ ans+=mp[rem]; } mp[rem]++; } return ans; }
+1
badgujarsachin834 months ago
long long subCount(long long arr[], int N, long long K)
{
// Your code goes here
unordered_map<int,int> mp;
int ans=0,cursum=0;
mp[0]=1;
int rem=0;
for(int i=0;i<N;i++){
cursum+=arr[i];
rem=cursum%K;
if(rem<0){
rem+=K;
}
if(mp.find(rem)!=mp.end()){
ans+=mp[rem];
mp[rem]++;
}
else{
mp[rem]++;
}
}
return ans;
}
0
Rahul Kumar8 months ago
Rahul Kumar
Pepcoding tutorial, in case you are stuck
-1
shahzdor9 months ago
shahzdor
Python solution:
class Solution: def subCount(self,arr, n, k): dict1=dict({0:1}) sum1=0 count=0 for i in range(n): sum1+=arr[i] x=(sum1%k)
if x not in dict1: dict1[x]=1
else: dict1[x]+=1 count+=dict1[x]-1
return count
0
Shreyansh Kumar Singh10 months ago
Shreyansh Kumar Singh
This is a Leetcode Medium level question but it's marked Easy here. Leetcode 974. Subarray Sums Divisible by K
-1
Soumya Sharma10 months ago
Soumya Sharma
EXECUTION TIME = 0.61 s
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": 394,
"s": 238,
"text": "You are given an array A of N positive and/or negative integers and a value K. The task is to find the count of all sub-arrays whose sum is divisible by K."
},
{
"code": null,
"e": 405,
"s": 394,
"text": "Example 1:"
},
{
"code": null,
"e": 616,
"s": 405,
"text": "Input: N = 6, K = 5\n arr[] = {4, 5, 0, -2, -3, 1}\nOutput: 7\nExplanation: There are 7 sub-arrays whose \nis divisible by K {4, 5, 0, -2, -3, 1}, {5}, \n{5, 0}, {5, 0, -2, -3}, {0}, {0, -2, -3} \nand {-2, -3}\n"
},
{
"code": null,
"e": 627,
"s": 616,
"text": "Example 2:"
},
{
"code": null,
"e": 745,
"s": 627,
"text": "Input: N = 6, K = 2\n arr[] = {2, 2, 2, 2, 2, 2}\nOutput: 21\nExplanation: All subarray sums are \ndivisible by 7\n\n"
},
{
"code": null,
"e": 1013,
"s": 747,
"text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function subCount() that takes array arr, integer N, and integer K as parameters and returns the desired output."
},
{
"code": null,
"e": 1079,
"s": 1013,
"text": "Expected Time Complexity: O(N+K).\nExpected Auxiliary Space: O(K)."
},
{
"code": null,
"e": 1106,
"s": 1081,
"text": "Constraints:\n2 ≤ N ≤ 105"
},
{
"code": null,
"e": 1111,
"s": 1108,
"text": "+1"
},
{
"code": null,
"e": 1145,
"s": 1111,
"text": "abhishekshrivastav19201 month ago"
},
{
"code": null,
"e": 1192,
"s": 1145,
"text": "not easy problem if you have to solve in O(N)."
},
{
"code": null,
"e": 1194,
"s": 1192,
"text": "0"
},
{
"code": null,
"e": 1217,
"s": 1194,
"text": "rajubugude3 months ago"
},
{
"code": null,
"e": 1248,
"s": 1217,
"text": "PYTHON (Prefix Sum + Hash map)"
},
{
"code": null,
"e": 1274,
"s": 1248,
"text": "Total Time Taken: 0.8/5.8"
},
{
"code": null,
"e": 1713,
"s": 1274,
"text": "class Solution:\n def subCount(self,arr, n, k):\n # Your code goes here\n res = {0:1} #coz len of arr >= 2\n summ = 0\n count = 0\n for i in range(n):\n summ += arr[i]\n rem = summ % k\n # If rem already in 'remMap'.\n if(rem in res):\n count += res[rem]\n res[rem] += 1\n else:\n res[rem] = 1\n return count"
},
{
"code": null,
"e": 1716,
"s": 1713,
"text": "+1"
},
{
"code": null,
"e": 1744,
"s": 1716,
"text": "aloksinghbais023 months ago"
},
{
"code": null,
"e": 1834,
"s": 1744,
"text": "C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-"
},
{
"code": null,
"e": 1868,
"s": 1836,
"text": "Execution Time :- 0.7 / 1.7 sec"
},
{
"code": null,
"e": 2267,
"s": 1870,
"text": "long long subCount(long long arr[], int n, long long k){ long long int cnt = 0; unordered_map<long long int,int> mp; long long int currSum = 0; mp[0]++; for(int i=0; i<n; i++){ currSum += arr[i]; int rem = currSum % k; if(rem < 0) rem = rem + k; if(mp.find(rem) != mp.end()){ cnt += mp[rem]; } mp[rem]++; } return (cnt);}"
},
{
"code": null,
"e": 2269,
"s": 2267,
"text": "0"
},
{
"code": null,
"e": 2293,
"s": 2269,
"text": "chessnoobdj3 months ago"
},
{
"code": null,
"e": 2297,
"s": 2293,
"text": "C++"
},
{
"code": null,
"e": 3193,
"s": 2297,
"text": "long long subCount(long long arr[], int N, long long K)\n\t{\n\t long long pref = 0; // prefix sum\n vector<long long> cPref(K); //sum will not exceed K as we are taking modulo at every step\n cPref[pref]++; // adding 0 as prefix sum, base case\n \n int answer = 0; // count of number of subarrays whose sum is divisible by K\n \n for(int i=0; i<N; i++) {\n \n pref = (pref + arr[i]) % K; // Here, we take modulo of prefix sum as outlined in the explanation\n \n if(pref < 0) pref += K; // since -1 mod 5 and 4 mod 5 are equivalent, we will keep only positives since we like them :)\n \n answer += cPref[pref]; // if we have already found pref, then increase the answer count\n \n cPref[pref]++; // add pref seen count by 1\n }\n \n return answer;\n\t}"
},
{
"code": null,
"e": 3195,
"s": 3193,
"text": "0"
},
{
"code": null,
"e": 3222,
"s": 3195,
"text": "radheshyamnitj4 months ago"
},
{
"code": null,
"e": 3526,
"s": 3222,
"text": " unordered_map<int,int> mp; int ans=0,cursum=0; mp[0]=1; int rem=0; for(int i=0;i<N;i++){ cursum+=arr[i]; rem=cursum%K; if(rem<0){ rem+=K; } if(mp.find(rem)!=mp.end()){ ans+=mp[rem]; } mp[rem]++; } return ans; }"
},
{
"code": null,
"e": 3529,
"s": 3526,
"text": "+1"
},
{
"code": null,
"e": 3558,
"s": 3529,
"text": "badgujarsachin834 months ago"
},
{
"code": null,
"e": 4035,
"s": 3558,
"text": "long long subCount(long long arr[], int N, long long K)\n\t{\n\t // Your code goes here\n\t unordered_map<int,int> mp;\n\t int ans=0,cursum=0;\n\t mp[0]=1;\n\t int rem=0;\n\t for(int i=0;i<N;i++){\n\t cursum+=arr[i];\n\t rem=cursum%K;\n\t if(rem<0){\n\t rem+=K;\n\t }\n\t if(mp.find(rem)!=mp.end()){\n\t ans+=mp[rem];\n\t mp[rem]++;\n\t }\n\t else{\n\t mp[rem]++;\n\t }\n\t }\n\t return ans;\n\t}"
},
{
"code": null,
"e": 4037,
"s": 4035,
"text": "0"
},
{
"code": null,
"e": 4061,
"s": 4037,
"text": "Rahul Kumar8 months ago"
},
{
"code": null,
"e": 4073,
"s": 4061,
"text": "Rahul Kumar"
},
{
"code": null,
"e": 4115,
"s": 4073,
"text": "Pepcoding tutorial, in case you are stuck"
},
{
"code": null,
"e": 4118,
"s": 4115,
"text": "-1"
},
{
"code": null,
"e": 4139,
"s": 4118,
"text": "shahzdor9 months ago"
},
{
"code": null,
"e": 4148,
"s": 4139,
"text": "shahzdor"
},
{
"code": null,
"e": 4165,
"s": 4148,
"text": "Python solution:"
},
{
"code": null,
"e": 4310,
"s": 4165,
"text": "class Solution: def subCount(self,arr, n, k): dict1=dict({0:1}) sum1=0 count=0 for i in range(n): sum1+=arr[i] x=(sum1%k)"
},
{
"code": null,
"e": 4353,
"s": 4310,
"text": " if x not in dict1: dict1[x]=1"
},
{
"code": null,
"e": 4409,
"s": 4353,
"text": " else: dict1[x]+=1 count+=dict1[x]-1"
},
{
"code": null,
"e": 4426,
"s": 4409,
"text": " return count"
},
{
"code": null,
"e": 4428,
"s": 4426,
"text": "0"
},
{
"code": null,
"e": 4463,
"s": 4428,
"text": "Shreyansh Kumar Singh10 months ago"
},
{
"code": null,
"e": 4485,
"s": 4463,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 4597,
"s": 4485,
"text": "This is a Leetcode Medium level question but it's marked Easy here. Leetcode 974. Subarray Sums Divisible by K"
},
{
"code": null,
"e": 4600,
"s": 4597,
"text": "-1"
},
{
"code": null,
"e": 4627,
"s": 4600,
"text": "Soumya Sharma10 months ago"
},
{
"code": null,
"e": 4641,
"s": 4627,
"text": "Soumya Sharma"
},
{
"code": null,
"e": 4665,
"s": 4641,
"text": "EXECUTION TIME = 0.61 s"
},
{
"code": null,
"e": 4811,
"s": 4665,
"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": 4847,
"s": 4811,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4857,
"s": 4847,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4867,
"s": 4857,
"text": "\nContest\n"
},
{
"code": null,
"e": 4930,
"s": 4867,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5078,
"s": 4930,
"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": 5286,
"s": 5078,
"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": 5392,
"s": 5286,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Printing Items in 0/1 Knapsack in C++ | Given weights and values of n items; the task is to print the items according to 0/1 knapsack for the following weights and values in a knapsack of capacity W, to get the maximum total value in the knapsack.
What is 0/1 Knapsack?
Knapsack is like a bag with only a fixed size or a bag which can handle a certain amount of weight. Each item which is included in a knapsack have some value(profit) and some weight to it. We have to add those weights which will get us the maximum profit according to the total weight a knapsack could hold.
So we have weights, their value(profit) and total weight of bag which a knapsack can hold, so in 0/1 knapsack we just mention 1 and 0 to the item which are included or not where 0 is for the item that can’t be added in a bag, whereas 1 is for the item that can be included in the knapsack.
Let’s understand with the help of a simple Example −
Let us assume val[] = {1, 2, 5, 6}//value or profit
wt[] = {2, 3, 4, 5}//weight
W = 8//Capacity
Its knapsack table would be −
knapsack.jpg
The Knapsack table can be filled with the help of the following formula −
K [i ,w] = max {K [i−1, w], K [i−1, w−wt [i]] + Val[i]}
Solving the table using backtracking approach,
Now we have the data of every item their profits and the maximum of the profit within the maximum weight we can get after adding certain items.
Start backtracking form k[n][w], where the k[n][w] is 8.
We will go in upward direction as the blue arrow guides to all way to the up where the black arrows are going. So the 8 is in 4th row only so we will include the 4th object, this means we got the maximum profit after adding the 4th item.
We will minus the total profit that is 8 with the profit obtained by adding the 4th item i.e, 6 we will get 2.
We will backtrack the table to look for when we get 2 as the maximum profit. We got it when we add the 2nd item
So we will add 2nd and 4th item in a knapsack to fill the bag efficiently and to achieve the maximum profit.
Input: val[] = {60, 100, 120}
wt[] = {10, 20, 30}
w = 50
Output: 220 //max value
30 20 //weights
Explanation: to reach till the maximum weight i.e. 50 we will add two weights value,
30 whose value is 120 and 20 whose value is 100
Input: val[] = {10, 40, 50}
wt[] = {2, 4, 5}
w = 6
Output: 50
4 2
Explanation: to reach till the maximum weight i.e. 6 we will add two weights value, 4
whose value is 40 and 2 whose value is 10.
Start
Step 1-> In function max(int a, int b)
Return (a > b) ? a : b
Step 2-> In function printknapSack(int W, int wt[], int val[], int n)
Decalare i, w, K[n + 1][W + 1]
Loop For i = 0 and i <= n and i++
Loop For w = 0 and w <= W and w++
If i == 0 || w == 0 then,
Set K[i][w] = 0
Else If wt[i - 1] <= w then,
Set K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w])
Else
Set K[i][w] = K[i - 1][w]
Set res = K[n][W]
Print res
Set w = W
Loop For i = n and i > 0 && res > 0 and i--
If res == K[i - 1][w] then,
Continue
Else {
Print wt[i - 1])
Set res = res - val[i - 1]
Set w = w - wt[i - 1]
Step 3-> In function int main()
Set val[] = { 50, 120, 70 }
Set wt[] = { 10, 20, 30 }
Set W = 50
Set n = sizeof(val) / sizeof(val[0])
Call function printknapSack(W, wt, val, n)
Stop
Live Demo
#include <bits/stdc++.h>
int max(int a, int b) { return (a > b) ? a : b; }
// Prints the items which are put in a knapsack of capacity W
void printknapSack(int W, int wt[], int val[], int n) {
int i, w;
int K[n + 1][W + 1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = max(val[i - 1] +
K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
// stores the result of Knapsack
int res = K[n][W];
printf("maximum value=%d\n", res);
w = W;
printf("weights included\n");
for (i = n; i > 0 && res > 0; i--) {
if (res == K[i - 1][w])
continue;
else {
printf("%d ", wt[i - 1]);
res = res - val[i - 1];
w = w - wt[i - 1];
}
}
}
// main code
int main() {
int val[] = { 50, 120, 70 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
printknapSack(W, wt, val, n);
return 0;
}
maximum value=190
weights included
30 20 | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "Given weights and values of n items; the task is to print the items according to 0/1 knapsack for the following weights and values in a knapsack of capacity W, to get the maximum total value in the knapsack."
},
{
"code": null,
"e": 1292,
"s": 1270,
"text": "What is 0/1 Knapsack?"
},
{
"code": null,
"e": 1600,
"s": 1292,
"text": "Knapsack is like a bag with only a fixed size or a bag which can handle a certain amount of weight. Each item which is included in a knapsack have some value(profit) and some weight to it. We have to add those weights which will get us the maximum profit according to the total weight a knapsack could hold."
},
{
"code": null,
"e": 1890,
"s": 1600,
"text": "So we have weights, their value(profit) and total weight of bag which a knapsack can hold, so in 0/1 knapsack we just mention 1 and 0 to the item which are included or not where 0 is for the item that can’t be added in a bag, whereas 1 is for the item that can be included in the knapsack."
},
{
"code": null,
"e": 1943,
"s": 1890,
"text": "Let’s understand with the help of a simple Example −"
},
{
"code": null,
"e": 2039,
"s": 1943,
"text": "Let us assume val[] = {1, 2, 5, 6}//value or profit\nwt[] = {2, 3, 4, 5}//weight\nW = 8//Capacity"
},
{
"code": null,
"e": 2069,
"s": 2039,
"text": "Its knapsack table would be −"
},
{
"code": null,
"e": 2082,
"s": 2069,
"text": "knapsack.jpg"
},
{
"code": null,
"e": 2156,
"s": 2082,
"text": "The Knapsack table can be filled with the help of the following formula −"
},
{
"code": null,
"e": 2213,
"s": 2156,
"text": "K [i ,w] = max {K [i−1, w], K [i−1, w−wt [i]] + Val[i]}"
},
{
"code": null,
"e": 2260,
"s": 2213,
"text": "Solving the table using backtracking approach,"
},
{
"code": null,
"e": 2404,
"s": 2260,
"text": "Now we have the data of every item their profits and the maximum of the profit within the maximum weight we can get after adding certain items."
},
{
"code": null,
"e": 2461,
"s": 2404,
"text": "Start backtracking form k[n][w], where the k[n][w] is 8."
},
{
"code": null,
"e": 2699,
"s": 2461,
"text": "We will go in upward direction as the blue arrow guides to all way to the up where the black arrows are going. So the 8 is in 4th row only so we will include the 4th object, this means we got the maximum profit after adding the 4th item."
},
{
"code": null,
"e": 2810,
"s": 2699,
"text": "We will minus the total profit that is 8 with the profit obtained by adding the 4th item i.e, 6 we will get 2."
},
{
"code": null,
"e": 2922,
"s": 2810,
"text": "We will backtrack the table to look for when we get 2 as the maximum profit. We got it when we add the 2nd item"
},
{
"code": null,
"e": 3031,
"s": 2922,
"text": "So we will add 2nd and 4th item in a knapsack to fill the bag efficiently and to achieve the maximum profit."
},
{
"code": null,
"e": 3457,
"s": 3031,
"text": "Input: val[] = {60, 100, 120}\nwt[] = {10, 20, 30}\nw = 50\nOutput: 220 //max value\n30 20 //weights\nExplanation: to reach till the maximum weight i.e. 50 we will add two weights value,\n30 whose value is 120 and 20 whose value is 100\n\nInput: val[] = {10, 40, 50}\nwt[] = {2, 4, 5}\nw = 6\nOutput: 50\n4 2\nExplanation: to reach till the maximum weight i.e. 6 we will add two weights value, 4\nwhose value is 40 and 2 whose value is 10."
},
{
"code": null,
"e": 4461,
"s": 3457,
"text": "Start\nStep 1-> In function max(int a, int b)\n Return (a > b) ? a : b\nStep 2-> In function printknapSack(int W, int wt[], int val[], int n)\n Decalare i, w, K[n + 1][W + 1]\n Loop For i = 0 and i <= n and i++\n Loop For w = 0 and w <= W and w++\n If i == 0 || w == 0 then,\n Set K[i][w] = 0\n Else If wt[i - 1] <= w then,\n Set K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w])\n Else\n Set K[i][w] = K[i - 1][w]\n Set res = K[n][W]\n Print res\n Set w = W\n Loop For i = n and i > 0 && res > 0 and i--\n If res == K[i - 1][w] then,\n Continue\n Else {\n Print wt[i - 1])\n Set res = res - val[i - 1]\n Set w = w - wt[i - 1]\nStep 3-> In function int main()\n Set val[] = { 50, 120, 70 }\n Set wt[] = { 10, 20, 30 }\n Set W = 50\n Set n = sizeof(val) / sizeof(val[0])\n Call function printknapSack(W, wt, val, n)\nStop"
},
{
"code": null,
"e": 4472,
"s": 4461,
"text": " Live Demo"
},
{
"code": null,
"e": 5595,
"s": 4472,
"text": "#include <bits/stdc++.h>\nint max(int a, int b) { return (a > b) ? a : b; }\n// Prints the items which are put in a knapsack of capacity W\nvoid printknapSack(int W, int wt[], int val[], int n) {\n int i, w;\n int K[n + 1][W + 1];\n // Build table K[][] in bottom up manner\n for (i = 0; i <= n; i++) {\n for (w = 0; w <= W; w++) {\n if (i == 0 || w == 0)\n K[i][w] = 0;\n else if (wt[i - 1] <= w)\n K[i][w] = max(val[i - 1] +\n K[i - 1][w - wt[i - 1]], K[i - 1][w]);\n else\n K[i][w] = K[i - 1][w];\n }\n }\n // stores the result of Knapsack\n int res = K[n][W];\n printf(\"maximum value=%d\\n\", res);\n w = W;\n printf(\"weights included\\n\");\n for (i = n; i > 0 && res > 0; i--) {\n if (res == K[i - 1][w])\n continue;\n else {\n printf(\"%d \", wt[i - 1]);\n res = res - val[i - 1];\n w = w - wt[i - 1];\n }\n }\n}\n// main code\nint main() {\n int val[] = { 50, 120, 70 };\n int wt[] = { 10, 20, 30 };\n int W = 50;\n int n = sizeof(val) / sizeof(val[0]);\n printknapSack(W, wt, val, n);\n return 0;\n}"
},
{
"code": null,
"e": 5636,
"s": 5595,
"text": "maximum value=190\nweights included\n30 20"
}
] |
Structural Time-Series Forecasting with TensorFlow Probability: Iron Ore Mine Production | by Chris Price | Towards Data Science | Iron ore is one of the most heavily traded commodities in the world. As the primary input for the production of steel, it provides the foundation upon which the world’s largest metal market trades, and commands one of the largest shares of the global dry bulk trade.
Iron ore production, unsurprisingly, starts at the mine. As a trader either physical or financial, an understanding of the fundamental supply-demand nature of the iron ore market is essential. Iron ore grade (quality) variance has a notable impact on not only the spot and forward contracts pricing, but also on mill penalty charges for impurities. Imbalances in the fundamental supply/demand relationship can cause dramatic rises in the price of iron ore. Forecasting iron ore output from the largest iron ore exporting countries in order to predict global iron ore supply can be very helpful when speculating on spot, futures and contaminant penalty price movements.
In this article, we are going to develop a forecast model using TensorFlow Probability’s Structural Time-Series (STS) framework, to forecast the aggregate output of major iron ore mines in Brazil.
Brazil is the second largest exporter of iron ore globally. Major changes in supply from Brazil can have an affect on the price of iron ore, as noted above. Furthermore, Brazilian iron ore is typically very high-grade and low in impurities. As a result, the relative supply of ore from Brazil can have an affect on the penalty pricing of impurities charged by steel mills. If global supply is dominated by high-contaminant iron ore as a result of a shortage in supply from Brazilian mines, the price penalty of contaminants can rise dramatically. Forecasting the output from Brazil therefore can lend itself to understanding the above dynamics.
The code used in this article follows similar logic to that outlined in the Structural Time Series modeling in TensorFlow Probability tutorial (Copyright 2019 The TensorFlow Authors).
When approaching a time series forecast problem, investing time into understanding the complexity of the variable you wish to forecast is paramount. Stationarity, seasonality, distributions and exogenous feature relationships are but a handful of the many considerations to bear in mind before designing any model’s architecture.
Structural time series models (sometimes referred to as Bayesian Structural Time Series) are expressed as a sum of components such as trend, seasonal patterns, cycles and residuals:
These individual components are themselves time series defined by a structural assumption. The ability to configure each component in the time series makes TFP’s STS library particularly relevant in the context of our time series forecasting problem, as it enables us to encode domain-specific knowledge, such as trader and mine operator expertise, and known events into our model.
Mines production outputs typically exhibit systematic behaviour that can be modelled as a structural time series. In the context of our problem, we know that many mines close down for a two-week period in December for scheduled maintenance. This repeatable pattern can be added as a seasonal component to a structural time series model. We also know that Iron ore and other open cast mines exhibit distinct seasonal patterns that correlate strongly with precipitation which, during periods of heavy rainfall, lead to reduced outputs as drainage pumps become overwhelmed.
What is particularly useful about structural time series models in the context of our problem is that they employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast, but also a means of quantifying model uncertainty.
Another exciting and highly useful feature of STS models is that the resulting model can be decomposed as a collection of it separate components. These components can then be plotted, giving us a valuable insight into their respective affects on the dependent variable (Y-hat), and a deeper understanding of the global time series problem:
Before we start, it is worth noting that TensorFlow probability has a specific set of dependencies. Moreover TensorFlow is not included as a dependency of the TensorFlow Probability library and will need to be installed separately:
github.com
pip install --upgrade tensorflow-probability
Alternatively, you can use Google’s Colaboratory (Colab), who kindly provide hosted runtimes in Colab completely free of charge (CPU, GPU and even TPU!) subject to memory limits.
Let’s get started.
We start by examining our mine loadings (output) data whose observations are the total weekly output of each mine in millions of metric tonnes, aggregated over all major Brazilian iron ore producers:
# Importsimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport seaborn as snsimport tensorflow_probability as tfpimport tensorflow as tffrom statsmodels.tsa.seasonal import seasonal_decomposedf = pd.read_excel( '/content/bloomberg_weekly_io_output_brazil.xlsx', header = 1, index_col = 0, parse_dates = True)# Loadingsdf.plot(figsize=(16, 8))plt.title(‘Weekly Iron Ore Output, Metric Tonnes’)plt.ylabel(‘Loadings, Mt’)
If we examine the observed output time series carefully, we can vaguely see some of the structural components mentioned earlier in the article that we can attempt to encode in an STS model:
A clear seasonal pattern. Judging by the amplitude and frequency of each cycle, it is reasonable to suggest that this is additive seasonality (defined below).
With the exception of late 2018/early 2019, a linear trend.
Around the Christmas period, a distinct drop in output when mines typically close for scheduled maintenance.
A degree of noise, possibly correlated with weather, strikes, equipment failures etc.
We can verify some of the aforementioned components in the time series by attempting to decompose the time series into its constituent parts. We will use statsmodels time series analysis library to perform the decomposition and choose an ‘additive’ model as the seasonal component on the basis of the observed behaviour in our time series plot. For reference, additive seasonality is estimated as:
Passing the ‘iron_ore_brazil’ Pandas Series to the seasonal_decompose method we imported from statsmodels yields the following plot:
tsa = seasonal_decompose( df[‘iron_ore_brazil’],model=’additive’).plot()
Upon inspection, we can immediately identify the (mostly) linear trend and the seasonal component. If we look closely at the frequency and amplitude, you can see when the mine output diminishes each year during the winter period.
It is immediately apparent upon inspection of the residuals, that there are other relationships within this time series that cannot be explained by the seasonal and trend elements alone. The variance in the residuals, however, remains fairly constant and within a defined bound. This is useful information to bear in mind when defining our structural components.
“Aha!” I hear you cry at this point. “Why decompose the time series if that is the point of the STS model?”. Well, for two reasons:
It helps as a starting point in identifying and understanding the various fundamental components in a time series: trend, seasonality, cycles and unexplained variance which in turn, can inform us how we can configure the input parameters to the STS model priors.TFP’s STS models are trained on data through Variational Inference (VI) or Hamiltonian Monte Carlo (HMC) methods:
It helps as a starting point in identifying and understanding the various fundamental components in a time series: trend, seasonality, cycles and unexplained variance which in turn, can inform us how we can configure the input parameters to the STS model priors.
TFP’s STS models are trained on data through Variational Inference (VI) or Hamiltonian Monte Carlo (HMC) methods:
# Fit model to observed data with HMCtfp.sts.fit_with_hmc( model, observed_time_series, num_results=100, num_warmup_steps=50, num_leapfrog_steps=15, initial_state=None, initial_step_size=None, chain_batch_shape=(), num_variational_steps=150, variational_optimizer=None, variational_sample_size=5, seed=None, name=None)# Or, fit model to data with VItfp.sts.build_factored_surrogate_posterior( model, batch_shape=(), seed=None, name=None)
Both of these methods are, generally-speaking, quite computationally intensive (particularly in the case of HMC) on high-dimensional problems and are quite sensitive to tuning. Having an informed choice of input parameters when configuring STS components can help save time, resources and increase posterior distribution accuracy.
Explaining the mathematics behind HMC and VI is beyond the scope of this article, but you can find out more on HMC here and VI here.
We can now define the various components to our STS model and configure them based on what we know about the data generating process. Let’s start with the seasonal component:
We define the seasonal inputs to our structural time series model as follows:
# Create train dataset_train = df[‘iron_ore_brazil’][df.index < ‘2018–01–01’]_dates = train.index# Test datatest = df[‘iron_ore_brazil’][df.index >= ‘2018–01–01’]# TensorFlow requires an an (N, 1) float tensortrain = _train.to_numpy().reshape(-1, 1))# Seasonal effect 1: weekly cycle as identified in decomp.weekly_cycle = tfp.sts.Seasonal( num_seasons=52, # 52 weeks in year observed_time_series=train, allow_drift=True, name=’weekly_effect’)# Seasonal effect 2: month of year to capture winter drop in output.monthly_affect = tfp.sts.Seasonal( num_seasons=12, # 12 months in year num_steps_per_season=4, # assumed 4 weeks in every month observed_time_series=train, name=’month_of_year_effect’)
A valuable feature offered by the tfp.sts.Seasonal model is the ability to add ‘drift’ to the seasonal affect. This parameter allows the effect of each season to evolve or ‘drift’ from one occurrence to the next following a Gaussian random walk(specifically, samples drawn from a normal distribution defined by a mean and variance plus some drift term). If we were confident of the mean and variance of the prior distribution of the seasonal component, we could configure it ourselves within the model:
monthly_effect = tfp.sts.Seasonal( num_seasons=12, # 12 months in year num_steps_per_season=4, # assumed 4 weeks in month observed_time_series=train, drift_scale_prior=tfd.Normal(loc=1., scale=0.1), # define priors initial_effect_prior=tfd.Normal(loc=0., scale=5.), name=’month_of_year_effect’)
For now, by setting the parameter ‘allow_drift=True’ we can let the model handle this for us.
A visual inspection of our iron ore mine outputs shows (with the exception of late 2018/early 2019) a consistent linear trend. We can model this behaviour with a LocalLinearTrend model.
The local linear trend model represents a time series trend as a combination of some magnitude (level) and slope. Each of these elements evolve through time via a Gaussian random-walk:
level[t] = level[t-1] + slope[t-1] + Normal(0., level_scale)slope[t] = slope[t-1] + Normal(0., slope_scale)
Implementation of the local linear trend component in our problem is quite straightforward:
# Add trendtrend = tfp.sts.LocalLinearTrend( observed_time_series=train, name='trend')
An important consideration to bear in mind when choosing how to model the trend component is the choice of model, which is dependent upon the nature of the problem. In the case of our time series problem, the observed trend is relatively stable over time and evolves gradually i.e. it does not display any strong nonlinear behaviour. Our choice of model to represent this trend, therefore, is a reasonable one, however this model can produce forecasts with very high uncertainty over longer forecast periods.
What is the alternative?
It is well known that most time series have inherent temporal structure where succeeding observations are dependent on the previous n observations in time i.e. autocorrelation. A wise choice therefore, might be to model the trend using TFP STS’s SemiLocalLinearTrend model. In a semi-local linear trend model, the slopecomponent evolves according to a first-order autoregressive process. The AR process can therefore account for the autocorrelative (of order n) effect in the time series, and typically lead to forecasts with greater certainty over a longer period of time.
As previously mentioned during our inspection of the seasonal decomposition plot, the residuals in our time series look relatively consistent suggesting that they are potentially stationary, i.e. they maintain a constant variance over time, do not exhibit bias or heteroskedasticity etc. We can therefore represent the residual behaviour in an sts.AutoRegressive model:
# Residualsresiduals = tfp.sts.Autoregressive( order=1, observed_time_series=train, coefficients_prior=None, level_scale_prior=None, initial_state_prior=None, name='residuals_autoregressive')
As with the other components, for a fully Bayesian approach one should specify the priors coefficients_prior, level_scale_prior and initial_state_prior. As we have not specified priors, a TensorFlow Distributions (tfd) MultivariateNormalDiag instance is used as a default prior for the coefficients, and a heuristic prior constructed for the level and initial states based on the input time series.
We can now define our structural time series model using the tfp.sts.Sum class. This class enables us to define the compositional specification of our structural time series model from the components we have defined above:
model = tfp.sts.Sum( components=[ trend, weekly_cycle, monthly_effect, residuals], observed_time_series=train)
We will now fit our model to the observed time series, namely our iron ore output. Unlike traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation, an STS model learns a distribution, namely, the posterior.
We are going to fit the model to the data and build a posterior predictive distribution using Variational Inference. Simply put, VI fits a set of approximate posterior distributions for the model parameters we have defined (for each component) and optimises these by minimising a variational loss function known as negative Evidence Lower Bound (ELBO):
# VI posterior variational_posteriors = tfp.sts.build_factored_surrogate_posterior( model=loadings_model)# Build and optimize the variational loss function (ELBO)[email protected]()def train_sts_model(): elbo_loss_curve = tfp.vi.fit_surrogate_posterior( target_log_prob_fn=loadings_model.joint_log_prob( observed_time_series=training_data), surrogate_posterior=variational_posteriors, ptimizer=tf.optimizers.Adam(learning_rate=.1), num_steps=200) return elbo_loss_curve# Plot KL divergenceelbo = train_sts_model()()plt.plot(elbo_loss_curve)plt.show()
The astute among us might have noticed the decorator, @tf.function(). This accepts a function, in this instance our STS model, as an argument and compiles it into a callable TensorFlow graph. An interesting introduction on how TensorFlow works and handles operations through the use of graphs can be found here.
Now for the fun part. After checking the loss function converges, we can perform a forecast. We draw traces (samples) from the variational posterior and construct a forecast by passing these as an argument to tfp.sts.forecast(). Given our model, the observed time series and our sampled parameters, forecast() returns the predictive distribution over the future observations for the desired number of forecast steps:
# Draw traces from posteriortraces__ = variational_posteriors.sample(50)# No timesteps to forecastn_forecast_steps = len(test)# Build forecast distribution over future timestepsforecast_distribution = tfp.sts.forecast( loadings_model, observed_time_series=train, parameter_samples=traces__ num_steps_forecast=n_forecast_steps)# Draw fcast samplesnum_samples=50# Assign vars corresponding to variational posteriorfcst_mu, fcast_scale, fcast_samples=( forecast_distribution.mean().numpy()[..., 0], forecast_distribution.stddev().numpy()[..., 0], forecast_distribution.sample(num_samples).numpy()[..., 0])
We can then visualise our forecast:
Upon first glance, we can observe that the model (with the exception of the 2019 force majeure) has performed quite reasonably in forecasting our mine outputs. We can validate the accuracy of our forecast against the observed data points by calculating the Mean Absolute Error. From a business perspective, however, given the scale of the label i.e. in millions of tonnes it makes more sense to calculate and present the Mean Average Percentage Error (MAPE), as this is more interpretable and meaningful to non-data science individuals:
# Remember to check for div by zero errors firstprint(np.mean(np.abs((test- fcast_mu) / test)) * 100)>>> 13.92
At 13.92% MAPE It is clear that our iron ore output model has done a reasonable job of modelling the data generating distribution, particularly when we have not fully tuned the parameters of the model.
We can further understand our model’s fit and verify the contribution of our individual structural components by decomposing it into their respective time series (again). We usetfp.sts.decompose_by_component to perform this operation which returns acollections.OrderedDict of the individual components posterior distributions, mapped back to its respective observation model:
# Dist. over individual component outputs from posterior (train)component_dists = tfp.sts.decompose_by_component( loadings_model, observed_time_series=train, parameter_samples=traces__)# Same for fcast.forecast_component_dists = tfp.sts.decompose_forecast_by_component( loadings_model, forecast_dist=loadings_model_distribution, parameter_samples=traces__)
After a bit of manipulation, we can plot the output of the decomposed time series to yield the following chart:
Examination of our decomposed model raises some points for further analysis:
The mean and std deviation of our forecast posterior distributions provide us with marginal uncertainty at each time step. With this in mind, we can observe that our model is confident of our trend component’s contribution to the time series, exhibiting a stable profile up until 2018 where model uncertainty compounds. To counter this, we could improve the accuracy of our trend component by modelling it as a SemiLocalLinearTrend model, which allows the slope component to evolve as an AutoRegressive process.Our model is confident of the weekly and monthly seasonal component contributions, exhibiting a consistent output at each time step, suggesting our configuration is correct. Whilst consistent, the uncertainty for our monthly component is significantly higher. We could potentially improve these components with the addition of informed priors i.e. initial_state_prior etc.Interestingly, our AutoRegressive component contributes very little. Our model is also reasonably confident about this, suggesting that the residuals are not explained by an AR process. We could explore adding external features such as local weather/precipitation patterns and iron ore spot prices as linear covariates using sts.LinearRegression.We might achieve a more accurate posterior by fitting the model to the data utilising a Markov chain Monte Carlo (MCMC) method i.e. tfp.sts.fit_with_hmc() as opposed to using VI.
The mean and std deviation of our forecast posterior distributions provide us with marginal uncertainty at each time step. With this in mind, we can observe that our model is confident of our trend component’s contribution to the time series, exhibiting a stable profile up until 2018 where model uncertainty compounds. To counter this, we could improve the accuracy of our trend component by modelling it as a SemiLocalLinearTrend model, which allows the slope component to evolve as an AutoRegressive process.
Our model is confident of the weekly and monthly seasonal component contributions, exhibiting a consistent output at each time step, suggesting our configuration is correct. Whilst consistent, the uncertainty for our monthly component is significantly higher. We could potentially improve these components with the addition of informed priors i.e. initial_state_prior etc.
Interestingly, our AutoRegressive component contributes very little. Our model is also reasonably confident about this, suggesting that the residuals are not explained by an AR process. We could explore adding external features such as local weather/precipitation patterns and iron ore spot prices as linear covariates using sts.LinearRegression.
We might achieve a more accurate posterior by fitting the model to the data utilising a Markov chain Monte Carlo (MCMC) method i.e. tfp.sts.fit_with_hmc() as opposed to using VI.
In this article, we have seen how we can develop a Bayesian Structural Time Series model using TensorFlow Probability’s Structural Time Series library. Additionally, we explored:
How define and configure structural time series model components.
How train an STS model to build a posterior predictive probability distribution.
How to sample the posterior distribution in order to preform a time series forecast.
How to decompose a structural time series models to examine the individual contributions of it’s respective components.
A brief look into some alternative ways of improving our STS model with some of the other awesome models offered by TensorFlow Probability STS.
Thank you for reading!
TensorFlow Blog, Structural Time Series Modelling in TensorFlow (2019): https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html
SPGlobal Platts, IODEX Iron Ore Metal Price Assessment (2020): https://www.spglobal.com/platts/en/our-methodology/price-assessments/metals/iodex-iron-ore-metals-price-assessment
IG.com, Top 10 Most Traded Commodities (2018), https://www.ig.com/en/trading-opportunities/top-10-most-traded-commodities-180905
Financial Times, Iron ore at five-year high above $100 a tonne after Vale warning(2019): https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201
Argus Media, Iron ore alumina penalties soar on supply crunch(2019): https://www.argusmedia.com/en/news/1893132-iron-ore-alumina-penalties-soar-on-supply-crunch
Roger D. Peng, A very short course on time series analysis:(2020): https://bookdown.org/rdpeng/timeseriesbook/the-structure-of-temporal-data.html
Wikipedia, Autocorrelation: https://en.wikipedia.org/wiki/Autocorrelation
Wikipedia, Hamiltonian Monte Carlo: https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo
Wikipedia, Variational Bayesian Methods: https://en.wikipedia.org/wiki/Variational_Bayesian_methods | [
{
"code": null,
"e": 439,
"s": 172,
"text": "Iron ore is one of the most heavily traded commodities in the world. As the primary input for the production of steel, it provides the foundation upon which the world’s largest metal market trades, and commands one of the largest shares of the global dry bulk trade."
},
{
"code": null,
"e": 1108,
"s": 439,
"text": "Iron ore production, unsurprisingly, starts at the mine. As a trader either physical or financial, an understanding of the fundamental supply-demand nature of the iron ore market is essential. Iron ore grade (quality) variance has a notable impact on not only the spot and forward contracts pricing, but also on mill penalty charges for impurities. Imbalances in the fundamental supply/demand relationship can cause dramatic rises in the price of iron ore. Forecasting iron ore output from the largest iron ore exporting countries in order to predict global iron ore supply can be very helpful when speculating on spot, futures and contaminant penalty price movements."
},
{
"code": null,
"e": 1305,
"s": 1108,
"text": "In this article, we are going to develop a forecast model using TensorFlow Probability’s Structural Time-Series (STS) framework, to forecast the aggregate output of major iron ore mines in Brazil."
},
{
"code": null,
"e": 1950,
"s": 1305,
"text": "Brazil is the second largest exporter of iron ore globally. Major changes in supply from Brazil can have an affect on the price of iron ore, as noted above. Furthermore, Brazilian iron ore is typically very high-grade and low in impurities. As a result, the relative supply of ore from Brazil can have an affect on the penalty pricing of impurities charged by steel mills. If global supply is dominated by high-contaminant iron ore as a result of a shortage in supply from Brazilian mines, the price penalty of contaminants can rise dramatically. Forecasting the output from Brazil therefore can lend itself to understanding the above dynamics."
},
{
"code": null,
"e": 2134,
"s": 1950,
"text": "The code used in this article follows similar logic to that outlined in the Structural Time Series modeling in TensorFlow Probability tutorial (Copyright 2019 The TensorFlow Authors)."
},
{
"code": null,
"e": 2464,
"s": 2134,
"text": "When approaching a time series forecast problem, investing time into understanding the complexity of the variable you wish to forecast is paramount. Stationarity, seasonality, distributions and exogenous feature relationships are but a handful of the many considerations to bear in mind before designing any model’s architecture."
},
{
"code": null,
"e": 2646,
"s": 2464,
"text": "Structural time series models (sometimes referred to as Bayesian Structural Time Series) are expressed as a sum of components such as trend, seasonal patterns, cycles and residuals:"
},
{
"code": null,
"e": 3028,
"s": 2646,
"text": "These individual components are themselves time series defined by a structural assumption. The ability to configure each component in the time series makes TFP’s STS library particularly relevant in the context of our time series forecasting problem, as it enables us to encode domain-specific knowledge, such as trader and mine operator expertise, and known events into our model."
},
{
"code": null,
"e": 3599,
"s": 3028,
"text": "Mines production outputs typically exhibit systematic behaviour that can be modelled as a structural time series. In the context of our problem, we know that many mines close down for a two-week period in December for scheduled maintenance. This repeatable pattern can be added as a seasonal component to a structural time series model. We also know that Iron ore and other open cast mines exhibit distinct seasonal patterns that correlate strongly with precipitation which, during periods of heavy rainfall, lead to reduced outputs as drainage pumps become overwhelmed."
},
{
"code": null,
"e": 3938,
"s": 3599,
"text": "What is particularly useful about structural time series models in the context of our problem is that they employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast, but also a means of quantifying model uncertainty."
},
{
"code": null,
"e": 4278,
"s": 3938,
"text": "Another exciting and highly useful feature of STS models is that the resulting model can be decomposed as a collection of it separate components. These components can then be plotted, giving us a valuable insight into their respective affects on the dependent variable (Y-hat), and a deeper understanding of the global time series problem:"
},
{
"code": null,
"e": 4510,
"s": 4278,
"text": "Before we start, it is worth noting that TensorFlow probability has a specific set of dependencies. Moreover TensorFlow is not included as a dependency of the TensorFlow Probability library and will need to be installed separately:"
},
{
"code": null,
"e": 4521,
"s": 4510,
"text": "github.com"
},
{
"code": null,
"e": 4566,
"s": 4521,
"text": "pip install --upgrade tensorflow-probability"
},
{
"code": null,
"e": 4745,
"s": 4566,
"text": "Alternatively, you can use Google’s Colaboratory (Colab), who kindly provide hosted runtimes in Colab completely free of charge (CPU, GPU and even TPU!) subject to memory limits."
},
{
"code": null,
"e": 4764,
"s": 4745,
"text": "Let’s get started."
},
{
"code": null,
"e": 4964,
"s": 4764,
"text": "We start by examining our mine loadings (output) data whose observations are the total weekly output of each mine in millions of metric tonnes, aggregated over all major Brazilian iron ore producers:"
},
{
"code": null,
"e": 5417,
"s": 4964,
"text": "# Importsimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport seaborn as snsimport tensorflow_probability as tfpimport tensorflow as tffrom statsmodels.tsa.seasonal import seasonal_decomposedf = pd.read_excel( '/content/bloomberg_weekly_io_output_brazil.xlsx', header = 1, index_col = 0, parse_dates = True)# Loadingsdf.plot(figsize=(16, 8))plt.title(‘Weekly Iron Ore Output, Metric Tonnes’)plt.ylabel(‘Loadings, Mt’)"
},
{
"code": null,
"e": 5607,
"s": 5417,
"text": "If we examine the observed output time series carefully, we can vaguely see some of the structural components mentioned earlier in the article that we can attempt to encode in an STS model:"
},
{
"code": null,
"e": 5766,
"s": 5607,
"text": "A clear seasonal pattern. Judging by the amplitude and frequency of each cycle, it is reasonable to suggest that this is additive seasonality (defined below)."
},
{
"code": null,
"e": 5826,
"s": 5766,
"text": "With the exception of late 2018/early 2019, a linear trend."
},
{
"code": null,
"e": 5935,
"s": 5826,
"text": "Around the Christmas period, a distinct drop in output when mines typically close for scheduled maintenance."
},
{
"code": null,
"e": 6021,
"s": 5935,
"text": "A degree of noise, possibly correlated with weather, strikes, equipment failures etc."
},
{
"code": null,
"e": 6419,
"s": 6021,
"text": "We can verify some of the aforementioned components in the time series by attempting to decompose the time series into its constituent parts. We will use statsmodels time series analysis library to perform the decomposition and choose an ‘additive’ model as the seasonal component on the basis of the observed behaviour in our time series plot. For reference, additive seasonality is estimated as:"
},
{
"code": null,
"e": 6552,
"s": 6419,
"text": "Passing the ‘iron_ore_brazil’ Pandas Series to the seasonal_decompose method we imported from statsmodels yields the following plot:"
},
{
"code": null,
"e": 6628,
"s": 6552,
"text": "tsa = seasonal_decompose( df[‘iron_ore_brazil’],model=’additive’).plot()"
},
{
"code": null,
"e": 6858,
"s": 6628,
"text": "Upon inspection, we can immediately identify the (mostly) linear trend and the seasonal component. If we look closely at the frequency and amplitude, you can see when the mine output diminishes each year during the winter period."
},
{
"code": null,
"e": 7221,
"s": 6858,
"text": "It is immediately apparent upon inspection of the residuals, that there are other relationships within this time series that cannot be explained by the seasonal and trend elements alone. The variance in the residuals, however, remains fairly constant and within a defined bound. This is useful information to bear in mind when defining our structural components."
},
{
"code": null,
"e": 7353,
"s": 7221,
"text": "“Aha!” I hear you cry at this point. “Why decompose the time series if that is the point of the STS model?”. Well, for two reasons:"
},
{
"code": null,
"e": 7729,
"s": 7353,
"text": "It helps as a starting point in identifying and understanding the various fundamental components in a time series: trend, seasonality, cycles and unexplained variance which in turn, can inform us how we can configure the input parameters to the STS model priors.TFP’s STS models are trained on data through Variational Inference (VI) or Hamiltonian Monte Carlo (HMC) methods:"
},
{
"code": null,
"e": 7992,
"s": 7729,
"text": "It helps as a starting point in identifying and understanding the various fundamental components in a time series: trend, seasonality, cycles and unexplained variance which in turn, can inform us how we can configure the input parameters to the STS model priors."
},
{
"code": null,
"e": 8106,
"s": 7992,
"text": "TFP’s STS models are trained on data through Variational Inference (VI) or Hamiltonian Monte Carlo (HMC) methods:"
},
{
"code": null,
"e": 8559,
"s": 8106,
"text": "# Fit model to observed data with HMCtfp.sts.fit_with_hmc( model, observed_time_series, num_results=100, num_warmup_steps=50, num_leapfrog_steps=15, initial_state=None, initial_step_size=None, chain_batch_shape=(), num_variational_steps=150, variational_optimizer=None, variational_sample_size=5, seed=None, name=None)# Or, fit model to data with VItfp.sts.build_factored_surrogate_posterior( model, batch_shape=(), seed=None, name=None)"
},
{
"code": null,
"e": 8890,
"s": 8559,
"text": "Both of these methods are, generally-speaking, quite computationally intensive (particularly in the case of HMC) on high-dimensional problems and are quite sensitive to tuning. Having an informed choice of input parameters when configuring STS components can help save time, resources and increase posterior distribution accuracy."
},
{
"code": null,
"e": 9023,
"s": 8890,
"text": "Explaining the mathematics behind HMC and VI is beyond the scope of this article, but you can find out more on HMC here and VI here."
},
{
"code": null,
"e": 9198,
"s": 9023,
"text": "We can now define the various components to our STS model and configure them based on what we know about the data generating process. Let’s start with the seasonal component:"
},
{
"code": null,
"e": 9276,
"s": 9198,
"text": "We define the seasonal inputs to our structural time series model as follows:"
},
{
"code": null,
"e": 9996,
"s": 9276,
"text": "# Create train dataset_train = df[‘iron_ore_brazil’][df.index < ‘2018–01–01’]_dates = train.index# Test datatest = df[‘iron_ore_brazil’][df.index >= ‘2018–01–01’]# TensorFlow requires an an (N, 1) float tensortrain = _train.to_numpy().reshape(-1, 1))# Seasonal effect 1: weekly cycle as identified in decomp.weekly_cycle = tfp.sts.Seasonal( num_seasons=52, # 52 weeks in year observed_time_series=train, allow_drift=True, name=’weekly_effect’)# Seasonal effect 2: month of year to capture winter drop in output.monthly_affect = tfp.sts.Seasonal( num_seasons=12, # 12 months in year num_steps_per_season=4, # assumed 4 weeks in every month observed_time_series=train, name=’month_of_year_effect’)"
},
{
"code": null,
"e": 10499,
"s": 9996,
"text": "A valuable feature offered by the tfp.sts.Seasonal model is the ability to add ‘drift’ to the seasonal affect. This parameter allows the effect of each season to evolve or ‘drift’ from one occurrence to the next following a Gaussian random walk(specifically, samples drawn from a normal distribution defined by a mean and variance plus some drift term). If we were confident of the mean and variance of the prior distribution of the seasonal component, we could configure it ourselves within the model:"
},
{
"code": null,
"e": 10812,
"s": 10499,
"text": "monthly_effect = tfp.sts.Seasonal( num_seasons=12, # 12 months in year num_steps_per_season=4, # assumed 4 weeks in month observed_time_series=train, drift_scale_prior=tfd.Normal(loc=1., scale=0.1), # define priors initial_effect_prior=tfd.Normal(loc=0., scale=5.), name=’month_of_year_effect’)"
},
{
"code": null,
"e": 10906,
"s": 10812,
"text": "For now, by setting the parameter ‘allow_drift=True’ we can let the model handle this for us."
},
{
"code": null,
"e": 11092,
"s": 10906,
"text": "A visual inspection of our iron ore mine outputs shows (with the exception of late 2018/early 2019) a consistent linear trend. We can model this behaviour with a LocalLinearTrend model."
},
{
"code": null,
"e": 11277,
"s": 11092,
"text": "The local linear trend model represents a time series trend as a combination of some magnitude (level) and slope. Each of these elements evolve through time via a Gaussian random-walk:"
},
{
"code": null,
"e": 11386,
"s": 11277,
"text": "level[t] = level[t-1] + slope[t-1] + Normal(0., level_scale)slope[t] = slope[t-1] + Normal(0., slope_scale) "
},
{
"code": null,
"e": 11478,
"s": 11386,
"text": "Implementation of the local linear trend component in our problem is quite straightforward:"
},
{
"code": null,
"e": 11571,
"s": 11478,
"text": "# Add trendtrend = tfp.sts.LocalLinearTrend( observed_time_series=train, name='trend')"
},
{
"code": null,
"e": 12080,
"s": 11571,
"text": "An important consideration to bear in mind when choosing how to model the trend component is the choice of model, which is dependent upon the nature of the problem. In the case of our time series problem, the observed trend is relatively stable over time and evolves gradually i.e. it does not display any strong nonlinear behaviour. Our choice of model to represent this trend, therefore, is a reasonable one, however this model can produce forecasts with very high uncertainty over longer forecast periods."
},
{
"code": null,
"e": 12105,
"s": 12080,
"text": "What is the alternative?"
},
{
"code": null,
"e": 12679,
"s": 12105,
"text": "It is well known that most time series have inherent temporal structure where succeeding observations are dependent on the previous n observations in time i.e. autocorrelation. A wise choice therefore, might be to model the trend using TFP STS’s SemiLocalLinearTrend model. In a semi-local linear trend model, the slopecomponent evolves according to a first-order autoregressive process. The AR process can therefore account for the autocorrelative (of order n) effect in the time series, and typically lead to forecasts with greater certainty over a longer period of time."
},
{
"code": null,
"e": 13049,
"s": 12679,
"text": "As previously mentioned during our inspection of the seasonal decomposition plot, the residuals in our time series look relatively consistent suggesting that they are potentially stationary, i.e. they maintain a constant variance over time, do not exhibit bias or heteroskedasticity etc. We can therefore represent the residual behaviour in an sts.AutoRegressive model:"
},
{
"code": null,
"e": 13259,
"s": 13049,
"text": "# Residualsresiduals = tfp.sts.Autoregressive( order=1, observed_time_series=train, coefficients_prior=None, level_scale_prior=None, initial_state_prior=None, name='residuals_autoregressive')"
},
{
"code": null,
"e": 13658,
"s": 13259,
"text": "As with the other components, for a fully Bayesian approach one should specify the priors coefficients_prior, level_scale_prior and initial_state_prior. As we have not specified priors, a TensorFlow Distributions (tfd) MultivariateNormalDiag instance is used as a default prior for the coefficients, and a heuristic prior constructed for the level and initial states based on the input time series."
},
{
"code": null,
"e": 13881,
"s": 13658,
"text": "We can now define our structural time series model using the tfp.sts.Sum class. This class enables us to define the compositional specification of our structural time series model from the components we have defined above:"
},
{
"code": null,
"e": 14027,
"s": 13881,
"text": "model = tfp.sts.Sum( components=[ trend, weekly_cycle, monthly_effect, residuals], observed_time_series=train) "
},
{
"code": null,
"e": 14481,
"s": 14027,
"text": "We will now fit our model to the observed time series, namely our iron ore output. Unlike traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation, an STS model learns a distribution, namely, the posterior."
},
{
"code": null,
"e": 14834,
"s": 14481,
"text": "We are going to fit the model to the data and build a posterior predictive distribution using Variational Inference. Simply put, VI fits a set of approximate posterior distributions for the model parameters we have defined (for each component) and optimises these by minimising a variational loss function known as negative Evidence Lower Bound (ELBO):"
},
{
"code": null,
"e": 15399,
"s": 14834,
"text": "# VI posterior variational_posteriors = tfp.sts.build_factored_surrogate_posterior( model=loadings_model)# Build and optimize the variational loss function (ELBO)[email protected]()def train_sts_model(): elbo_loss_curve = tfp.vi.fit_surrogate_posterior( target_log_prob_fn=loadings_model.joint_log_prob( observed_time_series=training_data), surrogate_posterior=variational_posteriors, ptimizer=tf.optimizers.Adam(learning_rate=.1), num_steps=200) return elbo_loss_curve# Plot KL divergenceelbo = train_sts_model()()plt.plot(elbo_loss_curve)plt.show()"
},
{
"code": null,
"e": 15711,
"s": 15399,
"text": "The astute among us might have noticed the decorator, @tf.function(). This accepts a function, in this instance our STS model, as an argument and compiles it into a callable TensorFlow graph. An interesting introduction on how TensorFlow works and handles operations through the use of graphs can be found here."
},
{
"code": null,
"e": 16128,
"s": 15711,
"text": "Now for the fun part. After checking the loss function converges, we can perform a forecast. We draw traces (samples) from the variational posterior and construct a forecast by passing these as an argument to tfp.sts.forecast(). Given our model, the observed time series and our sampled parameters, forecast() returns the predictive distribution over the future observations for the desired number of forecast steps:"
},
{
"code": null,
"e": 16752,
"s": 16128,
"text": "# Draw traces from posteriortraces__ = variational_posteriors.sample(50)# No timesteps to forecastn_forecast_steps = len(test)# Build forecast distribution over future timestepsforecast_distribution = tfp.sts.forecast( loadings_model, observed_time_series=train, parameter_samples=traces__ num_steps_forecast=n_forecast_steps)# Draw fcast samplesnum_samples=50# Assign vars corresponding to variational posteriorfcst_mu, fcast_scale, fcast_samples=( forecast_distribution.mean().numpy()[..., 0], forecast_distribution.stddev().numpy()[..., 0], forecast_distribution.sample(num_samples).numpy()[..., 0])"
},
{
"code": null,
"e": 16788,
"s": 16752,
"text": "We can then visualise our forecast:"
},
{
"code": null,
"e": 17325,
"s": 16788,
"text": "Upon first glance, we can observe that the model (with the exception of the 2019 force majeure) has performed quite reasonably in forecasting our mine outputs. We can validate the accuracy of our forecast against the observed data points by calculating the Mean Absolute Error. From a business perspective, however, given the scale of the label i.e. in millions of tonnes it makes more sense to calculate and present the Mean Average Percentage Error (MAPE), as this is more interpretable and meaningful to non-data science individuals:"
},
{
"code": null,
"e": 17436,
"s": 17325,
"text": "# Remember to check for div by zero errors firstprint(np.mean(np.abs((test- fcast_mu) / test)) * 100)>>> 13.92"
},
{
"code": null,
"e": 17638,
"s": 17436,
"text": "At 13.92% MAPE It is clear that our iron ore output model has done a reasonable job of modelling the data generating distribution, particularly when we have not fully tuned the parameters of the model."
},
{
"code": null,
"e": 18014,
"s": 17638,
"text": "We can further understand our model’s fit and verify the contribution of our individual structural components by decomposing it into their respective time series (again). We usetfp.sts.decompose_by_component to perform this operation which returns acollections.OrderedDict of the individual components posterior distributions, mapped back to its respective observation model:"
},
{
"code": null,
"e": 18389,
"s": 18014,
"text": "# Dist. over individual component outputs from posterior (train)component_dists = tfp.sts.decompose_by_component( loadings_model, observed_time_series=train, parameter_samples=traces__)# Same for fcast.forecast_component_dists = tfp.sts.decompose_forecast_by_component( loadings_model, forecast_dist=loadings_model_distribution, parameter_samples=traces__)"
},
{
"code": null,
"e": 18501,
"s": 18389,
"text": "After a bit of manipulation, we can plot the output of the decomposed time series to yield the following chart:"
},
{
"code": null,
"e": 18578,
"s": 18501,
"text": "Examination of our decomposed model raises some points for further analysis:"
},
{
"code": null,
"e": 19986,
"s": 18578,
"text": "The mean and std deviation of our forecast posterior distributions provide us with marginal uncertainty at each time step. With this in mind, we can observe that our model is confident of our trend component’s contribution to the time series, exhibiting a stable profile up until 2018 where model uncertainty compounds. To counter this, we could improve the accuracy of our trend component by modelling it as a SemiLocalLinearTrend model, which allows the slope component to evolve as an AutoRegressive process.Our model is confident of the weekly and monthly seasonal component contributions, exhibiting a consistent output at each time step, suggesting our configuration is correct. Whilst consistent, the uncertainty for our monthly component is significantly higher. We could potentially improve these components with the addition of informed priors i.e. initial_state_prior etc.Interestingly, our AutoRegressive component contributes very little. Our model is also reasonably confident about this, suggesting that the residuals are not explained by an AR process. We could explore adding external features such as local weather/precipitation patterns and iron ore spot prices as linear covariates using sts.LinearRegression.We might achieve a more accurate posterior by fitting the model to the data utilising a Markov chain Monte Carlo (MCMC) method i.e. tfp.sts.fit_with_hmc() as opposed to using VI."
},
{
"code": null,
"e": 20498,
"s": 19986,
"text": "The mean and std deviation of our forecast posterior distributions provide us with marginal uncertainty at each time step. With this in mind, we can observe that our model is confident of our trend component’s contribution to the time series, exhibiting a stable profile up until 2018 where model uncertainty compounds. To counter this, we could improve the accuracy of our trend component by modelling it as a SemiLocalLinearTrend model, which allows the slope component to evolve as an AutoRegressive process."
},
{
"code": null,
"e": 20871,
"s": 20498,
"text": "Our model is confident of the weekly and monthly seasonal component contributions, exhibiting a consistent output at each time step, suggesting our configuration is correct. Whilst consistent, the uncertainty for our monthly component is significantly higher. We could potentially improve these components with the addition of informed priors i.e. initial_state_prior etc."
},
{
"code": null,
"e": 21218,
"s": 20871,
"text": "Interestingly, our AutoRegressive component contributes very little. Our model is also reasonably confident about this, suggesting that the residuals are not explained by an AR process. We could explore adding external features such as local weather/precipitation patterns and iron ore spot prices as linear covariates using sts.LinearRegression."
},
{
"code": null,
"e": 21397,
"s": 21218,
"text": "We might achieve a more accurate posterior by fitting the model to the data utilising a Markov chain Monte Carlo (MCMC) method i.e. tfp.sts.fit_with_hmc() as opposed to using VI."
},
{
"code": null,
"e": 21576,
"s": 21397,
"text": "In this article, we have seen how we can develop a Bayesian Structural Time Series model using TensorFlow Probability’s Structural Time Series library. Additionally, we explored:"
},
{
"code": null,
"e": 21642,
"s": 21576,
"text": "How define and configure structural time series model components."
},
{
"code": null,
"e": 21723,
"s": 21642,
"text": "How train an STS model to build a posterior predictive probability distribution."
},
{
"code": null,
"e": 21808,
"s": 21723,
"text": "How to sample the posterior distribution in order to preform a time series forecast."
},
{
"code": null,
"e": 21928,
"s": 21808,
"text": "How to decompose a structural time series models to examine the individual contributions of it’s respective components."
},
{
"code": null,
"e": 22072,
"s": 21928,
"text": "A brief look into some alternative ways of improving our STS model with some of the other awesome models offered by TensorFlow Probability STS."
},
{
"code": null,
"e": 22095,
"s": 22072,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 22243,
"s": 22095,
"text": "TensorFlow Blog, Structural Time Series Modelling in TensorFlow (2019): https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html"
},
{
"code": null,
"e": 22421,
"s": 22243,
"text": "SPGlobal Platts, IODEX Iron Ore Metal Price Assessment (2020): https://www.spglobal.com/platts/en/our-methodology/price-assessments/metals/iodex-iron-ore-metals-price-assessment"
},
{
"code": null,
"e": 22550,
"s": 22421,
"text": "IG.com, Top 10 Most Traded Commodities (2018), https://www.ig.com/en/trading-opportunities/top-10-most-traded-commodities-180905"
},
{
"code": null,
"e": 22703,
"s": 22550,
"text": "Financial Times, Iron ore at five-year high above $100 a tonne after Vale warning(2019): https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201"
},
{
"code": null,
"e": 22864,
"s": 22703,
"text": "Argus Media, Iron ore alumina penalties soar on supply crunch(2019): https://www.argusmedia.com/en/news/1893132-iron-ore-alumina-penalties-soar-on-supply-crunch"
},
{
"code": null,
"e": 23010,
"s": 22864,
"text": "Roger D. Peng, A very short course on time series analysis:(2020): https://bookdown.org/rdpeng/timeseriesbook/the-structure-of-temporal-data.html"
},
{
"code": null,
"e": 23084,
"s": 23010,
"text": "Wikipedia, Autocorrelation: https://en.wikipedia.org/wiki/Autocorrelation"
},
{
"code": null,
"e": 23174,
"s": 23084,
"text": "Wikipedia, Hamiltonian Monte Carlo: https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo"
}
] |
Differences between static and non-static methods in Java | A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
A static method is also called a class method and is common across the objects of the class and this method can be accessed using class name as well.
Any method of a class which is not static is called non-static method or an instance method.
Following are the important differences between static and non-static method.
JavaTester.java
public class JavaTester {
public static void main(String args[]) {
Tiger.roar();
Tiger tiger = new Tiger();
tiger.eat();
}
}
class Tiger {
public void eat(){
System.out.println("Tiger eats");
}
public static void roar(){
System.out.println("Tiger roars");
}
}
Output
Tiger roars
Tiger eats | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console."
},
{
"code": null,
"e": 1461,
"s": 1311,
"text": "A static method is also called a class method and is common across the objects of the class and this method can be accessed using class name as well."
},
{
"code": null,
"e": 1554,
"s": 1461,
"text": "Any method of a class which is not static is called non-static method or an instance method."
},
{
"code": null,
"e": 1632,
"s": 1554,
"text": "Following are the important differences between static and non-static method."
},
{
"code": null,
"e": 1648,
"s": 1632,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1956,
"s": 1648,
"text": "public class JavaTester {\n public static void main(String args[]) {\n Tiger.roar();\n Tiger tiger = new Tiger();\n tiger.eat();\n }\n}\nclass Tiger {\n public void eat(){\n System.out.println(\"Tiger eats\");\n }\n public static void roar(){\n System.out.println(\"Tiger roars\");\n }\n}"
},
{
"code": null,
"e": 1963,
"s": 1956,
"text": "Output"
},
{
"code": null,
"e": 1986,
"s": 1963,
"text": "Tiger roars\nTiger eats"
}
] |
C Program for Find sum of odd factors of a number - GeeksforGeeks | 06 Oct, 2021
Given a number n, the task is to find the odd factor sum.Examples:
Input : n = 30
Output : 24
Odd dividers sum 1 + 3 + 5 + 15 = 24
Input : 18
Output : 13
Odd dividers sum 1 + 3 + 9 = 13
Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak).
Sum of divisors = (1 + p1 + p12 ... p1a1) *
(1 + p2 + p22 ... p2a2) *
.............................................
(1 + pk + pk2 ... pkak)
To find sum of odd factors, we simply need to ignore even factors and their powers. For example, consider n = 18. It can be written as 2132 and sun of all factors is (1)*(1 + 2)*(1 + 3 + 32). Sum of odd factors (1)*(1+3+32) = 13.To remove all even factors, we repeatedly divide n while it is divisible by 2. After this step, we only get odd factors. Note that 2 is the only even prime.
C++
Java
Python 3
C#
PHP
Javascript
// Formula based CPP program// to find sum of all// divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofoddFactors(int n){ // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1 int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 30; cout << sumofoddFactors(n); return 0;}
// Formula based Java program// to find sum of all// divisors of n.import java.io.*; class GFG{ // Returns sum of all factors of n. static int sumofoddFactors(int n) { // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= Math. sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code public static void main (String[] args) { int n = 30; System.out.println ( sumofoddFactors(n)); }} // This code is contributed by vt_m.
# Formula based Python 3 program# to find sum of all divisors of n # Returns sum of all factors of nimport mathdef sumofoddFactors(n): # Traversing through all prime factors res = 1 # ignore even factors by # removing all powers of 2 while (n % 2) == 0 : n = n / 2 i=3 while i <= math.sqrt(n): # While i divides n, print # i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i) == 0: count += 1 n = n / i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to handle # the case when n is a prime number. if (n >= 2): res *= (1 + n) return res # Driver coden = 30print(int(sumofoddFactors(n))) # This code is contributed# by Azkia Anam.
// Formula based Java program// to find sum of all// divisors of n.using System; class GFG{ // Returns sum of all factors of n. static int sumofoddFactors(int n) { // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= Math. Sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code public static void Main () { int n = 30; Console.WriteLine( sumofoddFactors(n)); }} // This code is contributed by vt_m.
<?php// Formula based PHP program to find// sum of all divisors of n. // Returns sum of all factors of n.function sumofoddFactors($n){ // Traversing through all // prime factors. $res = 1; // ignore even factors by removing // all powers of 2 while ($n % 2 == 0) $n = $n / 2; for ($i = 3; $i <= sqrt($n); $i++) { // While i divides n, print // i and divide n $count = 0; $curr_sum = 1 ; $curr_term = 1; while ($n % $i == 0) { $count++; $n = (int) $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle the // case when n is a prime number. if ($n >= 2) $res *= (1 + $n); return $res;} // Driver code$n = 30;echo sumofoddFactors($n); // This code is contributed// by Sach_Code?>
<script>// Formula based javascript program// to find sum of all// divisors of n. // Returns sum of all factors of n. function sumofoddFactors(n) { // Traversing through all // prime factors. var res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (var i = 3; i <= Math.sqrt(n); i++) { // While i divides n, print // i and divide n var count = 0, curr_sum = 1; var curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code var n = 30; document.write(sumofoddFactors(n)); // This code is contributed by gauravrajput1</script>
Output:
24
Time Complexity: O(n1/2)
Auxiliary Space: O(1)Please refer complete article on Find sum of odd factors of a number for more details!
Sach_Code
souravmahato348
GauravRajput1
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
C program to sort an array in ascending order
time() function in C
Flex (Fast Lexical Analyzer Generator )
C Program to Swap two Numbers
Program to find Prime Numbers Between given Interval | [
{
"code": null,
"e": 24279,
"s": 24251,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24347,
"s": 24279,
"text": "Given a number n, the task is to find the odd factor sum.Examples: "
},
{
"code": null,
"e": 24468,
"s": 24347,
"text": "Input : n = 30\nOutput : 24\nOdd dividers sum 1 + 3 + 5 + 15 = 24 \n\nInput : 18\nOutput : 13\nOdd dividers sum 1 + 3 + 9 = 13"
},
{
"code": null,
"e": 24648,
"s": 24468,
"text": "Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). "
},
{
"code": null,
"e": 24844,
"s": 24648,
"text": "Sum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n .............................................\n (1 + pk + pk2 ... pkak) "
},
{
"code": null,
"e": 25232,
"s": 24844,
"text": "To find sum of odd factors, we simply need to ignore even factors and their powers. For example, consider n = 18. It can be written as 2132 and sun of all factors is (1)*(1 + 2)*(1 + 3 + 32). Sum of odd factors (1)*(1+3+32) = 13.To remove all even factors, we repeatedly divide n while it is divisible by 2. After this step, we only get odd factors. Note that 2 is the only even prime. "
},
{
"code": null,
"e": 25236,
"s": 25232,
"text": "C++"
},
{
"code": null,
"e": 25241,
"s": 25236,
"text": "Java"
},
{
"code": null,
"e": 25250,
"s": 25241,
"text": "Python 3"
},
{
"code": null,
"e": 25253,
"s": 25250,
"text": "C#"
},
{
"code": null,
"e": 25257,
"s": 25253,
"text": "PHP"
},
{
"code": null,
"e": 25268,
"s": 25257,
"text": "Javascript"
},
{
"code": "// Formula based CPP program// to find sum of all// divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofoddFactors(int n){ // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1 int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 30; cout << sumofoddFactors(n); return 0;}",
"e": 26176,
"s": 25268,
"text": null
},
{
"code": "// Formula based Java program// to find sum of all// divisors of n.import java.io.*; class GFG{ // Returns sum of all factors of n. static int sumofoddFactors(int n) { // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= Math. sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code public static void main (String[] args) { int n = 30; System.out.println ( sumofoddFactors(n)); }} // This code is contributed by vt_m.",
"e": 27346,
"s": 26176,
"text": null
},
{
"code": "# Formula based Python 3 program# to find sum of all divisors of n # Returns sum of all factors of nimport mathdef sumofoddFactors(n): # Traversing through all prime factors res = 1 # ignore even factors by # removing all powers of 2 while (n % 2) == 0 : n = n / 2 i=3 while i <= math.sqrt(n): # While i divides n, print # i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i) == 0: count += 1 n = n / i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to handle # the case when n is a prime number. if (n >= 2): res *= (1 + n) return res # Driver coden = 30print(int(sumofoddFactors(n))) # This code is contributed# by Azkia Anam.",
"e": 28174,
"s": 27346,
"text": null
},
{
"code": "// Formula based Java program// to find sum of all// divisors of n.using System; class GFG{ // Returns sum of all factors of n. static int sumofoddFactors(int n) { // Traversing through all // prime factors. int res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (int i = 3; i <= Math. Sqrt(n); i++) { // While i divides n, print // i and divide n int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code public static void Main () { int n = 30; Console.WriteLine( sumofoddFactors(n)); }} // This code is contributed by vt_m.",
"e": 29328,
"s": 28174,
"text": null
},
{
"code": "<?php// Formula based PHP program to find// sum of all divisors of n. // Returns sum of all factors of n.function sumofoddFactors($n){ // Traversing through all // prime factors. $res = 1; // ignore even factors by removing // all powers of 2 while ($n % 2 == 0) $n = $n / 2; for ($i = 3; $i <= sqrt($n); $i++) { // While i divides n, print // i and divide n $count = 0; $curr_sum = 1 ; $curr_term = 1; while ($n % $i == 0) { $count++; $n = (int) $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle the // case when n is a prime number. if ($n >= 2) $res *= (1 + $n); return $res;} // Driver code$n = 30;echo sumofoddFactors($n); // This code is contributed// by Sach_Code?>",
"e": 30225,
"s": 29328,
"text": null
},
{
"code": "<script>// Formula based javascript program// to find sum of all// divisors of n. // Returns sum of all factors of n. function sumofoddFactors(n) { // Traversing through all // prime factors. var res = 1; // ignore even factors by // removing all powers of // 2 while (n % 2 == 0) n = n / 2; for (var i = 3; i <= Math.sqrt(n); i++) { // While i divides n, print // i and divide n var count = 0, curr_sum = 1; var curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number. if (n >= 2) res *= (1 + n); return res; } // Driver code var n = 30; document.write(sumofoddFactors(n)); // This code is contributed by gauravrajput1</script>",
"e": 31291,
"s": 30225,
"text": null
},
{
"code": null,
"e": 31300,
"s": 31291,
"text": "Output: "
},
{
"code": null,
"e": 31303,
"s": 31300,
"text": "24"
},
{
"code": null,
"e": 31328,
"s": 31303,
"text": "Time Complexity: O(n1/2)"
},
{
"code": null,
"e": 31436,
"s": 31328,
"text": "Auxiliary Space: O(1)Please refer complete article on Find sum of odd factors of a number for more details!"
},
{
"code": null,
"e": 31446,
"s": 31436,
"text": "Sach_Code"
},
{
"code": null,
"e": 31462,
"s": 31446,
"text": "souravmahato348"
},
{
"code": null,
"e": 31476,
"s": 31462,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31487,
"s": 31476,
"text": "C Programs"
},
{
"code": null,
"e": 31585,
"s": 31487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31594,
"s": 31585,
"text": "Comments"
},
{
"code": null,
"e": 31607,
"s": 31594,
"text": "Old Comments"
},
{
"code": null,
"e": 31648,
"s": 31607,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 31683,
"s": 31648,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 31742,
"s": 31683,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 31785,
"s": 31742,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 31829,
"s": 31785,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 31875,
"s": 31829,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 31896,
"s": 31875,
"text": "time() function in C"
},
{
"code": null,
"e": 31936,
"s": 31896,
"text": "Flex (Fast Lexical Analyzer Generator )"
},
{
"code": null,
"e": 31966,
"s": 31936,
"text": "C Program to Swap two Numbers"
}
] |
How to use Ejs in JavaScript ? | 30 Sep, 2020
EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template at the client-side and produce the final HTML.
Installation: Install module using the following command:
npm install ejs --save
Note: The npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies.
Now, the first thing we need to do is to set EJS as our templating engine with Express which is a Node.js web application server framework, which is specifically designed for building a single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js.
Data passed from the server is sent to the EJS file and then we can access that data using the below line and it will give that data to h, p, or another text tag.
<%= data %>
If we want to use this data for normal js operations like if-else and loops or other programming statements we can write it in the following form:
<% if(data == "1"){%>
<h5>Cricket</h5>
<%}else{%>
<h5>Football</h5>
<%}%>
Now to access that data in the script tag of EJS file or the .js file all you need to do is to pass that data in another variable as below:
let data = '<%-data%>'
Now you can perform any operation on the data variable which has the same value as EJS passed data variable.
Filename: index.js
// Set express as Node.js web application // server framework. // Install it using 'npm install express' command // and require like this:var express = require('express'); var app = express(); // Set EJS as templating engine app.set('view engine', 'ejs'); app.get("/", function(req, res) { res.render("home", {name:'Chris Martin'});}); // Server setupapp.listen(3000, function(req, res) { console.log("Connected on port:3000");});
The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “home.ejs” which is to be served on some desired request in our node project.
Filename: home.ejs
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <center> <!-- Text from EJS variable passed from server --> <h2> Text from EJS variable passed from server is = </h2> <h2 style="color:red"><%=name%></h2> <br> <!-- Text from EJS variable passed from script tag --> <h2 style="color: blue;"> Text from EJS variable passed from script tag = </h2> <h2 style="color: blue;" id="text_from_script"> </h2> <br> <!-- Text from EJS variable passed from script tag after manipulation --> <h2 style="color: green;"> Text from EJS variable passed from script tag after manipulation = </h2> <h2 style="color: green;" id="text_from_script_manipulated"> </h2> </center> <script> let name = '<%-name%>' let heading = document .getElementById('text_from_script'); heading.innerText = name; name = "Mr. " + name; let heading_man = document.getElementById( 'text_from_script_manipulated'); heading_man.innerText = name; </script></body> </html>
Name variable has been passed from server to name.ejs file and showed using h2 tag, to use the name variable in the script tag all we did is declare a variable and pass the EJS variable to declared variable using:
let name = '<%-name%>'
Steps to run the program:
After creating all the files go to the root directory of your project folder.
Run command prompt in this directory.
Type the following command to run your program and see the output as displayed.node index.js
node index.js
Output:
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to install the previous version of node.js and npm ?
Node.js fs.readFile() Method | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 298,
"s": 53,
"text": "EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template at the client-side and produce the final HTML."
},
{
"code": null,
"e": 356,
"s": 298,
"text": "Installation: Install module using the following command:"
},
{
"code": null,
"e": 388,
"s": 356,
"text": "npm install ejs --save \n"
},
{
"code": null,
"e": 632,
"s": 388,
"text": "Note: The npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies."
},
{
"code": null,
"e": 929,
"s": 632,
"text": "Now, the first thing we need to do is to set EJS as our templating engine with Express which is a Node.js web application server framework, which is specifically designed for building a single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js."
},
{
"code": null,
"e": 1092,
"s": 929,
"text": "Data passed from the server is sent to the EJS file and then we can access that data using the below line and it will give that data to h, p, or another text tag."
},
{
"code": null,
"e": 1105,
"s": 1092,
"text": "<%= data %>\n"
},
{
"code": null,
"e": 1252,
"s": 1105,
"text": "If we want to use this data for normal js operations like if-else and loops or other programming statements we can write it in the following form:"
},
{
"code": null,
"e": 1327,
"s": 1252,
"text": "<% if(data == \"1\"){%>\n<h5>Cricket</h5>\n<%}else{%>\n<h5>Football</h5>\n<%}%>\n"
},
{
"code": null,
"e": 1467,
"s": 1327,
"text": "Now to access that data in the script tag of EJS file or the .js file all you need to do is to pass that data in another variable as below:"
},
{
"code": null,
"e": 1491,
"s": 1467,
"text": "let data = '<%-data%>'\n"
},
{
"code": null,
"e": 1600,
"s": 1491,
"text": "Now you can perform any operation on the data variable which has the same value as EJS passed data variable."
},
{
"code": null,
"e": 1619,
"s": 1600,
"text": "Filename: index.js"
},
{
"code": "// Set express as Node.js web application // server framework. // Install it using 'npm install express' command // and require like this:var express = require('express'); var app = express(); // Set EJS as templating engine app.set('view engine', 'ejs'); app.get(\"/\", function(req, res) { res.render(\"home\", {name:'Chris Martin'});}); // Server setupapp.listen(3000, function(req, res) { console.log(\"Connected on port:3000\");});",
"e": 2065,
"s": 1619,
"text": null
},
{
"code": null,
"e": 2327,
"s": 2065,
"text": "The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “home.ejs” which is to be served on some desired request in our node project."
},
{
"code": null,
"e": 2346,
"s": 2327,
"text": "Filename: home.ejs"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <center> <!-- Text from EJS variable passed from server --> <h2> Text from EJS variable passed from server is = </h2> <h2 style=\"color:red\"><%=name%></h2> <br> <!-- Text from EJS variable passed from script tag --> <h2 style=\"color: blue;\"> Text from EJS variable passed from script tag = </h2> <h2 style=\"color: blue;\" id=\"text_from_script\"> </h2> <br> <!-- Text from EJS variable passed from script tag after manipulation --> <h2 style=\"color: green;\"> Text from EJS variable passed from script tag after manipulation = </h2> <h2 style=\"color: green;\" id=\"text_from_script_manipulated\"> </h2> </center> <script> let name = '<%-name%>' let heading = document .getElementById('text_from_script'); heading.innerText = name; name = \"Mr. \" + name; let heading_man = document.getElementById( 'text_from_script_manipulated'); heading_man.innerText = name; </script></body> </html>",
"e": 3726,
"s": 2346,
"text": null
},
{
"code": null,
"e": 3940,
"s": 3726,
"text": "Name variable has been passed from server to name.ejs file and showed using h2 tag, to use the name variable in the script tag all we did is declare a variable and pass the EJS variable to declared variable using:"
},
{
"code": null,
"e": 3963,
"s": 3940,
"text": "let name = '<%-name%>'"
},
{
"code": null,
"e": 3989,
"s": 3963,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 4067,
"s": 3989,
"text": "After creating all the files go to the root directory of your project folder."
},
{
"code": null,
"e": 4105,
"s": 4067,
"text": "Run command prompt in this directory."
},
{
"code": null,
"e": 4198,
"s": 4105,
"text": "Type the following command to run your program and see the output as displayed.node index.js"
},
{
"code": null,
"e": 4212,
"s": 4198,
"text": "node index.js"
},
{
"code": null,
"e": 4220,
"s": 4212,
"text": "Output:"
},
{
"code": null,
"e": 4235,
"s": 4220,
"text": "\nNode.js-Misc\n"
},
{
"code": null,
"e": 4248,
"s": 4235,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 4258,
"s": 4248,
"text": "\nNode.js\n"
},
{
"code": null,
"e": 4277,
"s": 4258,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 4482,
"s": 4277,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 4543,
"s": 4482,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4585,
"s": 4543,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4657,
"s": 4585,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4697,
"s": 4657,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4738,
"s": 4697,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4786,
"s": 4738,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4819,
"s": 4786,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4852,
"s": 4819,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 4909,
"s": 4852,
"text": "How to install the previous version of node.js and npm ?"
}
] |
Top 40 Python Interview Questions & Answers | 24 Feb, 2022
Python is a general-purpose, high-level programming language. It is the most popular language among developers and programmers as it can be used in Machine Learning, Web Development, Image Processing, etc. Currently a lot of tech companies like Google, Amazon, Facebook, etc. are using Python and hire a lot of people every year. We have prepared a list of Top 40 Python Interview Questions along with their Answers.
1. What is Python? List some popular applications of Python in the world of technology?
Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.It is used for:
System Scripting
Web Development
Game Development
Software Development
Complex Mathematics
2. What are the benefits of using Python language as a tool in the present scenario?
Following are the benefits of using Python language:
Object-Oriented Language
High Level Language
Dynamically Typed language
Extensive support Libraries
Presence of third-party modules
Open source and community development
Portable and Interactive
Portable across Operating systems
3. Which sorting technique is used by sort() and sorted() functions of python?
Python uses Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.
4. Differentiate between List and Tuple?
Let’s analyze the differences between List and Tuple:
List
Lists are Mutable datatype.
Lists consume more memory
The list is better for performing operations, such as insertion and deletion.
Implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consume less memory as compared to the list
Tuple data type is appropriate for accessing the elements
Implication of iterations is comparatively Faster
To read more, refer the article: List vs Tuple
5. How memory management is done in Python?Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.
To read more, refer the article: Memory Management in Python
6. What is PEP 8?
PEP 8 is a Python style guide. It is a document that provides the guidelines and best practices on how to write beautiful Python code. It promotes a very readable and eye-pleasing coding style.
To read more, refer the article: PEP 8 coding style
7. Is Python a compiled language or an interpreted language?
Actually, Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code and internally this byte code gets converted by the python virtual machine(p.v.m) according to the underlying platform(machine+operating system).
To read more, refer the article: Python – Compiled or Interpreted?
8. How to delete a file using Python?
We can delete a file using Python by following approaches:
os.remove()
os.unlink()
9. What are Decorators?
Decorators are a very powerful and useful tool in Python as they are the specific change that we make in Python syntax to alter functions easily.
To read more, refer the article: Decorators in Python
10. What is the difference between Mutable datatype and Immutable datatype?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
11. What is the difference between Set and Dictionary?
Set is an unordered collection of data type that is iterable, mutable, and has no duplicate elements.Dictionary in Python is an unordered collection of data values, used to store data values like a map.
To read more, refer the article: Sets and Dictionary
12. How do you debug a Python program?
By using this command we can debug a python program:
$ python -m pdb python-script.py
13. What is Pickling and Unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
To read more, refer to the article: Pickle module in Python
14. How are arguments passed by value or by reference in Python?Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.
15. What is List Comprehension? Give an Example.
List comprehension is a syntax construction to ease the creation of a list based on existing iterable.
For Example:
my_list = [i for i in range(1, 10)]
16. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable.
For Example: my_dict = {i:1+7 for i in range(1, 10)}
17. Is Tuple Comprehension? If yes, how and if not why?
(i for i in (1, 2, 3))
Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension.
18. What is namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
To read more, refer to the article: Namespace in Python
19. What is a lambda function?
A lambda function is an anonymous function. This function can have any number of parameters but, can have just one statement. For Example:
a = lambda x, y : x*y
print(a(7, 19))
To read more, refer to the article: Lambda functions
20. What is a pass in Python?
Pass means performing no operation or in other words, it is a place holder in the compound statement, where there should be a blank left and nothing has to be written there.
21. What is the difference between xrange and range function?
range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2.
range() – This returns a list of numbers created using range() function.
xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation.
To read more, refer to the article: Range vs Xrange
22. What is difference between / and // in Python?
// represents floor division whereas / represents precised division. For Example:
5//2 = 2
5/2 = 2.5
23. What is zip function?
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
24. What is swapcase function in Python?
It is a string’s function that converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. For Example:
string = "GeeksforGeeks"
string.swapcase() ---> "gEEKSFORgEEKS"
25. What are Iterators in Python?
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).
To read more, refer the article: Iterators in Python
26. What are Generators in Python?
In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.
To read more, refer the article: generators in Python
27. What are the new features added in Python 3.8 version?
Following are the new features in Python 3.8 version:
Positional Only parameter(/)
Assignment Expression(:=)
f-strings now support “=”
reversed() works with a dictionary
To read more, refer the article: Awesome features in Python 3.8
28. What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
# g.py
class GeeksClass:
def function(self):
print "function()"
import m
def monkey_function(self):
print "monkey_function()"
m.GeeksClass.function = monkey_function
obj = m.GeeksClass()
obj.function()
To read more, refer the article: Monkey patching in Python
29. Does Python supports multiple Inheritance?
Python does support multiple inheritance, unlike Java. Multiple inheritance means that a class can be derived from more than one parent classes.
30. What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
To read more, refer the article: Polymorphism in Python
31. Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.
To read more, refer the article: Encapsulation in Python
32. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
To read more, refer the article: Abstraction in Python
33. Which databases are supported by Python?
MySQL (Structured) and MongoDB (Unstructured) are the prominent databases that are supported natively in Python. Import the module and start using the functions to interact with the database.
34. How is Exceptional handling done in Python?
There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code which is monitored for errors. Except block gets executed when an error occurs.
The beauty of the final block is to execute the code after trying for error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables.
35. What does ‘#’ symbol do in Python?
‘#’ is used to comment out everything that comes after on the line.
36. Write a code to display the current time?
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)
37. What is the difference between a shallow copy and deep copy?
Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas deep coy makes it slow.
To read more, refer the article: Shallow copy vs Deep copy
38. What is PIP?
PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction.
To read more, refer the article: PIP in Python
39. What is __init__() in Python?
Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.
40. What is the maximum possible length of an identifier?
Identifiers in Python can be of any length.
interview-preparation
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 471,
"s": 54,
"text": "Python is a general-purpose, high-level programming language. It is the most popular language among developers and programmers as it can be used in Machine Learning, Web Development, Image Processing, etc. Currently a lot of tech companies like Google, Amazon, Facebook, etc. are using Python and hire a lot of people every year. We have prepared a list of Top 40 Python Interview Questions along with their Answers."
},
{
"code": null,
"e": 559,
"s": 471,
"text": "1. What is Python? List some popular applications of Python in the world of technology?"
},
{
"code": null,
"e": 886,
"s": 559,
"text": "Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.It is used for:"
},
{
"code": null,
"e": 903,
"s": 886,
"text": "System Scripting"
},
{
"code": null,
"e": 919,
"s": 903,
"text": "Web Development"
},
{
"code": null,
"e": 936,
"s": 919,
"text": "Game Development"
},
{
"code": null,
"e": 957,
"s": 936,
"text": "Software Development"
},
{
"code": null,
"e": 977,
"s": 957,
"text": "Complex Mathematics"
},
{
"code": null,
"e": 1062,
"s": 977,
"text": "2. What are the benefits of using Python language as a tool in the present scenario?"
},
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Following are the benefits of using Python language:"
},
{
"code": null,
"e": 1140,
"s": 1115,
"text": "Object-Oriented Language"
},
{
"code": null,
"e": 1160,
"s": 1140,
"text": "High Level Language"
},
{
"code": null,
"e": 1187,
"s": 1160,
"text": "Dynamically Typed language"
},
{
"code": null,
"e": 1215,
"s": 1187,
"text": "Extensive support Libraries"
},
{
"code": null,
"e": 1247,
"s": 1215,
"text": "Presence of third-party modules"
},
{
"code": null,
"e": 1285,
"s": 1247,
"text": "Open source and community development"
},
{
"code": null,
"e": 1310,
"s": 1285,
"text": "Portable and Interactive"
},
{
"code": null,
"e": 1344,
"s": 1310,
"text": "Portable across Operating systems"
},
{
"code": null,
"e": 1423,
"s": 1344,
"text": "3. Which sorting technique is used by sort() and sorted() functions of python?"
},
{
"code": null,
"e": 1657,
"s": 1423,
"text": "Python uses Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data."
},
{
"code": null,
"e": 1698,
"s": 1657,
"text": "4. Differentiate between List and Tuple?"
},
{
"code": null,
"e": 1752,
"s": 1698,
"text": "Let’s analyze the differences between List and Tuple:"
},
{
"code": null,
"e": 1757,
"s": 1752,
"text": "List"
},
{
"code": null,
"e": 1785,
"s": 1757,
"text": "Lists are Mutable datatype."
},
{
"code": null,
"e": 1811,
"s": 1785,
"text": "Lists consume more memory"
},
{
"code": null,
"e": 1889,
"s": 1811,
"text": "The list is better for performing operations, such as insertion and deletion."
},
{
"code": null,
"e": 1933,
"s": 1889,
"text": "Implication of iterations is Time-consuming"
},
{
"code": null,
"e": 1939,
"s": 1933,
"text": "Tuple"
},
{
"code": null,
"e": 1970,
"s": 1939,
"text": "Tuples are Immutable datatype."
},
{
"code": null,
"e": 2020,
"s": 1970,
"text": "Tuple consume less memory as compared to the list"
},
{
"code": null,
"e": 2078,
"s": 2020,
"text": "Tuple data type is appropriate for accessing the elements"
},
{
"code": null,
"e": 2128,
"s": 2078,
"text": "Implication of iterations is comparatively Faster"
},
{
"code": null,
"e": 2175,
"s": 2128,
"text": "To read more, refer the article: List vs Tuple"
},
{
"code": null,
"e": 2605,
"s": 2175,
"text": "5. How memory management is done in Python?Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space."
},
{
"code": null,
"e": 2666,
"s": 2605,
"text": "To read more, refer the article: Memory Management in Python"
},
{
"code": null,
"e": 2684,
"s": 2666,
"text": "6. What is PEP 8?"
},
{
"code": null,
"e": 2878,
"s": 2684,
"text": "PEP 8 is a Python style guide. It is a document that provides the guidelines and best practices on how to write beautiful Python code. It promotes a very readable and eye-pleasing coding style."
},
{
"code": null,
"e": 2930,
"s": 2878,
"text": "To read more, refer the article: PEP 8 coding style"
},
{
"code": null,
"e": 2991,
"s": 2930,
"text": "7. Is Python a compiled language or an interpreted language?"
},
{
"code": null,
"e": 3316,
"s": 2991,
"text": "Actually, Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code and internally this byte code gets converted by the python virtual machine(p.v.m) according to the underlying platform(machine+operating system)."
},
{
"code": null,
"e": 3383,
"s": 3316,
"text": "To read more, refer the article: Python – Compiled or Interpreted?"
},
{
"code": null,
"e": 3421,
"s": 3383,
"text": "8. How to delete a file using Python?"
},
{
"code": null,
"e": 3480,
"s": 3421,
"text": "We can delete a file using Python by following approaches:"
},
{
"code": null,
"e": 3492,
"s": 3480,
"text": "os.remove()"
},
{
"code": null,
"e": 3504,
"s": 3492,
"text": "os.unlink()"
},
{
"code": null,
"e": 3528,
"s": 3504,
"text": "9. What are Decorators?"
},
{
"code": null,
"e": 3674,
"s": 3528,
"text": "Decorators are a very powerful and useful tool in Python as they are the specific change that we make in Python syntax to alter functions easily."
},
{
"code": null,
"e": 3728,
"s": 3674,
"text": "To read more, refer the article: Decorators in Python"
},
{
"code": null,
"e": 3804,
"s": 3728,
"text": "10. What is the difference between Mutable datatype and Immutable datatype?"
},
{
"code": null,
"e": 4000,
"s": 3804,
"text": "Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc."
},
{
"code": null,
"e": 4055,
"s": 4000,
"text": "11. What is the difference between Set and Dictionary?"
},
{
"code": null,
"e": 4258,
"s": 4055,
"text": "Set is an unordered collection of data type that is iterable, mutable, and has no duplicate elements.Dictionary in Python is an unordered collection of data values, used to store data values like a map."
},
{
"code": null,
"e": 4311,
"s": 4258,
"text": "To read more, refer the article: Sets and Dictionary"
},
{
"code": null,
"e": 4350,
"s": 4311,
"text": "12. How do you debug a Python program?"
},
{
"code": null,
"e": 4403,
"s": 4350,
"text": "By using this command we can debug a python program:"
},
{
"code": null,
"e": 4437,
"s": 4403,
"text": "$ python -m pdb python-script.py\n"
},
{
"code": null,
"e": 4474,
"s": 4437,
"text": "13. What is Pickling and Unpickling?"
},
{
"code": null,
"e": 4761,
"s": 4474,
"text": "Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling."
},
{
"code": null,
"e": 4821,
"s": 4761,
"text": "To read more, refer to the article: Pickle module in Python"
},
{
"code": null,
"e": 5136,
"s": 4821,
"text": "14. How are arguments passed by value or by reference in Python?Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable."
},
{
"code": null,
"e": 5185,
"s": 5136,
"text": "15. What is List Comprehension? Give an Example."
},
{
"code": null,
"e": 5288,
"s": 5185,
"text": "List comprehension is a syntax construction to ease the creation of a list based on existing iterable."
},
{
"code": null,
"e": 5301,
"s": 5288,
"text": "For Example:"
},
{
"code": null,
"e": 5337,
"s": 5301,
"text": "my_list = [i for i in range(1, 10)]"
},
{
"code": null,
"e": 5391,
"s": 5337,
"text": "16. What is Dictionary Comprehension? Give an Example"
},
{
"code": null,
"e": 5510,
"s": 5391,
"text": "Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable."
},
{
"code": null,
"e": 5563,
"s": 5510,
"text": "For Example: my_dict = {i:1+7 for i in range(1, 10)}"
},
{
"code": null,
"e": 5619,
"s": 5563,
"text": "17. Is Tuple Comprehension? If yes, how and if not why?"
},
{
"code": null,
"e": 5642,
"s": 5619,
"text": "(i for i in (1, 2, 3))"
},
{
"code": null,
"e": 5754,
"s": 5642,
"text": "Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension."
},
{
"code": null,
"e": 5787,
"s": 5754,
"text": "18. What is namespace in Python?"
},
{
"code": null,
"e": 5885,
"s": 5787,
"text": "A namespace is a naming system used to make sure that names are unique to avoid naming conflicts."
},
{
"code": null,
"e": 5941,
"s": 5885,
"text": "To read more, refer to the article: Namespace in Python"
},
{
"code": null,
"e": 5972,
"s": 5941,
"text": "19. What is a lambda function?"
},
{
"code": null,
"e": 6111,
"s": 5972,
"text": "A lambda function is an anonymous function. This function can have any number of parameters but, can have just one statement. For Example:"
},
{
"code": null,
"e": 6150,
"s": 6111,
"text": "a = lambda x, y : x*y\nprint(a(7, 19))\n"
},
{
"code": null,
"e": 6203,
"s": 6150,
"text": "To read more, refer to the article: Lambda functions"
},
{
"code": null,
"e": 6233,
"s": 6203,
"text": "20. What is a pass in Python?"
},
{
"code": null,
"e": 6407,
"s": 6233,
"text": "Pass means performing no operation or in other words, it is a place holder in the compound statement, where there should be a blank left and nothing has to be written there."
},
{
"code": null,
"e": 6469,
"s": 6407,
"text": "21. What is the difference between xrange and range function?"
},
{
"code": null,
"e": 6677,
"s": 6469,
"text": "range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2."
},
{
"code": null,
"e": 6750,
"s": 6677,
"text": "range() – This returns a list of numbers created using range() function."
},
{
"code": null,
"e": 6940,
"s": 6750,
"text": "xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation."
},
{
"code": null,
"e": 6992,
"s": 6940,
"text": "To read more, refer to the article: Range vs Xrange"
},
{
"code": null,
"e": 7043,
"s": 6992,
"text": "22. What is difference between / and // in Python?"
},
{
"code": null,
"e": 7125,
"s": 7043,
"text": "// represents floor division whereas / represents precised division. For Example:"
},
{
"code": null,
"e": 7145,
"s": 7125,
"text": "5//2 = 2\n5/2 = 2.5\n"
},
{
"code": null,
"e": 7171,
"s": 7145,
"text": "23. What is zip function?"
},
{
"code": null,
"e": 7400,
"s": 7171,
"text": "Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples."
},
{
"code": null,
"e": 7441,
"s": 7400,
"text": "24. What is swapcase function in Python?"
},
{
"code": null,
"e": 7696,
"s": 7441,
"text": "It is a string’s function that converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. For Example:"
},
{
"code": null,
"e": 7761,
"s": 7696,
"text": "string = \"GeeksforGeeks\"\nstring.swapcase() ---> \"gEEKSFORgEEKS\"\n"
},
{
"code": null,
"e": 7795,
"s": 7761,
"text": "25. What are Iterators in Python?"
},
{
"code": null,
"e": 8136,
"s": 7795,
"text": "In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple)."
},
{
"code": null,
"e": 8189,
"s": 8136,
"text": "To read more, refer the article: Iterators in Python"
},
{
"code": null,
"e": 8224,
"s": 8189,
"text": "26. What are Generators in Python?"
},
{
"code": null,
"e": 8461,
"s": 8224,
"text": "In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduces other overheads as well."
},
{
"code": null,
"e": 8650,
"s": 8461,
"text": "If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required."
},
{
"code": null,
"e": 8704,
"s": 8650,
"text": "To read more, refer the article: generators in Python"
},
{
"code": null,
"e": 8763,
"s": 8704,
"text": "27. What are the new features added in Python 3.8 version?"
},
{
"code": null,
"e": 8817,
"s": 8763,
"text": "Following are the new features in Python 3.8 version:"
},
{
"code": null,
"e": 8846,
"s": 8817,
"text": "Positional Only parameter(/)"
},
{
"code": null,
"e": 8872,
"s": 8846,
"text": "Assignment Expression(:=)"
},
{
"code": null,
"e": 8898,
"s": 8872,
"text": "f-strings now support “=”"
},
{
"code": null,
"e": 8933,
"s": 8898,
"text": "reversed() works with a dictionary"
},
{
"code": null,
"e": 8997,
"s": 8933,
"text": "To read more, refer the article: Awesome features in Python 3.8"
},
{
"code": null,
"e": 9036,
"s": 8997,
"text": "28. What is monkey patching in Python?"
},
{
"code": null,
"e": 9140,
"s": 9036,
"text": "In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time."
},
{
"code": null,
"e": 9362,
"s": 9140,
"text": "# g.py\nclass GeeksClass:\n def function(self):\n print \"function()\"\n\nimport m\ndef monkey_function(self):\n print \"monkey_function()\"\n \nm.GeeksClass.function = monkey_function\nobj = m.GeeksClass()\nobj.function()\n"
},
{
"code": null,
"e": 9421,
"s": 9362,
"text": "To read more, refer the article: Monkey patching in Python"
},
{
"code": null,
"e": 9468,
"s": 9421,
"text": "29. Does Python supports multiple Inheritance?"
},
{
"code": null,
"e": 9613,
"s": 9468,
"text": "Python does support multiple inheritance, unlike Java. Multiple inheritance means that a class can be derived from more than one parent classes."
},
{
"code": null,
"e": 9649,
"s": 9613,
"text": "30. What is Polymorphism in Python?"
},
{
"code": null,
"e": 9901,
"s": 9649,
"text": "Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism."
},
{
"code": null,
"e": 9957,
"s": 9901,
"text": "To read more, refer the article: Polymorphism in Python"
},
{
"code": null,
"e": 9993,
"s": 9957,
"text": "31. Define encapsulation in Python?"
},
{
"code": null,
"e": 10100,
"s": 9993,
"text": "Encapsulation means binding the code and the data together. A Python class is an example of encapsulation."
},
{
"code": null,
"e": 10157,
"s": 10100,
"text": "To read more, refer the article: Encapsulation in Python"
},
{
"code": null,
"e": 10203,
"s": 10157,
"text": "32. How do you do data abstraction in Python?"
},
{
"code": null,
"e": 10376,
"s": 10203,
"text": "Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes."
},
{
"code": null,
"e": 10431,
"s": 10376,
"text": "To read more, refer the article: Abstraction in Python"
},
{
"code": null,
"e": 10476,
"s": 10431,
"text": "33. Which databases are supported by Python?"
},
{
"code": null,
"e": 10668,
"s": 10476,
"text": "MySQL (Structured) and MongoDB (Unstructured) are the prominent databases that are supported natively in Python. Import the module and start using the functions to interact with the database."
},
{
"code": null,
"e": 10716,
"s": 10668,
"text": "34. How is Exceptional handling done in Python?"
},
{
"code": null,
"e": 10963,
"s": 10716,
"text": "There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code which is monitored for errors. Except block gets executed when an error occurs."
},
{
"code": null,
"e": 11197,
"s": 10963,
"text": "The beauty of the final block is to execute the code after trying for error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables."
},
{
"code": null,
"e": 11236,
"s": 11197,
"text": "35. What does ‘#’ symbol do in Python?"
},
{
"code": null,
"e": 11304,
"s": 11236,
"text": "‘#’ is used to comment out everything that comes after on the line."
},
{
"code": null,
"e": 11350,
"s": 11304,
"text": "36. Write a code to display the current time?"
},
{
"code": null,
"e": 11431,
"s": 11350,
"text": "currenttime= time.localtime(time.time())\nprint (“Current time is”, currenttime)\n"
},
{
"code": null,
"e": 11496,
"s": 11431,
"text": "37. What is the difference between a shallow copy and deep copy?"
},
{
"code": null,
"e": 11648,
"s": 11496,
"text": "Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied."
},
{
"code": null,
"e": 11724,
"s": 11648,
"text": "A shallow copy has faster program execution whereas deep coy makes it slow."
},
{
"code": null,
"e": 11783,
"s": 11724,
"text": "To read more, refer the article: Shallow copy vs Deep copy"
},
{
"code": null,
"e": 11800,
"s": 11783,
"text": "38. What is PIP?"
},
{
"code": null,
"e": 12038,
"s": 11800,
"text": "PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction."
},
{
"code": null,
"e": 12085,
"s": 12038,
"text": "To read more, refer the article: PIP in Python"
},
{
"code": null,
"e": 12119,
"s": 12085,
"text": "39. What is __init__() in Python?"
},
{
"code": null,
"e": 12422,
"s": 12119,
"text": "Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables."
},
{
"code": null,
"e": 12480,
"s": 12422,
"text": "40. What is the maximum possible length of an identifier?"
},
{
"code": null,
"e": 12524,
"s": 12480,
"text": "Identifiers in Python can be of any length."
},
{
"code": null,
"e": 12546,
"s": 12524,
"text": "interview-preparation"
},
{
"code": null,
"e": 12553,
"s": 12546,
"text": "Python"
}
] |
Python | Pandas Series.to_json() | 05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_json() function is used to convert the object to a JSON string. Also note that NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.
Syntax: Series.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)
Parameter :path_or_buf : File path or object. If not specified, the result is returned as a string.orient : Indication of expected JSON string format.date_format : None, ‘epoch’, ‘iso’}double_precision : The number of decimal places to use when encoding floating point values.force_ascii : Force encoded string to be ASCII.date_unit : string, default ‘ms’ (milliseconds)default_handler : callable, default Nonelines : bool, default Falsecompression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}
Returns : Json string
Example #1: Use Series.to_json() function to convert the given series object to JSON string.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.to_json() function to convert the given series object to JSON string.
# convert to JSON stringsr.to_json()
Output :
As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.
Example #2: Use Series.to_json() function to convert the given series object to JSON string.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)
Output :
Now we will use Series.to_json() function to convert the given series object to JSON string.
# convert to JSON stringsr.to_json()
Output :
As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 481,
"s": 285,
"text": "Pandas Series.to_json() function is used to convert the object to a JSON string. Also note that NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps."
},
{
"code": null,
"e": 676,
"s": 481,
"text": "Syntax: Series.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)"
},
{
"code": null,
"e": 1171,
"s": 676,
"text": "Parameter :path_or_buf : File path or object. If not specified, the result is returned as a string.orient : Indication of expected JSON string format.date_format : None, ‘epoch’, ‘iso’}double_precision : The number of decimal places to use when encoding floating point values.force_ascii : Force encoded string to be ASCII.date_unit : string, default ‘ms’ (milliseconds)default_handler : callable, default Nonelines : bool, default Falsecompression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}"
},
{
"code": null,
"e": 1193,
"s": 1171,
"text": "Returns : Json string"
},
{
"code": null,
"e": 1286,
"s": 1193,
"text": "Example #1: Use Series.to_json() function to convert the given series object to JSON string."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 1638,
"s": 1286,
"text": null
},
{
"code": null,
"e": 1647,
"s": 1638,
"text": "Output :"
},
{
"code": null,
"e": 1740,
"s": 1647,
"text": "Now we will use Series.to_json() function to convert the given series object to JSON string."
},
{
"code": "# convert to JSON stringsr.to_json()",
"e": 1777,
"s": 1740,
"text": null
},
{
"code": null,
"e": 1786,
"s": 1777,
"text": "Output :"
},
{
"code": null,
"e": 1912,
"s": 1786,
"text": "As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string."
},
{
"code": null,
"e": 2005,
"s": 1912,
"text": "Example #2: Use Series.to_json() function to convert the given series object to JSON string."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)",
"e": 2153,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2162,
"s": 2153,
"text": "Output :"
},
{
"code": null,
"e": 2255,
"s": 2162,
"text": "Now we will use Series.to_json() function to convert the given series object to JSON string."
},
{
"code": "# convert to JSON stringsr.to_json()",
"e": 2292,
"s": 2255,
"text": null
},
{
"code": null,
"e": 2301,
"s": 2292,
"text": "Output :"
},
{
"code": null,
"e": 2427,
"s": 2301,
"text": "As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string."
},
{
"code": null,
"e": 2448,
"s": 2427,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2477,
"s": 2448,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2491,
"s": 2477,
"text": "Python-pandas"
},
{
"code": null,
"e": 2498,
"s": 2491,
"text": "Python"
}
] |
OpenCV | Displaying an Image | 09 Sep, 2019
To read an image file from videos or cameras having a wide range of types, OpenCV provides a good amount of utilities. OpenCV has such a toolkit known as HighGUI, which is a part of one of its utilities. Some of these utilities are used in this article to display and open an image on our system.Let’s understand line by line execution of the programCode:
IplImage* img_file = cvLoadImage("..input\\abcd.PNG");
This particular line will load the image with a high-level routine – cvLoadImage(). Based on the file name, it determines the file format to be loaded and then allocates the required memory for the image data structure automatically. One can read a huge range of different image formats from cvLoadImage(). These image formats can be – JPEG, BMP, PNG, JPE, DIB, PBM, PPM, RAS, SR and TIFF. Then, a pointer to the assigned image data structure is returned. The returned pointer is used to manipulate the image and its data. This structure is IplImage. IplImage is the OpenCV construct which is used by OpenCV for handling all different kind of images. These images can be a single-channel image, multi-channel images, floating-point valued images or integer values images.Here in the code above, the path to the image is given and it is different for each user. So, it can be set according to the location of the image on the user system.
Code:
if (!img_file->imageData)
Using this line of code, it can be checked whether the image actually exists or not. If there is no imageData, then, in that case, we can detect it easily using this.
Code:
cvNamedWindow( “Display”, CV_WINDOW_AUTOSIZE );
Now, cvNamedWindow() is another high-level function provided by the HighGUI library, It is responsible for opening a window on the screen. It is this window which has the image display. Using this, a name can also be assigned to the image window (“Display” in the code above). This name is further used in the code to make any HighGUI call.The second parameter to cvNamedWindow() defines the window properties and it can be either set to 0 (the default value) or to the CV_WINDOW_AUTOSIZE(as in the above code). In the case of ‘0’ value, the size of the window will be the same irrespective of the image size and the image will be scaled according to the default window size. In the case of ‘CV_WINDOW_AUTOSIZE’, the size of the window may vary as per the image size. The window will be scaled according to the default image size and the image will have its true size.
Code:
cvShowImage("Display", img_file);
cvShowImage() is used to display an image in the form as an IplImage* pointer, in an existing window. That means it needs an already existing window, which is created using cvNamedWindow(). The image is redrawn with the image present in it and window resize accordingly (if created with CV_WINDOW_AUTOSIZE), when we call cvShowImage().
Code:
cvWaitKey(0);
cvWaitKey() is defined to ask the program to wait or stop for a keypress. If it is given a positive argument, then the program will wait for that number of milliseconds. Then, even if no key is pressed, it will continue automatically. Otherwise as in the code above, using a negative or ‘0’ number means that the program will wait for keypress indefinitely.
Code:
cvReleaseImage( &img_file );
Now, we can free the allocated memory to the image, once we are done. A pointer to the IplImage* pointer is expected for this operation. The pointer ‘img_file’ will be set to NULL.
Code:
cvDestroyWindow("Display");
Finally, the window is also destroyed using cvDestroyWindow(). It will close and de-allocate the window memory or any associated data usage which can be (image buffer, copy of pixel info from *img_file). For a simple program, cvDestroyWindow() or cvReleaseImage() function need not be used as all resources close automatically by the OS but it is good to do it on your own.
#include <opencv2\opencv.hpp>#include <opencv2\highgui\highgui.hpp>#include <highlevelmonitorconfigurationapi.h> using namespace cv;using namespace std; int main(int argc, char** argv) { IplImage* img_file = cvLoadImage("..input\\abcd.jpg"); if (!img_file->imageData) { cout << "Sorry"; return -1; } cvNamedWindow("Display", CV_WINDOW_AUTOSIZE); cvShowImage("Display", img_file); cvWaitKey(0); cvReleaseImage(&img_file); cvDestroyWindow("Display");}
Output :
This program compiles, run and then loads an image into the window using memory and displays it in the window on the screen. It will then form the user keypress and then it closes and exits.
OpenCV
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2019"
},
{
"code": null,
"e": 384,
"s": 28,
"text": "To read an image file from videos or cameras having a wide range of types, OpenCV provides a good amount of utilities. OpenCV has such a toolkit known as HighGUI, which is a part of one of its utilities. Some of these utilities are used in this article to display and open an image on our system.Let’s understand line by line execution of the programCode:"
},
{
"code": "IplImage* img_file = cvLoadImage(\"..input\\\\abcd.PNG\");",
"e": 439,
"s": 384,
"text": null
},
{
"code": null,
"e": 1377,
"s": 439,
"text": "This particular line will load the image with a high-level routine – cvLoadImage(). Based on the file name, it determines the file format to be loaded and then allocates the required memory for the image data structure automatically. One can read a huge range of different image formats from cvLoadImage(). These image formats can be – JPEG, BMP, PNG, JPE, DIB, PBM, PPM, RAS, SR and TIFF. Then, a pointer to the assigned image data structure is returned. The returned pointer is used to manipulate the image and its data. This structure is IplImage. IplImage is the OpenCV construct which is used by OpenCV for handling all different kind of images. These images can be a single-channel image, multi-channel images, floating-point valued images or integer values images.Here in the code above, the path to the image is given and it is different for each user. So, it can be set according to the location of the image on the user system."
},
{
"code": null,
"e": 1383,
"s": 1377,
"text": "Code:"
},
{
"code": "if (!img_file->imageData)",
"e": 1409,
"s": 1383,
"text": null
},
{
"code": null,
"e": 1576,
"s": 1409,
"text": "Using this line of code, it can be checked whether the image actually exists or not. If there is no imageData, then, in that case, we can detect it easily using this."
},
{
"code": null,
"e": 1582,
"s": 1576,
"text": "Code:"
},
{
"code": "cvNamedWindow( “Display”, CV_WINDOW_AUTOSIZE );",
"e": 1630,
"s": 1582,
"text": null
},
{
"code": null,
"e": 2499,
"s": 1630,
"text": "Now, cvNamedWindow() is another high-level function provided by the HighGUI library, It is responsible for opening a window on the screen. It is this window which has the image display. Using this, a name can also be assigned to the image window (“Display” in the code above). This name is further used in the code to make any HighGUI call.The second parameter to cvNamedWindow() defines the window properties and it can be either set to 0 (the default value) or to the CV_WINDOW_AUTOSIZE(as in the above code). In the case of ‘0’ value, the size of the window will be the same irrespective of the image size and the image will be scaled according to the default window size. In the case of ‘CV_WINDOW_AUTOSIZE’, the size of the window may vary as per the image size. The window will be scaled according to the default image size and the image will have its true size."
},
{
"code": null,
"e": 2505,
"s": 2499,
"text": "Code:"
},
{
"code": "cvShowImage(\"Display\", img_file);",
"e": 2539,
"s": 2505,
"text": null
},
{
"code": null,
"e": 2875,
"s": 2539,
"text": "cvShowImage() is used to display an image in the form as an IplImage* pointer, in an existing window. That means it needs an already existing window, which is created using cvNamedWindow(). The image is redrawn with the image present in it and window resize accordingly (if created with CV_WINDOW_AUTOSIZE), when we call cvShowImage()."
},
{
"code": null,
"e": 2881,
"s": 2875,
"text": "Code:"
},
{
"code": "cvWaitKey(0);",
"e": 2895,
"s": 2881,
"text": null
},
{
"code": null,
"e": 3253,
"s": 2895,
"text": "cvWaitKey() is defined to ask the program to wait or stop for a keypress. If it is given a positive argument, then the program will wait for that number of milliseconds. Then, even if no key is pressed, it will continue automatically. Otherwise as in the code above, using a negative or ‘0’ number means that the program will wait for keypress indefinitely."
},
{
"code": null,
"e": 3259,
"s": 3253,
"text": "Code:"
},
{
"code": "cvReleaseImage( &img_file );",
"e": 3288,
"s": 3259,
"text": null
},
{
"code": null,
"e": 3469,
"s": 3288,
"text": "Now, we can free the allocated memory to the image, once we are done. A pointer to the IplImage* pointer is expected for this operation. The pointer ‘img_file’ will be set to NULL."
},
{
"code": null,
"e": 3475,
"s": 3469,
"text": "Code:"
},
{
"code": "cvDestroyWindow(\"Display\");",
"e": 3503,
"s": 3475,
"text": null
},
{
"code": null,
"e": 3877,
"s": 3503,
"text": "Finally, the window is also destroyed using cvDestroyWindow(). It will close and de-allocate the window memory or any associated data usage which can be (image buffer, copy of pixel info from *img_file). For a simple program, cvDestroyWindow() or cvReleaseImage() function need not be used as all resources close automatically by the OS but it is good to do it on your own."
},
{
"code": "#include <opencv2\\opencv.hpp>#include <opencv2\\highgui\\highgui.hpp>#include <highlevelmonitorconfigurationapi.h> using namespace cv;using namespace std; int main(int argc, char** argv) { IplImage* img_file = cvLoadImage(\"..input\\\\abcd.jpg\"); if (!img_file->imageData) { cout << \"Sorry\"; return -1; } cvNamedWindow(\"Display\", CV_WINDOW_AUTOSIZE); cvShowImage(\"Display\", img_file); cvWaitKey(0); cvReleaseImage(&img_file); cvDestroyWindow(\"Display\");}",
"e": 4380,
"s": 3877,
"text": null
},
{
"code": null,
"e": 4389,
"s": 4380,
"text": "Output :"
},
{
"code": null,
"e": 4580,
"s": 4389,
"text": "This program compiles, run and then loads an image into the window using memory and displays it in the window on the screen. It will then form the user keypress and then it closes and exits."
},
{
"code": null,
"e": 4587,
"s": 4580,
"text": "OpenCV"
},
{
"code": null,
"e": 4591,
"s": 4587,
"text": "C++"
},
{
"code": null,
"e": 4595,
"s": 4591,
"text": "CPP"
}
] |
How to search the max value of an attribute in an array object ? | 10 Jun, 2022
Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math.max.apply() method.
Example 1: In this example, the array is traversed and the required values of the object are compared for each index of the array.
javascript
// Array of objectvar arr = [ { a: 10, b: 25 }, { a: 30, b: 5 }, { a: 20, b: 15 }, { a: 50, b: 35 }, { a: 40, b: 45 }, ]; // Returns max value of // attribute 'a' in array function fun(arr){ var maxValue = Number.MIN_VALUE; for(var i=0;i<arr.length;i++){ if(arr[i].a>maxValue){ maxValue = arr[i].a; } } return maxValue; } var maxValue = fun(arr); console.log(maxValue);
Output:
50
Example 2: In this example, we find the max value of an attribute by using Math.max.apply() function. It has two parameters:
thisarray-like object
this
array-like object
Syntax:
Math.max.apply(thisArg, [ argsArray])
More information can be found at https://developer.mozilla.org/
javascript
var arr = [ { a: 10, b: 25 }, { a: 30, b: 5 }, { a: 20, b: 15 }, { a: 50, b: 35 }, { a: 40, b: 45 }, ]; var maxValue = Math.max.apply(null, arr.map(function(o) { return o.a; })); console.log(maxValue);
Output:
50
Example-3: In this example we will using reduce() method with which all the values will be compared and then at last the final value will be stored which further will be stored in a variable which will be output over console.
Javascript
let array = [ { a: 1, b: 2 }, { a: 2, b: 4 }, { a: 3, b: 6 }, { a: 4, b: 8 }, { a: 5, b: 10 }, { a: 6, b: 12 },]; let maxValue = array.reduce((acc, value) => { return (acc = acc > value.b ? acc : value.b);}, 0); console.log(maxValue); // This code is contributed by Aman Singla...
Output:
12
amansingla
javascript-array
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math.max.apply() method."
},
{
"code": null,
"e": 331,
"s": 200,
"text": "Example 1: In this example, the array is traversed and the required values of the object are compared for each index of the array."
},
{
"code": null,
"e": 342,
"s": 331,
"text": "javascript"
},
{
"code": "// Array of objectvar arr = [ { a: 10, b: 25 }, { a: 30, b: 5 }, { a: 20, b: 15 }, { a: 50, b: 35 }, { a: 40, b: 45 }, ]; // Returns max value of // attribute 'a' in array function fun(arr){ var maxValue = Number.MIN_VALUE; for(var i=0;i<arr.length;i++){ if(arr[i].a>maxValue){ maxValue = arr[i].a; } } return maxValue; } var maxValue = fun(arr); console.log(maxValue);",
"e": 852,
"s": 342,
"text": null
},
{
"code": null,
"e": 860,
"s": 852,
"text": "Output:"
},
{
"code": null,
"e": 863,
"s": 860,
"text": "50"
},
{
"code": null,
"e": 988,
"s": 863,
"text": "Example 2: In this example, we find the max value of an attribute by using Math.max.apply() function. It has two parameters:"
},
{
"code": null,
"e": 1010,
"s": 988,
"text": "thisarray-like object"
},
{
"code": null,
"e": 1015,
"s": 1010,
"text": "this"
},
{
"code": null,
"e": 1033,
"s": 1015,
"text": "array-like object"
},
{
"code": null,
"e": 1041,
"s": 1033,
"text": "Syntax:"
},
{
"code": null,
"e": 1079,
"s": 1041,
"text": "Math.max.apply(thisArg, [ argsArray])"
},
{
"code": null,
"e": 1143,
"s": 1079,
"text": "More information can be found at https://developer.mozilla.org/"
},
{
"code": null,
"e": 1154,
"s": 1143,
"text": "javascript"
},
{
"code": "var arr = [ { a: 10, b: 25 }, { a: 30, b: 5 }, { a: 20, b: 15 }, { a: 50, b: 35 }, { a: 40, b: 45 }, ]; var maxValue = Math.max.apply(null, arr.map(function(o) { return o.a; })); console.log(maxValue);",
"e": 1460,
"s": 1154,
"text": null
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "Output:"
},
{
"code": null,
"e": 1471,
"s": 1468,
"text": "50"
},
{
"code": null,
"e": 1697,
"s": 1471,
"text": "Example-3: In this example we will using reduce() method with which all the values will be compared and then at last the final value will be stored which further will be stored in a variable which will be output over console."
},
{
"code": null,
"e": 1708,
"s": 1697,
"text": "Javascript"
},
{
"code": "let array = [ { a: 1, b: 2 }, { a: 2, b: 4 }, { a: 3, b: 6 }, { a: 4, b: 8 }, { a: 5, b: 10 }, { a: 6, b: 12 },]; let maxValue = array.reduce((acc, value) => { return (acc = acc > value.b ? acc : value.b);}, 0); console.log(maxValue); // This code is contributed by Aman Singla...",
"e": 1996,
"s": 1708,
"text": null
},
{
"code": null,
"e": 2004,
"s": 1996,
"text": "Output:"
},
{
"code": null,
"e": 2008,
"s": 2004,
"text": " 12"
},
{
"code": null,
"e": 2019,
"s": 2008,
"text": "amansingla"
},
{
"code": null,
"e": 2036,
"s": 2019,
"text": "javascript-array"
},
{
"code": null,
"e": 2043,
"s": 2036,
"text": "Picked"
},
{
"code": null,
"e": 2054,
"s": 2043,
"text": "JavaScript"
},
{
"code": null,
"e": 2071,
"s": 2054,
"text": "Web Technologies"
},
{
"code": null,
"e": 2098,
"s": 2071,
"text": "Web technologies Questions"
}
] |
Why probability of an event always lie between 0 and 1? | 18 May, 2021
Probability refers to the extent of occurrence of events. When an event occurs like throwing a ball, picking a card from the deck, etc, then the must be some probability associated with that event.
Mutually Exclusive Event:Given two events A and B, if both of these events have nothing in common i.e. A ∩ B = ∅ then, the probability of the intersection of these events will also be equal to zero i.e. P(A ∩ B) = 0. Such events are known as Mutually Exclusive Events.
Sample Space:It is a set of all the possible outcomes of an experiment. In this article, we will denote a sample space by ‘S’.
Now, there are three important axioms related to Probability, which will really help us in proving the above statement. So, let’s have a look at these axioms-
Probability of an event will always be greater than or equal to zero i.e. P(A) >= 0 for any event A.Probability of a Sample Space will always be equal to 1 i.e. P(S) = 1Given some mutually exclusive events, the probability of the union of all these mutually exclusive events will always be equal to the summation of the probability of individual events i.e. P(A1 ∪ A2 ∪ A3 ∪ A4 ... ∪ AN) = P(A1) + P(A2) + P(A3) +P (A4) + .... + P(AN)
Probability of an event will always be greater than or equal to zero i.e. P(A) >= 0 for any event A.
Probability of a Sample Space will always be equal to 1 i.e. P(S) = 1
Given some mutually exclusive events, the probability of the union of all these mutually exclusive events will always be equal to the summation of the probability of individual events i.e. P(A1 ∪ A2 ∪ A3 ∪ A4 ... ∪ AN) = P(A1) + P(A2) + P(A3) +P (A4) + .... + P(AN)
Problem Statement:The task here is to prove that the probability of A will always lie between 0 and 1 i.e. 0 <= P(A) <= 1.
Solution: Consider event A. Below are the steps for the proof of the above problem statement-
According to axiom 1, the probability of an event will always be greater than or equal to 0.
P(A) >= 0 (According to Axiom 1) --- (1)
The probability of a sample space will be equal to the probability of the intersection of A and (S – A) i.e.
S = A + (S - A)
P(S) = P(A + (S - A))
Since A and (S – A) are two mutually exclusive events. So, according to axiom 3, it can be written-
P(A + (S - A)) = P(A) + P(S - A)
This implies,
P(S) = P(A) + P(S - A)) --- (2)
Now, from axiom 1, it can be said that the P(S – A) will always be greater than or equal to zero i.e. P(S – A) >= 0.
If something positive is added to a given value, its value will always increase. Since, P(S – A) >=0, it can be said that P(A) can’t be greater than P(S). Otherwise, equation (2) will not hold true.
This means-
P(S) >= P(A)
From axiom 2, the probability of a Sample Space always equals 1. So, this means-
1 >= P(A)
or
P(A) >= 1 --- (3)
From, equation (1) and (3), it can be shown that-
0 <= P(A) <= 1
This proves that the probability of an event will always lie between 0 and 1.
Probability
Articles
Mathematical
Mathematical
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 226,
"s": 28,
"text": "Probability refers to the extent of occurrence of events. When an event occurs like throwing a ball, picking a card from the deck, etc, then the must be some probability associated with that event."
},
{
"code": null,
"e": 496,
"s": 226,
"text": "Mutually Exclusive Event:Given two events A and B, if both of these events have nothing in common i.e. A ∩ B = ∅ then, the probability of the intersection of these events will also be equal to zero i.e. P(A ∩ B) = 0. Such events are known as Mutually Exclusive Events."
},
{
"code": null,
"e": 623,
"s": 496,
"text": "Sample Space:It is a set of all the possible outcomes of an experiment. In this article, we will denote a sample space by ‘S’."
},
{
"code": null,
"e": 782,
"s": 623,
"text": "Now, there are three important axioms related to Probability, which will really help us in proving the above statement. So, let’s have a look at these axioms-"
},
{
"code": null,
"e": 1217,
"s": 782,
"text": "Probability of an event will always be greater than or equal to zero i.e. P(A) >= 0 for any event A.Probability of a Sample Space will always be equal to 1 i.e. P(S) = 1Given some mutually exclusive events, the probability of the union of all these mutually exclusive events will always be equal to the summation of the probability of individual events i.e. P(A1 ∪ A2 ∪ A3 ∪ A4 ... ∪ AN) = P(A1) + P(A2) + P(A3) +P (A4) + .... + P(AN)"
},
{
"code": null,
"e": 1318,
"s": 1217,
"text": "Probability of an event will always be greater than or equal to zero i.e. P(A) >= 0 for any event A."
},
{
"code": null,
"e": 1388,
"s": 1318,
"text": "Probability of a Sample Space will always be equal to 1 i.e. P(S) = 1"
},
{
"code": null,
"e": 1654,
"s": 1388,
"text": "Given some mutually exclusive events, the probability of the union of all these mutually exclusive events will always be equal to the summation of the probability of individual events i.e. P(A1 ∪ A2 ∪ A3 ∪ A4 ... ∪ AN) = P(A1) + P(A2) + P(A3) +P (A4) + .... + P(AN)"
},
{
"code": null,
"e": 1777,
"s": 1654,
"text": "Problem Statement:The task here is to prove that the probability of A will always lie between 0 and 1 i.e. 0 <= P(A) <= 1."
},
{
"code": null,
"e": 1871,
"s": 1777,
"text": "Solution: Consider event A. Below are the steps for the proof of the above problem statement-"
},
{
"code": null,
"e": 1964,
"s": 1871,
"text": "According to axiom 1, the probability of an event will always be greater than or equal to 0."
},
{
"code": null,
"e": 2006,
"s": 1964,
"text": "P(A) >= 0 (According to Axiom 1) --- (1)"
},
{
"code": null,
"e": 2115,
"s": 2006,
"text": "The probability of a sample space will be equal to the probability of the intersection of A and (S – A) i.e."
},
{
"code": null,
"e": 2153,
"s": 2115,
"text": "S = A + (S - A)\nP(S) = P(A + (S - A))"
},
{
"code": null,
"e": 2253,
"s": 2153,
"text": "Since A and (S – A) are two mutually exclusive events. So, according to axiom 3, it can be written-"
},
{
"code": null,
"e": 2286,
"s": 2253,
"text": "P(A + (S - A)) = P(A) + P(S - A)"
},
{
"code": null,
"e": 2302,
"s": 2286,
"text": "This implies, "
},
{
"code": null,
"e": 2334,
"s": 2302,
"text": "P(S) = P(A) + P(S - A)) --- (2)"
},
{
"code": null,
"e": 2451,
"s": 2334,
"text": "Now, from axiom 1, it can be said that the P(S – A) will always be greater than or equal to zero i.e. P(S – A) >= 0."
},
{
"code": null,
"e": 2651,
"s": 2451,
"text": "If something positive is added to a given value, its value will always increase. Since, P(S – A) >=0, it can be said that P(A) can’t be greater than P(S). Otherwise, equation (2) will not hold true. "
},
{
"code": null,
"e": 2663,
"s": 2651,
"text": "This means-"
},
{
"code": null,
"e": 2676,
"s": 2663,
"text": "P(S) >= P(A)"
},
{
"code": null,
"e": 2758,
"s": 2676,
"text": "From axiom 2, the probability of a Sample Space always equals 1. So, this means- "
},
{
"code": null,
"e": 2792,
"s": 2758,
"text": "1 >= P(A)\n or\nP(A) >= 1 --- (3)"
},
{
"code": null,
"e": 2842,
"s": 2792,
"text": "From, equation (1) and (3), it can be shown that-"
},
{
"code": null,
"e": 2857,
"s": 2842,
"text": "0 <= P(A) <= 1"
},
{
"code": null,
"e": 2935,
"s": 2857,
"text": "This proves that the probability of an event will always lie between 0 and 1."
},
{
"code": null,
"e": 2947,
"s": 2935,
"text": "Probability"
},
{
"code": null,
"e": 2956,
"s": 2947,
"text": "Articles"
},
{
"code": null,
"e": 2969,
"s": 2956,
"text": "Mathematical"
},
{
"code": null,
"e": 2982,
"s": 2969,
"text": "Mathematical"
},
{
"code": null,
"e": 2994,
"s": 2982,
"text": "Probability"
},
{
"code": null,
"e": 3092,
"s": 2994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3118,
"s": 3092,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3165,
"s": 3118,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 3186,
"s": 3165,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 3222,
"s": 3186,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 3265,
"s": 3222,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 3295,
"s": 3265,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 3338,
"s": 3295,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3398,
"s": 3338,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 3413,
"s": 3398,
"text": "C++ Data Types"
}
] |
Python | Pandas Index.nunique() | 18 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.nunique() function return number of unique elements in the object. It returns a scalar value which is the count of all the unique values in the Index. By default the NaN values are not included in the count. If dropna parameter is set to be False then it includes NaN value in the count.
Syntax: Index.nunique(dropna=True)
Parameters :dropna : Don’t include NaN in the count.
Returns : nunique : int
Example #1: Use Index.nunique()() function to find the count of unique values in the Index. Do not include NaN values in the count.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx
Output :
Let’s find the count of unique values in the Index.
# to find the count of unique values.idx.nunique(dropna = True)
Output :As we can see in the output, the function has returned 4 indicating that there are only 4 unique values in the Index. Example #2: Use Index.nunique() function find out all the unique values in the Index. Also include the missing values i.e. NaN values in the count.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx
Output :
Let’s find the count of unique values in the Index.
# to find the count of unique values.idx.nunique(dropna = False)
Output :As we can see in the output, the function has returned 5 indicating that there are only 5 unique values in the Index. We have also included the missing values in the count.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 543,
"s": 242,
"text": "Pandas Index.nunique() function return number of unique elements in the object. It returns a scalar value which is the count of all the unique values in the Index. By default the NaN values are not included in the count. If dropna parameter is set to be False then it includes NaN value in the count."
},
{
"code": null,
"e": 578,
"s": 543,
"text": "Syntax: Index.nunique(dropna=True)"
},
{
"code": null,
"e": 631,
"s": 578,
"text": "Parameters :dropna : Don’t include NaN in the count."
},
{
"code": null,
"e": 655,
"s": 631,
"text": "Returns : nunique : int"
},
{
"code": null,
"e": 787,
"s": 655,
"text": "Example #1: Use Index.nunique()() function to find the count of unique values in the Index. Do not include NaN values in the count."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx",
"e": 977,
"s": 787,
"text": null
},
{
"code": null,
"e": 986,
"s": 977,
"text": "Output :"
},
{
"code": null,
"e": 1038,
"s": 986,
"text": "Let’s find the count of unique values in the Index."
},
{
"code": "# to find the count of unique values.idx.nunique(dropna = True)",
"e": 1102,
"s": 1038,
"text": null
},
{
"code": null,
"e": 1376,
"s": 1102,
"text": "Output :As we can see in the output, the function has returned 4 indicating that there are only 4 unique values in the Index. Example #2: Use Index.nunique() function find out all the unique values in the Index. Also include the missing values i.e. NaN values in the count."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx",
"e": 1566,
"s": 1376,
"text": null
},
{
"code": null,
"e": 1575,
"s": 1566,
"text": "Output :"
},
{
"code": null,
"e": 1627,
"s": 1575,
"text": "Let’s find the count of unique values in the Index."
},
{
"code": "# to find the count of unique values.idx.nunique(dropna = False)",
"e": 1692,
"s": 1627,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1692,
"text": "Output :As we can see in the output, the function has returned 5 indicating that there are only 5 unique values in the Index. We have also included the missing values in the count."
},
{
"code": null,
"e": 1896,
"s": 1873,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 1910,
"s": 1896,
"text": "Python-pandas"
},
{
"code": null,
"e": 1917,
"s": 1910,
"text": "Python"
}
] |
PHP | cURL | 04 Oct, 2021
The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl.
libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcurl supports TTPS certificates, HTTP POST, HTTP PUT, FTP uploading, kerberos, HTTP based upload, proxies, cookies, user & password authentication, file transfer resume, HTTP proxy tunneling and many more. libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported and fast.
curl: A command line tool for getting or sending files using URL syntax. Since curl uses libcurl, it supports a range of common internal protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, TELNET, DICT, and FILE.
What is PHP/cURL? The module for PHP that makes it possible for PHP programs to access curl functions within PHP. cURL support is enabled in PHP, the phpinfo() function will display in its output. You are requested to check it before writing your first simple program in PHP.
php
<?php phpinfo(); ?>
Simple Uses: The simplest and most common request/operation made using HTTP is to get a URL. The URL itself can refer to a webpage, an image or a file. The client issues a GET request to the server and receives the document it asked for.Some basic cURL functions:
The curl_init() function will initialize a new session and return a cURL handle.
curl_exec($ch) function should be called after initialize a cURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by ch).
curl_setopt($ch, option, value) set an option for a cURL session identified by the ch parameter. Option specifies which option is to set, and value specifies the value for the given option.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) return page contents. If set 0 then no output will be returned.
curl_setopt($ch, CURLOPT_URL, $url) pass URL as a parameter. This is your target server website address. This is the URL you want to get from the internet.
curl_exec($ch) grab URL and pass it to the variable for showing output.
curl_close($ch) close curl resource, and free up system resources.
Example:
php
<?php // From URL to get webpage contents.$url = "https://www.geeksforgeeks.org/"; // Initialize a CURL session.$ch = curl_init(); // Return Page contents.curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //grab URL and pass it to the variable.curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); echo $result; ?>
Output:
Reference: http://php.net/manual/en/book.curl.php
saurabh1990aror
Web technologies
Articles
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
SQL | Views
SQL Interview Questions
Mutex vs Semaphore
Docker - COPY Instruction
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 261,
"s": 52,
"text": "The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl. "
},
{
"code": null,
"e": 694,
"s": 261,
"text": "libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcurl supports TTPS certificates, HTTP POST, HTTP PUT, FTP uploading, kerberos, HTTP based upload, proxies, cookies, user & password authentication, file transfer resume, HTTP proxy tunneling and many more. libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported and fast."
},
{
"code": null,
"e": 918,
"s": 694,
"text": "curl: A command line tool for getting or sending files using URL syntax. Since curl uses libcurl, it supports a range of common internal protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, TELNET, DICT, and FILE."
},
{
"code": null,
"e": 1196,
"s": 918,
"text": "What is PHP/cURL? The module for PHP that makes it possible for PHP programs to access curl functions within PHP. cURL support is enabled in PHP, the phpinfo() function will display in its output. You are requested to check it before writing your first simple program in PHP. "
},
{
"code": null,
"e": 1200,
"s": 1196,
"text": "php"
},
{
"code": "<?php phpinfo(); ?>",
"e": 1220,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1220,
"text": "Simple Uses: The simplest and most common request/operation made using HTTP is to get a URL. The URL itself can refer to a webpage, an image or a file. The client issues a GET request to the server and receives the document it asked for.Some basic cURL functions: "
},
{
"code": null,
"e": 1567,
"s": 1486,
"text": "The curl_init() function will initialize a new session and return a cURL handle."
},
{
"code": null,
"e": 1761,
"s": 1567,
"text": "curl_exec($ch) function should be called after initialize a cURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by ch)."
},
{
"code": null,
"e": 1951,
"s": 1761,
"text": "curl_setopt($ch, option, value) set an option for a cURL session identified by the ch parameter. Option specifies which option is to set, and value specifies the value for the given option."
},
{
"code": null,
"e": 2059,
"s": 1951,
"text": "curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) return page contents. If set 0 then no output will be returned."
},
{
"code": null,
"e": 2215,
"s": 2059,
"text": "curl_setopt($ch, CURLOPT_URL, $url) pass URL as a parameter. This is your target server website address. This is the URL you want to get from the internet."
},
{
"code": null,
"e": 2287,
"s": 2215,
"text": "curl_exec($ch) grab URL and pass it to the variable for showing output."
},
{
"code": null,
"e": 2354,
"s": 2287,
"text": "curl_close($ch) close curl resource, and free up system resources."
},
{
"code": null,
"e": 2365,
"s": 2354,
"text": "Example: "
},
{
"code": null,
"e": 2369,
"s": 2365,
"text": "php"
},
{
"code": "<?php // From URL to get webpage contents.$url = \"https://www.geeksforgeeks.org/\"; // Initialize a CURL session.$ch = curl_init(); // Return Page contents.curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //grab URL and pass it to the variable.curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); echo $result; ?>",
"e": 2688,
"s": 2369,
"text": null
},
{
"code": null,
"e": 2698,
"s": 2688,
"text": "Output: "
},
{
"code": null,
"e": 2749,
"s": 2698,
"text": "Reference: http://php.net/manual/en/book.curl.php "
},
{
"code": null,
"e": 2765,
"s": 2749,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2782,
"s": 2765,
"text": "Web technologies"
},
{
"code": null,
"e": 2791,
"s": 2782,
"text": "Articles"
},
{
"code": null,
"e": 2808,
"s": 2791,
"text": "Web Technologies"
},
{
"code": null,
"e": 2906,
"s": 2808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2943,
"s": 2906,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 2955,
"s": 2943,
"text": "SQL | Views"
},
{
"code": null,
"e": 2979,
"s": 2955,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2998,
"s": 2979,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 3024,
"s": 2998,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3057,
"s": 3024,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3119,
"s": 3057,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3180,
"s": 3119,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3222,
"s": 3180,
"text": "Roadmap to Learn JavaScript For Beginners"
}
] |
How to check if a set contains an element in Python? | 28 Nov, 2021
In this article, we will discuss how to check if a set contains an element in python.
This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is present in set , otherwise False.
Syntax:
element in set
where
set is an input set
element is the value to be checked
Example: Check if an element is present in a set
Python3
# import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # check 7058print(7058 in data) # check 7059print(7059 in data) # check 7071print(7071 in data)
Output:
True
True
False
This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is not present in set, otherwise False
Syntax:
element not in set
where,
set is an input set
element is the value to be checked
Example: Check if an element is present in a set
Python3
# import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # check 7058print(7058 not in data) # check 7059print(7059 not in data) # check 7071print(7071 not in data)
Output:
False
False
True
Picked
Python set-programs
python-set
Python
Python Programs
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "In this article, we will discuss how to check if a set contains an element in python."
},
{
"code": null,
"e": 287,
"s": 114,
"text": "This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is present in set , otherwise False."
},
{
"code": null,
"e": 295,
"s": 287,
"text": "Syntax:"
},
{
"code": null,
"e": 310,
"s": 295,
"text": "element in set"
},
{
"code": null,
"e": 316,
"s": 310,
"text": "where"
},
{
"code": null,
"e": 336,
"s": 316,
"text": "set is an input set"
},
{
"code": null,
"e": 371,
"s": 336,
"text": "element is the value to be checked"
},
{
"code": null,
"e": 420,
"s": 371,
"text": "Example: Check if an element is present in a set"
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Python3"
},
{
"code": "# import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # check 7058print(7058 in data) # check 7059print(7059 in data) # check 7071print(7071 in data)",
"e": 640,
"s": 428,
"text": null
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Output:"
},
{
"code": null,
"e": 664,
"s": 648,
"text": "True\nTrue\nFalse"
},
{
"code": null,
"e": 839,
"s": 664,
"text": "This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is not present in set, otherwise False"
},
{
"code": null,
"e": 847,
"s": 839,
"text": "Syntax:"
},
{
"code": null,
"e": 866,
"s": 847,
"text": "element not in set"
},
{
"code": null,
"e": 873,
"s": 866,
"text": "where,"
},
{
"code": null,
"e": 893,
"s": 873,
"text": "set is an input set"
},
{
"code": null,
"e": 928,
"s": 893,
"text": "element is the value to be checked"
},
{
"code": null,
"e": 977,
"s": 928,
"text": "Example: Check if an element is present in a set"
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Python3"
},
{
"code": "# import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # check 7058print(7058 not in data) # check 7059print(7059 not in data) # check 7071print(7071 not in data)",
"e": 1209,
"s": 985,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1234,
"s": 1217,
"text": "False\nFalse\nTrue"
},
{
"code": null,
"e": 1241,
"s": 1234,
"text": "Picked"
},
{
"code": null,
"e": 1261,
"s": 1241,
"text": "Python set-programs"
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": "python-set"
},
{
"code": null,
"e": 1279,
"s": 1272,
"text": "Python"
},
{
"code": null,
"e": 1295,
"s": 1279,
"text": "Python Programs"
},
{
"code": null,
"e": 1306,
"s": 1295,
"text": "python-set"
}
] |
Java Guava | Chars.contains() method with Examples | 31 Jan, 2019
The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter.
Syntax:
public static boolean contains(char[] array,
char target)
Parameters: This method accepts two mandatory parameters:
array: which is an array of char values in which the target value is to be searched.
target: which is the char value to be searched for presence in the array.
Return Value: This method returns a boolean value stating whether the target char value is present in the specified char array. It returns True if the target value is present in the array. Else it returns False.
Below programs illustrate the use of contains() method:
Example 1:
// Java code to show implementation of// Guava's Chars.contains() method import com.google.common.primitives.Chars;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a character array char[] arr = { 'g', 'e', 'e', 'k', 's' }; char target = 'k'; // Using Chars.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Chars.contains(arr, target)) System.out.println("Target is present" + " in the array"); else System.out.println("Target is not present" + " in the array"); }}
Target is present in the array
Example 2:
// Java code to show implementation of// Guava's Chars.contains() method import com.google.common.primitives.Chars;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a character array char[] arr = { 'g', 'e', 'e', 'k', 's' }; char target = 'a'; // Using Chars.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Chars.contains(arr, target)) System.out.println("Target is present" + " in the array"); else System.out.println("Target is not present" + " in the array"); }}
Target is not present in the array
Reference: https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#contains(char[], %20char)
Guava-Chars
Guava-Functions
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter."
},
{
"code": null,
"e": 289,
"s": 281,
"text": "Syntax:"
},
{
"code": null,
"e": 380,
"s": 289,
"text": "public static boolean contains(char[] array, \n char target)\n"
},
{
"code": null,
"e": 438,
"s": 380,
"text": "Parameters: This method accepts two mandatory parameters:"
},
{
"code": null,
"e": 523,
"s": 438,
"text": "array: which is an array of char values in which the target value is to be searched."
},
{
"code": null,
"e": 597,
"s": 523,
"text": "target: which is the char value to be searched for presence in the array."
},
{
"code": null,
"e": 809,
"s": 597,
"text": "Return Value: This method returns a boolean value stating whether the target char value is present in the specified char array. It returns True if the target value is present in the array. Else it returns False."
},
{
"code": null,
"e": 865,
"s": 809,
"text": "Below programs illustrate the use of contains() method:"
},
{
"code": null,
"e": 876,
"s": 865,
"text": "Example 1:"
},
{
"code": "// Java code to show implementation of// Guava's Chars.contains() method import com.google.common.primitives.Chars;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a character array char[] arr = { 'g', 'e', 'e', 'k', 's' }; char target = 'k'; // Using Chars.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Chars.contains(arr, target)) System.out.println(\"Target is present\" + \" in the array\"); else System.out.println(\"Target is not present\" + \" in the array\"); }}",
"e": 1652,
"s": 876,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1652,
"text": "Target is present in the array\n"
},
{
"code": null,
"e": 1695,
"s": 1684,
"text": "Example 2:"
},
{
"code": "// Java code to show implementation of// Guava's Chars.contains() method import com.google.common.primitives.Chars;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a character array char[] arr = { 'g', 'e', 'e', 'k', 's' }; char target = 'a'; // Using Chars.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Chars.contains(arr, target)) System.out.println(\"Target is present\" + \" in the array\"); else System.out.println(\"Target is not present\" + \" in the array\"); }}",
"e": 2471,
"s": 1695,
"text": null
},
{
"code": null,
"e": 2507,
"s": 2471,
"text": "Target is not present in the array\n"
},
{
"code": null,
"e": 2638,
"s": 2507,
"text": "Reference: https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#contains(char[], %20char)"
},
{
"code": null,
"e": 2650,
"s": 2638,
"text": "Guava-Chars"
},
{
"code": null,
"e": 2666,
"s": 2650,
"text": "Guava-Functions"
},
{
"code": null,
"e": 2681,
"s": 2666,
"text": "Java-Functions"
},
{
"code": null,
"e": 2692,
"s": 2681,
"text": "java-guava"
},
{
"code": null,
"e": 2697,
"s": 2692,
"text": "Java"
},
{
"code": null,
"e": 2702,
"s": 2697,
"text": "Java"
},
{
"code": null,
"e": 2800,
"s": 2702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2815,
"s": 2800,
"text": "Stream In Java"
},
{
"code": null,
"e": 2836,
"s": 2815,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2857,
"s": 2836,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2876,
"s": 2857,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2893,
"s": 2876,
"text": "Generics in Java"
},
{
"code": null,
"e": 2923,
"s": 2893,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2939,
"s": 2923,
"text": "Strings in Java"
},
{
"code": null,
"e": 2965,
"s": 2939,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2985,
"s": 2965,
"text": "Abstraction in Java"
}
] |
Do and don’t when using transformation to improve CNN deep learning model | by Chien Vu | Towards Data Science | According to wikipedia [1]
Data transformation is the process of converting data from one format or structure into another format or structure.
In computer vision, Data Augmentation is very important to regularize your network and increase the size of your training set. There are many Data transformation techniques (rotation, flip, crop, etc...) that can change the images’ pixel values but still keep almost the whole information of the image, so that human could hardly tell whether it was augmented or not. This forces the model to be more flexible with the large variation of object inside the image, regarding less on position, orientation, size, color,...Models trained with data augmentation usually generalize better but the remaining question is to what extend the Data Transformation can improve the performance of CNN model on image dataset.
Let’s take a look at some Data transformation techniques supporting by Pytorch in Torchvision that can help you to conduct augmentation on your ơn images. I also provide an experiment with real image dataset to show the performance when applying different approaches.
torchvision.transforms.CenterCrop(size): It’s similar to zooming in the center of image. It will crop the given image to a desired output size and position (size can be square or rectangle).
torchvision.transforms.Pad(padding): It equals to zooming out the image. It will create a pad outside the given image on all sides with the certain value.
torchvision.transforms.RandomCrop(size, padding): this function will crop the given image at random locations to create a bunch of images for training.
torchvision.transforms.RandomHorizontalFlip(p): This function will flip horizontally the given image randomly with a given probability.
torchvision.transforms.RandomVerticalFlip(p):This function will flip the given image vertically in random with a given probability.
torchvision.transforms.RandomPerspective(distortion_scale, p): This unction will perform perspective transformation of the given image randomly given a probability. It reduces the effect of perspective for model learning by distorting whole the image.
torchvision.transforms.Grayscale(num_output_channels): Convert image to grayscale. It’s sometimes helpful for CNN model to train faster with single channel and to learn more easily the pattern of images.
torchvision.transforms.ColorJitter(brightness, contrast, saturation, hue):I can randomly change the brightness, contrast and saturation of an image
torchvision.transforms.Normalize(mean, std): Normalize a tensor image with mean and standard deviation. It will help the CNN model to easily convert to global minimum or quickly reduce the loss. If you want to know why data normalization is essential and how to conduct normalization to improve the performance of machine learning model, you can refer to the below blog.
towardsdatascience.com
torchvision.transforms.RandomErasing(p, scale, ratio, value) randomly selects a rectangle region in the image and erases its pixels. This method penalizes the CNN model and helps to prevent the over-fitting phenomenon when training.
Augmentation can also be applied for NLP to improve performance. For example: randomly insert, swap, replace words in the sentences; using an intermediate language in translation (Back translation), shuffle sentences.
There are several libraries providing excellent augmentation modules such as Albumentations, NLPAug... Below is a great article for further exploration from neptune.ai.
neptune.ai
Let’s discuss the effect of Transformation technique on CNN model. The dataset used in this experiment is Dog Breed Identification from Kaggle competition which provided a strictly canine subset of ImageNet in order to practice fine-grained image categorization. This dataset includes 120 breeds of dogs with total 10,222 images. We split data to train/valid at 0.8/0.2 ratio.
In this article, pre-trained ResNet [2] (Residual Networks) model will be used as backbone for Classification CNN model. ResNet is one of the SOTA pre-trained models that reveals good results on a wide range of Computer Vision tasks. Instead of learning input features of image directly with a function H(x) (A stacking of multi-layer perceptron networks), the main idea of ResNet is to provide a residual function that can reframe H(x) = F(x)+x, where F(x) and x represent the stacked non-linear layers and the identity function (input=output) respectively. This idea can solve the degradation problem of deep neuron networks (vanishing gradient) because it is easier to optimize the residual mapping function F(x) than the original one.
First, we will load the original data.
# Create a custom Dataset class to read in data from dataframeclass BreedDogDataset(Dataset): def __init__(self, dataframe, root_dir, transform=None): self.dataframe = dataframe self.root_dir = root_dir self.transform = transform def __len__(self): return (len(self.dataframe)) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.dataframe.iloc[idx, 0]) image = Image.open(img_name) target = self.dataframe.iloc[idx, 1] target_processed = breeds_processed_dict[target] if self.transform: image = self.transform(image) sample = (image, target_processed) return sampletransform = transforms.Compose([transforms.Resize((255, 255)), transforms.ToTensor()])train_ds = BreedDogDataset(df_train,TRAIN_DIR, transform=transform)val_ds = BreedDogDataset(df_val,TRAIN_DIR, transform=transform)
Then we create a model like this structure:
# load pre-trained modelconv_base = models.resnet50(pretrained=True)# create a new model classclass Model(nn.Module): def __init__(self, base_model, output): super(Model, self).__init__() self.base_model = base_model self.output = output self.fc1 = nn.Linear(n_outs, 512) self.fc2 = nn.Linear(512, output) self.dropout = nn.Dropout(0.5) def forward(self, image): x = self.base_model(image) x = self.dropout(x) x = F.relu(self.fc1(x)) x = self.dropout(x) outs = self.fc2(x) return outs
One of the most important hyperparameters to tune in a deep learning model is the learning rate. Picking the right learning rate is very important, if it’s too high, the model will face with diverge problem but if it’s too low, the model will take a lot of time to converge. The idea is that we can find a good learning rate by training the model for a few hundred iterations and then based on the learning curve, we pick up a good learning rate. There are a lot of Learning Rate Scheduling techniques, for example, Power scheduling, Exponential scheduling, 1Cycle Scheduling, constant scheduling,... In this experiment, we will apply 1Cycle Scheduling. In Leslie Smith’s paper, this technique was proved to push up remarkably the training time. You can check out this blog for more explanation.
towardsdatascience.com
According to the above learning curve result, it shows that the lower bound is 0.9E-04, I rounded values to 1.0E-03. Now, I can fine-tune the pre-trained ResNet50 on the new image dataset by defining a range of learning rates using the rule of thumb: starting at a rate that is one order lower than the learning rate where loss is minimum and ending at the “secure” rate 1E-03.
After training with 5 epochs, we got the accuracy in valid set is 83.284 %
Train loss and valid loss are shown below. It’s seen that both values decreased. From the 4th to 5th epoch, both loss and accuracy were almost constant. It means the model has learned relatively everything from data, all the good information that helps the model to distinguish breed dog was captured.
Then we check the top 6 highest loss images. We can see that one of the reasons for the model misclassifies some images is that the dog breed prediction is similar to other different breed samples, this is even impossible for humans to differentiate them. To solve this problem, the Transformation technique is very promising to help the model to learn deeply the pattern of each breed. Another issue is that some pictures have 2 different dogs within but the label shows only one. A wrong label is also another issue. These problems cannot be solved and it seems to be an outlier case.
Let’s apply some Transformation technique in this dataset.
mean = [0.4766, 0.4527, 0.3926]std = [0.2275, 0.2224, 0.2210]# define transform functiontransforms_train = transforms.Compose([ transforms.Pad(25, padding_mode='symmetric'), transforms.RandomHorizontalFlip(), transforms.RandomRotation(10), transforms.ToTensor(), transforms.Normalize(mean, std), transforms.RandomErasing(p=0.75,scale=(0.02, 0.1),value=1.0, inplace=False)])transforms_val = transforms.Compose([ transforms.Resize((255, 255)), transforms.ToTensor(), transforms.Normalize(mean, std)])# load in the temporary dataset from the original dataframe with transformtrain_ds = BreedDogDataset(df_train,TRAIN_DIR, transform=transforms_train)val_ds = BreedDogDataset(df_val,TRAIN_DIR, transform=transforms_val)
After training with 5 epochs on the transformed dataset, we got the accuracy in valid set reached 0.817, a a slight degrading compared to the original image.
The new train loss and valid loss are shown below. The distance from train loss and valid loss increased vs the above model while the accuracy in the 4th and 5th epoch slightly dropped. This indicates that the new model faced an underfitting problem. Generally, transformation does help the model to prevent the overfitting issue. However in this case, because the previous model didn’t have the overfitting issue, and the training loss was even higher than valid loss, when applying the transformation, there was no improvement.
Let’s see the top 6 images that have the highest loss. We can see that some confusing images now could be classified but some haven’t. However, this problem cannot be solved and some outliers still affect the performance of model.
The main purpose of this blog is to introduce some techniques to transform images. Fundamentally, this will help to avoid the overfitting problem as well as to increase the number of training data for the CNN model. But it doesn’t mean that Transformation will always improve the model’s accuracy, it must depend on the input image (satellite, bacteria, animal, objects,..) and model structure. Many Deep-ML practitioners meet this problem, they usually did transform before checking how well their model can learn from their original image. If the model is underfitting the original image, transforming data wasn’t help to solve the problem, in other words, it will decrease the accuracy of your model. Therefore, we have to do step by step to diagnose our model and analysis the results visualize via the worst predictions.
You can contact me if you want further discussion. Here is my LinkedIn
Enjoy!!! 👦🏻
[1] https://en.wikipedia.org/wiki/Data_transformation
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun, Deep Residual Learning for Image Recognition, 2015. | [
{
"code": null,
"e": 199,
"s": 172,
"text": "According to wikipedia [1]"
},
{
"code": null,
"e": 316,
"s": 199,
"text": "Data transformation is the process of converting data from one format or structure into another format or structure."
},
{
"code": null,
"e": 1027,
"s": 316,
"text": "In computer vision, Data Augmentation is very important to regularize your network and increase the size of your training set. There are many Data transformation techniques (rotation, flip, crop, etc...) that can change the images’ pixel values but still keep almost the whole information of the image, so that human could hardly tell whether it was augmented or not. This forces the model to be more flexible with the large variation of object inside the image, regarding less on position, orientation, size, color,...Models trained with data augmentation usually generalize better but the remaining question is to what extend the Data Transformation can improve the performance of CNN model on image dataset."
},
{
"code": null,
"e": 1296,
"s": 1027,
"text": "Let’s take a look at some Data transformation techniques supporting by Pytorch in Torchvision that can help you to conduct augmentation on your ơn images. I also provide an experiment with real image dataset to show the performance when applying different approaches."
},
{
"code": null,
"e": 1487,
"s": 1296,
"text": "torchvision.transforms.CenterCrop(size): It’s similar to zooming in the center of image. It will crop the given image to a desired output size and position (size can be square or rectangle)."
},
{
"code": null,
"e": 1642,
"s": 1487,
"text": "torchvision.transforms.Pad(padding): It equals to zooming out the image. It will create a pad outside the given image on all sides with the certain value."
},
{
"code": null,
"e": 1794,
"s": 1642,
"text": "torchvision.transforms.RandomCrop(size, padding): this function will crop the given image at random locations to create a bunch of images for training."
},
{
"code": null,
"e": 1930,
"s": 1794,
"text": "torchvision.transforms.RandomHorizontalFlip(p): This function will flip horizontally the given image randomly with a given probability."
},
{
"code": null,
"e": 2062,
"s": 1930,
"text": "torchvision.transforms.RandomVerticalFlip(p):This function will flip the given image vertically in random with a given probability."
},
{
"code": null,
"e": 2314,
"s": 2062,
"text": "torchvision.transforms.RandomPerspective(distortion_scale, p): This unction will perform perspective transformation of the given image randomly given a probability. It reduces the effect of perspective for model learning by distorting whole the image."
},
{
"code": null,
"e": 2518,
"s": 2314,
"text": "torchvision.transforms.Grayscale(num_output_channels): Convert image to grayscale. It’s sometimes helpful for CNN model to train faster with single channel and to learn more easily the pattern of images."
},
{
"code": null,
"e": 2666,
"s": 2518,
"text": "torchvision.transforms.ColorJitter(brightness, contrast, saturation, hue):I can randomly change the brightness, contrast and saturation of an image"
},
{
"code": null,
"e": 3037,
"s": 2666,
"text": "torchvision.transforms.Normalize(mean, std): Normalize a tensor image with mean and standard deviation. It will help the CNN model to easily convert to global minimum or quickly reduce the loss. If you want to know why data normalization is essential and how to conduct normalization to improve the performance of machine learning model, you can refer to the below blog."
},
{
"code": null,
"e": 3060,
"s": 3037,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3293,
"s": 3060,
"text": "torchvision.transforms.RandomErasing(p, scale, ratio, value) randomly selects a rectangle region in the image and erases its pixels. This method penalizes the CNN model and helps to prevent the over-fitting phenomenon when training."
},
{
"code": null,
"e": 3511,
"s": 3293,
"text": "Augmentation can also be applied for NLP to improve performance. For example: randomly insert, swap, replace words in the sentences; using an intermediate language in translation (Back translation), shuffle sentences."
},
{
"code": null,
"e": 3680,
"s": 3511,
"text": "There are several libraries providing excellent augmentation modules such as Albumentations, NLPAug... Below is a great article for further exploration from neptune.ai."
},
{
"code": null,
"e": 3691,
"s": 3680,
"text": "neptune.ai"
},
{
"code": null,
"e": 4068,
"s": 3691,
"text": "Let’s discuss the effect of Transformation technique on CNN model. The dataset used in this experiment is Dog Breed Identification from Kaggle competition which provided a strictly canine subset of ImageNet in order to practice fine-grained image categorization. This dataset includes 120 breeds of dogs with total 10,222 images. We split data to train/valid at 0.8/0.2 ratio."
},
{
"code": null,
"e": 4807,
"s": 4068,
"text": "In this article, pre-trained ResNet [2] (Residual Networks) model will be used as backbone for Classification CNN model. ResNet is one of the SOTA pre-trained models that reveals good results on a wide range of Computer Vision tasks. Instead of learning input features of image directly with a function H(x) (A stacking of multi-layer perceptron networks), the main idea of ResNet is to provide a residual function that can reframe H(x) = F(x)+x, where F(x) and x represent the stacked non-linear layers and the identity function (input=output) respectively. This idea can solve the degradation problem of deep neuron networks (vanishing gradient) because it is easier to optimize the residual mapping function F(x) than the original one."
},
{
"code": null,
"e": 4846,
"s": 4807,
"text": "First, we will load the original data."
},
{
"code": null,
"e": 5806,
"s": 4846,
"text": "# Create a custom Dataset class to read in data from dataframeclass BreedDogDataset(Dataset): def __init__(self, dataframe, root_dir, transform=None): self.dataframe = dataframe self.root_dir = root_dir self.transform = transform def __len__(self): return (len(self.dataframe)) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.dataframe.iloc[idx, 0]) image = Image.open(img_name) target = self.dataframe.iloc[idx, 1] target_processed = breeds_processed_dict[target] if self.transform: image = self.transform(image) sample = (image, target_processed) return sampletransform = transforms.Compose([transforms.Resize((255, 255)), transforms.ToTensor()])train_ds = BreedDogDataset(df_train,TRAIN_DIR, transform=transform)val_ds = BreedDogDataset(df_val,TRAIN_DIR, transform=transform)"
},
{
"code": null,
"e": 5850,
"s": 5806,
"text": "Then we create a model like this structure:"
},
{
"code": null,
"e": 6429,
"s": 5850,
"text": "# load pre-trained modelconv_base = models.resnet50(pretrained=True)# create a new model classclass Model(nn.Module): def __init__(self, base_model, output): super(Model, self).__init__() self.base_model = base_model self.output = output self.fc1 = nn.Linear(n_outs, 512) self.fc2 = nn.Linear(512, output) self.dropout = nn.Dropout(0.5) def forward(self, image): x = self.base_model(image) x = self.dropout(x) x = F.relu(self.fc1(x)) x = self.dropout(x) outs = self.fc2(x) return outs"
},
{
"code": null,
"e": 7225,
"s": 6429,
"text": "One of the most important hyperparameters to tune in a deep learning model is the learning rate. Picking the right learning rate is very important, if it’s too high, the model will face with diverge problem but if it’s too low, the model will take a lot of time to converge. The idea is that we can find a good learning rate by training the model for a few hundred iterations and then based on the learning curve, we pick up a good learning rate. There are a lot of Learning Rate Scheduling techniques, for example, Power scheduling, Exponential scheduling, 1Cycle Scheduling, constant scheduling,... In this experiment, we will apply 1Cycle Scheduling. In Leslie Smith’s paper, this technique was proved to push up remarkably the training time. You can check out this blog for more explanation."
},
{
"code": null,
"e": 7248,
"s": 7225,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7626,
"s": 7248,
"text": "According to the above learning curve result, it shows that the lower bound is 0.9E-04, I rounded values to 1.0E-03. Now, I can fine-tune the pre-trained ResNet50 on the new image dataset by defining a range of learning rates using the rule of thumb: starting at a rate that is one order lower than the learning rate where loss is minimum and ending at the “secure” rate 1E-03."
},
{
"code": null,
"e": 7701,
"s": 7626,
"text": "After training with 5 epochs, we got the accuracy in valid set is 83.284 %"
},
{
"code": null,
"e": 8003,
"s": 7701,
"text": "Train loss and valid loss are shown below. It’s seen that both values decreased. From the 4th to 5th epoch, both loss and accuracy were almost constant. It means the model has learned relatively everything from data, all the good information that helps the model to distinguish breed dog was captured."
},
{
"code": null,
"e": 8590,
"s": 8003,
"text": "Then we check the top 6 highest loss images. We can see that one of the reasons for the model misclassifies some images is that the dog breed prediction is similar to other different breed samples, this is even impossible for humans to differentiate them. To solve this problem, the Transformation technique is very promising to help the model to learn deeply the pattern of each breed. Another issue is that some pictures have 2 different dogs within but the label shows only one. A wrong label is also another issue. These problems cannot be solved and it seems to be an outlier case."
},
{
"code": null,
"e": 8649,
"s": 8590,
"text": "Let’s apply some Transformation technique in this dataset."
},
{
"code": null,
"e": 9392,
"s": 8649,
"text": "mean = [0.4766, 0.4527, 0.3926]std = [0.2275, 0.2224, 0.2210]# define transform functiontransforms_train = transforms.Compose([ transforms.Pad(25, padding_mode='symmetric'), transforms.RandomHorizontalFlip(), transforms.RandomRotation(10), transforms.ToTensor(), transforms.Normalize(mean, std), transforms.RandomErasing(p=0.75,scale=(0.02, 0.1),value=1.0, inplace=False)])transforms_val = transforms.Compose([ transforms.Resize((255, 255)), transforms.ToTensor(), transforms.Normalize(mean, std)])# load in the temporary dataset from the original dataframe with transformtrain_ds = BreedDogDataset(df_train,TRAIN_DIR, transform=transforms_train)val_ds = BreedDogDataset(df_val,TRAIN_DIR, transform=transforms_val)"
},
{
"code": null,
"e": 9550,
"s": 9392,
"text": "After training with 5 epochs on the transformed dataset, we got the accuracy in valid set reached 0.817, a a slight degrading compared to the original image."
},
{
"code": null,
"e": 10080,
"s": 9550,
"text": "The new train loss and valid loss are shown below. The distance from train loss and valid loss increased vs the above model while the accuracy in the 4th and 5th epoch slightly dropped. This indicates that the new model faced an underfitting problem. Generally, transformation does help the model to prevent the overfitting issue. However in this case, because the previous model didn’t have the overfitting issue, and the training loss was even higher than valid loss, when applying the transformation, there was no improvement."
},
{
"code": null,
"e": 10311,
"s": 10080,
"text": "Let’s see the top 6 images that have the highest loss. We can see that some confusing images now could be classified but some haven’t. However, this problem cannot be solved and some outliers still affect the performance of model."
},
{
"code": null,
"e": 11137,
"s": 10311,
"text": "The main purpose of this blog is to introduce some techniques to transform images. Fundamentally, this will help to avoid the overfitting problem as well as to increase the number of training data for the CNN model. But it doesn’t mean that Transformation will always improve the model’s accuracy, it must depend on the input image (satellite, bacteria, animal, objects,..) and model structure. Many Deep-ML practitioners meet this problem, they usually did transform before checking how well their model can learn from their original image. If the model is underfitting the original image, transforming data wasn’t help to solve the problem, in other words, it will decrease the accuracy of your model. Therefore, we have to do step by step to diagnose our model and analysis the results visualize via the worst predictions."
},
{
"code": null,
"e": 11208,
"s": 11137,
"text": "You can contact me if you want further discussion. Here is my LinkedIn"
},
{
"code": null,
"e": 11220,
"s": 11208,
"text": "Enjoy!!! 👦🏻"
},
{
"code": null,
"e": 11274,
"s": 11220,
"text": "[1] https://en.wikipedia.org/wiki/Data_transformation"
}
] |
OUT a8 instruction in 8085 Microprocessor | In 8085 Instruction set, OUT is a mnemonic that stands for OUTput Accumulator contents to an output port whose8-bit address is indicated in the instruction as a8. It occupies 2 Bytes in the memory. First Byte specifies the opcode, and the next Byte provides the 8-bit port address.
OUT F0H is an example instruction of this type. The result of execution of this instruction is shown below with an example.
OUT instruction is the only instruction using whichAccumulator contents can be sent out to an output port. A possible chip select circuit to connect an output port with an address as F0His as shown in the following Fig.
Chip select circuit for output port F0H
Here as the port address is F0H so the bits ranging from A7 to A0 should have the bit pattern
A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1 0 0 0 0, with WR* = 0, and IO/M* = 1
A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1 0 0 0 0, with WR* = 0, and IO/M* = 1
All these bits will pass through a NAND Gate to product the output logic 1 as Chip-Select (CS), and so the output port chip gets selected. Thus, the chip responds when the 8085 sends out the address as F0H, IO/M* as 1, and WR* as 0. In other words, we consider that it is having the output port number F0H.
Notice that it is possible to have an input port with the address F0H, and an output port with the same address F0H. When the 8085 sends out the address as EFH and IO/M* as 1, only one of them is selected based on the RD* and WR* signal status values. Thus, it is possible to have a total of 256 input ports and a total of 256output ports.
The timing diagram against this instruction OUT F0H execution is as follows –
Summary − So this instruction OUT requires 2-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, I/O write) and 10 T-States for execution as shown in the timing diagram. | [
{
"code": null,
"e": 1345,
"s": 1062,
"text": "In 8085 Instruction set, OUT is a mnemonic that stands for OUTput Accumulator contents to an output port whose8-bit address is indicated in the instruction as a8. It occupies 2 Bytes in the memory. First Byte specifies the opcode, and the next Byte provides the 8-bit port address. "
},
{
"code": null,
"e": 1469,
"s": 1345,
"text": "OUT F0H is an example instruction of this type. The result of execution of this instruction is shown below with an example."
},
{
"code": null,
"e": 1689,
"s": 1469,
"text": "OUT instruction is the only instruction using whichAccumulator contents can be sent out to an output port. A possible chip select circuit to connect an output port with an address as F0His as shown in the following Fig."
},
{
"code": null,
"e": 1729,
"s": 1689,
"text": "Chip select circuit for output port F0H"
},
{
"code": null,
"e": 1823,
"s": 1729,
"text": "Here as the port address is F0H so the bits ranging from A7 to A0 should have the bit pattern"
},
{
"code": null,
"e": 1894,
"s": 1823,
"text": "A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1 0 0 0 0, with WR* = 0, and IO/M* = 1"
},
{
"code": null,
"e": 1965,
"s": 1894,
"text": "A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1 0 0 0 0, with WR* = 0, and IO/M* = 1"
},
{
"code": null,
"e": 2272,
"s": 1965,
"text": "All these bits will pass through a NAND Gate to product the output logic 1 as Chip-Select (CS), and so the output port chip gets selected. Thus, the chip responds when the 8085 sends out the address as F0H, IO/M* as 1, and WR* as 0. In other words, we consider that it is having the output port number F0H."
},
{
"code": null,
"e": 2612,
"s": 2272,
"text": "Notice that it is possible to have an input port with the address F0H, and an output port with the same address F0H. When the 8085 sends out the address as EFH and IO/M* as 1, only one of them is selected based on the RD* and WR* signal status values. Thus, it is possible to have a total of 256 input ports and a total of 256output ports."
},
{
"code": null,
"e": 2690,
"s": 2612,
"text": "The timing diagram against this instruction OUT F0H execution is as follows –"
},
{
"code": null,
"e": 2860,
"s": 2690,
"text": "Summary − So this instruction OUT requires 2-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, I/O write) and 10 T-States for execution as shown in the timing diagram."
}
] |
CICS - Nohandle | Nohandle can be specified for any CICS command. It will cause no action to be taken for any exceptional conditions that may occur during the execution of the CICS command. This command temporarily deactivates all the other handle conditions. If an exception arises during the execution of the command, the control will be transferred to the next statement after the Command. It can be used with Read, Write, Delete, etc. The syntax of Nohandle is as follows −
EXEC CICS
program statements
NOHANDLE
END-EXEC.
Following is the example of Nohandle command. We are using it with a Read statement. If Read statement fails, it will not abend the program.
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
PROCEDURE DIVISION.
EXEC CICS READ
FILE('FILE1')
INTO(WS-FILE-REC)
RIDFLD(WS-STDID)
NOHANDLE
END-EXEC.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2386,
"s": 1926,
"text": "Nohandle can be specified for any CICS command. It will cause no action to be taken for any exceptional conditions that may occur during the execution of the CICS command. This command temporarily deactivates all the other handle conditions. If an exception arises during the execution of the command, the control will be transferred to the next statement after the Command. It can be used with Read, Write, Delete, etc. The syntax of Nohandle is as follows −"
},
{
"code": null,
"e": 2445,
"s": 2386,
"text": "EXEC CICS\n program statements\n NOHANDLE \nEND-EXEC.\n"
},
{
"code": null,
"e": 2586,
"s": 2445,
"text": "Following is the example of Nohandle command. We are using it with a Read statement. If Read statement fails, it will not abend the program."
},
{
"code": null,
"e": 2905,
"s": 2586,
"text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nPROCEDURE DIVISION.\nEXEC CICS READ \n FILE('FILE1') \n INTO(WS-FILE-REC) \n RIDFLD(WS-STDID) \n NOHANDLE \nEND-EXEC. "
},
{
"code": null,
"e": 2912,
"s": 2905,
"text": " Print"
},
{
"code": null,
"e": 2923,
"s": 2912,
"text": " Add Notes"
}
] |
How to Set up Python3 the Right Easy Way! | by Salma El Shahawy | Towards Data Science | Update 12/12/2020 — Utilizing pyenv virtualenv to automate activate/deactivate the virtual environment. — Joe Klemmer Suggestion
Recently, I treated myself by purchasing a new Macbook Pro and started setting up my development environment for python. This step is pretty essential because if you did it the wrong way, plenty of issues would arise and distract you from focusing on the actual development work. So, I’ve decided to write a comprehensive guide listing the steps to help others setting their python development environment from scratch. Hence, you have a more comfortable life handling errors. Let’s get started!
For Data Scientist who doesn’t have much experience in the shell command.For Data Scientists/Developers who have errors like import pandas as pd ImportError: No module named pandas
For Data Scientist who doesn’t have much experience in the shell command.
For Data Scientists/Developers who have errors like import pandas as pd ImportError: No module named pandas
3. For Data Scientists/Developers who want to make python3 the default interpreter — type python → get python3 not python 2.7.
4. For Data Scientists who want to start using virtualenv within their machine learning projects to have reproducible notebooks — no more fighting between Dev-ops Engineers and Data Scientists.
5. For future me 😎 in case I treat myself again!
First, you need to do is installing the Xcode if you don’t have one already. This step is necessary because MacOs has to set up some local development utilities, including various tools like git.
The second step would be the magic wand of MacOs, which is homebrew. All you have to do is to copy and paste the link into your terminal and hit return, and that’s it.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Please be sure to navigate to the link before installing and reading what will be installed on your machine to ensure that you are ok with it.
Once installed, you can grab a cup of coffee and start installing whatever you want without worry about anything. Don’t jump to conclusions and begin installing python using brew! Instead, install the environment manager pyenv. Pyenv is a tool to manage the python versions installed in your local machine; it is available to many other operating systems, including Ubuntu, windows.
Stick with one version of python across the project workspace.Switch between python versions peacefully.If you want to use a specific python version like 2.7, for instance.Be able to make python3 as the global interpreter.
Stick with one version of python across the project workspace.
Switch between python versions peacefully.
If you want to use a specific python version like 2.7, for instance.
Be able to make python3 as the global interpreter.
Open terminal and type the following command to install pyenv using homebrew.
Open terminal and type the following command to install pyenv using homebrew.
brew install pyenv
Please note that MacOs use zsh as the default shell command. in case you want to move into bash just run chsh -s/bin/bash in the terminal. Also, you can change it using the GUI in MacOs using this guide.
2. Restart the terminal for changes to take effect or run exec "$SHELL".
3. Set up the zlib compression algorithm and SQLite database to avoid any build issues if you intend to develop python packages or frameworks to automate your machine learning pipeline. You can configure them simply by exporting their paths in the .bash_profile
export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/sqlite/lib"export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/sqlite/include"
In case you don’t have a .bash_profile file, you can follow this answer on StackOverflow to create one or this one.
4. The next step is to install xz package using homebrew. This step is optional; however, it may avoid Runtime errors when importing pandas. This error might be raised due to lzma compression that the python installation is not complete. We need to install some dependencies — like xz package, before python installation via the pyenv to avoid those errors. You can run the following line in the terminal:
brew install xz
If you already installed python via pyenv before xz, you can use the pyenv uninstall <the version>. The installation of xz should be prior to pyenv.
5. Now it is finally time to install python 😄. To do so, you need to choose which python version you want to install. you can list all the available python versions supported by pyenv using this command
pyenv install --list
pyenv supports many python versions including anaconda, jython, miniconda, etc.
6. I will install python version 3.8.6(I found pandas installation has some issues with 3.9.0) by running the following command in the terminal :
pyenv install 3.8.6
7. The following command should make the installed version global. This will override python 2.7 shipped with the MacOs by default — no more python3 command👌.
pyenv global 3.8.6
8. To confirm
pyenv which python/Users/salmaelshahawy/.pyenv/versions/3.8.6/bin/python
9. To enable shims and autocompletion, you need to include this configuration in the .bash_profile if you are using bash — as per documentation instruction.
Navigate to the home directory and open the .bash-profile. Then copy and paste the following snippet — check pyenv for zch.
if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)"fi
To avoid the persistent warning about upgrading the pip package. It would be best if you upgrade the pip package.
According to the documentation, you can run the following command in the terminal to upgrade
python -m pip install -U pip
If you still have issues with the upgrade, run the previous command with the sudo -H command, however, this is not preferable.
Thanks to Joe Klemmer suggestion, I was able to use the pyenv-virtualenv plugin instead of the virtualenv package. Utilizing this plugin would automatically activate and deactivate the virtual environment after adding the required configuration in the bash_profile — no more source/bin/activate👍.
If you like to use virtualenvwrapper or virtualenv, I will keep the steps below for future reference.
Begin with installing pyenv-virtualenv via the homebrew
brew install pyenv-virtualenv
To enable automatically activating the virtualenv every time you open a project directory, you need two steps:
Open the .bash_profile and paste the following line.
Open the .bash_profile and paste the following line.
eval "$(pyenv virtualenv-init -)"
2. Create a new environment venv38 from the current pyenv version via
pyenv version3.8.6 (set by /Users/salmaelshahawy/.pyenv/version)pyenv virtualenv venv38
3. Check if it was created
pyenv virtualenvsvenv38 (created from /Users/salmaelshahawy/.pyenv/versions/3.8.6)
4. Create a project directory with the valid virtualenv environment version
mkdir package cd package touch .python-versionecho "venv38" >> .python-version
Now, you can easily switching between environments easily without worry about activating commands.
It is a good practice to use a virtual environment for your projects so you can worry less about sharing your projects, notebooks, packages, frameworks, etc. So, your team can reproduce the code and easily running your code without issues. I would focus on utilizing vertualenv; however, other methods can automatically initialize the virtualenv every time you create a project directory, virtualenvwrapper, for example. Start by installing virtualenv using the following.
pip install virtualenv
Now, you may start creating a new project folder with a new virtualenv using the following series of commands.
mkdir package cd package virtualenv devenv --system-site-packagessource devenv/bin/activatetouch test.pypip install pandas
Create a new project directory named package and move inside of it.Initialize a new virtual environment named devenv and the flag --system-site-packages to include the preinstalled packages in your system like setuptools and wheels, for instance — the flag could be surpassed, it is a personal preference.Activating the virtual environment using the source command.Create a new python file to start coding.Installing the required packages within this project.
Create a new project directory named package and move inside of it.
Initialize a new virtual environment named devenv and the flag --system-site-packages to include the preinstalled packages in your system like setuptools and wheels, for instance — the flag could be surpassed, it is a personal preference.
Activating the virtual environment using the source command.
Create a new python file to start coding.
Installing the required packages within this project.
As demonstrated in the captured image, the file ran successfully free from any errors. The command deactivate might be used to deactivating the running virtual environment.
It is a good practice to include a requirements.txt file with the project directory to make it easy for others to download and run smoothly. This can be done using the pip freeze command to list all the packages in requirements.txt format — specifying each package's specific version to avoid conflict.
pip freeze > requirements.txt
Also, you can use pip list to list the installed packages — check the main differences between list and freeze commands.
If you use VSCode, make sure that it utilizes the proper interpreter — the created virtual environment. You can follow this guide to switch between the interpreters.
For MacOs, press shift + cmd + p, then navigate to Select Interpreter.
Then select the virtualenv in our case, is devenv
If you want to install a newer version of python via pyenv, you can list all the installed versions using:
ls ~/.pyenv/versions/3.7.1 3.8.6
To remove a specific version
rm -rf ~/.pyenv/versions/3.7.1
This will remove the specified version from your machine.
At this point, the development environment is up and running. That way, you would spend less time debugging intimidating system issues and focus on building instead.
Another way to set up your development environment without worried about writing some shell commands is to use Ansible Playbook. It is a set of configurations for most of the software required for the Mac. It does include Sequal Pro, homebrew, etc.
If you would like to make your terminal more pretty with colors, you can use this configurations to set your bash_profile.
If you would like to make it simple like mine, you can fork or copy my bash_profile config file at this link, including anaconda config, but different python version, this link to the simple bash_profile to follow up with this tutorial, in addition to git-completion.
Finally, I wish this gave a comprehensive guide to set up your python development environment. If you encountered any issues, please list them in the comment section; I would be happy to help. The best way to encourage me is by following me here on Medium, LinkedIn, and Github. Happy learning! | [
{
"code": null,
"e": 301,
"s": 172,
"text": "Update 12/12/2020 — Utilizing pyenv virtualenv to automate activate/deactivate the virtual environment. — Joe Klemmer Suggestion"
},
{
"code": null,
"e": 797,
"s": 301,
"text": "Recently, I treated myself by purchasing a new Macbook Pro and started setting up my development environment for python. This step is pretty essential because if you did it the wrong way, plenty of issues would arise and distract you from focusing on the actual development work. So, I’ve decided to write a comprehensive guide listing the steps to help others setting their python development environment from scratch. Hence, you have a more comfortable life handling errors. Let’s get started!"
},
{
"code": null,
"e": 978,
"s": 797,
"text": "For Data Scientist who doesn’t have much experience in the shell command.For Data Scientists/Developers who have errors like import pandas as pd ImportError: No module named pandas"
},
{
"code": null,
"e": 1052,
"s": 978,
"text": "For Data Scientist who doesn’t have much experience in the shell command."
},
{
"code": null,
"e": 1160,
"s": 1052,
"text": "For Data Scientists/Developers who have errors like import pandas as pd ImportError: No module named pandas"
},
{
"code": null,
"e": 1287,
"s": 1160,
"text": "3. For Data Scientists/Developers who want to make python3 the default interpreter — type python → get python3 not python 2.7."
},
{
"code": null,
"e": 1481,
"s": 1287,
"text": "4. For Data Scientists who want to start using virtualenv within their machine learning projects to have reproducible notebooks — no more fighting between Dev-ops Engineers and Data Scientists."
},
{
"code": null,
"e": 1530,
"s": 1481,
"text": "5. For future me 😎 in case I treat myself again!"
},
{
"code": null,
"e": 1726,
"s": 1530,
"text": "First, you need to do is installing the Xcode if you don’t have one already. This step is necessary because MacOs has to set up some local development utilities, including various tools like git."
},
{
"code": null,
"e": 1894,
"s": 1726,
"text": "The second step would be the magic wand of MacOs, which is homebrew. All you have to do is to copy and paste the link into your terminal and hit return, and that’s it."
},
{
"code": null,
"e": 1990,
"s": 1894,
"text": "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
},
{
"code": null,
"e": 2133,
"s": 1990,
"text": "Please be sure to navigate to the link before installing and reading what will be installed on your machine to ensure that you are ok with it."
},
{
"code": null,
"e": 2516,
"s": 2133,
"text": "Once installed, you can grab a cup of coffee and start installing whatever you want without worry about anything. Don’t jump to conclusions and begin installing python using brew! Instead, install the environment manager pyenv. Pyenv is a tool to manage the python versions installed in your local machine; it is available to many other operating systems, including Ubuntu, windows."
},
{
"code": null,
"e": 2739,
"s": 2516,
"text": "Stick with one version of python across the project workspace.Switch between python versions peacefully.If you want to use a specific python version like 2.7, for instance.Be able to make python3 as the global interpreter."
},
{
"code": null,
"e": 2802,
"s": 2739,
"text": "Stick with one version of python across the project workspace."
},
{
"code": null,
"e": 2845,
"s": 2802,
"text": "Switch between python versions peacefully."
},
{
"code": null,
"e": 2914,
"s": 2845,
"text": "If you want to use a specific python version like 2.7, for instance."
},
{
"code": null,
"e": 2965,
"s": 2914,
"text": "Be able to make python3 as the global interpreter."
},
{
"code": null,
"e": 3043,
"s": 2965,
"text": "Open terminal and type the following command to install pyenv using homebrew."
},
{
"code": null,
"e": 3121,
"s": 3043,
"text": "Open terminal and type the following command to install pyenv using homebrew."
},
{
"code": null,
"e": 3140,
"s": 3121,
"text": "brew install pyenv"
},
{
"code": null,
"e": 3344,
"s": 3140,
"text": "Please note that MacOs use zsh as the default shell command. in case you want to move into bash just run chsh -s/bin/bash in the terminal. Also, you can change it using the GUI in MacOs using this guide."
},
{
"code": null,
"e": 3417,
"s": 3344,
"text": "2. Restart the terminal for changes to take effect or run exec \"$SHELL\"."
},
{
"code": null,
"e": 3679,
"s": 3417,
"text": "3. Set up the zlib compression algorithm and SQLite database to avoid any build issues if you intend to develop python packages or frameworks to automate your machine learning pipeline. You can configure them simply by exporting their paths in the .bash_profile"
},
{
"code": null,
"e": 3829,
"s": 3679,
"text": "export LDFLAGS=\"-L/usr/local/opt/zlib/lib -L/usr/local/opt/sqlite/lib\"export CPPFLAGS=\"-I/usr/local/opt/zlib/include -I/usr/local/opt/sqlite/include\""
},
{
"code": null,
"e": 3945,
"s": 3829,
"text": "In case you don’t have a .bash_profile file, you can follow this answer on StackOverflow to create one or this one."
},
{
"code": null,
"e": 4351,
"s": 3945,
"text": "4. The next step is to install xz package using homebrew. This step is optional; however, it may avoid Runtime errors when importing pandas. This error might be raised due to lzma compression that the python installation is not complete. We need to install some dependencies — like xz package, before python installation via the pyenv to avoid those errors. You can run the following line in the terminal:"
},
{
"code": null,
"e": 4367,
"s": 4351,
"text": "brew install xz"
},
{
"code": null,
"e": 4516,
"s": 4367,
"text": "If you already installed python via pyenv before xz, you can use the pyenv uninstall <the version>. The installation of xz should be prior to pyenv."
},
{
"code": null,
"e": 4719,
"s": 4516,
"text": "5. Now it is finally time to install python 😄. To do so, you need to choose which python version you want to install. you can list all the available python versions supported by pyenv using this command"
},
{
"code": null,
"e": 4740,
"s": 4719,
"text": "pyenv install --list"
},
{
"code": null,
"e": 4820,
"s": 4740,
"text": "pyenv supports many python versions including anaconda, jython, miniconda, etc."
},
{
"code": null,
"e": 4966,
"s": 4820,
"text": "6. I will install python version 3.8.6(I found pandas installation has some issues with 3.9.0) by running the following command in the terminal :"
},
{
"code": null,
"e": 4986,
"s": 4966,
"text": "pyenv install 3.8.6"
},
{
"code": null,
"e": 5145,
"s": 4986,
"text": "7. The following command should make the installed version global. This will override python 2.7 shipped with the MacOs by default — no more python3 command👌."
},
{
"code": null,
"e": 5164,
"s": 5145,
"text": "pyenv global 3.8.6"
},
{
"code": null,
"e": 5178,
"s": 5164,
"text": "8. To confirm"
},
{
"code": null,
"e": 5251,
"s": 5178,
"text": "pyenv which python/Users/salmaelshahawy/.pyenv/versions/3.8.6/bin/python"
},
{
"code": null,
"e": 5408,
"s": 5251,
"text": "9. To enable shims and autocompletion, you need to include this configuration in the .bash_profile if you are using bash — as per documentation instruction."
},
{
"code": null,
"e": 5532,
"s": 5408,
"text": "Navigate to the home directory and open the .bash-profile. Then copy and paste the following snippet — check pyenv for zch."
},
{
"code": null,
"e": 5601,
"s": 5532,
"text": "if command -v pyenv 1>/dev/null 2>&1; then eval \"$(pyenv init -)\"fi"
},
{
"code": null,
"e": 5715,
"s": 5601,
"text": "To avoid the persistent warning about upgrading the pip package. It would be best if you upgrade the pip package."
},
{
"code": null,
"e": 5808,
"s": 5715,
"text": "According to the documentation, you can run the following command in the terminal to upgrade"
},
{
"code": null,
"e": 5837,
"s": 5808,
"text": "python -m pip install -U pip"
},
{
"code": null,
"e": 5964,
"s": 5837,
"text": "If you still have issues with the upgrade, run the previous command with the sudo -H command, however, this is not preferable."
},
{
"code": null,
"e": 6261,
"s": 5964,
"text": "Thanks to Joe Klemmer suggestion, I was able to use the pyenv-virtualenv plugin instead of the virtualenv package. Utilizing this plugin would automatically activate and deactivate the virtual environment after adding the required configuration in the bash_profile — no more source/bin/activate👍."
},
{
"code": null,
"e": 6363,
"s": 6261,
"text": "If you like to use virtualenvwrapper or virtualenv, I will keep the steps below for future reference."
},
{
"code": null,
"e": 6419,
"s": 6363,
"text": "Begin with installing pyenv-virtualenv via the homebrew"
},
{
"code": null,
"e": 6449,
"s": 6419,
"text": "brew install pyenv-virtualenv"
},
{
"code": null,
"e": 6560,
"s": 6449,
"text": "To enable automatically activating the virtualenv every time you open a project directory, you need two steps:"
},
{
"code": null,
"e": 6613,
"s": 6560,
"text": "Open the .bash_profile and paste the following line."
},
{
"code": null,
"e": 6666,
"s": 6613,
"text": "Open the .bash_profile and paste the following line."
},
{
"code": null,
"e": 6700,
"s": 6666,
"text": "eval \"$(pyenv virtualenv-init -)\""
},
{
"code": null,
"e": 6770,
"s": 6700,
"text": "2. Create a new environment venv38 from the current pyenv version via"
},
{
"code": null,
"e": 6859,
"s": 6770,
"text": "pyenv version3.8.6 (set by /Users/salmaelshahawy/.pyenv/version)pyenv virtualenv venv38 "
},
{
"code": null,
"e": 6886,
"s": 6859,
"text": "3. Check if it was created"
},
{
"code": null,
"e": 6969,
"s": 6886,
"text": "pyenv virtualenvsvenv38 (created from /Users/salmaelshahawy/.pyenv/versions/3.8.6)"
},
{
"code": null,
"e": 7045,
"s": 6969,
"text": "4. Create a project directory with the valid virtualenv environment version"
},
{
"code": null,
"e": 7124,
"s": 7045,
"text": "mkdir package cd package touch .python-versionecho \"venv38\" >> .python-version"
},
{
"code": null,
"e": 7223,
"s": 7124,
"text": "Now, you can easily switching between environments easily without worry about activating commands."
},
{
"code": null,
"e": 7696,
"s": 7223,
"text": "It is a good practice to use a virtual environment for your projects so you can worry less about sharing your projects, notebooks, packages, frameworks, etc. So, your team can reproduce the code and easily running your code without issues. I would focus on utilizing vertualenv; however, other methods can automatically initialize the virtualenv every time you create a project directory, virtualenvwrapper, for example. Start by installing virtualenv using the following."
},
{
"code": null,
"e": 7719,
"s": 7696,
"text": "pip install virtualenv"
},
{
"code": null,
"e": 7830,
"s": 7719,
"text": "Now, you may start creating a new project folder with a new virtualenv using the following series of commands."
},
{
"code": null,
"e": 7953,
"s": 7830,
"text": "mkdir package cd package virtualenv devenv --system-site-packagessource devenv/bin/activatetouch test.pypip install pandas"
},
{
"code": null,
"e": 8413,
"s": 7953,
"text": "Create a new project directory named package and move inside of it.Initialize a new virtual environment named devenv and the flag --system-site-packages to include the preinstalled packages in your system like setuptools and wheels, for instance — the flag could be surpassed, it is a personal preference.Activating the virtual environment using the source command.Create a new python file to start coding.Installing the required packages within this project."
},
{
"code": null,
"e": 8481,
"s": 8413,
"text": "Create a new project directory named package and move inside of it."
},
{
"code": null,
"e": 8720,
"s": 8481,
"text": "Initialize a new virtual environment named devenv and the flag --system-site-packages to include the preinstalled packages in your system like setuptools and wheels, for instance — the flag could be surpassed, it is a personal preference."
},
{
"code": null,
"e": 8781,
"s": 8720,
"text": "Activating the virtual environment using the source command."
},
{
"code": null,
"e": 8823,
"s": 8781,
"text": "Create a new python file to start coding."
},
{
"code": null,
"e": 8877,
"s": 8823,
"text": "Installing the required packages within this project."
},
{
"code": null,
"e": 9050,
"s": 8877,
"text": "As demonstrated in the captured image, the file ran successfully free from any errors. The command deactivate might be used to deactivating the running virtual environment."
},
{
"code": null,
"e": 9353,
"s": 9050,
"text": "It is a good practice to include a requirements.txt file with the project directory to make it easy for others to download and run smoothly. This can be done using the pip freeze command to list all the packages in requirements.txt format — specifying each package's specific version to avoid conflict."
},
{
"code": null,
"e": 9383,
"s": 9353,
"text": "pip freeze > requirements.txt"
},
{
"code": null,
"e": 9504,
"s": 9383,
"text": "Also, you can use pip list to list the installed packages — check the main differences between list and freeze commands."
},
{
"code": null,
"e": 9670,
"s": 9504,
"text": "If you use VSCode, make sure that it utilizes the proper interpreter — the created virtual environment. You can follow this guide to switch between the interpreters."
},
{
"code": null,
"e": 9741,
"s": 9670,
"text": "For MacOs, press shift + cmd + p, then navigate to Select Interpreter."
},
{
"code": null,
"e": 9791,
"s": 9741,
"text": "Then select the virtualenv in our case, is devenv"
},
{
"code": null,
"e": 9898,
"s": 9791,
"text": "If you want to install a newer version of python via pyenv, you can list all the installed versions using:"
},
{
"code": null,
"e": 9933,
"s": 9898,
"text": "ls ~/.pyenv/versions/3.7.1 3.8.6"
},
{
"code": null,
"e": 9962,
"s": 9933,
"text": "To remove a specific version"
},
{
"code": null,
"e": 9993,
"s": 9962,
"text": "rm -rf ~/.pyenv/versions/3.7.1"
},
{
"code": null,
"e": 10051,
"s": 9993,
"text": "This will remove the specified version from your machine."
},
{
"code": null,
"e": 10217,
"s": 10051,
"text": "At this point, the development environment is up and running. That way, you would spend less time debugging intimidating system issues and focus on building instead."
},
{
"code": null,
"e": 10466,
"s": 10217,
"text": "Another way to set up your development environment without worried about writing some shell commands is to use Ansible Playbook. It is a set of configurations for most of the software required for the Mac. It does include Sequal Pro, homebrew, etc."
},
{
"code": null,
"e": 10589,
"s": 10466,
"text": "If you would like to make your terminal more pretty with colors, you can use this configurations to set your bash_profile."
},
{
"code": null,
"e": 10857,
"s": 10589,
"text": "If you would like to make it simple like mine, you can fork or copy my bash_profile config file at this link, including anaconda config, but different python version, this link to the simple bash_profile to follow up with this tutorial, in addition to git-completion."
}
] |
Report Variables | Report variables are special objects built on top of the report expression.
Report variables simplify the following tasks −
Report expressions, which are heavily used throughout the report template. These expressions can be declared only once by using the report variables.
Report expressions, which are heavily used throughout the report template. These expressions can be declared only once by using the report variables.
Report variables can perform various calculations based on the corresponding expressions values such as count, sum, average, lowest, highest, variance, etc.
Report variables can perform various calculations based on the corresponding expressions values such as count, sum, average, lowest, highest, variance, etc.
If variables are defined in a report design, then these can be referenced by new variables in the expressions. Hence, the order in which the variables are declared in a report design is important.
A variable declaration is as follows −
<variable name = "CityNumber" class = "java.lang.Integer" incrementType = "Group"
incrementGroup = "CityGroup" calculation = "Count">
<variableExpression>
<![CDATA[Boolean.TRUE]]>
</variableExpression>
</variable>
As seen above, <variable> element contains number of attributes. These attributes are summarized below −
Similar to parameters and fields, the name attribute of </variable> element is mandatory. It allows referencing the variable by its declared name in the report expressions.
The class attribute is also mandatory that specifies the class name for the variable values. Its default value is java.lang.String. This can be changed to any class available in the classpath, both at the report-compilation time and the report filling time. The engine takes care of type-casting in report expressions which the $V{} token is used, hence manual type-casting is not required.
This attribute determines − what calculation to perform on the variable when filling the report. The following subsections describe all the possible values for the calculation attribute of the <variable> element.
Average − The variable value is the average of every non-null value of the variable expression. Valid for numeric variables only.
Average − The variable value is the average of every non-null value of the variable expression. Valid for numeric variables only.
Count − The variable value is the count of non-null instances of the variable expression.
Count − The variable value is the count of non-null instances of the variable expression.
First − The variable value is the value of the first instance of the variable expression. Subsequent values are ignored.
First − The variable value is the value of the first instance of the variable expression. Subsequent values are ignored.
Highest − The variable value is the highest value for the variable expression.
Highest − The variable value is the highest value for the variable expression.
Lowest − The variable value is the lowest value for the variable expression in the report.
Lowest − The variable value is the lowest value for the variable expression in the report.
Nothing − No calculations are performed on the variable.
Nothing − No calculations are performed on the variable.
StandardDeviation − The variable value is the standard deviation of all non-null values matching the report expression. Valid for numeric variables only.
StandardDeviation − The variable value is the standard deviation of all non-null values matching the report expression. Valid for numeric variables only.
Sum − The variable value is the sum of all non-null values returned by the report expression.
Sum − The variable value is the sum of all non-null values returned by the report expression.
System − The variable value is a custom calculation (calculating the value for that variable yourself, using the scriptlets functionality of JasperReports).
System − The variable value is a custom calculation (calculating the value for that variable yourself, using the scriptlets functionality of JasperReports).
Variance − The variable value is the variance of all non-null values returned by evaluation of the report variable's expression.
Variance − The variable value is the variance of all non-null values returned by evaluation of the report variable's expression.
This attribute determines the class used to calculate the value of the variable when filling the current record on the report. Default value would be any class implementing net.sf.jasperreports.engine.fill.JRIncrementerFactory. The factory class will be used by the engine to instantiate incrementer objects at runtime depending on the calculation attribute set for the variable.
This determines when to recalculate the value of the variable. This attribute uses values, as below −
Column − The variable value is recalculated at the end of each column.
Column − The variable value is recalculated at the end of each column.
Group − The variable value is recalculated when the group specified by incrementGroup changes.
Group − The variable value is recalculated when the group specified by incrementGroup changes.
None − The variable value is recalculated with every record.
None − The variable value is recalculated with every record.
Page − The variable value is recalculated at the end of every page.
Page − The variable value is recalculated at the end of every page.
Report − The variable value is recalculated once, at the end of the report.
Report − The variable value is recalculated once, at the end of the report.
This determines the name of the group at which the variable value is recalculated, when incrementType is Group. This takes name of any group declared in the JRXML report template.
This determines when the value of a variable is reset. This attribute uses values, as below −
Column − The variable value is reset at the beginning of each column.
Column − The variable value is reset at the beginning of each column.
Group − The variable value is reset when the group specified by incrementGroup changes.
Group − The variable value is reset when the group specified by incrementGroup changes.
None − The variable value is never reset.
None − The variable value is never reset.
Page − The variable value is reset at the beginning of every page.
Page − The variable value is reset at the beginning of every page.
Report − The variable value is reset only once, at the beginning of the report.
Report − The variable value is reset only once, at the beginning of the report.
This determines the name of the group at which the variable value is reset, when resetType is Group. The values for this attribute would be the name of any group declared in the JRXML report template.
There are some built-in system variables, ready to use in expressions, as follows −
PAGE_NUMBER
This variable's value is its current page number. It can be used to display both the current page number and the total number of pages using a special feature of JasperReports text field elements, the evaluationTime attribute.
COLUMN_NUMBER
This variable contains the current column number.
REPORT_COUNT
This report variable contains the total number of records processed.
PAGE_COUNT
This variable contains the number of records that were processed when generating the current page.
COLUMN_COUNT
This variable contains the number of records that were processed when generating the current column.
GroupName_COUNT
The name of this variable is derived from the name of the group it corresponds to, suffixed with the _COUNT sequence. This variable contains the number of records in the current group.
Let's add a variable (countNumber) to our existing report template (Chapter Report Designs). We will prefix the count to each record. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory −
<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
"//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" pageWidth = "595"
pageHeight = "842" columnWidth = "515"
leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50">
<parameter name = "ReportTitle" class = "java.lang.String"/>
<parameter name = "Author" class = "java.lang.String"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name = "country" class = "java.lang.String">
<fieldDescription>
<![CDATA[country]]>
</fieldDescription>
</field>
<field name = "name" class = "java.lang.String">
<fieldDescription>
<![CDATA[name]]>
</fieldDescription>
</field>
<variable name = "countNumber" class = "java.lang.Integer" calculation = "Count">
<variableExpression>
<![CDATA[Boolean.TRUE]]>
</variableExpression>
</variable>
<title>
<band height = "70">
<line>
<reportElement x = "0" y = "0" width = "515" height = "1"/>
</line>
<textField isBlankWhenNull = "true" bookmarkLevel = "1">
<reportElement x = "0" y = "10" width = "515" height = "30"/>
<textElement textAlignment = "Center">
<font size = "22"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{ReportTitle}]]>
</textFieldExpression>
<anchorNameExpression>
<![CDATA["Title"]]>
</anchorNameExpression>
</textField>
<textField isBlankWhenNull = "true">
<reportElement x = "0" y = "40" width = "515" height = "20"/>
<textElement textAlignment = "Center">
<font size = "10"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{Author}]]>
</textFieldExpression>
</textField>
</band>
</title>
<columnHeader>
<band height = "23">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15"
backcolor = "#70A9A9" />
<box>
<bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
</box>
<textElement />
<text>
<![CDATA[]]>
</text>
</staticText>
<staticText>
<reportElement x = "414" y = "3" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x = "0" y = "3" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height = "16">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14"
backcolor = "#E5ECF9" />
<box>
<bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
</box>
<textElement />
<text>
<![CDATA[]]>
</text>
</staticText>
<textField>
<reportElement x = "414" y = "0" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font size = "9" />
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x = "0" y = "0" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle" />
<textFieldExpression class = "java.lang.String">
<![CDATA[" " + String.valueOf($V{countNumber}) +"."+$F{name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class JasperReportFill {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String sourceFileName =
"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";
DataBeanList DataBeanList = new DataBeanList();
ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
/**
* Passing ReportTitle and Author as parameters
*/
parameters.put("ReportTitle", "List of Contacts");
parameters.put("Author", "Prepared By Manisha");
try {
JasperFillManager.fillReportToFile(
sourceFileName, parameters, beanColDataSource);
} catch (JRException e) {
e.printStackTrace();
}
}
}
The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −
package com.tutorialspoint;
public class DataBean {
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
public class DataBeanList {
public ArrayList<DataBean> getDataBeanList() {
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
dataBeanList.add(produce("Manisha", "India"));
dataBeanList.add(produce("Dennis Ritchie", "USA"));
dataBeanList.add(produce("V.Anand", "India"));
dataBeanList.add(produce("Shrinath", "California"));
return dataBeanList;
}
/**
* This method returns a DataBean object,
* with name and country set in it.
*/
private DataBean produce(String name, String country) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
return dataBean;
}
}
We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.
The import file - baseBuild.xml is picked from the chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewFillReport" depends = "compile,compilereportdesing,run"
description = "Launches the report viewer to preview
the report stored in the .JRprint file.">
<java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
<arg value = "-F${file.name}.JRprint" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc"
classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning:
'includeantruntime' was not set, defaulting to build.sysclasspath=last;
set to false for repeatable builds
[javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.JasperReportFill
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
viewFillReport:
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
BUILD SUCCESSFUL
Total time: 18 seconds
As a result of above compilation, a JasperViewer window opens up as in the screen below −
Here, we see that the count is prefixed for each record.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2330,
"s": 2254,
"text": "Report variables are special objects built on top of the report expression."
},
{
"code": null,
"e": 2378,
"s": 2330,
"text": "Report variables simplify the following tasks −"
},
{
"code": null,
"e": 2528,
"s": 2378,
"text": "Report expressions, which are heavily used throughout the report template. These expressions can be declared only once by using the report variables."
},
{
"code": null,
"e": 2678,
"s": 2528,
"text": "Report expressions, which are heavily used throughout the report template. These expressions can be declared only once by using the report variables."
},
{
"code": null,
"e": 2835,
"s": 2678,
"text": "Report variables can perform various calculations based on the corresponding expressions values such as count, sum, average, lowest, highest, variance, etc."
},
{
"code": null,
"e": 2992,
"s": 2835,
"text": "Report variables can perform various calculations based on the corresponding expressions values such as count, sum, average, lowest, highest, variance, etc."
},
{
"code": null,
"e": 3189,
"s": 2992,
"text": "If variables are defined in a report design, then these can be referenced by new variables in the expressions. Hence, the order in which the variables are declared in a report design is important."
},
{
"code": null,
"e": 3228,
"s": 3189,
"text": "A variable declaration is as follows −"
},
{
"code": null,
"e": 3457,
"s": 3228,
"text": "<variable name = \"CityNumber\" class = \"java.lang.Integer\" incrementType = \"Group\"\n incrementGroup = \"CityGroup\" calculation = \"Count\">\n <variableExpression>\n <![CDATA[Boolean.TRUE]]>\n </variableExpression>\n</variable>"
},
{
"code": null,
"e": 3562,
"s": 3457,
"text": "As seen above, <variable> element contains number of attributes. These attributes are summarized below −"
},
{
"code": null,
"e": 3735,
"s": 3562,
"text": "Similar to parameters and fields, the name attribute of </variable> element is mandatory. It allows referencing the variable by its declared name in the report expressions."
},
{
"code": null,
"e": 4126,
"s": 3735,
"text": "The class attribute is also mandatory that specifies the class name for the variable values. Its default value is java.lang.String. This can be changed to any class available in the classpath, both at the report-compilation time and the report filling time. The engine takes care of type-casting in report expressions which the $V{} token is used, hence manual type-casting is not required."
},
{
"code": null,
"e": 4339,
"s": 4126,
"text": "This attribute determines − what calculation to perform on the variable when filling the report. The following subsections describe all the possible values for the calculation attribute of the <variable> element."
},
{
"code": null,
"e": 4470,
"s": 4339,
"text": "Average − The variable value is the average of every non-null value of the variable expression. Valid for numeric variables only. "
},
{
"code": null,
"e": 4601,
"s": 4470,
"text": "Average − The variable value is the average of every non-null value of the variable expression. Valid for numeric variables only. "
},
{
"code": null,
"e": 4691,
"s": 4601,
"text": "Count − The variable value is the count of non-null instances of the variable expression."
},
{
"code": null,
"e": 4781,
"s": 4691,
"text": "Count − The variable value is the count of non-null instances of the variable expression."
},
{
"code": null,
"e": 4902,
"s": 4781,
"text": "First − The variable value is the value of the first instance of the variable expression. Subsequent values are ignored."
},
{
"code": null,
"e": 5023,
"s": 4902,
"text": "First − The variable value is the value of the first instance of the variable expression. Subsequent values are ignored."
},
{
"code": null,
"e": 5102,
"s": 5023,
"text": "Highest − The variable value is the highest value for the variable expression."
},
{
"code": null,
"e": 5181,
"s": 5102,
"text": "Highest − The variable value is the highest value for the variable expression."
},
{
"code": null,
"e": 5272,
"s": 5181,
"text": "Lowest − The variable value is the lowest value for the variable expression in the report."
},
{
"code": null,
"e": 5363,
"s": 5272,
"text": "Lowest − The variable value is the lowest value for the variable expression in the report."
},
{
"code": null,
"e": 5420,
"s": 5363,
"text": "Nothing − No calculations are performed on the variable."
},
{
"code": null,
"e": 5477,
"s": 5420,
"text": "Nothing − No calculations are performed on the variable."
},
{
"code": null,
"e": 5631,
"s": 5477,
"text": "StandardDeviation − The variable value is the standard deviation of all non-null values matching the report expression. Valid for numeric variables only."
},
{
"code": null,
"e": 5785,
"s": 5631,
"text": "StandardDeviation − The variable value is the standard deviation of all non-null values matching the report expression. Valid for numeric variables only."
},
{
"code": null,
"e": 5879,
"s": 5785,
"text": "Sum − The variable value is the sum of all non-null values returned by the report expression."
},
{
"code": null,
"e": 5973,
"s": 5879,
"text": "Sum − The variable value is the sum of all non-null values returned by the report expression."
},
{
"code": null,
"e": 6130,
"s": 5973,
"text": "System − The variable value is a custom calculation (calculating the value for that variable yourself, using the scriptlets functionality of JasperReports)."
},
{
"code": null,
"e": 6287,
"s": 6130,
"text": "System − The variable value is a custom calculation (calculating the value for that variable yourself, using the scriptlets functionality of JasperReports)."
},
{
"code": null,
"e": 6416,
"s": 6287,
"text": "Variance − The variable value is the variance of all non-null values returned by evaluation of the report variable's expression."
},
{
"code": null,
"e": 6545,
"s": 6416,
"text": "Variance − The variable value is the variance of all non-null values returned by evaluation of the report variable's expression."
},
{
"code": null,
"e": 6925,
"s": 6545,
"text": "This attribute determines the class used to calculate the value of the variable when filling the current record on the report. Default value would be any class implementing net.sf.jasperreports.engine.fill.JRIncrementerFactory. The factory class will be used by the engine to instantiate incrementer objects at runtime depending on the calculation attribute set for the variable."
},
{
"code": null,
"e": 7027,
"s": 6925,
"text": "This determines when to recalculate the value of the variable. This attribute uses values, as below −"
},
{
"code": null,
"e": 7098,
"s": 7027,
"text": "Column − The variable value is recalculated at the end of each column."
},
{
"code": null,
"e": 7169,
"s": 7098,
"text": "Column − The variable value is recalculated at the end of each column."
},
{
"code": null,
"e": 7264,
"s": 7169,
"text": "Group − The variable value is recalculated when the group specified by incrementGroup changes."
},
{
"code": null,
"e": 7359,
"s": 7264,
"text": "Group − The variable value is recalculated when the group specified by incrementGroup changes."
},
{
"code": null,
"e": 7420,
"s": 7359,
"text": "None − The variable value is recalculated with every record."
},
{
"code": null,
"e": 7481,
"s": 7420,
"text": "None − The variable value is recalculated with every record."
},
{
"code": null,
"e": 7549,
"s": 7481,
"text": "Page − The variable value is recalculated at the end of every page."
},
{
"code": null,
"e": 7617,
"s": 7549,
"text": "Page − The variable value is recalculated at the end of every page."
},
{
"code": null,
"e": 7693,
"s": 7617,
"text": "Report − The variable value is recalculated once, at the end of the report."
},
{
"code": null,
"e": 7769,
"s": 7693,
"text": "Report − The variable value is recalculated once, at the end of the report."
},
{
"code": null,
"e": 7949,
"s": 7769,
"text": "This determines the name of the group at which the variable value is recalculated, when incrementType is Group. This takes name of any group declared in the JRXML report template."
},
{
"code": null,
"e": 8043,
"s": 7949,
"text": "This determines when the value of a variable is reset. This attribute uses values, as below −"
},
{
"code": null,
"e": 8113,
"s": 8043,
"text": "Column − The variable value is reset at the beginning of each column."
},
{
"code": null,
"e": 8183,
"s": 8113,
"text": "Column − The variable value is reset at the beginning of each column."
},
{
"code": null,
"e": 8271,
"s": 8183,
"text": "Group − The variable value is reset when the group specified by incrementGroup changes."
},
{
"code": null,
"e": 8359,
"s": 8271,
"text": "Group − The variable value is reset when the group specified by incrementGroup changes."
},
{
"code": null,
"e": 8401,
"s": 8359,
"text": "None − The variable value is never reset."
},
{
"code": null,
"e": 8443,
"s": 8401,
"text": "None − The variable value is never reset."
},
{
"code": null,
"e": 8510,
"s": 8443,
"text": "Page − The variable value is reset at the beginning of every page."
},
{
"code": null,
"e": 8577,
"s": 8510,
"text": "Page − The variable value is reset at the beginning of every page."
},
{
"code": null,
"e": 8657,
"s": 8577,
"text": "Report − The variable value is reset only once, at the beginning of the report."
},
{
"code": null,
"e": 8737,
"s": 8657,
"text": "Report − The variable value is reset only once, at the beginning of the report."
},
{
"code": null,
"e": 8938,
"s": 8737,
"text": "This determines the name of the group at which the variable value is reset, when resetType is Group. The values for this attribute would be the name of any group declared in the JRXML report template."
},
{
"code": null,
"e": 9022,
"s": 8938,
"text": "There are some built-in system variables, ready to use in expressions, as follows −"
},
{
"code": null,
"e": 9034,
"s": 9022,
"text": "PAGE_NUMBER"
},
{
"code": null,
"e": 9261,
"s": 9034,
"text": "This variable's value is its current page number. It can be used to display both the current page number and the total number of pages using a special feature of JasperReports text field elements, the evaluationTime attribute."
},
{
"code": null,
"e": 9275,
"s": 9261,
"text": "COLUMN_NUMBER"
},
{
"code": null,
"e": 9325,
"s": 9275,
"text": "This variable contains the current column number."
},
{
"code": null,
"e": 9338,
"s": 9325,
"text": "REPORT_COUNT"
},
{
"code": null,
"e": 9407,
"s": 9338,
"text": "This report variable contains the total number of records processed."
},
{
"code": null,
"e": 9418,
"s": 9407,
"text": "PAGE_COUNT"
},
{
"code": null,
"e": 9517,
"s": 9418,
"text": "This variable contains the number of records that were processed when generating the current page."
},
{
"code": null,
"e": 9530,
"s": 9517,
"text": "COLUMN_COUNT"
},
{
"code": null,
"e": 9631,
"s": 9530,
"text": "This variable contains the number of records that were processed when generating the current column."
},
{
"code": null,
"e": 9647,
"s": 9631,
"text": "GroupName_COUNT"
},
{
"code": null,
"e": 9832,
"s": 9647,
"text": "The name of this variable is derived from the name of the group it corresponds to, suffixed with the _COUNT sequence. This variable contains the number of records in the current group."
},
{
"code": null,
"e": 10097,
"s": 9832,
"text": "Let's add a variable (countNumber) to our existing report template (Chapter Report Designs). We will prefix the count to each record. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −"
},
{
"code": null,
"e": 15069,
"s": 10097,
"text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"515\"\n leftMargin = \"40\" rightMargin = \"40\" topMargin = \"50\" bottomMargin = \"50\">\n\t\n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n\n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription>\n <![CDATA[country]]>\n </fieldDescription>\n </field>\n\n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription>\n <![CDATA[name]]>\n </fieldDescription>\n </field>\n \n <variable name = \"countNumber\" class = \"java.lang.Integer\" calculation = \"Count\">\n <variableExpression>\n <![CDATA[Boolean.TRUE]]>\n </variableExpression>\n </variable>\n \n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n\t\t\t\n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </title>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" width = \"535\"\theight = \"15\"\n backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" width = \"535\" height = \"14\"\n backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[\" \" + String.valueOf($V{countNumber}) +\".\"+$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\n</jasperReport>"
},
{
"code": null,
"e": 15247,
"s": 15069,
"text": "The java codes for report filling remains unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −"
},
{
"code": null,
"e": 16381,
"s": 15247,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName =\n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 16503,
"s": 16381,
"text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as given below −"
},
{
"code": null,
"e": 16871,
"s": 16503,
"text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}"
},
{
"code": null,
"e": 16992,
"s": 16871,
"text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as given below −"
},
{
"code": null,
"e": 17756,
"s": 16992,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}"
},
{
"code": null,
"e": 17949,
"s": 17756,
"text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below."
},
{
"code": null,
"e": 18087,
"s": 17949,
"text": "The import file - baseBuild.xml is picked from the chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 19172,
"s": 18087,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n \n <import file = \"baseBuild.xml\" />\n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview\n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\"\n classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>"
},
{
"code": null,
"e": 19386,
"s": 19172,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −"
},
{
"code": null,
"e": 21059,
"s": 19386,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28: warning:\n 'includeantruntime' was not set, defaulting to build.sysclasspath=last;\n set to false for repeatable builds\n [javac] Compiling 7 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig\n for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 18 seconds\n"
},
{
"code": null,
"e": 21149,
"s": 21059,
"text": "As a result of above compilation, a JasperViewer window opens up as in the screen below −"
},
{
"code": null,
"e": 21206,
"s": 21149,
"text": "Here, we see that the count is prefixed for each record."
},
{
"code": null,
"e": 21213,
"s": 21206,
"text": " Print"
},
{
"code": null,
"e": 21224,
"s": 21213,
"text": " Add Notes"
}
] |
What is -551 error code in DB2? How will you resolve it? | When we get -551 in the SQLCODE then there is some privilege level issue. It signifies that the user does not have access to the database/tablespace/view/table that he is trying to access. As per the IBM documentation -551 SQLCODE states that.
-551 auth-id DOES NOT HAVE THE PRIVILEGE TO PERFORM OPERATION operation ON OBJECT object-name
There are DCL (Data control language) statements which are used by DBAs in order to control the access on DB2 objects. We can raise a request with DBA to provide access to the particular object for which user is getting -551 SQLCODE.
Following DCL statement will give access to user id Z5564 to execute PLAN ORDERPLAN:
GRANT EXECUTE ON PLAN ORDERPLAN TO Z5564
In a practical scenario, the access on DB2 objects such as PLAN, TABLES, VIEWS, etc., is given at RACF level rather than at user level. RACF stands for Resource Access Control Facility which is a Z/OS security management product used for providing access control and auditing purposes.
The RACF contains its own database having different RACF groups. Each user in the mainframe will be assigned to a RACF group.
For example, there are 3 departments in an organization: SALES, MARKETING, WARRANTY. So, 3 RACF groups can be created for each department and each RACF group has employee user ids for respective employees. The access to DB2 can be given based on RACF groups. So the SALES group can have access to ORDERS, TRANSACTIONS table. The MARKETING group can have access to DEALERS and INCENTIVE table and WARRANTY group can have access to PRODUCTS and VENDORS table.
If the user from one RACF group will try to access the table assigned for a different group, then the user will get -551 DB2 error code. | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "When we get -551 in the SQLCODE then there is some privilege level issue. It signifies that the user does not have access to the database/tablespace/view/table that he is trying to access. As per the IBM documentation -551 SQLCODE states that."
},
{
"code": null,
"e": 1400,
"s": 1306,
"text": "-551 auth-id DOES NOT HAVE THE PRIVILEGE TO PERFORM OPERATION operation ON OBJECT object-name"
},
{
"code": null,
"e": 1634,
"s": 1400,
"text": "There are DCL (Data control language) statements which are used by DBAs in order to control the access on DB2 objects. We can raise a request with DBA to provide access to the particular object for which user is getting -551 SQLCODE."
},
{
"code": null,
"e": 1719,
"s": 1634,
"text": "Following DCL statement will give access to user id Z5564 to execute PLAN ORDERPLAN:"
},
{
"code": null,
"e": 1760,
"s": 1719,
"text": "GRANT EXECUTE ON PLAN ORDERPLAN TO Z5564"
},
{
"code": null,
"e": 2046,
"s": 1760,
"text": "In a practical scenario, the access on DB2 objects such as PLAN, TABLES, VIEWS, etc., is given at RACF level rather than at user level. RACF stands for Resource Access Control Facility which is a Z/OS security management product used for providing access control and auditing purposes."
},
{
"code": null,
"e": 2172,
"s": 2046,
"text": "The RACF contains its own database having different RACF groups. Each user in the mainframe will be assigned to a RACF group."
},
{
"code": null,
"e": 2630,
"s": 2172,
"text": "For example, there are 3 departments in an organization: SALES, MARKETING, WARRANTY. So, 3 RACF groups can be created for each department and each RACF group has employee user ids for respective employees. The access to DB2 can be given based on RACF groups. So the SALES group can have access to ORDERS, TRANSACTIONS table. The MARKETING group can have access to DEALERS and INCENTIVE table and WARRANTY group can have access to PRODUCTS and VENDORS table."
},
{
"code": null,
"e": 2767,
"s": 2630,
"text": "If the user from one RACF group will try to access the table assigned for a different group, then the user will get -551 DB2 error code."
}
] |
Pascal - Units | A Pascal program can consist of modules called units. A unit might consist of some code blocks, which in turn are made up of variables and type declarations, statements, procedures, etc. There are many built-in units in Pascal and Pascal allows programmers to define and write their own units to be used later in various programs.
Both the built-in units and user-defined units are included in a program by the uses clause. We have already used the variants unit in Pascal - Variants tutorial. This tutorial explains creating and including user-defined units. However, let us first see how to include a built-in unit crt in your program −
program myprog;
uses crt;
The following example illustrates using the crt unit −
Program Calculate_Area (input, output);
uses crt;
var
a, b, c, s, area: real;
begin
textbackground(white); (* gives a white background *)
clrscr; (*clears the screen *)
textcolor(green); (* text color is green *)
gotoxy(30, 4); (* takes the pointer to the 4th line and 30th column)
writeln('This program calculates area of a triangle:');
writeln('Area = area = sqrt(s(s-a)(s-b)(s-c))');
writeln('S stands for semi-perimeter');
writeln('a, b, c are sides of the triangle');
writeln('Press any key when you are ready');
readkey;
clrscr;
gotoxy(20,3);
write('Enter a: ');
readln(a);
gotoxy(20,5);
write('Enter b:');
readln(b);
gotoxy(20, 7);
write('Enter c: ');
readln(c);
s := (a + b + c)/2.0;
area := sqrt(s * (s - a)*(s-b)*(s-c));
gotoxy(20, 9);
writeln('Area: ',area:10:3);
readkey;
end.
It is the same program we used right at the beginning of the Pascal tutorial, compile and run it to find the effects of the change.
To create a unit, you need to write the modules or subprograms you want to store in it and save it in a file with .pas extension. The first line of this file should start with the keyword unit followed by the name of the unit. For example −
unit calculateArea;
Following are three important steps in creating a Pascal unit −
The name of the file and the name of the unit should be exactly same. So, our unit calculateArea will be saved in a file named calculateArea.pas.
The name of the file and the name of the unit should be exactly same. So, our unit calculateArea will be saved in a file named calculateArea.pas.
The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit.
The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit.
Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms.
Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms.
The following program creates the unit named calculateArea −
unit CalculateArea;
interface
function RectangleArea( length, width: real): real;
function CircleArea(radius: real) : real;
function TriangleArea( side1, side2, side3: real): real;
implementation
function RectangleArea( length, width: real): real;
begin
RectangleArea := length * width;
end;
function CircleArea(radius: real) : real;
const
PI = 3.14159;
begin
CircleArea := PI * radius * radius;
end;
function TriangleArea( side1, side2, side3: real): real;
var
s, area: real;
begin
s := (side1 + side2 + side3)/2.0;
area := sqrt(s * (s - side1)*(s-side2)*(s-side3));
TriangleArea := area;
end;
end.
Next, let us write a simple program that would use the unit we defined above −
program AreaCalculation;
uses CalculateArea,crt;
var
l, w, r, a, b, c, area: real;
begin
clrscr;
l := 5.4;
w := 4.7;
area := RectangleArea(l, w);
writeln('Area of Rectangle 5.4 x 4.7 is: ', area:7:3);
r:= 7.0;
area:= CircleArea(r);
writeln('Area of Circle with radius 7.0 is: ', area:7:3);
a := 3.0;
b:= 4.0;
c:= 5.0;
area:= TriangleArea(a, b, c);
writeln('Area of Triangle 3.0 by 4.0 by 5.0 is: ', area:7:3);
end.
When the above code is compiled and executed, it produces the following result −
Area of Rectangle 5.4 x 4.7 is: 25.380
Area of Circle with radius 7.0 is: 153.938
Area of Triangle 3.0 by 4.0 by 5.0 is: 6.000
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2414,
"s": 2083,
"text": "A Pascal program can consist of modules called units. A unit might consist of some code blocks, which in turn are made up of variables and type declarations, statements, procedures, etc. There are many built-in units in Pascal and Pascal allows programmers to define and write their own units to be used later in various programs."
},
{
"code": null,
"e": 2722,
"s": 2414,
"text": "Both the built-in units and user-defined units are included in a program by the uses clause. We have already used the variants unit in Pascal - Variants tutorial. This tutorial explains creating and including user-defined units. However, let us first see how to include a built-in unit crt in your program −"
},
{
"code": null,
"e": 2749,
"s": 2722,
"text": "program myprog;\nuses crt;\n"
},
{
"code": null,
"e": 2804,
"s": 2749,
"text": "The following example illustrates using the crt unit −"
},
{
"code": null,
"e": 3703,
"s": 2804,
"text": "Program Calculate_Area (input, output);\nuses crt;\nvar \n a, b, c, s, area: real;\n\nbegin\n textbackground(white); (* gives a white background *)\n clrscr; (*clears the screen *)\n \n textcolor(green); (* text color is green *)\n gotoxy(30, 4); (* takes the pointer to the 4th line and 30th column) \n \n writeln('This program calculates area of a triangle:');\n writeln('Area = area = sqrt(s(s-a)(s-b)(s-c))');\n writeln('S stands for semi-perimeter');\n writeln('a, b, c are sides of the triangle');\n writeln('Press any key when you are ready');\n \n readkey;\n clrscr;\n gotoxy(20,3);\n \n write('Enter a: ');\n readln(a);\n gotoxy(20,5);\n \n write('Enter b:');\n readln(b);\n gotoxy(20, 7);\n \n write('Enter c: ');\n readln(c);\n\n s := (a + b + c)/2.0;\n area := sqrt(s * (s - a)*(s-b)*(s-c));\n gotoxy(20, 9);\n \n writeln('Area: ',area:10:3);\n readkey;\nend."
},
{
"code": null,
"e": 3835,
"s": 3703,
"text": "It is the same program we used right at the beginning of the Pascal tutorial, compile and run it to find the effects of the change."
},
{
"code": null,
"e": 4076,
"s": 3835,
"text": "To create a unit, you need to write the modules or subprograms you want to store in it and save it in a file with .pas extension. The first line of this file should start with the keyword unit followed by the name of the unit. For example −"
},
{
"code": null,
"e": 4097,
"s": 4076,
"text": "unit calculateArea;\n"
},
{
"code": null,
"e": 4161,
"s": 4097,
"text": "Following are three important steps in creating a Pascal unit −"
},
{
"code": null,
"e": 4307,
"s": 4161,
"text": "The name of the file and the name of the unit should be exactly same. So, our unit calculateArea will be saved in a file named calculateArea.pas."
},
{
"code": null,
"e": 4453,
"s": 4307,
"text": "The name of the file and the name of the unit should be exactly same. So, our unit calculateArea will be saved in a file named calculateArea.pas."
},
{
"code": null,
"e": 4628,
"s": 4453,
"text": "The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit."
},
{
"code": null,
"e": 4803,
"s": 4628,
"text": "The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit."
},
{
"code": null,
"e": 4996,
"s": 4803,
"text": "Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms."
},
{
"code": null,
"e": 5189,
"s": 4996,
"text": "Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms."
},
{
"code": null,
"e": 5250,
"s": 5189,
"text": "The following program creates the unit named calculateArea −"
},
{
"code": null,
"e": 5878,
"s": 5250,
"text": "unit CalculateArea;\ninterface\n\nfunction RectangleArea( length, width: real): real;\nfunction CircleArea(radius: real) : real;\nfunction TriangleArea( side1, side2, side3: real): real;\n\nimplementation\n\nfunction RectangleArea( length, width: real): real;\nbegin\n RectangleArea := length * width;\nend;\n\nfunction CircleArea(radius: real) : real;\nconst\n PI = 3.14159;\nbegin\n CircleArea := PI * radius * radius;\nend;\n\nfunction TriangleArea( side1, side2, side3: real): real;\nvar\n s, area: real;\n\nbegin\n s := (side1 + side2 + side3)/2.0;\n area := sqrt(s * (s - side1)*(s-side2)*(s-side3));\n TriangleArea := area;\nend;\n\nend."
},
{
"code": null,
"e": 5957,
"s": 5878,
"text": "Next, let us write a simple program that would use the unit we defined above −"
},
{
"code": null,
"e": 6421,
"s": 5957,
"text": "program AreaCalculation;\nuses CalculateArea,crt;\n\nvar\n l, w, r, a, b, c, area: real;\n\nbegin\n clrscr;\n l := 5.4;\n w := 4.7;\n area := RectangleArea(l, w);\n writeln('Area of Rectangle 5.4 x 4.7 is: ', area:7:3);\n\n r:= 7.0;\n area:= CircleArea(r);\n writeln('Area of Circle with radius 7.0 is: ', area:7:3);\n\n a := 3.0;\n b:= 4.0;\n c:= 5.0;\n \n area:= TriangleArea(a, b, c);\n writeln('Area of Triangle 3.0 by 4.0 by 5.0 is: ', area:7:3);\nend."
},
{
"code": null,
"e": 6502,
"s": 6421,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6630,
"s": 6502,
"text": "Area of Rectangle 5.4 x 4.7 is: 25.380\nArea of Circle with radius 7.0 is: 153.938\nArea of Triangle 3.0 by 4.0 by 5.0 is: 6.000\n"
},
{
"code": null,
"e": 6665,
"s": 6630,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6688,
"s": 6665,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 6695,
"s": 6688,
"text": " Print"
},
{
"code": null,
"e": 6706,
"s": 6695,
"text": " Add Notes"
}
] |
Java Examples - Display different shapes | How to display different shapes using GUI?
Following example demonstrates how to display different shapes using Arc2D, Ellipse2D, Rectangle2D, RoundRectangle2D classes.
import java.awt.Shape;
import java.awt.geom.*;
public class Main {
public static void main(String[] args) {
int x1 = 1, x2 = 2, w = 3, h = 4,
x = 5, y = 6,
y1 = 1, y2 = 2, start = 3;
Shape line = new Line2D.Float(x1, y1, x2, y2);
Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);
Shape oval = new Ellipse2D.Float(x, y, w, h);
Shape rectangle = new Rectangle2D.Float(x, y, w, h);
Shape roundRectangle = new RoundRectangle2D.Float (x, y, w, h, 1, 2);
System.out.println("Different shapes are created:");
}
}
The above code sample will produce the following result.
Different shapes are created.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2111,
"s": 2068,
"text": "How to display different shapes using GUI?"
},
{
"code": null,
"e": 2237,
"s": 2111,
"text": "Following example demonstrates how to display different shapes using Arc2D, Ellipse2D, Rectangle2D, RoundRectangle2D classes."
},
{
"code": null,
"e": 2815,
"s": 2237,
"text": "import java.awt.Shape;\nimport java.awt.geom.*;\n\npublic class Main {\n public static void main(String[] args) {\n int x1 = 1, x2 = 2, w = 3, h = 4, \n x = 5, y = 6, \n\t y1 = 1, y2 = 2, start = 3;\n \n Shape line = new Line2D.Float(x1, y1, x2, y2);\n Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);\n Shape oval = new Ellipse2D.Float(x, y, w, h);\n Shape rectangle = new Rectangle2D.Float(x, y, w, h);\n Shape roundRectangle = new RoundRectangle2D.Float (x, y, w, h, 1, 2);\n System.out.println(\"Different shapes are created:\");\n }\n}"
},
{
"code": null,
"e": 2872,
"s": 2815,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2903,
"s": 2872,
"text": "Different shapes are created.\n"
},
{
"code": null,
"e": 2910,
"s": 2903,
"text": " Print"
},
{
"code": null,
"e": 2921,
"s": 2910,
"text": " Add Notes"
}
] |
How to set a Check Box in the DateTimePicker in C#? - GeeksforGeeks | 02 Aug, 2019
In Windows Form, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you are allowed to set a checkbox in the DateTimePicker using the ShowCheckBox Property.If the value of this property is set to true, then a checkbox display in the DateTimePicker control, otherwise, false. When the checkbox is selected which means the date/time is updated and if the checkbox is unchecked, then you cannot update date/time. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set a checkbox in the DateTimePicker as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the DateTimePicker and set a checkbox in the DateTimePicker as shown in the below image:Output:
Output:
Run-Time: It is a little bit trickier than the above method. In this method, you can set a checkbox in the DateTimePicker control programmatically with the help of given syntax:
public bool ShowCheckBox { get; set; }
The value of this property is of System.Boolean type, either true or false. The default value of this property is false. The following steps show how to set a checkbox in the DateTimePicker dynamically:
Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
Step 2: After creating DateTimePicker, set the ShowCheckBox property of the DateTimePicker provided by the DateTimePicker class.// Setting the ShowCheckBox property
dt.ShowCheckBox = true;
// Setting the ShowCheckBox property
dt.ShowCheckBox = true;
Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form
this.Controls.Add(dt);
// Adding this control to the form
this.Controls.Add(dt);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp49 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = "Select Date of Birth"; lab.Font = new Font("Comic Sans MS", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); ; dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Short; dt.Name = "MyPicker"; dt.Font = new Font("Comic Sans MS", 12); dt.ShowCheckBox = true; // Adding this control to the form this.Controls.Add(dt); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Linked List Implementation in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 24841,
"s": 24302,
"text": "In Windows Form, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you are allowed to set a checkbox in the DateTimePicker using the ShowCheckBox Property.If the value of this property is set to true, then a checkbox display in the DateTimePicker control, otherwise, false. When the checkbox is selected which means the date/time is updated and if the checkbox is unchecked, then you cannot update date/time. You can set this property in two different ways:"
},
{
"code": null,
"e": 24952,
"s": 24841,
"text": "1. Design-Time: It is the easiest way to set a checkbox in the DateTimePicker as shown in the following steps:"
},
{
"code": null,
"e": 25068,
"s": 24952,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 25181,
"s": 25068,
"text": "Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 25338,
"s": 25181,
"text": "Step 3: After drag and drop you will go to the properties of the DateTimePicker and set a checkbox in the DateTimePicker as shown in the below image:Output:"
},
{
"code": null,
"e": 25346,
"s": 25338,
"text": "Output:"
},
{
"code": null,
"e": 25524,
"s": 25346,
"text": "Run-Time: It is a little bit trickier than the above method. In this method, you can set a checkbox in the DateTimePicker control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25563,
"s": 25524,
"text": "public bool ShowCheckBox { get; set; }"
},
{
"code": null,
"e": 25766,
"s": 25563,
"text": "The value of this property is of System.Boolean type, either true or false. The default value of this property is false. The following steps show how to set a checkbox in the DateTimePicker dynamically:"
},
{
"code": null,
"e": 25949,
"s": 25766,
"text": "Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 26021,
"s": 25949,
"text": "// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 26211,
"s": 26021,
"text": "Step 2: After creating DateTimePicker, set the ShowCheckBox property of the DateTimePicker provided by the DateTimePicker class.// Setting the ShowCheckBox property\ndt.ShowCheckBox = true;\n"
},
{
"code": null,
"e": 26273,
"s": 26211,
"text": "// Setting the ShowCheckBox property\ndt.ShowCheckBox = true;\n"
},
{
"code": null,
"e": 26423,
"s": 26273,
"text": "Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 26482,
"s": 26423,
"text": "// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 26491,
"s": 26482,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp49 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = \"Select Date of Birth\"; lab.Font = new Font(\"Comic Sans MS\", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); ; dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Short; dt.Name = \"MyPicker\"; dt.Font = new Font(\"Comic Sans MS\", 12); dt.ShowCheckBox = true; // Adding this control to the form this.Controls.Add(dt); }}}",
"e": 27782,
"s": 26491,
"text": null
},
{
"code": null,
"e": 27790,
"s": 27782,
"text": "Output:"
},
{
"code": null,
"e": 27821,
"s": 27790,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 27824,
"s": 27821,
"text": "C#"
},
{
"code": null,
"e": 27922,
"s": 27824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27945,
"s": 27922,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27973,
"s": 27945,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28013,
"s": 27973,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28056,
"s": 28013,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28073,
"s": 28056,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28089,
"s": 28073,
"text": "C# | List Class"
},
{
"code": null,
"e": 28111,
"s": 28089,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28151,
"s": 28111,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28176,
"s": 28151,
"text": "Lambda Expressions in C#"
}
] |
Java Examples - Thread completion | How to check a thread has stopped or not ?
Following example demonstrates how to check a thread has stop or not by checking with isAlive() method.
public class Main {
public static void main(String[] argv)throws Exception {
Thread thread = new MyThread();
thread.start();
if (thread.isAlive()) {
System.out.println("Thread has not finished");
} else {
System.out.println("Finished");
}
long delayMillis = 5000;
thread.join(delayMillis);
if (thread.isAlive()) {
System.out.println("thread has not finished");
} else {
System.out.println("Finished");
}
thread.join();
}
}
class MyThread extends Thread {
boolean stop = false;
public void run() {
while (true) {
if (stop) {
return;
}
}
}
}
The above code sample will produce the following result.
Thread has not finished
Finished
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2111,
"s": 2068,
"text": "How to check a thread has stopped or not ?"
},
{
"code": null,
"e": 2215,
"s": 2111,
"text": "Following example demonstrates how to check a thread has stop or not by checking with isAlive() method."
},
{
"code": null,
"e": 2930,
"s": 2215,
"text": "public class Main {\n public static void main(String[] argv)throws Exception { \n Thread thread = new MyThread();\n thread.start();\n \n if (thread.isAlive()) {\n System.out.println(\"Thread has not finished\");\n } else {\n System.out.println(\"Finished\");\n }\n long delayMillis = 5000; \n thread.join(delayMillis);\n \n if (thread.isAlive()) {\n System.out.println(\"thread has not finished\");\n } else {\n System.out.println(\"Finished\");\n }\n thread.join();\n }\n}\nclass MyThread extends Thread {\n boolean stop = false;\n public void run() {\n while (true) {\n if (stop) {\n return;\n }\n }\n }\n}"
},
{
"code": null,
"e": 2987,
"s": 2930,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3021,
"s": 2987,
"text": "Thread has not finished\nFinished\n"
},
{
"code": null,
"e": 3028,
"s": 3021,
"text": " Print"
},
{
"code": null,
"e": 3039,
"s": 3028,
"text": " Add Notes"
}
] |
atomic.CompareAndSwapInt64() Function in Golang With Examples - GeeksforGeeks | 01 Apr, 2020
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapInt64() function in Go language is used to perform the compare and swap operation for an int64 value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
Here, addr indicates address, old indicates int64 value that is the old swapped value which is returned from the swapped operation, and new is the int64 new value that will swap itself from the old swapped value.
Note: (*int64) is the pointer to a int64 value. And int64 is integer type of bit size 64. Moreover, int64 contains the set of all signed 64-bit integers from -9223372036854775808 to 9223372036854775807.
Return Value: It returns true if swapping is accomplished else it returns false.
Below examples illustrates the use of the above method:
Example 1:
// Golang Program to illustrate the usage of// CompareAndSwapInt64 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Main functionfunc main() { // Assigning variable values to the int64 var ( i int64 = 686788787 ) // Swapping var old_value = atomic.SwapInt64(&i, 56677) // Printing old value and swapped value fmt.Println("Swapped:", i, ", old value:", old_value) // Calling CompareAndSwapInt64 // method with its parameters Swap := atomic.CompareAndSwapInt64(&i, 56677, 908998) // Displays true if swapped else false fmt.Println(Swap) fmt.Println("The Value of i is: ",i)}
Output:
Swapped: 56677 , old value: 686788787
true
The Value of i is: 908998
Example 2:
// Golang Program to illustrate the usage of// CompareAndSwapInt64 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Main functionfunc main() { // Assigning variable values to the int64 var ( i int64 = 686788787 ) // Swapping var old_value = atomic.SwapInt64(&i, 56677) // Printing old value and swapped value fmt.Println("Swapped:", i, ", old value:", old_value) // Calling CompareAndSwapInt64 // method with its parameters Swap := atomic.CompareAndSwapInt64(&i, 686788787, 908998) // Displays true if swapped else false fmt.Println(Swap) fmt.Println(i)}
Output:
Swapped: 56677, old value: 686788787
false
56677
Here, the old value in the CompareAndSwapInt64 method must be the swapped value returned from the SwapInt64 method. And here the swapping is not performed so false is returned.
GoLang-atomic
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to Trim a String in Golang? | [
{
"code": null,
"e": 24430,
"s": 24402,
"text": "\n01 Apr, 2020"
},
{
"code": null,
"e": 24806,
"s": 24430,
"text": "In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapInt64() function in Go language is used to perform the compare and swap operation for an int64 value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions."
},
{
"code": null,
"e": 24814,
"s": 24806,
"text": "Syntax:"
},
{
"code": null,
"e": 24884,
"s": 24814,
"text": "func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)\n"
},
{
"code": null,
"e": 25097,
"s": 24884,
"text": "Here, addr indicates address, old indicates int64 value that is the old swapped value which is returned from the swapped operation, and new is the int64 new value that will swap itself from the old swapped value."
},
{
"code": null,
"e": 25300,
"s": 25097,
"text": "Note: (*int64) is the pointer to a int64 value. And int64 is integer type of bit size 64. Moreover, int64 contains the set of all signed 64-bit integers from -9223372036854775808 to 9223372036854775807."
},
{
"code": null,
"e": 25381,
"s": 25300,
"text": "Return Value: It returns true if swapping is accomplished else it returns false."
},
{
"code": null,
"e": 25437,
"s": 25381,
"text": "Below examples illustrates the use of the above method:"
},
{
"code": null,
"e": 25448,
"s": 25437,
"text": "Example 1:"
},
{
"code": "// Golang Program to illustrate the usage of// CompareAndSwapInt64 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Main functionfunc main() { // Assigning variable values to the int64 var ( i int64 = 686788787 ) // Swapping var old_value = atomic.SwapInt64(&i, 56677) // Printing old value and swapped value fmt.Println(\"Swapped:\", i, \", old value:\", old_value) // Calling CompareAndSwapInt64 // method with its parameters Swap := atomic.CompareAndSwapInt64(&i, 56677, 908998) // Displays true if swapped else false fmt.Println(Swap) fmt.Println(\"The Value of i is: \",i)}",
"e": 26150,
"s": 25448,
"text": null
},
{
"code": null,
"e": 26158,
"s": 26150,
"text": "Output:"
},
{
"code": null,
"e": 26229,
"s": 26158,
"text": "Swapped: 56677 , old value: 686788787\ntrue\nThe Value of i is: 908998\n"
},
{
"code": null,
"e": 26240,
"s": 26229,
"text": "Example 2:"
},
{
"code": "// Golang Program to illustrate the usage of// CompareAndSwapInt64 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Main functionfunc main() { // Assigning variable values to the int64 var ( i int64 = 686788787 ) // Swapping var old_value = atomic.SwapInt64(&i, 56677) // Printing old value and swapped value fmt.Println(\"Swapped:\", i, \", old value:\", old_value) // Calling CompareAndSwapInt64 // method with its parameters Swap := atomic.CompareAndSwapInt64(&i, 686788787, 908998) // Displays true if swapped else false fmt.Println(Swap) fmt.Println(i)}",
"e": 26924,
"s": 26240,
"text": null
},
{
"code": null,
"e": 26932,
"s": 26924,
"text": "Output:"
},
{
"code": null,
"e": 26982,
"s": 26932,
"text": "Swapped: 56677, old value: 686788787\nfalse\n56677\n"
},
{
"code": null,
"e": 27159,
"s": 26982,
"text": "Here, the old value in the CompareAndSwapInt64 method must be the swapped value returned from the SwapInt64 method. And here the swapping is not performed so false is returned."
},
{
"code": null,
"e": 27173,
"s": 27159,
"text": "GoLang-atomic"
},
{
"code": null,
"e": 27185,
"s": 27173,
"text": "Go Language"
},
{
"code": null,
"e": 27283,
"s": 27185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27309,
"s": 27283,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 27360,
"s": 27309,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27407,
"s": 27360,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27440,
"s": 27407,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27453,
"s": 27440,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27465,
"s": 27453,
"text": "Golang Maps"
},
{
"code": null,
"e": 27482,
"s": 27465,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27531,
"s": 27482,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 27563,
"s": 27531,
"text": "How to compare times in Golang?"
}
] |
C# Program To Copy Content Of One File To Another File By Overwriting Same File Name - GeeksforGeeks | 19 Jan, 2022
Given a file, now our task is to copy data from one file to another file by overwriting the same file name using C#. So we use the following methods to perform this task:
1. Copy(String, String, Boolean): It is used to copy the content of one file to a new file with overwrite.
Syntax:
File.Copy(Myfile1, Myfile2, owrite);
Where Myfile1 is the first file, Myfile2 is the second file, and owrite is a boolean variable if the destination file can be overwritten then it is set to true otherwise false.
2. ReadAllText(String): It opens a text file, then reads the data present in it, and after that closes the file. This method will definitely close the file handle even when an exception arises.
File.ReadAllText(Mypath)
Where Mypath is the location of the file that we want to read. It is of String type.
Let’s consider the two files in the source and destination folder with the name sai.txt
source(first):
Hello Geeks welcome to c#.
destination(last):
Hello Geeks welcome to java/php.
Now, our task is to overwrite the last file with the source content so we use the following approach.
Approach:
Declare variable
Read source and destination file using ReadAllText() method
file = File.ReadAllText("first/sai.TXT");
file = File.ReadAllText("last/sai.TXT");
Copy the file by overwriting source(first) file with Copy() method
File.Copy("first/sai.TXT", "last/sai.TXT",true);
Read source and destination file using ReadAllText() method and display
file = File.ReadAllText("first/sai.TXT");
file = File.ReadAllText("last/sai.TXT");
Example:
C#
// C# program to copy the data of one file to// another file by overwriting the same file nameusing System;using System.IO; class GfG{ static void Main(){ // Declare file name string file; // Content in files before copying Console.WriteLine("Before copy:\n"); file = File.ReadAllText("first/sai.TXT"); Console.WriteLine("data in first:\n" + file); file = File.ReadAllText("last/sai.TXT"); Console.WriteLine("data in last :\n" + file + "\n\n\n"); // Copy file with overwriting File.Copy("first/sai.TXT", "last/sai.TXT", true); // Content in files after copying Console.WriteLine("After copy:\n"); file = File.ReadAllText("first/sai.TXT"); Console.WriteLine("data in first:\n" + file); file = File.ReadAllText("last/sai.TXT"); Console.WriteLine("data in last :\n" + file + "\n\n\n");}}
Output:
Before copy:
data in first:
Hello Geeks welcome to c#.
data in last:
Hello Geeks welcome to java/php.
After copy:
data in first:
Hello Geeks welcome to c#.
data in last:
Hello Geeks welcome to c#.
simranarora5sos
CSharp-File-Handling
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 24474,
"s": 24302,
"text": "Given a file, now our task is to copy data from one file to another file by overwriting the same file name using C#. So we use the following methods to perform this task: "
},
{
"code": null,
"e": 24582,
"s": 24474,
"text": "1. Copy(String, String, Boolean): It is used to copy the content of one file to a new file with overwrite. "
},
{
"code": null,
"e": 24590,
"s": 24582,
"text": "Syntax:"
},
{
"code": null,
"e": 24627,
"s": 24590,
"text": "File.Copy(Myfile1, Myfile2, owrite);"
},
{
"code": null,
"e": 24804,
"s": 24627,
"text": "Where Myfile1 is the first file, Myfile2 is the second file, and owrite is a boolean variable if the destination file can be overwritten then it is set to true otherwise false."
},
{
"code": null,
"e": 24998,
"s": 24804,
"text": "2. ReadAllText(String): It opens a text file, then reads the data present in it, and after that closes the file. This method will definitely close the file handle even when an exception arises."
},
{
"code": null,
"e": 25023,
"s": 24998,
"text": "File.ReadAllText(Mypath)"
},
{
"code": null,
"e": 25108,
"s": 25023,
"text": "Where Mypath is the location of the file that we want to read. It is of String type."
},
{
"code": null,
"e": 25196,
"s": 25108,
"text": "Let’s consider the two files in the source and destination folder with the name sai.txt"
},
{
"code": null,
"e": 25211,
"s": 25196,
"text": "source(first):"
},
{
"code": null,
"e": 25238,
"s": 25211,
"text": "Hello Geeks welcome to c#."
},
{
"code": null,
"e": 25257,
"s": 25238,
"text": "destination(last):"
},
{
"code": null,
"e": 25290,
"s": 25257,
"text": "Hello Geeks welcome to java/php."
},
{
"code": null,
"e": 25392,
"s": 25290,
"text": "Now, our task is to overwrite the last file with the source content so we use the following approach."
},
{
"code": null,
"e": 25402,
"s": 25392,
"text": "Approach:"
},
{
"code": null,
"e": 25419,
"s": 25402,
"text": "Declare variable"
},
{
"code": null,
"e": 25479,
"s": 25419,
"text": "Read source and destination file using ReadAllText() method"
},
{
"code": null,
"e": 25562,
"s": 25479,
"text": "file = File.ReadAllText(\"first/sai.TXT\");\nfile = File.ReadAllText(\"last/sai.TXT\");"
},
{
"code": null,
"e": 25629,
"s": 25562,
"text": "Copy the file by overwriting source(first) file with Copy() method"
},
{
"code": null,
"e": 25679,
"s": 25629,
"text": " File.Copy(\"first/sai.TXT\", \"last/sai.TXT\",true);"
},
{
"code": null,
"e": 25751,
"s": 25679,
"text": "Read source and destination file using ReadAllText() method and display"
},
{
"code": null,
"e": 25834,
"s": 25751,
"text": "file = File.ReadAllText(\"first/sai.TXT\");\nfile = File.ReadAllText(\"last/sai.TXT\");"
},
{
"code": null,
"e": 25843,
"s": 25834,
"text": "Example:"
},
{
"code": null,
"e": 25846,
"s": 25843,
"text": "C#"
},
{
"code": "// C# program to copy the data of one file to// another file by overwriting the same file nameusing System;using System.IO; class GfG{ static void Main(){ // Declare file name string file; // Content in files before copying Console.WriteLine(\"Before copy:\\n\"); file = File.ReadAllText(\"first/sai.TXT\"); Console.WriteLine(\"data in first:\\n\" + file); file = File.ReadAllText(\"last/sai.TXT\"); Console.WriteLine(\"data in last :\\n\" + file + \"\\n\\n\\n\"); // Copy file with overwriting File.Copy(\"first/sai.TXT\", \"last/sai.TXT\", true); // Content in files after copying Console.WriteLine(\"After copy:\\n\"); file = File.ReadAllText(\"first/sai.TXT\"); Console.WriteLine(\"data in first:\\n\" + file); file = File.ReadAllText(\"last/sai.TXT\"); Console.WriteLine(\"data in last :\\n\" + file + \"\\n\\n\\n\");}}",
"e": 26701,
"s": 25846,
"text": null
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Output:"
},
{
"code": null,
"e": 26909,
"s": 26709,
"text": "Before copy:\n\ndata in first:\nHello Geeks welcome to c#.\ndata in last:\nHello Geeks welcome to java/php.\n\nAfter copy:\n\ndata in first:\nHello Geeks welcome to c#.\ndata in last:\nHello Geeks welcome to c#."
},
{
"code": null,
"e": 26925,
"s": 26909,
"text": "simranarora5sos"
},
{
"code": null,
"e": 26946,
"s": 26925,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 26953,
"s": 26946,
"text": "Picked"
},
{
"code": null,
"e": 26956,
"s": 26953,
"text": "C#"
},
{
"code": null,
"e": 26968,
"s": 26956,
"text": "C# Programs"
},
{
"code": null,
"e": 27066,
"s": 26968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27075,
"s": 27066,
"text": "Comments"
},
{
"code": null,
"e": 27088,
"s": 27075,
"text": "Old Comments"
},
{
"code": null,
"e": 27111,
"s": 27088,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27139,
"s": 27111,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27179,
"s": 27139,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27222,
"s": 27179,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27239,
"s": 27222,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27279,
"s": 27239,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27304,
"s": 27279,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 27338,
"s": 27304,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 27384,
"s": 27338,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
Find first and last positions of an element in a sorted array - GeeksforGeeks | 09 Mar, 2022
Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Examples:
Input : arr[] = {1, 3, 5, 5, 5, 5, 67, 123, 125}
x = 5
Output : First Occurrence = 2
Last Occurrence = 5
Input : arr[] = {1, 3, 5, 5, 5, 5, 7, 123, 125 }
x = 7
Output : First Occurrence = 6
Last Occurrence = 6
The Naive Approach is to run a for loop and check given elements in an array.
1. Run a for loop and for i = 0 to n-1
2. Take first = -1 and last = -1
3. When we find element first time then we update first = i
4. We always update last=i whenever we find the element.
5. We print first and last.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find first and last occurrence of// an elements in given sorted array#include <bits/stdc++.h>using namespace std; // Function for finding first and last occurrence// of an elementsvoid findFirstAndLast(int arr[], int n, int x){ int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) cout << "First Occurrence = " << first << "\nLast Occurrence = " << last; else cout << "Not Found";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; findFirstAndLast(arr, n, x); return 0;}
// Java program to find first and last occurrence of// an elements in given sorted arrayimport java.io.*; class GFG { // Function for finding first and last occurrence // of an elements public static void findFirstAndLast(int arr[], int x) { int n = arr.length; int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { System.out.println("First Occurrence = " + first); System.out.println("Last Occurrence = " + last); } else System.out.println("Not Found"); } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int x = 8; findFirstAndLast(arr, x); }}
# Python 3 program to find first and# last occurrence of an elements in# given sorted array # Function for finding first and last# occurrence of an elementsdef findFirstAndLast(arr, n, x) : first = -1 last = -1 for i in range(0, n) : if (x != arr[i]) : continue if (first == -1) : first = i last = i if (first != -1) : print( "First Occurrence = ", first, " \nLast Occurrence = ", last) else : print("Not Found") # Driver codearr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]n = len(arr)x = 8findFirstAndLast(arr, n, x) # This code is contributed by Nikita Tiwari.
// C# program to find first and last// occurrence of an elements in given// sorted arrayusing System; class GFG { // Function for finding first and // last occurrence of an elements static void findFirstAndLast(int[] arr, int x) { int n = arr.Length; int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { Console.WriteLine("First " + "Occurrence = " + first); Console.Write("Last " + "Occurrence = " + last); } else Console.Write("Not Found"); } // Driver code public static void Main() { int[] arr = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int x = 8; findFirstAndLast(arr, x); }} // This code is contributed by nitin mittal.
<?php// PHP program to find first and last// occurrence of an elements in given// sorted array // Function for finding first and last// occurrence of an elementsfunction findFirstAndLast( $arr, $n, $x){ $first = -1; $last = -1; for ( $i = 0; $i < $n; $i++) { if ($x != $arr[$i]) continue; if ($first == -1) $first = $i; $last = $i; } if ($first != -1) echo "First Occurrence = ", $first, "\n", "\nLast Occurrence = ", $last; else echo "Not Found";} // Driver code $arr = array(1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ); $n = count($arr); $x = 8; findFirstAndLast($arr, $n, $x); // This code is contributed by anuj_67.?>
<script>// Javascript program to find first and last occurrence of// an elements in given sorted array // Function for finding first and last occurrence // of an elements function findFirstAndLast(arr,x) { let n = arr.length; let first = -1, last = -1; for (let i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { document.write("First Occurrence = " + first + "<br>"); document.write("Last Occurrence = " + last + "<br>"); } else document.write("Not Found"); } let arr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let x = 8; findFirstAndLast(arr, x); // This code is contributed by avanitrachhadiya2155</script>
First Occurrence = 8nLast Occurrence = 9
Time Complexity: O(n) Auxiliary Space: O(1) An Efficient solution to this problem is to use a binary search. 1. For the first occurrence of a number
a) If (high >= low)
b) Calculate mid = low + (high - low)/2;
c) If ((mid == 0 || x > arr[mid-1]) && arr[mid] == x)
return mid;
d) Else if (x > arr[mid])
return first(arr, (mid + 1), high, x, n);
e) Else
return first(arr, low, (mid -1), x, n);
f) Otherwise return -1;
2. For the last occurrence of a number
a) if (high >= low)
b) calculate mid = low + (high - low)/2;
c)if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x )
return mid;
d) else if(x < arr[mid])
return last(arr, low, (mid -1), x, n);
e) else
return last(arr, (mid + 1), high, x, n);
f) otherwise return -1;
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find first and last occurrences of// a number in a given sorted array#include <bits/stdc++.h>using namespace std; /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */int first(int arr[], int low, int high, int x, int n){ if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1;} /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */int last(int arr[], int low, int high, int x, int n){ if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1;} // Driver programint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; printf("First Occurrence = %d\t", first(arr, 0, n - 1, x, n)); printf("\nLast Occurrence = %d\n", last(arr, 0, n - 1, x, n)); return 0;}
// Java program to find first and last occurrence of// an elements in given sorted arrayimport java.io.*; class GFG { /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int first(int arr[], int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1; } /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int last(int arr[], int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = arr.length; int x = 8; System.out.println("First Occurrence = " + first(arr, 0, n - 1, x, n)); System.out.println("Last Occurrence = " + last(arr, 0, n - 1, x, n)); }}
# Python 3 program to find first and# last occurrences of a number in# a given sorted array # if x is present in arr[] then# returns the index of FIRST# occurrence of x in arr[0..n-1],# otherwise returns -1def first(arr, low, high, x, n) : if(high >= low) : mid = low + (high - low) // 2 if( ( mid == 0 or x > arr[mid - 1]) and arr[mid] == x) : return mid else if(x > arr[mid]) : return first(arr, (mid + 1), high, x, n) else : return first(arr, low, (mid - 1), x, n) return -1 # if x is present in arr[] then# returns the index of LAST occurrence# of x in arr[0..n-1], otherwise# returns -1def last(arr, low, high, x, n) : if (high >= low) : mid = low + (high - low) // 2 if (( mid == n - 1 or x < arr[mid + 1]) and arr[mid] == x) : return mid else if (x < arr[mid]) : return last(arr, low, (mid - 1), x, n) else : return last(arr, (mid + 1), high, x, n) return -1 # Driver programarr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8]n = len(arr) x = 8print("First Occurrence = ", first(arr, 0, n - 1, x, n))print("Last Occurrence = ", last(arr, 0, n - 1, x, n)) # This code is contributed by Nikita Tiwari.
// C# program to find first and last occurrence// of an elements in given sorted arrayusing System; class GFG { /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int first(int[] arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1; } /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int last(int[] arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } // Driver code public static void Main() { int[] arr = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = arr.Length; int x = 8; Console.WriteLine("First Occurrence = " + first(arr, 0, n - 1, x, n)); Console.Write("Last Occurrence = " + last(arr, 0, n - 1, x, n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find first// and last occurrences of a// number in a given sorted array // if x is present in arr[] then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1function first($arr, $low, $high, $x, $n){ if($high >= $low) { $mid = floor($low + ($high - $low) / 2); if(($mid == 0 or $x > $arr[$mid - 1]) and $arr[$mid] == $x) return $mid; else if($x > $arr[$mid]) return first($arr, ($mid + 1), $high, $x, $n); else return first($arr, $low, ($mid - 1), $x, $n); } return -1;} // if x is present in arr[]// then returns the index of// LAST occurrence of x in// arr[0..n-1], otherwise// returns -1function last($arr, $low, $high, $x, $n){ if ($high >= $low) { $mid = floor($low + ($high - $low) / 2); if (( $mid == $n - 1 or $x < $arr[$mid + 1]) and $arr[$mid] == $x) return $mid; else if ($x < $arr[$mid]) return last($arr, $low, ($mid - 1), $x, $n); else return last($arr, ($mid + 1), $high, $x, $n); return -1; }} // Driver Code $arr = array(1, 2, 2, 2, 2, 3, 4, 7, 8, 8); $n = count($arr); $x = 8; echo "First Occurrence = ", first($arr, 0, $n - 1, $x, $n), "\n"; echo "Last Occurrence = ", last($arr, 0, $n - 1, $x, $n); // This code is contributed by anuj_67?>
<script> // JavaScript program to find first and last occurrences of// a number in a given sorted array /* if x is present in arr then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ function first(arr,low,high,x,n){ if (high >= low) { let mid = low + Math.floor((high - low) / 2); if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1;} /* if x is present in arr then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */function last(arr, low, high, x, n){ if (high >= low) { let mid = low + Math.floor((high - low) / 2); if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1;} // Driver program let arr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let n = arr.length; let x = 8; document.write("First Occurrence = " + first(arr, 0, n - 1, x, n),"</br>"); console.log("Last Occurrence = " + last(arr, 0, n - 1, x, n),"</br>"); // code is contributed by shinjanpatra </script>
First Occurrence = 8
Last Occurrence = 9
Time Complexity : O(log n) Auxiliary Space : O(Log n)
Iterative Implementation of Binary Search Solution :
C++
C
Java
Python3
C#
Javascript
// C++ program to find first and last occurrences// of a number in a given sorted array#include <bits/stdc++.h>using namespace std; /* if x is present in arr[] then returns theindex of FIRST occurrence of x in arr[0..n-1],otherwise returns -1 */int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* If x is present in arr[] then returnsthe index of LAST occurrence of x inarr[0..n-1], otherwise returns -1 */int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; cout <<"First Occurrence = " << first(arr, x, n); cout <<"\nLast Occurrence = "<< last(arr, x, n); return 0;} // This code is contributed by shivanisinghss2110
// C program to find first and last occurrences of// a number in a given sorted array#include <stdio.h> /* if x is present in arr[] then returns the index ofFIRST occurrence of x in arr[0..n-1], otherwisereturns -1 */int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* if x is present in arr[] then returns the index ofLAST occurrence of x in arr[0..n-1], otherwisereturns -1 */int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver programint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; printf("First Occurrence = %d\t", first(arr, x, n)); printf("\nLast Occurrence = %d\n", last(arr, x, n)); return 0;}
// Java program to find first// and last occurrences of a// number in a given sorted arrayimport java.util.*;class GFG{ // if x is present in arr[] then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1static int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as // x, we update res and // move to the left half. else { res = mid; high = mid - 1; } } return res;} // If x is present in arr[] then returns// the index of LAST occurrence of x in// arr[0..n-1], otherwise returns -1static int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, // we update res and move to // the right half. else { res = mid; low = mid + 1; } } return res;} // Driver programpublic static void main(String[] args){ int arr[] = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.length; int x = 8; System.out.println("First Occurrence = " + first(arr, x, n)); System.out.println("Last Occurrence = " + last(arr, x, n));}} // This code is contributed by Chitranayal
# Python3 program to find first and# last occurrences of a number in a# given sorted array # If x is present in arr[] then# returns the index of FIRST# occurrence of x in arr[0..n-1],# otherwise returns -1def first(arr, x, n): low = 0 high = n - 1 res = -1 while (low <= high): # Normal Binary Search Logic mid = (low + high) // 2 if arr[mid] > x: high = mid - 1 else if arr[mid] < x: low = mid + 1 # If arr[mid] is same as x, we # update res and move to the left # half. else: res = mid high = mid - 1 return res # If x is present in arr[] then returns# the index of FIRST occurrence of x in# arr[0..n-1], otherwise returns -1def last(arr, x, n): low = 0 high = n - 1 res = -1 while(low <= high): # Normal Binary Search Logic mid = (low + high) // 2 if arr[mid] > x: high = mid - 1 else if arr[mid] < x: low = mid + 1 # If arr[mid] is same as x, we # update res and move to the Right # half. else: res = mid low = mid + 1 return res # Driver codearr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]n = len(arr)x = 8 print("First Occurrence =", first(arr, x, n))print("Last Occurrence =", last(arr, x, n)) # This code is contributed by Ediga_Manisha.
// C# program to find first// and last occurrences of a// number in a given sorted arrayusing System;class GFG{ // if x is present in []arr then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1static int first(int []arr, int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as // x, we update res and // move to the left half. else { res = mid; high = mid - 1; } } return res;} // If x is present in []arr then returns// the index of LAST occurrence of x in// arr[0..n-1], otherwise returns -1static int last(int []arr, int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, // we update res and move to // the right half. else { res = mid; low = mid + 1; } } return res;} // Driver programpublic static void Main(String[] args){ int []arr = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.Length; int x = 8; Console.WriteLine("First Occurrence = " + first(arr, x, n)); Console.WriteLine("Last Occurrence = " + last(arr, x, n));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find first and last occurrences// of a number in a given sorted array /* if x is present in arr[] then returns theindex of FIRST occurrence of x in arr[0..n-1],otherwise returns -1 */ function first(arr, x, n){ let low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic let mid = Math.floor((low + high) / 2); if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* If x is present in arr[] then returnsthe index of LAST occurrence of x inarr[0..n-1], otherwise returns -1 */function last(arr, x, n){ let low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic let mid = Math.floor((low + high) / 2); if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver code let arr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let n = arr.length; let x = 8; document.write("First Occurrence = " + first(arr, x, n),"</br>"); document.write("Last Occurrence = " + last(arr, x, n)); // This code is contributed by shinjanpatra </script>
First Occurrence = 8
Last Occurrence = 9
Time Complexity : O(log n) Auxiliary Space : O(1)
Using ArrayList
Add all the elements of the array to ArrayList and using indexOf() and lastIndexOf() method we will find the first position and the last position of the element in the array.
Java
// Java program for the above approachimport java.util.ArrayList;public class GFG { public static int first(ArrayList list, int x) { // return first occurrence index // of element x in ArrayList // using method indexOf() return list.indexOf(x); } public static int last(ArrayList list, int x) { // return last occurrence index // of element x in ArrayList // using method lastIndexOf() return list.lastIndexOf(x); } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; ArrayList<Integer> clist = new ArrayList<>(); // adding elements of array to ArrayList for (int i : arr) clist.add(i); int x = 8; // displaying the first occurrence System.out.println("First Occurrence = " + first(clist, x)); // displaying the last occurrence System.out.println("Last Occurrence = " + last(clist, x)); }}
Output:
First Occurrence = 8
Last Occurrence = 9
Another approach using c++ STL functions lower and upper bound
C++
#include <bits/stdc++.h>using namespace std; void findFirstAndLast(int arr[], int n, int x){ int first, last; // to store first occurrence first = lower_bound(arr, arr + n, x) - arr; // to store last occurrence last = upper_bound(arr, arr + n, x) - arr - 1; if (first == n) { first = -1; last = -1; } cout << "First Occurrence = " << first << "\nLast Occurrence = " << last;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; findFirstAndLast(arr, n, x); return 0;}
First Occurrence = 8
Last Occurrence = 9
Time Complexity : O(log n)
Auxiliary Space : O(1)
Extended Problem : Count number of occurrences in a sorted arrayThis article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
harshitSingh_11
manishaediga23
ukasp
29AjayKumar
le0
prathamverma42
avanitrachhadiya2155
anushikasethh
sumitgumber28
shivanisinghss2110
sagar0719kumar
gjain2299
ruhelaa48
shinjanpatra
surinderdawra388
Amazon
Binary Search
Arrays
Amazon
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation) | [
{
"code": null,
"e": 24916,
"s": 24888,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 25066,
"s": 24916,
"text": "Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array. "
},
{
"code": null,
"e": 25077,
"s": 25066,
"text": "Examples: "
},
{
"code": null,
"e": 25330,
"s": 25077,
"text": "Input : arr[] = {1, 3, 5, 5, 5, 5, 67, 123, 125} \n x = 5\nOutput : First Occurrence = 2\n Last Occurrence = 5\n\nInput : arr[] = {1, 3, 5, 5, 5, 5, 7, 123, 125 } \n x = 7\nOutput : First Occurrence = 6\n Last Occurrence = 6"
},
{
"code": null,
"e": 25410,
"s": 25330,
"text": "The Naive Approach is to run a for loop and check given elements in an array. "
},
{
"code": null,
"e": 25629,
"s": 25410,
"text": "1. Run a for loop and for i = 0 to n-1\n2. Take first = -1 and last = -1 \n3. When we find element first time then we update first = i \n4. We always update last=i whenever we find the element.\n5. We print first and last."
},
{
"code": null,
"e": 25633,
"s": 25629,
"text": "C++"
},
{
"code": null,
"e": 25638,
"s": 25633,
"text": "Java"
},
{
"code": null,
"e": 25646,
"s": 25638,
"text": "Python3"
},
{
"code": null,
"e": 25649,
"s": 25646,
"text": "C#"
},
{
"code": null,
"e": 25653,
"s": 25649,
"text": "PHP"
},
{
"code": null,
"e": 25664,
"s": 25653,
"text": "Javascript"
},
{
"code": "// C++ program to find first and last occurrence of// an elements in given sorted array#include <bits/stdc++.h>using namespace std; // Function for finding first and last occurrence// of an elementsvoid findFirstAndLast(int arr[], int n, int x){ int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) cout << \"First Occurrence = \" << first << \"\\nLast Occurrence = \" << last; else cout << \"Not Found\";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; findFirstAndLast(arr, n, x); return 0;}",
"e": 26409,
"s": 25664,
"text": null
},
{
"code": "// Java program to find first and last occurrence of// an elements in given sorted arrayimport java.io.*; class GFG { // Function for finding first and last occurrence // of an elements public static void findFirstAndLast(int arr[], int x) { int n = arr.length; int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { System.out.println(\"First Occurrence = \" + first); System.out.println(\"Last Occurrence = \" + last); } else System.out.println(\"Not Found\"); } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int x = 8; findFirstAndLast(arr, x); }}",
"e": 27274,
"s": 26409,
"text": null
},
{
"code": "# Python 3 program to find first and# last occurrence of an elements in# given sorted array # Function for finding first and last# occurrence of an elementsdef findFirstAndLast(arr, n, x) : first = -1 last = -1 for i in range(0, n) : if (x != arr[i]) : continue if (first == -1) : first = i last = i if (first != -1) : print( \"First Occurrence = \", first, \" \\nLast Occurrence = \", last) else : print(\"Not Found\") # Driver codearr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]n = len(arr)x = 8findFirstAndLast(arr, n, x) # This code is contributed by Nikita Tiwari.",
"e": 27941,
"s": 27274,
"text": null
},
{
"code": "// C# program to find first and last// occurrence of an elements in given// sorted arrayusing System; class GFG { // Function for finding first and // last occurrence of an elements static void findFirstAndLast(int[] arr, int x) { int n = arr.Length; int first = -1, last = -1; for (int i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { Console.WriteLine(\"First \" + \"Occurrence = \" + first); Console.Write(\"Last \" + \"Occurrence = \" + last); } else Console.Write(\"Not Found\"); } // Driver code public static void Main() { int[] arr = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int x = 8; findFirstAndLast(arr, x); }} // This code is contributed by nitin mittal.",
"e": 28953,
"s": 27941,
"text": null
},
{
"code": "<?php// PHP program to find first and last// occurrence of an elements in given// sorted array // Function for finding first and last// occurrence of an elementsfunction findFirstAndLast( $arr, $n, $x){ $first = -1; $last = -1; for ( $i = 0; $i < $n; $i++) { if ($x != $arr[$i]) continue; if ($first == -1) $first = $i; $last = $i; } if ($first != -1) echo \"First Occurrence = \", $first, \"\\n\", \"\\nLast Occurrence = \", $last; else echo \"Not Found\";} // Driver code $arr = array(1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ); $n = count($arr); $x = 8; findFirstAndLast($arr, $n, $x); // This code is contributed by anuj_67.?>",
"e": 29739,
"s": 28953,
"text": null
},
{
"code": "<script>// Javascript program to find first and last occurrence of// an elements in given sorted array // Function for finding first and last occurrence // of an elements function findFirstAndLast(arr,x) { let n = arr.length; let first = -1, last = -1; for (let i = 0; i < n; i++) { if (x != arr[i]) continue; if (first == -1) first = i; last = i; } if (first != -1) { document.write(\"First Occurrence = \" + first + \"<br>\"); document.write(\"Last Occurrence = \" + last + \"<br>\"); } else document.write(\"Not Found\"); } let arr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let x = 8; findFirstAndLast(arr, x); // This code is contributed by avanitrachhadiya2155</script>",
"e": 30584,
"s": 29739,
"text": null
},
{
"code": null,
"e": 30625,
"s": 30584,
"text": "First Occurrence = 8nLast Occurrence = 9"
},
{
"code": null,
"e": 30777,
"s": 30627,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) An Efficient solution to this problem is to use a binary search. 1. For the first occurrence of a number "
},
{
"code": null,
"e": 31082,
"s": 30777,
"text": " a) If (high >= low)\n b) Calculate mid = low + (high - low)/2;\n c) If ((mid == 0 || x > arr[mid-1]) && arr[mid] == x)\n return mid;\n d) Else if (x > arr[mid])\n return first(arr, (mid + 1), high, x, n);\n e) Else\n return first(arr, low, (mid -1), x, n);\n f) Otherwise return -1;"
},
{
"code": null,
"e": 31122,
"s": 31082,
"text": "2. For the last occurrence of a number "
},
{
"code": null,
"e": 31431,
"s": 31122,
"text": " a) if (high >= low)\n b) calculate mid = low + (high - low)/2;\n c)if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x )\n return mid;\n d) else if(x < arr[mid])\n return last(arr, low, (mid -1), x, n);\n e) else\n return last(arr, (mid + 1), high, x, n); \n f) otherwise return -1;"
},
{
"code": null,
"e": 31435,
"s": 31431,
"text": "C++"
},
{
"code": null,
"e": 31440,
"s": 31435,
"text": "Java"
},
{
"code": null,
"e": 31448,
"s": 31440,
"text": "Python3"
},
{
"code": null,
"e": 31451,
"s": 31448,
"text": "C#"
},
{
"code": null,
"e": 31455,
"s": 31451,
"text": "PHP"
},
{
"code": null,
"e": 31466,
"s": 31455,
"text": "Javascript"
},
{
"code": "// C++ program to find first and last occurrences of// a number in a given sorted array#include <bits/stdc++.h>using namespace std; /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */int first(int arr[], int low, int high, int x, int n){ if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1;} /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */int last(int arr[], int low, int high, int x, int n){ if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1;} // Driver programint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; printf(\"First Occurrence = %d\\t\", first(arr, 0, n - 1, x, n)); printf(\"\\nLast Occurrence = %d\\n\", last(arr, 0, n - 1, x, n)); return 0;}",
"e": 32870,
"s": 31466,
"text": null
},
{
"code": "// Java program to find first and last occurrence of// an elements in given sorted arrayimport java.io.*; class GFG { /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int first(int arr[], int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1; } /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int last(int arr[], int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = arr.length; int x = 8; System.out.println(\"First Occurrence = \" + first(arr, 0, n - 1, x, n)); System.out.println(\"Last Occurrence = \" + last(arr, 0, n - 1, x, n)); }}",
"e": 34414,
"s": 32870,
"text": null
},
{
"code": "# Python 3 program to find first and# last occurrences of a number in# a given sorted array # if x is present in arr[] then# returns the index of FIRST# occurrence of x in arr[0..n-1],# otherwise returns -1def first(arr, low, high, x, n) : if(high >= low) : mid = low + (high - low) // 2 if( ( mid == 0 or x > arr[mid - 1]) and arr[mid] == x) : return mid else if(x > arr[mid]) : return first(arr, (mid + 1), high, x, n) else : return first(arr, low, (mid - 1), x, n) return -1 # if x is present in arr[] then# returns the index of LAST occurrence# of x in arr[0..n-1], otherwise# returns -1def last(arr, low, high, x, n) : if (high >= low) : mid = low + (high - low) // 2 if (( mid == n - 1 or x < arr[mid + 1]) and arr[mid] == x) : return mid else if (x < arr[mid]) : return last(arr, low, (mid - 1), x, n) else : return last(arr, (mid + 1), high, x, n) return -1 # Driver programarr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8]n = len(arr) x = 8print(\"First Occurrence = \", first(arr, 0, n - 1, x, n))print(\"Last Occurrence = \", last(arr, 0, n - 1, x, n)) # This code is contributed by Nikita Tiwari.",
"e": 35675,
"s": 34414,
"text": null
},
{
"code": "// C# program to find first and last occurrence// of an elements in given sorted arrayusing System; class GFG { /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int first(int[] arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1; } /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */ public static int last(int[] arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } // Driver code public static void Main() { int[] arr = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = arr.Length; int x = 8; Console.WriteLine(\"First Occurrence = \" + first(arr, 0, n - 1, x, n)); Console.Write(\"Last Occurrence = \" + last(arr, 0, n - 1, x, n)); }} // This code is contributed by nitin mittal.",
"e": 37505,
"s": 35675,
"text": null
},
{
"code": "<?php// PHP program to find first// and last occurrences of a// number in a given sorted array // if x is present in arr[] then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1function first($arr, $low, $high, $x, $n){ if($high >= $low) { $mid = floor($low + ($high - $low) / 2); if(($mid == 0 or $x > $arr[$mid - 1]) and $arr[$mid] == $x) return $mid; else if($x > $arr[$mid]) return first($arr, ($mid + 1), $high, $x, $n); else return first($arr, $low, ($mid - 1), $x, $n); } return -1;} // if x is present in arr[]// then returns the index of// LAST occurrence of x in// arr[0..n-1], otherwise// returns -1function last($arr, $low, $high, $x, $n){ if ($high >= $low) { $mid = floor($low + ($high - $low) / 2); if (( $mid == $n - 1 or $x < $arr[$mid + 1]) and $arr[$mid] == $x) return $mid; else if ($x < $arr[$mid]) return last($arr, $low, ($mid - 1), $x, $n); else return last($arr, ($mid + 1), $high, $x, $n); return -1; }} // Driver Code $arr = array(1, 2, 2, 2, 2, 3, 4, 7, 8, 8); $n = count($arr); $x = 8; echo \"First Occurrence = \", first($arr, 0, $n - 1, $x, $n), \"\\n\"; echo \"Last Occurrence = \", last($arr, 0, $n - 1, $x, $n); // This code is contributed by anuj_67?>",
"e": 39131,
"s": 37505,
"text": null
},
{
"code": "<script> // JavaScript program to find first and last occurrences of// a number in a given sorted array /* if x is present in arr then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ function first(arr,low,high,x,n){ if (high >= low) { let mid = low + Math.floor((high - low) / 2); if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; else if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1;} /* if x is present in arr then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */function last(arr, low, high, x, n){ if (high >= low) { let mid = low + Math.floor((high - low) / 2); if ((mid == n - 1 || x < arr[mid + 1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1;} // Driver program let arr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let n = arr.length; let x = 8; document.write(\"First Occurrence = \" + first(arr, 0, n - 1, x, n),\"</br>\"); console.log(\"Last Occurrence = \" + last(arr, 0, n - 1, x, n),\"</br>\"); // code is contributed by shinjanpatra </script>",
"e": 40499,
"s": 39131,
"text": null
},
{
"code": null,
"e": 40544,
"s": 40499,
"text": "First Occurrence = 8 \nLast Occurrence = 9"
},
{
"code": null,
"e": 40601,
"s": 40546,
"text": "Time Complexity : O(log n) Auxiliary Space : O(Log n) "
},
{
"code": null,
"e": 40655,
"s": 40601,
"text": "Iterative Implementation of Binary Search Solution : "
},
{
"code": null,
"e": 40659,
"s": 40655,
"text": "C++"
},
{
"code": null,
"e": 40661,
"s": 40659,
"text": "C"
},
{
"code": null,
"e": 40666,
"s": 40661,
"text": "Java"
},
{
"code": null,
"e": 40674,
"s": 40666,
"text": "Python3"
},
{
"code": null,
"e": 40677,
"s": 40674,
"text": "C#"
},
{
"code": null,
"e": 40688,
"s": 40677,
"text": "Javascript"
},
{
"code": "// C++ program to find first and last occurrences// of a number in a given sorted array#include <bits/stdc++.h>using namespace std; /* if x is present in arr[] then returns theindex of FIRST occurrence of x in arr[0..n-1],otherwise returns -1 */int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* If x is present in arr[] then returnsthe index of LAST occurrence of x inarr[0..n-1], otherwise returns -1 */int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; cout <<\"First Occurrence = \" << first(arr, x, n); cout <<\"\\nLast Occurrence = \"<< last(arr, x, n); return 0;} // This code is contributed by shivanisinghss2110",
"e": 42342,
"s": 40688,
"text": null
},
{
"code": "// C program to find first and last occurrences of// a number in a given sorted array#include <stdio.h> /* if x is present in arr[] then returns the index ofFIRST occurrence of x in arr[0..n-1], otherwisereturns -1 */int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* if x is present in arr[] then returns the index ofLAST occurrence of x in arr[0..n-1], otherwisereturns -1 */int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver programint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; printf(\"First Occurrence = %d\\t\", first(arr, x, n)); printf(\"\\nLast Occurrence = %d\\n\", last(arr, x, n)); return 0;}",
"e": 43892,
"s": 42342,
"text": null
},
{
"code": "// Java program to find first// and last occurrences of a// number in a given sorted arrayimport java.util.*;class GFG{ // if x is present in arr[] then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1static int first(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as // x, we update res and // move to the left half. else { res = mid; high = mid - 1; } } return res;} // If x is present in arr[] then returns// the index of LAST occurrence of x in// arr[0..n-1], otherwise returns -1static int last(int arr[], int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, // we update res and move to // the right half. else { res = mid; low = mid + 1; } } return res;} // Driver programpublic static void main(String[] args){ int arr[] = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.length; int x = 8; System.out.println(\"First Occurrence = \" + first(arr, x, n)); System.out.println(\"Last Occurrence = \" + last(arr, x, n));}} // This code is contributed by Chitranayal",
"e": 45460,
"s": 43892,
"text": null
},
{
"code": "# Python3 program to find first and# last occurrences of a number in a# given sorted array # If x is present in arr[] then# returns the index of FIRST# occurrence of x in arr[0..n-1],# otherwise returns -1def first(arr, x, n): low = 0 high = n - 1 res = -1 while (low <= high): # Normal Binary Search Logic mid = (low + high) // 2 if arr[mid] > x: high = mid - 1 else if arr[mid] < x: low = mid + 1 # If arr[mid] is same as x, we # update res and move to the left # half. else: res = mid high = mid - 1 return res # If x is present in arr[] then returns# the index of FIRST occurrence of x in# arr[0..n-1], otherwise returns -1def last(arr, x, n): low = 0 high = n - 1 res = -1 while(low <= high): # Normal Binary Search Logic mid = (low + high) // 2 if arr[mid] > x: high = mid - 1 else if arr[mid] < x: low = mid + 1 # If arr[mid] is same as x, we # update res and move to the Right # half. else: res = mid low = mid + 1 return res # Driver codearr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]n = len(arr)x = 8 print(\"First Occurrence =\", first(arr, x, n))print(\"Last Occurrence =\", last(arr, x, n)) # This code is contributed by Ediga_Manisha.",
"e": 46911,
"s": 45460,
"text": null
},
{
"code": "// C# program to find first// and last occurrences of a// number in a given sorted arrayusing System;class GFG{ // if x is present in []arr then// returns the index of FIRST// occurrence of x in arr[0..n-1],// otherwise returns -1static int first(int []arr, int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as // x, we update res and // move to the left half. else { res = mid; high = mid - 1; } } return res;} // If x is present in []arr then returns// the index of LAST occurrence of x in// arr[0..n-1], otherwise returns -1static int last(int []arr, int x, int n){ int low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic int mid = (low + high) / 2; if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, // we update res and move to // the right half. else { res = mid; low = mid + 1; } } return res;} // Driver programpublic static void Main(String[] args){ int []arr = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.Length; int x = 8; Console.WriteLine(\"First Occurrence = \" + first(arr, x, n)); Console.WriteLine(\"Last Occurrence = \" + last(arr, x, n));}} // This code is contributed by 29AjayKumar",
"e": 48469,
"s": 46911,
"text": null
},
{
"code": "<script> // JavaScript program to find first and last occurrences// of a number in a given sorted array /* if x is present in arr[] then returns theindex of FIRST occurrence of x in arr[0..n-1],otherwise returns -1 */ function first(arr, x, n){ let low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic let mid = Math.floor((low + high) / 2); if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the left // half. else { res = mid; high = mid - 1; } } return res;} /* If x is present in arr[] then returnsthe index of LAST occurrence of x inarr[0..n-1], otherwise returns -1 */function last(arr, x, n){ let low = 0, high = n - 1, res = -1; while (low <= high) { // Normal Binary Search Logic let mid = Math.floor((low + high) / 2); if (arr[mid] > x) high = mid - 1; else if (arr[mid] < x) low = mid + 1; // If arr[mid] is same as x, we // update res and move to the right // half. else { res = mid; low = mid + 1; } } return res;} // Driver code let arr = [ 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]; let n = arr.length; let x = 8; document.write(\"First Occurrence = \" + first(arr, x, n),\"</br>\"); document.write(\"Last Occurrence = \" + last(arr, x, n)); // This code is contributed by shinjanpatra </script>",
"e": 50088,
"s": 48469,
"text": null
},
{
"code": null,
"e": 50133,
"s": 50088,
"text": "First Occurrence = 8 \nLast Occurrence = 9"
},
{
"code": null,
"e": 50186,
"s": 50135,
"text": "Time Complexity : O(log n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 50202,
"s": 50186,
"text": "Using ArrayList"
},
{
"code": null,
"e": 50377,
"s": 50202,
"text": "Add all the elements of the array to ArrayList and using indexOf() and lastIndexOf() method we will find the first position and the last position of the element in the array."
},
{
"code": null,
"e": 50382,
"s": 50377,
"text": "Java"
},
{
"code": "// Java program for the above approachimport java.util.ArrayList;public class GFG { public static int first(ArrayList list, int x) { // return first occurrence index // of element x in ArrayList // using method indexOf() return list.indexOf(x); } public static int last(ArrayList list, int x) { // return last occurrence index // of element x in ArrayList // using method lastIndexOf() return list.lastIndexOf(x); } public static void main(String[] args) { int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; ArrayList<Integer> clist = new ArrayList<>(); // adding elements of array to ArrayList for (int i : arr) clist.add(i); int x = 8; // displaying the first occurrence System.out.println(\"First Occurrence = \" + first(clist, x)); // displaying the last occurrence System.out.println(\"Last Occurrence = \" + last(clist, x)); }}",
"e": 51419,
"s": 50382,
"text": null
},
{
"code": null,
"e": 51427,
"s": 51419,
"text": "Output:"
},
{
"code": null,
"e": 51468,
"s": 51427,
"text": "First Occurrence = 8\nLast Occurrence = 9"
},
{
"code": null,
"e": 51532,
"s": 51468,
"text": " Another approach using c++ STL functions lower and upper bound"
},
{
"code": null,
"e": 51536,
"s": 51532,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void findFirstAndLast(int arr[], int n, int x){ int first, last; // to store first occurrence first = lower_bound(arr, arr + n, x) - arr; // to store last occurrence last = upper_bound(arr, arr + n, x) - arr - 1; if (first == n) { first = -1; last = -1; } cout << \"First Occurrence = \" << first << \"\\nLast Occurrence = \" << last;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; int n = sizeof(arr) / sizeof(int); int x = 8; findFirstAndLast(arr, n, x); return 0;}",
"e": 52132,
"s": 51536,
"text": null
},
{
"code": null,
"e": 52173,
"s": 52132,
"text": "First Occurrence = 8\nLast Occurrence = 9"
},
{
"code": null,
"e": 52200,
"s": 52173,
"text": "Time Complexity : O(log n)"
},
{
"code": null,
"e": 52225,
"s": 52200,
"text": " Auxiliary Space : O(1) "
},
{
"code": null,
"e": 52708,
"s": 52225,
"text": "Extended Problem : Count number of occurrences in a sorted arrayThis article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 52721,
"s": 52708,
"text": "nitin mittal"
},
{
"code": null,
"e": 52726,
"s": 52721,
"text": "vt_m"
},
{
"code": null,
"e": 52742,
"s": 52726,
"text": "harshitSingh_11"
},
{
"code": null,
"e": 52757,
"s": 52742,
"text": "manishaediga23"
},
{
"code": null,
"e": 52763,
"s": 52757,
"text": "ukasp"
},
{
"code": null,
"e": 52775,
"s": 52763,
"text": "29AjayKumar"
},
{
"code": null,
"e": 52779,
"s": 52775,
"text": "le0"
},
{
"code": null,
"e": 52794,
"s": 52779,
"text": "prathamverma42"
},
{
"code": null,
"e": 52815,
"s": 52794,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 52829,
"s": 52815,
"text": "anushikasethh"
},
{
"code": null,
"e": 52843,
"s": 52829,
"text": "sumitgumber28"
},
{
"code": null,
"e": 52862,
"s": 52843,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 52877,
"s": 52862,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 52887,
"s": 52877,
"text": "gjain2299"
},
{
"code": null,
"e": 52897,
"s": 52887,
"text": "ruhelaa48"
},
{
"code": null,
"e": 52910,
"s": 52897,
"text": "shinjanpatra"
},
{
"code": null,
"e": 52927,
"s": 52910,
"text": "surinderdawra388"
},
{
"code": null,
"e": 52934,
"s": 52927,
"text": "Amazon"
},
{
"code": null,
"e": 52948,
"s": 52934,
"text": "Binary Search"
},
{
"code": null,
"e": 52955,
"s": 52948,
"text": "Arrays"
},
{
"code": null,
"e": 52962,
"s": 52955,
"text": "Amazon"
},
{
"code": null,
"e": 52969,
"s": 52962,
"text": "Arrays"
},
{
"code": null,
"e": 52983,
"s": 52969,
"text": "Binary Search"
},
{
"code": null,
"e": 53081,
"s": 52983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53129,
"s": 53081,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 53197,
"s": 53129,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 53241,
"s": 53197,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 53273,
"s": 53241,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 53296,
"s": 53273,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 53310,
"s": 53296,
"text": "Linear Search"
},
{
"code": null,
"e": 53355,
"s": 53310,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 53376,
"s": 53355,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 53461,
"s": 53376,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
Can we declare a top level class as protected or private in Java?
| No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier). If it does not have a modifier, it is supposed to have a default access.
// A top level class
public class TopLevelClassTest {
// Class body
}
If a top-level class is declared as private the compiler will complain that the modifier private is not allowed here. This means that a top-level class cannot be a private, the same can be applied to protected access specifier also.
Protected means that the member can be accessed by any class in the same package and by subclasses even if they are in another package.
The top-level classes can only have public, abstract and final modifiers, and it is also possible to not define any class modifiers at all. This is called default/package accessibility.
We can declare the inner classes as private or protected, but it is not allowed in outer
classes.
More than one top-level class can be defined in a Java source file, but there can be at most one public top-level class declaration. The file name must match the name of the public class.
Live Demo
protected class ProtectedClassTest {
int i = 10;
void show() {
System.out.println("Declare top-level class as protected");
}
}
public class Test {
public static void main(String args[]) {
ProtectedClassTest pc = new ProtectedClassTest();
System.out.println(pc.i);
pc.show();
System.out.println("Main class declaration as public");
}
}
In the above example, we can declare the class as protected, it will throw an error says that modifier protected not allowed here. So the above code doesn't execute.
modifier protected not allowed here
Live Demo
private class PrivateClassTest {
int x = 20;
void show() {
System.out.println("Declare top-level class as private");
}
}
public class Test {
public static void main(String args[]) {
PrivateClassTest pc = new PrivateClassTest();
System.out.println(pc.x);
pc.show();
System.out.println("Main class declaration as public");
}
}
In the above example, we can declare the class as private, it will throw an error says that modifier private not allowed here. So the above code doesn't execute.
modifier private not allowed here | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier). If it does not have a modifier, it is supposed to have a default access."
},
{
"code": null,
"e": 1329,
"s": 1250,
"text": "// A top level class\n public class TopLevelClassTest {\n // Class body\n}"
},
{
"code": null,
"e": 1562,
"s": 1329,
"text": "If a top-level class is declared as private the compiler will complain that the modifier private is not allowed here. This means that a top-level class cannot be a private, the same can be applied to protected access specifier also."
},
{
"code": null,
"e": 1698,
"s": 1562,
"text": "Protected means that the member can be accessed by any class in the same package and by subclasses even if they are in another package."
},
{
"code": null,
"e": 1884,
"s": 1698,
"text": "The top-level classes can only have public, abstract and final modifiers, and it is also possible to not define any class modifiers at all. This is called default/package accessibility."
},
{
"code": null,
"e": 1982,
"s": 1884,
"text": "We can declare the inner classes as private or protected, but it is not allowed in outer\nclasses."
},
{
"code": null,
"e": 2170,
"s": 1982,
"text": "More than one top-level class can be defined in a Java source file, but there can be at most one public top-level class declaration. The file name must match the name of the public class."
},
{
"code": null,
"e": 2180,
"s": 2170,
"text": "Live Demo"
},
{
"code": null,
"e": 2560,
"s": 2180,
"text": "protected class ProtectedClassTest {\n int i = 10;\n void show() {\n System.out.println(\"Declare top-level class as protected\");\n }\n}\npublic class Test {\n public static void main(String args[]) {\n ProtectedClassTest pc = new ProtectedClassTest();\n System.out.println(pc.i);\n pc.show();\n System.out.println(\"Main class declaration as public\");\n }\n}"
},
{
"code": null,
"e": 2726,
"s": 2560,
"text": "In the above example, we can declare the class as protected, it will throw an error says that modifier protected not allowed here. So the above code doesn't execute."
},
{
"code": null,
"e": 2762,
"s": 2726,
"text": "modifier protected not allowed here"
},
{
"code": null,
"e": 2772,
"s": 2762,
"text": "Live Demo"
},
{
"code": null,
"e": 3142,
"s": 2772,
"text": "private class PrivateClassTest {\n int x = 20;\n void show() {\n System.out.println(\"Declare top-level class as private\");\n }\n}\npublic class Test {\n public static void main(String args[]) {\n PrivateClassTest pc = new PrivateClassTest();\n System.out.println(pc.x);\n pc.show();\n System.out.println(\"Main class declaration as public\");\n }\n}"
},
{
"code": null,
"e": 3304,
"s": 3142,
"text": "In the above example, we can declare the class as private, it will throw an error says that modifier private not allowed here. So the above code doesn't execute."
},
{
"code": null,
"e": 3338,
"s": 3304,
"text": "modifier private not allowed here"
}
] |
Excel Data Financial Analysis | You can perform financial analysis with Excel in an easy way. Excel provides you several financial functions such as PMT, PV, NPV, XNPV, IRR, MIRR, XIRR, and so on that enable you to quickly arrive at the financial analysis results.
In this chapter, you will learn where and how you can use these functions for your analysis.
An annuity is a series of constant cash payments made over a continuous period. For example, savings for retirement, insurance payments, home loan, mortgage, etc. In annuity functions −
A positive number represents cash received.
A negative number represents cash paid out.
The present value is the total amount that a series of future payments is worth now. You can calculate the present value using the Excel functions −
PV − Calculates the present value of an investment by using an interest rate and a series of future payments (negative values) and income (positive values). At least one of the cash flows must be positive and at least one must be negative.
PV − Calculates the present value of an investment by using an interest rate and a series of future payments (negative values) and income (positive values). At least one of the cash flows must be positive and at least one must be negative.
NPV − Calculates the net present value of an investment by using a discount rate and a series of periodic future payments (negative values) and income (positive values).
NPV − Calculates the net present value of an investment by using a discount rate and a series of periodic future payments (negative values) and income (positive values).
XNPV − Calculates the net present value for a schedule of cash flows that is not necessarily periodic.
XNPV − Calculates the net present value for a schedule of cash flows that is not necessarily periodic.
Note that −
PV cash flows must be constant whereas NPV cash flows can be variable.
PV cash flows must be constant whereas NPV cash flows can be variable.
PV cash flows can be either at the beginning or at the end of the period whereas NPV cash flows must be at the end of the period.
PV cash flows can be either at the beginning or at the end of the period whereas NPV cash flows must be at the end of the period.
NPV cash flows must be periodic whereas XNPV cash flows need not be periodic.
NPV cash flows must be periodic whereas XNPV cash flows need not be periodic.
In this section, you will understand how to work with PV. You will learn about NPV in a later section.
Suppose you are buying a refrigerator. The salesperson tells you that the price of the refrigerator is 32000, but you have an option to pay out the amount in 8 years with an interest rate of 13% per annum and yearly payments of 6000. You also have an option to make the payments either at the beginning or end of each year.
You want to know which of these options is beneficial for you.
You can use Excel function PV −
PV (rate, nper, pmt, [fv ], [type])
To calculate present value with payments at the end of each year, omit type or specify 0 for type.
To calculate present value with payments at the end of each year, specify 1 for type.
You will get the following results −
Therefore,
If you make the payment now, you need to pay 32,000 of present value.
If you opt for yearly payments with payment at the end of the year, you need to pay 28, 793 of present value.
If you opt for yearly payments with payment at the end of the year, you need to pay 32,536 of present value.
You can clearly see that option 2 is beneficial for you.
An Equated Monthly Installment (EMI) is defined by Investopedia as "A fixed payment amount made by a borrower to a lender at a specified date each calendar month. Equated monthly installments are used to pay off both interest and principal each month, so that over a specified number of years, the loan is paid off in full."
In Excel, you can calculate the EMI on a loan with the PMT function.
Suppose, you want to take a home loan of 5000000 with an annual interest rate of 11.5% and the term of the loan for 25 years. You can find your EMI as follows −
Calculate interest rate per month (Interest Rate per Annum/12)
Calculate number of monthly payments (No. of years * 12)
Use PMT function to calculate EMI
As you observe,
Present Value (PV) is the loan amount.
Future Value (FV) is 0 as at the end of the term the loan amount should be 0.
Type is 1 as the EMIs are paid at the beginning of each month.
You will get the following results −
EMI includes both-interest and a part payment of principal. As the time increases, these two components of EMI will vary, reducing the balance.
To get
The interest part of your monthly payments, you can use the Excel IPMT function.
The interest part of your monthly payments, you can use the Excel IPMT function.
The payment of principal part of your monthly payments, you can use the Excel PPMT function.
The payment of principal part of your monthly payments, you can use the Excel PPMT function.
For example, if you have taken a loan of 1,000,000 for a term of 8 months at the rate of 16% per annum. You can get values for the EMI, the decreasing interest amounts, the increasing payment of principal amounts and the diminishing loan balance over the 8 months. At the end of 8 months, loan balance will be 0.
Follow the procedure given below.
Step 1 − Calculate the EMI as follows.
This results in an EMI of Rs. 13261.59.
Step 2 − Next calculate the interest and principal parts of the EMI for the 8 months as shown below.
You will get the following results.
You can compute the interest and principal paid between two periods, inclusive.
Compute the cumulative interest paid between 2nd and 3rd months using the CUMIPMT function.
Compute the cumulative interest paid between 2nd and 3rd months using the CUMIPMT function.
Verify the result summing up the interest values for 2nd and 3rd months.
Verify the result summing up the interest values for 2nd and 3rd months.
Compute the cumulative principal paid between 2nd and 3rd months using the CUMPRINC function.
Compute the cumulative principal paid between 2nd and 3rd months using the CUMPRINC function.
Verify the result summing up the principal values for 2nd and 3rd months.
Verify the result summing up the principal values for 2nd and 3rd months.
You will get the following results.
You can see that your calculations match with your verification results.
Suppose you take a loan of 100,000 and you want to pay back in 15 months with a maximum monthly payment of 12000. You might want to know the interest rate at which you have to pay.
Find the interest rate with the Excel RATE function −
You will get the result as 8%.
Suppose you take a loan of 100,000 at the interest rate 10%. You want a maximum monthly payment of 15,000. You might want to know how long it will take for you to clear the loan.
Find the number of payments with Excel NPER function
You will get the result as 12 months.
When you want to make an investment, you compare the different options and choose the one that yields better returns. Net present value is useful in comparing cash flows over a period of time and deciding which one is better. The cash flows can occur at regular, periodical intervals or at irregular intervals.
First, we consider the case of regular, periodical cash flows.
The net present value of a sequence of cash flows received at different points in time in n years from now (n can be a fraction) is 1/(1 + r)n, where r is the annual interest rate.
Consider the following two investments over a period of 3 years.
At face value, Investment 1 looks better than Investment 2. However, you can decide on which investment is better only when you know the true worth of the investment as of today. You can use the NPV function to calculate the returns.
The cash flows can occur
At the end of every year.
At the beginning of every year.
In the middle of every year.
NPV function assumes that the cash flows are at the end of the year. If the cash flows occur at different times then you have to take into account that particular factor along with the calculation with NPV.
Suppose the cash flows occur at the end of the year. Then you can straight away use the NPV function.
You will get the following results −
As you observe NPV for Investment 2 is higher than that for Investment 1. Hence, Investment 2 is a better choice. You got this result as cash out flows for Investment 2 are at later periods as compared to that of Investment 1.
Suppose the cash flows occur at the beginning of every year. In such a case, you should not include the first cash flow in NPV calculation as it already represents the current value. You need to add the first cash flow to the NPV obtained from rest of the cash flows to get the net present value.
You will get the following results −
Suppose the cash flows occur in the middle of every year. In such a case, you need to multiply the NPV obtained from the cash flows by $\sqrt{1+r}$ to get the net present value.
You will get the following results −
If you want to calculate the net present value with irregular cash flows, i.e. cash flows occurring at random times, the calculation is a bit complex.
However, in Excel, you can easily do such a calculation with XNPV function.
Arrange your data with the dates and the cash flows.
Note − The first date in your data should be the earliest of all the dates. The other dates can occur in any order.
Use the XNPV function to calculate the net present value.
You will get the following results −
Suppose today’s date is 15th March, 2015. As you observe, all the dates of cash flows are of later dates. If you want to find the net present value as of today, include it in the data at the top and specify 0 for the cash flow.
You will get the following results −
Internal Rate of Return (IRR) of an investment is the rate of interest at which NPV is 0. It is the rate value for which the present values of the positive cash flows exactly compensate the negative ones. When the discount rate is the IRR, the investment is perfectly indifferent, i.e. the investor is neither gaining nor losing money.
Consider the following cash flows, different interest rates and the corresponding NPV values.
As you can observe between the values of interest rate 10% and 11%, the sign of NPV changes. When you fine-tune the interest rate to 10.53%, NPV is nearly 0. Hence, IRR is 10.53%.
You can calculate IRR of cash flows with Excel function IRR.
The IRR is 10.53% as you had seen in the previous section.
For the given cash flows, IRR may −
exist and unique
exist and multiple
not exist
If IRR exists and is unique, it can be used to choose the best investment among several possibilities.
If the first cash flow is negative, it means the investor has the money and wants to invest. Then, the higher the IRR the better, since it represents the interest rate the investor is receiving.
If the first cash flow is negative, it means the investor has the money and wants to invest. Then, the higher the IRR the better, since it represents the interest rate the investor is receiving.
If the first cash flow is positive, it means the investor needs money and is looking for a loan, the lower the IRR the better since it represents the interest rate the investor is paying.
If the first cash flow is positive, it means the investor needs money and is looking for a loan, the lower the IRR the better since it represents the interest rate the investor is paying.
To find if an IRR is unique or not, vary the guess value and calculate IRR. If IRR remains constant then it is unique.
As you observe, the IRR has a unique value for the different guess values.
In certain cases, you may have multiple IRRs. Consider the following cash flows. Calculate IRR with different guess values.
You will get the following results −
You can observe that there are two IRRs - -9.59% and 216.09%. You can verify these two IRRs calculating NPV.
For both -9.59% and 216.09%, NPV is 0.
In certain cases, you may not have IRR. Consider the following cash flows. Calculate IRR with different guess values.
You will get the result as #NUM for all the guess values.
The result #NUM means that there is no IRR for the cash flows considered.
If there is only one sign change in the cash flows, such as from negative to positive or positive to negative, then a unique IRR is guaranteed. For example, in capital investments, the first cash flow will be negative, while the rest of the cash flows will be positive. In such cases, unique IRR exists.
If there is more than one sign change in the cash flows, IRR may not exist. Even if it exists, it may not be unique.
Many analysts prefer to use IRR and it is a popular profitability measure because, as a percentage, it is easy to understand and easy to compare to the required return. However, there are certain problems while making decisions with IRR. If you rank with IRRs and make decisions based on these ranks, you may end up with wrong decisions.
You have already seen that NPV will enable you to make financial decisions. However, IRR and NPV will not always lead to the same decision when projects are mutually exclusive.
Mutually exclusive projects are those for which the selection of one project precludes the acceptance of another. When projects that are being compared are mutually exclusive, a ranking conflict may arise between NPV and IRR. If you have to choose between project A and project B, NPV may suggest acceptance of project A whereas IRR may suggest project B.
This type of conflict between NPV and IRR may arise because of one of the following reasons −
The projects are of greatly different sizes, or
The timing of the cash flows are different.
If you want to make a decision by IRR, project A yields a return of 100 and Project B a return of 50. Hence, investment on project A looks profitable. However, this is a wrong decision because of the difference in the scale of projects.
Consider −
You have 1000 to invest.
You have 1000 to invest.
If you invest entire 1000 on project A, you get a return of 100.
If you invest entire 1000 on project A, you get a return of 100.
If you invest 100 on project B, you will still have 900 in your hand that you can invest on another project, say project C. Suppose you get a return of 20% on project C, then the total return on project B and project C is 230, which is way ahead in profitability.
If you invest 100 on project B, you will still have 900 in your hand that you can invest on another project, say project C. Suppose you get a return of 20% on project C, then the total return on project B and project C is 230, which is way ahead in profitability.
Thus, NPV is a better way for decision making in such cases.
Again, if you consider IRR to decide, project B would be the choice. However, project A has a higher NPV and is an ideal choice.
Your cash flows may sometimes be irregularly spaced. In such a case, you cannot use IRR as IRR requires equally spaced time intervals. You can use XIRR instead, which takes into account the dates of the cash flows along with the cash flows.
The Internal Rate of Return that results in is 26.42%.
Consider a case when your finance rate is different from your reinvestment rate. If you calculate Internal Rate of Return with IRR, it assumes same rate for both finance and reinvestment. Further, you might also get multiple IRRs.
For example, consider the cash flows given below −
As you observe, NPV is 0 more than once, resulting in multiple IRRs. Further, reinvestment rate is not taken into account. In such cases, you can use modified IRR (MIRR).
You will get a result of 7% as shown below −
Note − Unlike IRR, MIRR will always be unique.
102 Lectures
10 hours
Pavan Lalwani
101 Lectures
6 hours
Pavan Lalwani
56 Lectures
5.5 hours
Pavan Lalwani
63 Lectures
3.5 hours
Yoda Learning
134 Lectures
8.5 hours
Yoda Learning
33 Lectures
3 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2867,
"s": 2634,
"text": "You can perform financial analysis with Excel in an easy way. Excel provides you several financial functions such as PMT, PV, NPV, XNPV, IRR, MIRR, XIRR, and so on that enable you to quickly arrive at the financial analysis results."
},
{
"code": null,
"e": 2960,
"s": 2867,
"text": "In this chapter, you will learn where and how you can use these functions for your analysis."
},
{
"code": null,
"e": 3146,
"s": 2960,
"text": "An annuity is a series of constant cash payments made over a continuous period. For example, savings for retirement, insurance payments, home loan, mortgage, etc. In annuity functions −"
},
{
"code": null,
"e": 3190,
"s": 3146,
"text": "A positive number represents cash received."
},
{
"code": null,
"e": 3234,
"s": 3190,
"text": "A negative number represents cash paid out."
},
{
"code": null,
"e": 3383,
"s": 3234,
"text": "The present value is the total amount that a series of future payments is worth now. You can calculate the present value using the Excel functions −"
},
{
"code": null,
"e": 3623,
"s": 3383,
"text": "PV − Calculates the present value of an investment by using an interest rate and a series of future payments (negative values) and income (positive values). At least one of the cash flows must be positive and at least one must be negative."
},
{
"code": null,
"e": 3863,
"s": 3623,
"text": "PV − Calculates the present value of an investment by using an interest rate and a series of future payments (negative values) and income (positive values). At least one of the cash flows must be positive and at least one must be negative."
},
{
"code": null,
"e": 4033,
"s": 3863,
"text": "NPV − Calculates the net present value of an investment by using a discount rate and a series of periodic future payments (negative values) and income (positive values)."
},
{
"code": null,
"e": 4203,
"s": 4033,
"text": "NPV − Calculates the net present value of an investment by using a discount rate and a series of periodic future payments (negative values) and income (positive values)."
},
{
"code": null,
"e": 4306,
"s": 4203,
"text": "XNPV − Calculates the net present value for a schedule of cash flows that is not necessarily periodic."
},
{
"code": null,
"e": 4409,
"s": 4306,
"text": "XNPV − Calculates the net present value for a schedule of cash flows that is not necessarily periodic."
},
{
"code": null,
"e": 4421,
"s": 4409,
"text": "Note that −"
},
{
"code": null,
"e": 4492,
"s": 4421,
"text": "PV cash flows must be constant whereas NPV cash flows can be variable."
},
{
"code": null,
"e": 4563,
"s": 4492,
"text": "PV cash flows must be constant whereas NPV cash flows can be variable."
},
{
"code": null,
"e": 4693,
"s": 4563,
"text": "PV cash flows can be either at the beginning or at the end of the period whereas NPV cash flows must be at the end of the period."
},
{
"code": null,
"e": 4823,
"s": 4693,
"text": "PV cash flows can be either at the beginning or at the end of the period whereas NPV cash flows must be at the end of the period."
},
{
"code": null,
"e": 4901,
"s": 4823,
"text": "NPV cash flows must be periodic whereas XNPV cash flows need not be periodic."
},
{
"code": null,
"e": 4979,
"s": 4901,
"text": "NPV cash flows must be periodic whereas XNPV cash flows need not be periodic."
},
{
"code": null,
"e": 5082,
"s": 4979,
"text": "In this section, you will understand how to work with PV. You will learn about NPV in a later section."
},
{
"code": null,
"e": 5406,
"s": 5082,
"text": "Suppose you are buying a refrigerator. The salesperson tells you that the price of the refrigerator is 32000, but you have an option to pay out the amount in 8 years with an interest rate of 13% per annum and yearly payments of 6000. You also have an option to make the payments either at the beginning or end of each year."
},
{
"code": null,
"e": 5469,
"s": 5406,
"text": "You want to know which of these options is beneficial for you."
},
{
"code": null,
"e": 5501,
"s": 5469,
"text": "You can use Excel function PV −"
},
{
"code": null,
"e": 5538,
"s": 5501,
"text": "PV (rate, nper, pmt, [fv ], [type])\n"
},
{
"code": null,
"e": 5637,
"s": 5538,
"text": "To calculate present value with payments at the end of each year, omit type or specify 0 for type."
},
{
"code": null,
"e": 5723,
"s": 5637,
"text": "To calculate present value with payments at the end of each year, specify 1 for type."
},
{
"code": null,
"e": 5760,
"s": 5723,
"text": "You will get the following results −"
},
{
"code": null,
"e": 5771,
"s": 5760,
"text": "Therefore,"
},
{
"code": null,
"e": 5841,
"s": 5771,
"text": "If you make the payment now, you need to pay 32,000 of present value."
},
{
"code": null,
"e": 5951,
"s": 5841,
"text": "If you opt for yearly payments with payment at the end of the year, you need to pay 28, 793 of present value."
},
{
"code": null,
"e": 6060,
"s": 5951,
"text": "If you opt for yearly payments with payment at the end of the year, you need to pay 32,536 of present value."
},
{
"code": null,
"e": 6117,
"s": 6060,
"text": "You can clearly see that option 2 is beneficial for you."
},
{
"code": null,
"e": 6442,
"s": 6117,
"text": "An Equated Monthly Installment (EMI) is defined by Investopedia as \"A fixed payment amount made by a borrower to a lender at a specified date each calendar month. Equated monthly installments are used to pay off both interest and principal each month, so that over a specified number of years, the loan is paid off in full.\""
},
{
"code": null,
"e": 6511,
"s": 6442,
"text": "In Excel, you can calculate the EMI on a loan with the PMT function."
},
{
"code": null,
"e": 6672,
"s": 6511,
"text": "Suppose, you want to take a home loan of 5000000 with an annual interest rate of 11.5% and the term of the loan for 25 years. You can find your EMI as follows −"
},
{
"code": null,
"e": 6735,
"s": 6672,
"text": "Calculate interest rate per month (Interest Rate per Annum/12)"
},
{
"code": null,
"e": 6792,
"s": 6735,
"text": "Calculate number of monthly payments (No. of years * 12)"
},
{
"code": null,
"e": 6826,
"s": 6792,
"text": "Use PMT function to calculate EMI"
},
{
"code": null,
"e": 6842,
"s": 6826,
"text": "As you observe,"
},
{
"code": null,
"e": 6881,
"s": 6842,
"text": "Present Value (PV) is the loan amount."
},
{
"code": null,
"e": 6959,
"s": 6881,
"text": "Future Value (FV) is 0 as at the end of the term the loan amount should be 0."
},
{
"code": null,
"e": 7022,
"s": 6959,
"text": "Type is 1 as the EMIs are paid at the beginning of each month."
},
{
"code": null,
"e": 7059,
"s": 7022,
"text": "You will get the following results −"
},
{
"code": null,
"e": 7203,
"s": 7059,
"text": "EMI includes both-interest and a part payment of principal. As the time increases, these two components of EMI will vary, reducing the balance."
},
{
"code": null,
"e": 7210,
"s": 7203,
"text": "To get"
},
{
"code": null,
"e": 7291,
"s": 7210,
"text": "The interest part of your monthly payments, you can use the Excel IPMT function."
},
{
"code": null,
"e": 7372,
"s": 7291,
"text": "The interest part of your monthly payments, you can use the Excel IPMT function."
},
{
"code": null,
"e": 7465,
"s": 7372,
"text": "The payment of principal part of your monthly payments, you can use the Excel PPMT function."
},
{
"code": null,
"e": 7558,
"s": 7465,
"text": "The payment of principal part of your monthly payments, you can use the Excel PPMT function."
},
{
"code": null,
"e": 7871,
"s": 7558,
"text": "For example, if you have taken a loan of 1,000,000 for a term of 8 months at the rate of 16% per annum. You can get values for the EMI, the decreasing interest amounts, the increasing payment of principal amounts and the diminishing loan balance over the 8 months. At the end of 8 months, loan balance will be 0."
},
{
"code": null,
"e": 7905,
"s": 7871,
"text": "Follow the procedure given below."
},
{
"code": null,
"e": 7944,
"s": 7905,
"text": "Step 1 − Calculate the EMI as follows."
},
{
"code": null,
"e": 7984,
"s": 7944,
"text": "This results in an EMI of Rs. 13261.59."
},
{
"code": null,
"e": 8085,
"s": 7984,
"text": "Step 2 − Next calculate the interest and principal parts of the EMI for the 8 months as shown below."
},
{
"code": null,
"e": 8121,
"s": 8085,
"text": "You will get the following results."
},
{
"code": null,
"e": 8201,
"s": 8121,
"text": "You can compute the interest and principal paid between two periods, inclusive."
},
{
"code": null,
"e": 8293,
"s": 8201,
"text": "Compute the cumulative interest paid between 2nd and 3rd months using the CUMIPMT function."
},
{
"code": null,
"e": 8385,
"s": 8293,
"text": "Compute the cumulative interest paid between 2nd and 3rd months using the CUMIPMT function."
},
{
"code": null,
"e": 8458,
"s": 8385,
"text": "Verify the result summing up the interest values for 2nd and 3rd months."
},
{
"code": null,
"e": 8531,
"s": 8458,
"text": "Verify the result summing up the interest values for 2nd and 3rd months."
},
{
"code": null,
"e": 8625,
"s": 8531,
"text": "Compute the cumulative principal paid between 2nd and 3rd months using the CUMPRINC function."
},
{
"code": null,
"e": 8719,
"s": 8625,
"text": "Compute the cumulative principal paid between 2nd and 3rd months using the CUMPRINC function."
},
{
"code": null,
"e": 8793,
"s": 8719,
"text": "Verify the result summing up the principal values for 2nd and 3rd months."
},
{
"code": null,
"e": 8867,
"s": 8793,
"text": "Verify the result summing up the principal values for 2nd and 3rd months."
},
{
"code": null,
"e": 8903,
"s": 8867,
"text": "You will get the following results."
},
{
"code": null,
"e": 8976,
"s": 8903,
"text": "You can see that your calculations match with your verification results."
},
{
"code": null,
"e": 9157,
"s": 8976,
"text": "Suppose you take a loan of 100,000 and you want to pay back in 15 months with a maximum monthly payment of 12000. You might want to know the interest rate at which you have to pay."
},
{
"code": null,
"e": 9211,
"s": 9157,
"text": "Find the interest rate with the Excel RATE function −"
},
{
"code": null,
"e": 9242,
"s": 9211,
"text": "You will get the result as 8%."
},
{
"code": null,
"e": 9421,
"s": 9242,
"text": "Suppose you take a loan of 100,000 at the interest rate 10%. You want a maximum monthly payment of 15,000. You might want to know how long it will take for you to clear the loan."
},
{
"code": null,
"e": 9474,
"s": 9421,
"text": "Find the number of payments with Excel NPER function"
},
{
"code": null,
"e": 9512,
"s": 9474,
"text": "You will get the result as 12 months."
},
{
"code": null,
"e": 9823,
"s": 9512,
"text": "When you want to make an investment, you compare the different options and choose the one that yields better returns. Net present value is useful in comparing cash flows over a period of time and deciding which one is better. The cash flows can occur at regular, periodical intervals or at irregular intervals."
},
{
"code": null,
"e": 9886,
"s": 9823,
"text": "First, we consider the case of regular, periodical cash flows."
},
{
"code": null,
"e": 10067,
"s": 9886,
"text": "The net present value of a sequence of cash flows received at different points in time in n years from now (n can be a fraction) is 1/(1 + r)n, where r is the annual interest rate."
},
{
"code": null,
"e": 10132,
"s": 10067,
"text": "Consider the following two investments over a period of 3 years."
},
{
"code": null,
"e": 10366,
"s": 10132,
"text": "At face value, Investment 1 looks better than Investment 2. However, you can decide on which investment is better only when you know the true worth of the investment as of today. You can use the NPV function to calculate the returns."
},
{
"code": null,
"e": 10391,
"s": 10366,
"text": "The cash flows can occur"
},
{
"code": null,
"e": 10417,
"s": 10391,
"text": "At the end of every year."
},
{
"code": null,
"e": 10449,
"s": 10417,
"text": "At the beginning of every year."
},
{
"code": null,
"e": 10478,
"s": 10449,
"text": "In the middle of every year."
},
{
"code": null,
"e": 10685,
"s": 10478,
"text": "NPV function assumes that the cash flows are at the end of the year. If the cash flows occur at different times then you have to take into account that particular factor along with the calculation with NPV."
},
{
"code": null,
"e": 10787,
"s": 10685,
"text": "Suppose the cash flows occur at the end of the year. Then you can straight away use the NPV function."
},
{
"code": null,
"e": 10824,
"s": 10787,
"text": "You will get the following results −"
},
{
"code": null,
"e": 11051,
"s": 10824,
"text": "As you observe NPV for Investment 2 is higher than that for Investment 1. Hence, Investment 2 is a better choice. You got this result as cash out flows for Investment 2 are at later periods as compared to that of Investment 1."
},
{
"code": null,
"e": 11348,
"s": 11051,
"text": "Suppose the cash flows occur at the beginning of every year. In such a case, you should not include the first cash flow in NPV calculation as it already represents the current value. You need to add the first cash flow to the NPV obtained from rest of the cash flows to get the net present value."
},
{
"code": null,
"e": 11385,
"s": 11348,
"text": "You will get the following results −"
},
{
"code": null,
"e": 11563,
"s": 11385,
"text": "Suppose the cash flows occur in the middle of every year. In such a case, you need to multiply the NPV obtained from the cash flows by $\\sqrt{1+r}$ to get the net present value."
},
{
"code": null,
"e": 11600,
"s": 11563,
"text": "You will get the following results −"
},
{
"code": null,
"e": 11751,
"s": 11600,
"text": "If you want to calculate the net present value with irregular cash flows, i.e. cash flows occurring at random times, the calculation is a bit complex."
},
{
"code": null,
"e": 11827,
"s": 11751,
"text": "However, in Excel, you can easily do such a calculation with XNPV function."
},
{
"code": null,
"e": 11880,
"s": 11827,
"text": "Arrange your data with the dates and the cash flows."
},
{
"code": null,
"e": 11996,
"s": 11880,
"text": "Note − The first date in your data should be the earliest of all the dates. The other dates can occur in any order."
},
{
"code": null,
"e": 12054,
"s": 11996,
"text": "Use the XNPV function to calculate the net present value."
},
{
"code": null,
"e": 12091,
"s": 12054,
"text": "You will get the following results −"
},
{
"code": null,
"e": 12319,
"s": 12091,
"text": "Suppose today’s date is 15th March, 2015. As you observe, all the dates of cash flows are of later dates. If you want to find the net present value as of today, include it in the data at the top and specify 0 for the cash flow."
},
{
"code": null,
"e": 12356,
"s": 12319,
"text": "You will get the following results −"
},
{
"code": null,
"e": 12692,
"s": 12356,
"text": "Internal Rate of Return (IRR) of an investment is the rate of interest at which NPV is 0. It is the rate value for which the present values of the positive cash flows exactly compensate the negative ones. When the discount rate is the IRR, the investment is perfectly indifferent, i.e. the investor is neither gaining nor losing money."
},
{
"code": null,
"e": 12786,
"s": 12692,
"text": "Consider the following cash flows, different interest rates and the corresponding NPV values."
},
{
"code": null,
"e": 12966,
"s": 12786,
"text": "As you can observe between the values of interest rate 10% and 11%, the sign of NPV changes. When you fine-tune the interest rate to 10.53%, NPV is nearly 0. Hence, IRR is 10.53%."
},
{
"code": null,
"e": 13027,
"s": 12966,
"text": "You can calculate IRR of cash flows with Excel function IRR."
},
{
"code": null,
"e": 13086,
"s": 13027,
"text": "The IRR is 10.53% as you had seen in the previous section."
},
{
"code": null,
"e": 13122,
"s": 13086,
"text": "For the given cash flows, IRR may −"
},
{
"code": null,
"e": 13139,
"s": 13122,
"text": "exist and unique"
},
{
"code": null,
"e": 13158,
"s": 13139,
"text": "exist and multiple"
},
{
"code": null,
"e": 13168,
"s": 13158,
"text": "not exist"
},
{
"code": null,
"e": 13271,
"s": 13168,
"text": "If IRR exists and is unique, it can be used to choose the best investment among several possibilities."
},
{
"code": null,
"e": 13466,
"s": 13271,
"text": "If the first cash flow is negative, it means the investor has the money and wants to invest. Then, the higher the IRR the better, since it represents the interest rate the investor is receiving."
},
{
"code": null,
"e": 13661,
"s": 13466,
"text": "If the first cash flow is negative, it means the investor has the money and wants to invest. Then, the higher the IRR the better, since it represents the interest rate the investor is receiving."
},
{
"code": null,
"e": 13849,
"s": 13661,
"text": "If the first cash flow is positive, it means the investor needs money and is looking for a loan, the lower the IRR the better since it represents the interest rate the investor is paying."
},
{
"code": null,
"e": 14037,
"s": 13849,
"text": "If the first cash flow is positive, it means the investor needs money and is looking for a loan, the lower the IRR the better since it represents the interest rate the investor is paying."
},
{
"code": null,
"e": 14156,
"s": 14037,
"text": "To find if an IRR is unique or not, vary the guess value and calculate IRR. If IRR remains constant then it is unique."
},
{
"code": null,
"e": 14231,
"s": 14156,
"text": "As you observe, the IRR has a unique value for the different guess values."
},
{
"code": null,
"e": 14355,
"s": 14231,
"text": "In certain cases, you may have multiple IRRs. Consider the following cash flows. Calculate IRR with different guess values."
},
{
"code": null,
"e": 14392,
"s": 14355,
"text": "You will get the following results −"
},
{
"code": null,
"e": 14501,
"s": 14392,
"text": "You can observe that there are two IRRs - -9.59% and 216.09%. You can verify these two IRRs calculating NPV."
},
{
"code": null,
"e": 14540,
"s": 14501,
"text": "For both -9.59% and 216.09%, NPV is 0."
},
{
"code": null,
"e": 14658,
"s": 14540,
"text": "In certain cases, you may not have IRR. Consider the following cash flows. Calculate IRR with different guess values."
},
{
"code": null,
"e": 14716,
"s": 14658,
"text": "You will get the result as #NUM for all the guess values."
},
{
"code": null,
"e": 14790,
"s": 14716,
"text": "The result #NUM means that there is no IRR for the cash flows considered."
},
{
"code": null,
"e": 15094,
"s": 14790,
"text": "If there is only one sign change in the cash flows, such as from negative to positive or positive to negative, then a unique IRR is guaranteed. For example, in capital investments, the first cash flow will be negative, while the rest of the cash flows will be positive. In such cases, unique IRR exists."
},
{
"code": null,
"e": 15211,
"s": 15094,
"text": "If there is more than one sign change in the cash flows, IRR may not exist. Even if it exists, it may not be unique."
},
{
"code": null,
"e": 15549,
"s": 15211,
"text": "Many analysts prefer to use IRR and it is a popular profitability measure because, as a percentage, it is easy to understand and easy to compare to the required return. However, there are certain problems while making decisions with IRR. If you rank with IRRs and make decisions based on these ranks, you may end up with wrong decisions."
},
{
"code": null,
"e": 15726,
"s": 15549,
"text": "You have already seen that NPV will enable you to make financial decisions. However, IRR and NPV will not always lead to the same decision when projects are mutually exclusive."
},
{
"code": null,
"e": 16082,
"s": 15726,
"text": "Mutually exclusive projects are those for which the selection of one project precludes the acceptance of another. When projects that are being compared are mutually exclusive, a ranking conflict may arise between NPV and IRR. If you have to choose between project A and project B, NPV may suggest acceptance of project A whereas IRR may suggest project B."
},
{
"code": null,
"e": 16176,
"s": 16082,
"text": "This type of conflict between NPV and IRR may arise because of one of the following reasons −"
},
{
"code": null,
"e": 16224,
"s": 16176,
"text": "The projects are of greatly different sizes, or"
},
{
"code": null,
"e": 16268,
"s": 16224,
"text": "The timing of the cash flows are different."
},
{
"code": null,
"e": 16505,
"s": 16268,
"text": "If you want to make a decision by IRR, project A yields a return of 100 and Project B a return of 50. Hence, investment on project A looks profitable. However, this is a wrong decision because of the difference in the scale of projects."
},
{
"code": null,
"e": 16516,
"s": 16505,
"text": "Consider −"
},
{
"code": null,
"e": 16541,
"s": 16516,
"text": "You have 1000 to invest."
},
{
"code": null,
"e": 16566,
"s": 16541,
"text": "You have 1000 to invest."
},
{
"code": null,
"e": 16631,
"s": 16566,
"text": "If you invest entire 1000 on project A, you get a return of 100."
},
{
"code": null,
"e": 16696,
"s": 16631,
"text": "If you invest entire 1000 on project A, you get a return of 100."
},
{
"code": null,
"e": 16960,
"s": 16696,
"text": "If you invest 100 on project B, you will still have 900 in your hand that you can invest on another project, say project C. Suppose you get a return of 20% on project C, then the total return on project B and project C is 230, which is way ahead in profitability."
},
{
"code": null,
"e": 17224,
"s": 16960,
"text": "If you invest 100 on project B, you will still have 900 in your hand that you can invest on another project, say project C. Suppose you get a return of 20% on project C, then the total return on project B and project C is 230, which is way ahead in profitability."
},
{
"code": null,
"e": 17285,
"s": 17224,
"text": "Thus, NPV is a better way for decision making in such cases."
},
{
"code": null,
"e": 17414,
"s": 17285,
"text": "Again, if you consider IRR to decide, project B would be the choice. However, project A has a higher NPV and is an ideal choice."
},
{
"code": null,
"e": 17655,
"s": 17414,
"text": "Your cash flows may sometimes be irregularly spaced. In such a case, you cannot use IRR as IRR requires equally spaced time intervals. You can use XIRR instead, which takes into account the dates of the cash flows along with the cash flows."
},
{
"code": null,
"e": 17710,
"s": 17655,
"text": "The Internal Rate of Return that results in is 26.42%."
},
{
"code": null,
"e": 17941,
"s": 17710,
"text": "Consider a case when your finance rate is different from your reinvestment rate. If you calculate Internal Rate of Return with IRR, it assumes same rate for both finance and reinvestment. Further, you might also get multiple IRRs."
},
{
"code": null,
"e": 17992,
"s": 17941,
"text": "For example, consider the cash flows given below −"
},
{
"code": null,
"e": 18163,
"s": 17992,
"text": "As you observe, NPV is 0 more than once, resulting in multiple IRRs. Further, reinvestment rate is not taken into account. In such cases, you can use modified IRR (MIRR)."
},
{
"code": null,
"e": 18208,
"s": 18163,
"text": "You will get a result of 7% as shown below −"
},
{
"code": null,
"e": 18255,
"s": 18208,
"text": "Note − Unlike IRR, MIRR will always be unique."
},
{
"code": null,
"e": 18290,
"s": 18255,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 18305,
"s": 18290,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 18339,
"s": 18305,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 18354,
"s": 18339,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 18389,
"s": 18354,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 18404,
"s": 18389,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 18439,
"s": 18404,
"text": "\n 63 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 18454,
"s": 18439,
"text": " Yoda Learning"
},
{
"code": null,
"e": 18490,
"s": 18454,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 18505,
"s": 18490,
"text": " Yoda Learning"
},
{
"code": null,
"e": 18538,
"s": 18505,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 18560,
"s": 18538,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 18567,
"s": 18560,
"text": " Print"
},
{
"code": null,
"e": 18578,
"s": 18567,
"text": " Add Notes"
}
] |
PHP Closure class | Anonymous functions (also called lambda) return object of Closure class. This class has some additional methods that provide further control over anonymous functions.
Closure {
/* Methods */
private __construct ( void )
public static bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
public call ( object $newthis [, mixed $... ] ) : mixed
public static fromCallable ( callable $callable ) : Closure
}
private Closure::__construct ( void ) — This method exists only to disallow instantiation of the Closure class. Objects of this class are created by anonymous function.
public static Closure::bind ( Closure closure,objectnewthis [, mixed $newscope = "static" ] ) − Closure — Duplicates a closure with a specific bound object and class scope. This method is a static version of Closure::bindTo().
public Closure::bindTo ( object newthis[,mixednewscope = "static" ] ) − Closure — Duplicates the closure with a new bound object and class scope. Creates and returns a new anonymous function with the same body and bound variables, but with a different object and a new class scope.
public Closure::call ( object newthis[,mixed... ] ) − mixed — Temporarily binds the closure to newthis, and calls it with any given parameters.
Live Demo
<?php
class A {
public $nm;
function __construct($x){
$this->nm=$x;
}
}
// Using call method
$hello = function() {
return "Hello " . $this->nm;
};
echo $hello->call(new A("Amar")). "\n";;
// using bind method
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>
Above program shows following output
Hello Amar
Hello Amar | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "Anonymous functions (also called lambda) return object of Closure class. This class has some additional methods that provide further control over anonymous functions."
},
{
"code": null,
"e": 1594,
"s": 1229,
"text": "Closure {\n /* Methods */\n private __construct ( void )\n public static bind ( Closure $closure , object $newthis [, mixed $newscope = \"static\" ] ) : Closure\n public bindTo ( object $newthis [, mixed $newscope = \"static\" ] ) : Closure\n public call ( object $newthis [, mixed $... ] ) : mixed\n public static fromCallable ( callable $callable ) : Closure\n}"
},
{
"code": null,
"e": 1763,
"s": 1594,
"text": "private Closure::__construct ( void ) — This method exists only to disallow instantiation of the Closure class. Objects of this class are created by anonymous function."
},
{
"code": null,
"e": 1990,
"s": 1763,
"text": "public static Closure::bind ( Closure closure,objectnewthis [, mixed $newscope = \"static\" ] ) − Closure — Duplicates a closure with a specific bound object and class scope. This method is a static version of Closure::bindTo()."
},
{
"code": null,
"e": 2272,
"s": 1990,
"text": "public Closure::bindTo ( object newthis[,mixednewscope = \"static\" ] ) − Closure — Duplicates the closure with a new bound object and class scope. Creates and returns a new anonymous function with the same body and bound variables, but with a different object and a new class scope."
},
{
"code": null,
"e": 2416,
"s": 2272,
"text": "public Closure::call ( object newthis[,mixed... ] ) − mixed — Temporarily binds the closure to newthis, and calls it with any given parameters."
},
{
"code": null,
"e": 2427,
"s": 2416,
"text": " Live Demo"
},
{
"code": null,
"e": 2722,
"s": 2427,
"text": "<?php\nclass A {\n public $nm;\n function __construct($x){\n $this->nm=$x;\n }\n}\n// Using call method\n$hello = function() {\n return \"Hello \" . $this->nm;\n};\necho $hello->call(new A(\"Amar\")). \"\\n\";;\n// using bind method\n$sayhello = $hello->bindTo(new A(\"Amar\"),'A');\necho $sayhello();\n?>"
},
{
"code": null,
"e": 2759,
"s": 2722,
"text": "Above program shows following output"
},
{
"code": null,
"e": 2781,
"s": 2759,
"text": "Hello Amar\nHello Amar"
}
] |
Comparing multiple frequency distribution | Towards Data Science | A frequency distribution is a graphical or tabular representation that shows the number of observations within a given interval. Bar plot, pie chart, and histogram are used to visualize the frequency distribution of an individual variable. What if when we need to compare multiple frequency distribution tables at once. Simple bar plots, pie charts, etc. won’t work for comparing multiple frequency tables. No worries, there might be alternative ways to do so. And this article will cover all the techniques to accomplish our job. All you need is to read the article till the end.
Road map........
Why do we need to Compare the Frequency Distribution?
Grouped Bar Plots
Kernel Density Estimate Plots
Strip Plots
Box Plots
Here our journey starts
Familiarize with Dataset
Throughout this article, we are using the wnba.csv dataset. The Women’s National Basketball Association (WNBA) is the professional basketball league in the USA. It has currently composed twelve teams. In our dataset, we have stats from all games of season 2016–2017. The dataset has 143 rows and 32 columns. The overview of a dataset is given below.
Prior knowledge of frequency distribution and visualization
To have a better insight into the necessity of comparing the frequency distribution, you need to have prior knowledge of frequency distribution and its visualization. If you haven’t any idea about it, you may read out my previous articles on frequency distribution and visualization.
towardsdatascience.com
towardsdatascience.com
For better explanation, we will use the wnba.csv dataset so that you can learn with a real-world example.
At first, we try to represent the experience column into Exper_ordianl column which variable measured in ordinal scale. In the below table, we try to describe the level of experience of players according to the following labeling convention:
Now, we are highly interested to know about the distribution of the ‘Pos’(Player position) variable with the level of experience. For example, we want to compare among the positions of experienced, very experienced, and veteran players.
We have used the below code to convert the experience of players according to the above labeling convention.
Output:
Now we try to segment the dataset according to the level of experience. Then we generate frequency distribution for each segment of the dataset. Finally, we try to have a comparative analysis of the frequency distribution.
Output:
The example shows that it’s a bit tricky to compare the distribution of multiple variables. Sometimes you have represented data in front of a non-technical audience. Understanding the above scenario is so difficult for the non-technical audience. Graphical representation is the best way to present our findings to a non-technical audience. In this article, we’ll discuss three kinds of graphs to compare the frequency of different variables. The following graphs will help us to get our job done —
(i)Grouped Bar Plots
(ii)Kernal Density Plot
(iii)Box Plot
A grouped bar plot (aka clustered bar chart, multi-series bar chart) extends the bar plot, plotting numeric values for two or more categorical variables instead of one. Bars are grouped by position for levels of one categorical variable, with color indicating the secondary category level within each group.
How to generate Grouped bar plot
The seaborn.countplot() function from the seaborn module, are using to generate grouped bar plot. To generate grouped bar plot, we’ll use the following parameter
(i)x — specifies as a string the name of the column we want on the x-axis.
(ii)hue — specifies as a string the name of the column we want the bar plots generated for.
(iii)data — specifies the name of the variable which stores the data set.
import seaborn as snssns.countplot(x = ‘Exper_ordianl’, hue = ‘Pos’, data = wnba)
Output:
Here, we use Exper_ordianl column to the x-axis. Here, we generate the bar plots for the Pos column. We stored the data in a variable named wnba.
How to Customize Grouped Bar Plot
The seaborn.countplot() function from the seaborn module has many parameters. By changing those parameters we can customize the graph according to our demand. We can also set the order of the x-axis value in ascending order and change the hue order using hue_order parameter.
import seaborn as snssns.countplot(x = ‘Exper_ordianl’, hue = ‘Pos’, data = wnba,order = [‘Rookie’, ‘Little experience’, ‘Experienced’, ‘Very experienced’, ‘Veteran’],hue_order = [‘C’, ‘F’, ‘F/C’, ‘G’, ‘G/F’])
Output:
It’s your turn to think a little bit and find the answer to the question.
Exercise Problem: Do Older Players Play Less? Use the mentioned dataset and the above knowledge to answer the question.
A kernel density estimate (KDE) plot is a method for visualizing the distribution of observations in a dataset, analogous to a histogram. KDE represents the data using a continuous probability density curve in one or more dimensions.
Each of the smoothed histograms above is called a kernel density estimate plot or, shorter, kernel density plot. Unlike histograms, kernel density plots display densities on the y-axis instead of frequencies.
Why Kernel Density Estimate Plots are used?
The Kernel Density Estimate Plots(KDE plots) are mainly used to comparing the histogram. Now we try to understand the need for KDE plots.
The easiest way to compare two histograms is to superimpose one on top of the other. We can do that by using the pandas visualization methods mission.
import matplotlib.pyplot as pltwnba[wnba.Age >= 27][‘MIN’].plot.hist(histtype = ‘step’, label = ‘Old’, legend = True)wnba[wnba.Age < 27][‘MIN’].plot.hist(histtype = ‘step’, label = ‘Young’, legend = True)
Output:
In the above, We want to compare two different scenarios. One for the players who have aged above 27 and others for the players who have aged below 27. We draw two histograms one over another so that we can compare them easily. We can easily compare between two histograms. What if for the number of histograms more than two. Is it easy to compare between those histograms? The necessity of KDE plot comes in for such kinds of scenarios.
How to generate KDE plots?
The Series.plot.kde() method are used to generate kde plots.
wnba[wnba.Age >= 27][‘MIN’].plot.kde(label = ‘Old’, legend = True)wnba[wnba.Age < 27][‘MIN’].plot.kde(label = ‘Young’, legend = True)
Output:
Here, we execute same process using KDE plots.
A strip plot is a graphical data analysis technique for summarizing a univariate data set. The strip plot consists of:
Horizontal axis = the value of the response variable;
Vertical axis = all values are set to 1.
In fact, strip plots are actually scatter plots.
When one of the variables is nominal or ordinal, a scatter plot will generally take the form of a series of narrow strips.
How to generate Strips plots
The sns.stripplot() function are used to generate strips plots.
sns.stripplot(x = ‘Pos’, y = ‘Height’, data = wnba)
Output:
We place Pos variable on the x-axis and the Height variable on the y-axis.The pattern we can see in the graphs that most of the short players played for the Goalkeeper position and most of the tall players played for the Center Back position. You can also try it for the weight variable. The number of narrow strips is the same as the number of unique values in the nominal or ordinal variable.
A boxplot is a standardized way of displaying the distribution of data based on a five-number summary (“minimum”, first quartile (Q1), median, third quartile (Q3), and “maximum”).
The above graph shows the boxplot. A boxplot is a graph that gives you a good indication of how the values in the data are spread out.
median (Q2 or 50th Percentile): It represents the middle value of the dataset.
first quartile (Q1or 25th Percentile): It represents the middle value between the smallest and median value dataset.
third quartile (Q3 or 75th Percentile): It represents the middle value between the highest and median value of the dataset.
interquartile range (IQR): It represents the value between 25th and 75th percentiles
whiskers: The whiskers are the two lines outside the box that extend to the highest and lowest observations. In the above graph, one line in the left and others in the right represent the whiskers.
outliers: A data point that is located outside the whiskers of the box plot. In the above graph, green points represent the outliers.
How to generate Box Plot
The sns.boxplot() function is used to generate box plots.
sns.boxplot(x = ‘Pos’, y = ‘Height’, data = wnba)
Output:
Using sns.boxplot(), generate a series of box plots to examine the distribution of players’ height as a function of players’ position. Place the Pos variable on the x-axis and the Weight variable on the y-axis.
Outlier point denotes — -
If the points are larger than the upper quartile by 1.5 times the difference between the upper quartile and the lower quartile (the difference is also called the interquartile range).
If the points are lower than the lower quartile by 1.5 times the difference between the upper quartile and the lower quartile (the difference is also called the interquartile range).
We can also change the factor from 1.5 to custom value using whis parameter.
sns.boxplot(x = ‘Pos’, y = ‘Height’, data = wnba, whis=4)
Output:
In this article, we try to learn how to compare frequency distribution using graphs. Grouped bar plots are used to compare the frequency distributions of nominal or ordinal variables. If the variables are measured in interval or ratio scale, we can use the kernel density plots and strip plots or box plots for better understanding.
If you are a data science enthusiast, please stay connected with me. I will come back shortly with another interesting article.
Previous series of articles about the basics of data science
towardsdatascience.com
towardsdatascience.com
Interesting article which will help you to know how to embed the interactive dataset with articles
towardsdatascience.com
If you enjoy the article, follow me on medium for more.
Connect me on LinkedIn for collaboration. | [
{
"code": null,
"e": 753,
"s": 172,
"text": "A frequency distribution is a graphical or tabular representation that shows the number of observations within a given interval. Bar plot, pie chart, and histogram are used to visualize the frequency distribution of an individual variable. What if when we need to compare multiple frequency distribution tables at once. Simple bar plots, pie charts, etc. won’t work for comparing multiple frequency tables. No worries, there might be alternative ways to do so. And this article will cover all the techniques to accomplish our job. All you need is to read the article till the end."
},
{
"code": null,
"e": 770,
"s": 753,
"text": "Road map........"
},
{
"code": null,
"e": 824,
"s": 770,
"text": "Why do we need to Compare the Frequency Distribution?"
},
{
"code": null,
"e": 842,
"s": 824,
"text": "Grouped Bar Plots"
},
{
"code": null,
"e": 872,
"s": 842,
"text": "Kernel Density Estimate Plots"
},
{
"code": null,
"e": 884,
"s": 872,
"text": "Strip Plots"
},
{
"code": null,
"e": 894,
"s": 884,
"text": "Box Plots"
},
{
"code": null,
"e": 918,
"s": 894,
"text": "Here our journey starts"
},
{
"code": null,
"e": 943,
"s": 918,
"text": "Familiarize with Dataset"
},
{
"code": null,
"e": 1293,
"s": 943,
"text": "Throughout this article, we are using the wnba.csv dataset. The Women’s National Basketball Association (WNBA) is the professional basketball league in the USA. It has currently composed twelve teams. In our dataset, we have stats from all games of season 2016–2017. The dataset has 143 rows and 32 columns. The overview of a dataset is given below."
},
{
"code": null,
"e": 1353,
"s": 1293,
"text": "Prior knowledge of frequency distribution and visualization"
},
{
"code": null,
"e": 1637,
"s": 1353,
"text": "To have a better insight into the necessity of comparing the frequency distribution, you need to have prior knowledge of frequency distribution and its visualization. If you haven’t any idea about it, you may read out my previous articles on frequency distribution and visualization."
},
{
"code": null,
"e": 1660,
"s": 1637,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1683,
"s": 1660,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1789,
"s": 1683,
"text": "For better explanation, we will use the wnba.csv dataset so that you can learn with a real-world example."
},
{
"code": null,
"e": 2031,
"s": 1789,
"text": "At first, we try to represent the experience column into Exper_ordianl column which variable measured in ordinal scale. In the below table, we try to describe the level of experience of players according to the following labeling convention:"
},
{
"code": null,
"e": 2268,
"s": 2031,
"text": "Now, we are highly interested to know about the distribution of the ‘Pos’(Player position) variable with the level of experience. For example, we want to compare among the positions of experienced, very experienced, and veteran players."
},
{
"code": null,
"e": 2377,
"s": 2268,
"text": "We have used the below code to convert the experience of players according to the above labeling convention."
},
{
"code": null,
"e": 2385,
"s": 2377,
"text": "Output:"
},
{
"code": null,
"e": 2608,
"s": 2385,
"text": "Now we try to segment the dataset according to the level of experience. Then we generate frequency distribution for each segment of the dataset. Finally, we try to have a comparative analysis of the frequency distribution."
},
{
"code": null,
"e": 2616,
"s": 2608,
"text": "Output:"
},
{
"code": null,
"e": 3115,
"s": 2616,
"text": "The example shows that it’s a bit tricky to compare the distribution of multiple variables. Sometimes you have represented data in front of a non-technical audience. Understanding the above scenario is so difficult for the non-technical audience. Graphical representation is the best way to present our findings to a non-technical audience. In this article, we’ll discuss three kinds of graphs to compare the frequency of different variables. The following graphs will help us to get our job done —"
},
{
"code": null,
"e": 3136,
"s": 3115,
"text": "(i)Grouped Bar Plots"
},
{
"code": null,
"e": 3160,
"s": 3136,
"text": "(ii)Kernal Density Plot"
},
{
"code": null,
"e": 3174,
"s": 3160,
"text": "(iii)Box Plot"
},
{
"code": null,
"e": 3482,
"s": 3174,
"text": "A grouped bar plot (aka clustered bar chart, multi-series bar chart) extends the bar plot, plotting numeric values for two or more categorical variables instead of one. Bars are grouped by position for levels of one categorical variable, with color indicating the secondary category level within each group."
},
{
"code": null,
"e": 3515,
"s": 3482,
"text": "How to generate Grouped bar plot"
},
{
"code": null,
"e": 3677,
"s": 3515,
"text": "The seaborn.countplot() function from the seaborn module, are using to generate grouped bar plot. To generate grouped bar plot, we’ll use the following parameter"
},
{
"code": null,
"e": 3752,
"s": 3677,
"text": "(i)x — specifies as a string the name of the column we want on the x-axis."
},
{
"code": null,
"e": 3844,
"s": 3752,
"text": "(ii)hue — specifies as a string the name of the column we want the bar plots generated for."
},
{
"code": null,
"e": 3918,
"s": 3844,
"text": "(iii)data — specifies the name of the variable which stores the data set."
},
{
"code": null,
"e": 4000,
"s": 3918,
"text": "import seaborn as snssns.countplot(x = ‘Exper_ordianl’, hue = ‘Pos’, data = wnba)"
},
{
"code": null,
"e": 4008,
"s": 4000,
"text": "Output:"
},
{
"code": null,
"e": 4154,
"s": 4008,
"text": "Here, we use Exper_ordianl column to the x-axis. Here, we generate the bar plots for the Pos column. We stored the data in a variable named wnba."
},
{
"code": null,
"e": 4188,
"s": 4154,
"text": "How to Customize Grouped Bar Plot"
},
{
"code": null,
"e": 4464,
"s": 4188,
"text": "The seaborn.countplot() function from the seaborn module has many parameters. By changing those parameters we can customize the graph according to our demand. We can also set the order of the x-axis value in ascending order and change the hue order using hue_order parameter."
},
{
"code": null,
"e": 4674,
"s": 4464,
"text": "import seaborn as snssns.countplot(x = ‘Exper_ordianl’, hue = ‘Pos’, data = wnba,order = [‘Rookie’, ‘Little experience’, ‘Experienced’, ‘Very experienced’, ‘Veteran’],hue_order = [‘C’, ‘F’, ‘F/C’, ‘G’, ‘G/F’])"
},
{
"code": null,
"e": 4682,
"s": 4674,
"text": "Output:"
},
{
"code": null,
"e": 4756,
"s": 4682,
"text": "It’s your turn to think a little bit and find the answer to the question."
},
{
"code": null,
"e": 4876,
"s": 4756,
"text": "Exercise Problem: Do Older Players Play Less? Use the mentioned dataset and the above knowledge to answer the question."
},
{
"code": null,
"e": 5110,
"s": 4876,
"text": "A kernel density estimate (KDE) plot is a method for visualizing the distribution of observations in a dataset, analogous to a histogram. KDE represents the data using a continuous probability density curve in one or more dimensions."
},
{
"code": null,
"e": 5319,
"s": 5110,
"text": "Each of the smoothed histograms above is called a kernel density estimate plot or, shorter, kernel density plot. Unlike histograms, kernel density plots display densities on the y-axis instead of frequencies."
},
{
"code": null,
"e": 5363,
"s": 5319,
"text": "Why Kernel Density Estimate Plots are used?"
},
{
"code": null,
"e": 5501,
"s": 5363,
"text": "The Kernel Density Estimate Plots(KDE plots) are mainly used to comparing the histogram. Now we try to understand the need for KDE plots."
},
{
"code": null,
"e": 5652,
"s": 5501,
"text": "The easiest way to compare two histograms is to superimpose one on top of the other. We can do that by using the pandas visualization methods mission."
},
{
"code": null,
"e": 5857,
"s": 5652,
"text": "import matplotlib.pyplot as pltwnba[wnba.Age >= 27][‘MIN’].plot.hist(histtype = ‘step’, label = ‘Old’, legend = True)wnba[wnba.Age < 27][‘MIN’].plot.hist(histtype = ‘step’, label = ‘Young’, legend = True)"
},
{
"code": null,
"e": 5865,
"s": 5857,
"text": "Output:"
},
{
"code": null,
"e": 6303,
"s": 5865,
"text": "In the above, We want to compare two different scenarios. One for the players who have aged above 27 and others for the players who have aged below 27. We draw two histograms one over another so that we can compare them easily. We can easily compare between two histograms. What if for the number of histograms more than two. Is it easy to compare between those histograms? The necessity of KDE plot comes in for such kinds of scenarios."
},
{
"code": null,
"e": 6330,
"s": 6303,
"text": "How to generate KDE plots?"
},
{
"code": null,
"e": 6391,
"s": 6330,
"text": "The Series.plot.kde() method are used to generate kde plots."
},
{
"code": null,
"e": 6525,
"s": 6391,
"text": "wnba[wnba.Age >= 27][‘MIN’].plot.kde(label = ‘Old’, legend = True)wnba[wnba.Age < 27][‘MIN’].plot.kde(label = ‘Young’, legend = True)"
},
{
"code": null,
"e": 6533,
"s": 6525,
"text": "Output:"
},
{
"code": null,
"e": 6580,
"s": 6533,
"text": "Here, we execute same process using KDE plots."
},
{
"code": null,
"e": 6699,
"s": 6580,
"text": "A strip plot is a graphical data analysis technique for summarizing a univariate data set. The strip plot consists of:"
},
{
"code": null,
"e": 6753,
"s": 6699,
"text": "Horizontal axis = the value of the response variable;"
},
{
"code": null,
"e": 6794,
"s": 6753,
"text": "Vertical axis = all values are set to 1."
},
{
"code": null,
"e": 6843,
"s": 6794,
"text": "In fact, strip plots are actually scatter plots."
},
{
"code": null,
"e": 6966,
"s": 6843,
"text": "When one of the variables is nominal or ordinal, a scatter plot will generally take the form of a series of narrow strips."
},
{
"code": null,
"e": 6995,
"s": 6966,
"text": "How to generate Strips plots"
},
{
"code": null,
"e": 7059,
"s": 6995,
"text": "The sns.stripplot() function are used to generate strips plots."
},
{
"code": null,
"e": 7111,
"s": 7059,
"text": "sns.stripplot(x = ‘Pos’, y = ‘Height’, data = wnba)"
},
{
"code": null,
"e": 7119,
"s": 7111,
"text": "Output:"
},
{
"code": null,
"e": 7514,
"s": 7119,
"text": "We place Pos variable on the x-axis and the Height variable on the y-axis.The pattern we can see in the graphs that most of the short players played for the Goalkeeper position and most of the tall players played for the Center Back position. You can also try it for the weight variable. The number of narrow strips is the same as the number of unique values in the nominal or ordinal variable."
},
{
"code": null,
"e": 7694,
"s": 7514,
"text": "A boxplot is a standardized way of displaying the distribution of data based on a five-number summary (“minimum”, first quartile (Q1), median, third quartile (Q3), and “maximum”)."
},
{
"code": null,
"e": 7829,
"s": 7694,
"text": "The above graph shows the boxplot. A boxplot is a graph that gives you a good indication of how the values in the data are spread out."
},
{
"code": null,
"e": 7908,
"s": 7829,
"text": "median (Q2 or 50th Percentile): It represents the middle value of the dataset."
},
{
"code": null,
"e": 8025,
"s": 7908,
"text": "first quartile (Q1or 25th Percentile): It represents the middle value between the smallest and median value dataset."
},
{
"code": null,
"e": 8149,
"s": 8025,
"text": "third quartile (Q3 or 75th Percentile): It represents the middle value between the highest and median value of the dataset."
},
{
"code": null,
"e": 8234,
"s": 8149,
"text": "interquartile range (IQR): It represents the value between 25th and 75th percentiles"
},
{
"code": null,
"e": 8432,
"s": 8234,
"text": "whiskers: The whiskers are the two lines outside the box that extend to the highest and lowest observations. In the above graph, one line in the left and others in the right represent the whiskers."
},
{
"code": null,
"e": 8566,
"s": 8432,
"text": "outliers: A data point that is located outside the whiskers of the box plot. In the above graph, green points represent the outliers."
},
{
"code": null,
"e": 8591,
"s": 8566,
"text": "How to generate Box Plot"
},
{
"code": null,
"e": 8649,
"s": 8591,
"text": "The sns.boxplot() function is used to generate box plots."
},
{
"code": null,
"e": 8699,
"s": 8649,
"text": "sns.boxplot(x = ‘Pos’, y = ‘Height’, data = wnba)"
},
{
"code": null,
"e": 8707,
"s": 8699,
"text": "Output:"
},
{
"code": null,
"e": 8918,
"s": 8707,
"text": "Using sns.boxplot(), generate a series of box plots to examine the distribution of players’ height as a function of players’ position. Place the Pos variable on the x-axis and the Weight variable on the y-axis."
},
{
"code": null,
"e": 8944,
"s": 8918,
"text": "Outlier point denotes — -"
},
{
"code": null,
"e": 9128,
"s": 8944,
"text": "If the points are larger than the upper quartile by 1.5 times the difference between the upper quartile and the lower quartile (the difference is also called the interquartile range)."
},
{
"code": null,
"e": 9311,
"s": 9128,
"text": "If the points are lower than the lower quartile by 1.5 times the difference between the upper quartile and the lower quartile (the difference is also called the interquartile range)."
},
{
"code": null,
"e": 9388,
"s": 9311,
"text": "We can also change the factor from 1.5 to custom value using whis parameter."
},
{
"code": null,
"e": 9446,
"s": 9388,
"text": "sns.boxplot(x = ‘Pos’, y = ‘Height’, data = wnba, whis=4)"
},
{
"code": null,
"e": 9454,
"s": 9446,
"text": "Output:"
},
{
"code": null,
"e": 9787,
"s": 9454,
"text": "In this article, we try to learn how to compare frequency distribution using graphs. Grouped bar plots are used to compare the frequency distributions of nominal or ordinal variables. If the variables are measured in interval or ratio scale, we can use the kernel density plots and strip plots or box plots for better understanding."
},
{
"code": null,
"e": 9915,
"s": 9787,
"text": "If you are a data science enthusiast, please stay connected with me. I will come back shortly with another interesting article."
},
{
"code": null,
"e": 9976,
"s": 9915,
"text": "Previous series of articles about the basics of data science"
},
{
"code": null,
"e": 9999,
"s": 9976,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10022,
"s": 9999,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10121,
"s": 10022,
"text": "Interesting article which will help you to know how to embed the interactive dataset with articles"
},
{
"code": null,
"e": 10144,
"s": 10121,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10200,
"s": 10144,
"text": "If you enjoy the article, follow me on medium for more."
}
] |
Passing Drop Down Box Data to CGI Program in Python | Drop Down Box is used when we have many options available but only one or two will be selected.
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
The result of this code is the following form −
Below is dropdown.py script to handle input given by web browser.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('dropdown'):
subject = form.getvalue('dropdown')
else:
subject = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>" | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "Drop Down Box is used when we have many options available but only one or two will be selected."
},
{
"code": null,
"e": 1220,
"s": 1158,
"text": "Here is example HTML code for a form with one drop down box −"
},
{
"code": null,
"e": 1471,
"s": 1220,
"text": "<form action = \"/cgi-bin/dropdown.py\" method = \"post\" target = \"_blank\">\n<select name = \"dropdown\">\n<option value = \"Maths\" selected>Maths</option>\n<option value = \"Physics\">Physics</option>\n</select>\n<input type = \"submit\" value = \"Submit\"/>\n</form>"
},
{
"code": null,
"e": 1519,
"s": 1471,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 1585,
"s": 1519,
"text": "Below is dropdown.py script to handle input given by web browser."
},
{
"code": null,
"e": 2079,
"s": 1585,
"text": "#!/usr/bin/python\n# Import modules for CGI handling\nimport cgi, cgitb\n# Create instance of FieldStorage\nform = cgi.FieldStorage()\n# Get data from fields\nif form.getvalue('dropdown'):\n subject = form.getvalue('dropdown')\nelse:\n subject = \"Not entered\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Dropdown Box - Sixth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\""
}
] |
Dart - this keyword - GeeksforGeeks | 15 Jul, 2020
this keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name. When the class attributes and the parameter names are the same this keyword is used to avoid ambiguity by prefixing class attributes with this keyword. this keyword can be used to refer to any member of the current object from within an instance method or a constructor
It can be used to refer to the instance variable of the current classIt can be used to make or Initiate current class constructorIt can be passed as an argument in the method callIt can be passed as an argument in the constructor callIt can be used to make a current class methodIt can be used to return the current class Instance
It can be used to refer to the instance variable of the current class
It can be used to make or Initiate current class constructor
It can be passed as an argument in the method call
It can be passed as an argument in the constructor call
It can be used to make a current class method
It can be used to return the current class Instance
Example 1: The following example shows the use of this keyword
Dart
// Dart program to illustrate// this keyword void main(){ Student s1 = new Student('S001');} class Student{ // defining local st_id variable var st_id; Student(var st_id) { // using this keyword this.st_id = st_id; print("GFG - Dart THIS Example"); print("The Student ID is : ${st_id}"); }}
Output:
Example 2:
Dart
// Dart program to illustrate// this keyword void main() { mob m1 = new mobile('M101'); } class mob { String mobile; Car(String mobile) { // use of this keyword this.mobile = mobile; print("The mobile is : ${mobile}"); } }
Output:
The mobile is : M101
Dart-Keywords
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Google Sign in UI and Authentication
Difference Between Stateless and Stateful Widget in Flutter
Dart - Null Aware Operators
Format Dates in Flutter
Flutter - SilverAppBar Widget
Flutter - Staggered Grid View | [
{
"code": null,
"e": 23930,
"s": 23902,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 24475,
"s": 23930,
"text": "this keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name. When the class attributes and the parameter names are the same this keyword is used to avoid ambiguity by prefixing class attributes with this keyword. this keyword can be used to refer to any member of the current object from within an instance method or a constructor"
},
{
"code": null,
"e": 24806,
"s": 24475,
"text": "It can be used to refer to the instance variable of the current classIt can be used to make or Initiate current class constructorIt can be passed as an argument in the method callIt can be passed as an argument in the constructor callIt can be used to make a current class methodIt can be used to return the current class Instance"
},
{
"code": null,
"e": 24876,
"s": 24806,
"text": "It can be used to refer to the instance variable of the current class"
},
{
"code": null,
"e": 24937,
"s": 24876,
"text": "It can be used to make or Initiate current class constructor"
},
{
"code": null,
"e": 24988,
"s": 24937,
"text": "It can be passed as an argument in the method call"
},
{
"code": null,
"e": 25044,
"s": 24988,
"text": "It can be passed as an argument in the constructor call"
},
{
"code": null,
"e": 25090,
"s": 25044,
"text": "It can be used to make a current class method"
},
{
"code": null,
"e": 25142,
"s": 25090,
"text": "It can be used to return the current class Instance"
},
{
"code": null,
"e": 25206,
"s": 25142,
"text": "Example 1: The following example shows the use of this keyword "
},
{
"code": null,
"e": 25211,
"s": 25206,
"text": "Dart"
},
{
"code": "// Dart program to illustrate// this keyword void main(){ Student s1 = new Student('S001');} class Student{ // defining local st_id variable var st_id; Student(var st_id) { // using this keyword this.st_id = st_id; print(\"GFG - Dart THIS Example\"); print(\"The Student ID is : ${st_id}\"); }}",
"e": 25521,
"s": 25211,
"text": null
},
{
"code": null,
"e": 25531,
"s": 25523,
"text": "Output:"
},
{
"code": null,
"e": 25542,
"s": 25531,
"text": "Example 2:"
},
{
"code": null,
"e": 25547,
"s": 25542,
"text": "Dart"
},
{
"code": "// Dart program to illustrate// this keyword void main() { mob m1 = new mobile('M101'); } class mob { String mobile; Car(String mobile) { // use of this keyword this.mobile = mobile; print(\"The mobile is : ${mobile}\"); } }",
"e": 25807,
"s": 25547,
"text": null
},
{
"code": null,
"e": 25817,
"s": 25809,
"text": "Output:"
},
{
"code": null,
"e": 25839,
"s": 25817,
"text": "The mobile is : M101\n"
},
{
"code": null,
"e": 25853,
"s": 25839,
"text": "Dart-Keywords"
},
{
"code": null,
"e": 25858,
"s": 25853,
"text": "Dart"
},
{
"code": null,
"e": 25956,
"s": 25858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25965,
"s": 25956,
"text": "Comments"
},
{
"code": null,
"e": 25978,
"s": 25965,
"text": "Old Comments"
},
{
"code": null,
"e": 26006,
"s": 25978,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 26045,
"s": 26006,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 26071,
"s": 26045,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 26094,
"s": 26071,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 26141,
"s": 26094,
"text": "Flutter - Google Sign in UI and Authentication"
},
{
"code": null,
"e": 26201,
"s": 26141,
"text": "Difference Between Stateless and Stateful Widget in Flutter"
},
{
"code": null,
"e": 26229,
"s": 26201,
"text": "Dart - Null Aware Operators"
},
{
"code": null,
"e": 26253,
"s": 26229,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 26283,
"s": 26253,
"text": "Flutter - SilverAppBar Widget"
}
] |
Pydash: A Kitchen Sink of Missing Python Utilities | by Khuyen Tran | Towards Data Science | Have you ever tried to flatten a nested array like this?
If you found it difficult to flatten such a nested array, you would be happy to find an elegant solution like this:
...or to get the object of a deeply nested dictionary-like below in one line of code.
If you are looking for a library that provides useful utilities to deal with Python objects like above, pydash will be your go-to library.
Pydash is the kitchen sink of Python utility libraries for doing “stuff” in a functional way.
To install pydash, make sure your Python version is ≥ 3.6, then type:
pip install pydash
Start with importing pydash:
You can flatten a nested Python list using the py_.flatten method:
What if your list is deeply nested like below?
That is when the py_.flatten_deep method comes in handy:
If you can flatten a list, can you also turn a flattened list into a nested one? Yes, that could be done with the py_.chunk method:
Nice! The elements in the list are split into groups of 2.
To omit an attribute from the dictionary, we can use the py_.omit method:
How do you get the price of an apple from Walmart that is in season in a nested dictionary like below?
Normally, you need to use a lot of brackets to get that information:
[2, 4]
Wouldn’t it be nice if you could use the dot notation instead of brackets? That could be done with the py_.get method:
Cool! You can also get the element in an array using [index] :
2
To get the index of an element in a list using a function, use the py_.find_index method:
The py_.find_index method allows you to get the index of the object that matches a certain pattern. But what if you want to get the items in a list instead of the index?
That could be done with the py_.filter method:
Sometimes your list of dictionaries can be nested like below. How can you get the taste attribute of apple ?
Luckily, this can be easily done with the py_.map_ method:
You can execute a function n times using the py_.times method. This method is a good alternative to a for loop.
Sometimes you might want to apply several methods to an object. Instead of writing several lines of code, can you apply all methods at once?
That is when method chaining comes in handy. To apply method chaining in an object, use the py_.chain method:
Note that running the code above will not give us the value:
<pydash.chaining.Chain at 0x7f8d256b0dc0>
Only when we add .value() to the end of the chain, the final value is computed:
This is called lazy evaluation. Lazy evaluation holds the evaluation of an expression until its value is needed, which avoids repeated evaluation.
If you want to use your own methods instead of pydash’s methods, use the map method:
To replace the initial value of a chain with another value, use the plant method:
Cool! We replace ['apple', 'orange', 'grapes'] with ['apple', 'orange'] while using the same chain!
Congratulations! You have just learned how to manipulate Python objects efficiently with pydash. I hope this article will add some more useful tools to your Python toolkit.
There are so many more cool methods pydash provides that I could not cover in this article. I encourage you to check out pydash’s API reference.
Feel free to fork and play with the code for this article in this Github repo:
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 229,
"s": 172,
"text": "Have you ever tried to flatten a nested array like this?"
},
{
"code": null,
"e": 345,
"s": 229,
"text": "If you found it difficult to flatten such a nested array, you would be happy to find an elegant solution like this:"
},
{
"code": null,
"e": 431,
"s": 345,
"text": "...or to get the object of a deeply nested dictionary-like below in one line of code."
},
{
"code": null,
"e": 570,
"s": 431,
"text": "If you are looking for a library that provides useful utilities to deal with Python objects like above, pydash will be your go-to library."
},
{
"code": null,
"e": 664,
"s": 570,
"text": "Pydash is the kitchen sink of Python utility libraries for doing “stuff” in a functional way."
},
{
"code": null,
"e": 734,
"s": 664,
"text": "To install pydash, make sure your Python version is ≥ 3.6, then type:"
},
{
"code": null,
"e": 753,
"s": 734,
"text": "pip install pydash"
},
{
"code": null,
"e": 782,
"s": 753,
"text": "Start with importing pydash:"
},
{
"code": null,
"e": 849,
"s": 782,
"text": "You can flatten a nested Python list using the py_.flatten method:"
},
{
"code": null,
"e": 896,
"s": 849,
"text": "What if your list is deeply nested like below?"
},
{
"code": null,
"e": 953,
"s": 896,
"text": "That is when the py_.flatten_deep method comes in handy:"
},
{
"code": null,
"e": 1085,
"s": 953,
"text": "If you can flatten a list, can you also turn a flattened list into a nested one? Yes, that could be done with the py_.chunk method:"
},
{
"code": null,
"e": 1144,
"s": 1085,
"text": "Nice! The elements in the list are split into groups of 2."
},
{
"code": null,
"e": 1218,
"s": 1144,
"text": "To omit an attribute from the dictionary, we can use the py_.omit method:"
},
{
"code": null,
"e": 1321,
"s": 1218,
"text": "How do you get the price of an apple from Walmart that is in season in a nested dictionary like below?"
},
{
"code": null,
"e": 1390,
"s": 1321,
"text": "Normally, you need to use a lot of brackets to get that information:"
},
{
"code": null,
"e": 1397,
"s": 1390,
"text": "[2, 4]"
},
{
"code": null,
"e": 1516,
"s": 1397,
"text": "Wouldn’t it be nice if you could use the dot notation instead of brackets? That could be done with the py_.get method:"
},
{
"code": null,
"e": 1579,
"s": 1516,
"text": "Cool! You can also get the element in an array using [index] :"
},
{
"code": null,
"e": 1581,
"s": 1579,
"text": "2"
},
{
"code": null,
"e": 1671,
"s": 1581,
"text": "To get the index of an element in a list using a function, use the py_.find_index method:"
},
{
"code": null,
"e": 1841,
"s": 1671,
"text": "The py_.find_index method allows you to get the index of the object that matches a certain pattern. But what if you want to get the items in a list instead of the index?"
},
{
"code": null,
"e": 1888,
"s": 1841,
"text": "That could be done with the py_.filter method:"
},
{
"code": null,
"e": 1997,
"s": 1888,
"text": "Sometimes your list of dictionaries can be nested like below. How can you get the taste attribute of apple ?"
},
{
"code": null,
"e": 2056,
"s": 1997,
"text": "Luckily, this can be easily done with the py_.map_ method:"
},
{
"code": null,
"e": 2168,
"s": 2056,
"text": "You can execute a function n times using the py_.times method. This method is a good alternative to a for loop."
},
{
"code": null,
"e": 2309,
"s": 2168,
"text": "Sometimes you might want to apply several methods to an object. Instead of writing several lines of code, can you apply all methods at once?"
},
{
"code": null,
"e": 2419,
"s": 2309,
"text": "That is when method chaining comes in handy. To apply method chaining in an object, use the py_.chain method:"
},
{
"code": null,
"e": 2480,
"s": 2419,
"text": "Note that running the code above will not give us the value:"
},
{
"code": null,
"e": 2522,
"s": 2480,
"text": "<pydash.chaining.Chain at 0x7f8d256b0dc0>"
},
{
"code": null,
"e": 2602,
"s": 2522,
"text": "Only when we add .value() to the end of the chain, the final value is computed:"
},
{
"code": null,
"e": 2749,
"s": 2602,
"text": "This is called lazy evaluation. Lazy evaluation holds the evaluation of an expression until its value is needed, which avoids repeated evaluation."
},
{
"code": null,
"e": 2834,
"s": 2749,
"text": "If you want to use your own methods instead of pydash’s methods, use the map method:"
},
{
"code": null,
"e": 2916,
"s": 2834,
"text": "To replace the initial value of a chain with another value, use the plant method:"
},
{
"code": null,
"e": 3016,
"s": 2916,
"text": "Cool! We replace ['apple', 'orange', 'grapes'] with ['apple', 'orange'] while using the same chain!"
},
{
"code": null,
"e": 3189,
"s": 3016,
"text": "Congratulations! You have just learned how to manipulate Python objects efficiently with pydash. I hope this article will add some more useful tools to your Python toolkit."
},
{
"code": null,
"e": 3334,
"s": 3189,
"text": "There are so many more cool methods pydash provides that I could not cover in this article. I encourage you to check out pydash’s API reference."
},
{
"code": null,
"e": 3413,
"s": 3334,
"text": "Feel free to fork and play with the code for this article in this Github repo:"
},
{
"code": null,
"e": 3424,
"s": 3413,
"text": "github.com"
},
{
"code": null,
"e": 3584,
"s": 3424,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Dart Programming - Map.remove() Function | Removes key and its associated value, if present, from the map. The function also returns the value associated with the key.
Map.remove(Object key)
Keys − identifies the entry to be deleted.
Keys − identifies the entry to be deleted.
Return Type − Returns the value corresponding to the specified key.
void main() {
Map m = {'name':'Tom','Id':'E1001'};
print('Map :${m}');
dynamic res = m.remove('name');
print('Value popped from the Map :${res}');
}
It will produce the following output −
Map :{name: Tom, Id: E1001}
Value popped from the Map :Tom
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2650,
"s": 2525,
"text": "Removes key and its associated value, if present, from the map. The function also returns the value associated with the key."
},
{
"code": null,
"e": 2675,
"s": 2650,
"text": "Map.remove(Object key) \n"
},
{
"code": null,
"e": 2718,
"s": 2675,
"text": "Keys − identifies the entry to be deleted."
},
{
"code": null,
"e": 2761,
"s": 2718,
"text": "Keys − identifies the entry to be deleted."
},
{
"code": null,
"e": 2829,
"s": 2761,
"text": "Return Type − Returns the value corresponding to the specified key."
},
{
"code": null,
"e": 3000,
"s": 2829,
"text": "void main() { \n Map m = {'name':'Tom','Id':'E1001'}; \n print('Map :${m}'); \n \n dynamic res = m.remove('name'); \n print('Value popped from the Map :${res}'); \n} "
},
{
"code": null,
"e": 3039,
"s": 3000,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3102,
"s": 3039,
"text": "Map :{name: Tom, Id: E1001} \nValue popped from the Map :Tom \n"
},
{
"code": null,
"e": 3137,
"s": 3102,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3157,
"s": 3137,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3190,
"s": 3157,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3210,
"s": 3190,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3243,
"s": 3210,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3260,
"s": 3243,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3295,
"s": 3260,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3312,
"s": 3295,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3347,
"s": 3312,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3367,
"s": 3347,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3400,
"s": 3367,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3420,
"s": 3400,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3427,
"s": 3420,
"text": " Print"
},
{
"code": null,
"e": 3438,
"s": 3427,
"text": " Add Notes"
}
] |
JAX: Differentiable Computing by Google | by Branislav Holländer | Towards Data Science | Since deep learning took off in the early 2010s, many frameworks were written to facilitate deep learning in both research and production. For the record, let us mention Caffe, Theano, Torch, Lasagne, Tensorflow, Keras or PyTorch. Some of these frameworks disappeared after a while. Others survived and thrive to this day, mainly PyTorch and Tensorflow. Over time, these frameworks evolved into large ecosystems with many different functionalities. On one hand, they support the training of new models including massively parallel training on many-GPU systems. On the other hand, they allow users to deploy the trained models easily in the cloud or on mobile devices.
Unfortunately, this streamlining sometimes comes at the cost of flexibility required by machine learning researchers to test out new model ideas. It is precisely this user group that Google is targeting with its new framework called JAX. In this blog post, I will show you how JAX encourages experimentation by providing a low-level, high-performance interface to vectorized computing and gradient computation.
The goal of JAX is to allow the user to speed up raw Python and NumPy functions by just-in-time compilation and auto-parallelization as well as to compute gradients of these functions. In order to do this, JAX employs a functional design. Functions such as gradient computation are implemented as functional transforms (or functors) acting on user-defined Python functions. For instance, to calculate the gradient of the absolute value function, you can write:
from jax import graddef abs_val(x): if x > 0: return x else: return -xabs_val_grad = grad(abs_val)
As you can see, abs_val is a normal Python function, which is transformed by the functor grad.
In order to be able to use JAX functors, the user-defined functions have to follow some restrictions:
Every function processed by JAX is required to be pure. This means that it should always return the same result when called with the same input. In functional terms, it may not have any side effects. Otherwise, correctness when using just-in-time compilation or parallelization cannot be guaranteed by JAX. Functional purity isn’t actually enforced. Although errors may be thrown sometimes, it is mainly the responsibility of the programmer to ensure this condition.Instead of in-place mutating updates such as x[i] += 1, one has to use functional alternatives in the jax.ops package.Just-In-Time (JIT) compilation has some restrictions on Python control flow.
Every function processed by JAX is required to be pure. This means that it should always return the same result when called with the same input. In functional terms, it may not have any side effects. Otherwise, correctness when using just-in-time compilation or parallelization cannot be guaranteed by JAX. Functional purity isn’t actually enforced. Although errors may be thrown sometimes, it is mainly the responsibility of the programmer to ensure this condition.
Instead of in-place mutating updates such as x[i] += 1, one has to use functional alternatives in the jax.ops package.
Just-In-Time (JIT) compilation has some restrictions on Python control flow.
In terms of philosophy, JAX is similar to what you would experience when using purely functional languages such as Haskell. In fact, the developers even use Haskell-type signatures in the documentation to explain some of the transformations.
One of the main features of JAX is the ability to speed up execution of Python code by JIT. Internally, JAX uses the XLA compiler to accomplish this. XLA is able to compile code not only for CPUs, but also for GPUs or even TPUs. This makes JAX very powerful and versatile. In order to compile a function using XLA, you can use the jit functor like this:
from jax import jitimport jax.numpy as jnpdef selu(x, alpha=1.67, lmbda=1.05): return lmbda * jnp.where(x > 0, x, alpha * jnp.exp(x) - alpha)selu_jit = jit(selu)
Alternatively, you may also use jit as a decorator on top of the function definition:
@jitdef selu(x, alpha=1.67, lmbda=1.05): return lmbda * jnp.where(x > 0, x, alpha * jnp.exp(x) - alpha)
The jit functor transforms the input function by returning a compiled version of it to the caller. Calling the original selu function will use the Python interpreter, while calling selu_jit will call the compiled version, which should be much faster, especially for vectorized inputs such as numpy arrays. Furthermore, the JIT compilation only occurs once and is cached thereafter, making subsequent calls of the function very efficient.
When training machine learning models, you are usually computing some loss for a subset of input data, then updating the model parameters. Since computing the forward function of the model for every input sequentially would be too slow, it is customary to batch together the subset of data into one batch and computing the forward function in a parallel fashion on an accelerator such as the GPU. This is accomplished in JAX by using the function vmap:
def forward(input, w, b): input = jnp.dot(input, w) + b return jnp.max(input, 0)jax.vmap(forward, in_axes=(0, None, None), out_axes=0)(inputs, w, b)
This code snippet takes a forward function of a fully-connected layer with ReLU activation and parallelizes its execution over a batch of inputs. The parameters in_axes and out_axes specify over which parameters and axes the parallelization occurs. In this case, (0, None, None) means that the input is parallelized over the 0-th axis while w and b are left untouched. The output is parallelized over the 0-th axis.
What makes JAX particularly interesting to machine learning researchers is its ability to compute gradients of arbitrary pure functions. JAX inherited this capability from autograd, a package to compute derivatives of NumPy arrays.
To compute the gradient of a function, simply use the grad transformation:
import jax.numpy as jnpgrad(jnp.tanh))(2.0)[0.070650816]
If you want to compute higher-order derivatives, you can simply chain together multiple grad transformations like this:
import jax.numpy as jnpgrad(grad(jnp.tanh))(2.0)[-0.13621889]
While applying grad to a function in R (the set of real numbers) will give you a single number as the output, you may also apply it to a vector-valued function to obtain a Jacobian:
def f(x): return jnp.asarray( [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jnp.sin(x[0])])print(jax.jacfwd(f)(jnp.array([1., 2., 3.])))[[ 1. 0. 0. ] [ 0. 0. 5. ] [ 0. 16. -2. ] [ 1.6209 0. 0.84147]]
Here, we do not use the grad transformation, since it only works on scalar-output functions. Instead, we use a similar function called jacfwd for automatic forward-mode differentiation (for a detailed discussion of forward- and backward-mode differentiation please refer to the JAX docs).
Note that we may chain together the functional transformations in JAX. For instance, we may vectorize our function using vmap, calculate the gradients using grad and then compile the resulting function using jit, such as in this example of a standard mini-batch training loop in deep learning:
def loss(x, y): out = net(x) cross_entropy = -y * np.log(out) - (1 - y)*np.log(1 - out) return cross_entropyloss_grad = jax.jit(jax.vmap(jax.grad(loss), in_axes=(0, 0), out_axes=0))
Here, loss_grad computes the gradient of the cross-entropy loss, while paralleling over the input (x, y) and the single output (the loss). The entire function is jitted to allow for fast computation on the GPU. The resulting function is cached, allowing it to be called with different outputs without any further overhead.
The composition of multiple transformations makes the framework extremely powerful and gives the user great flexibility in designing the data flow.
JAX provides a useful alternative to more high-level frameworks such as PyTorch or Tensorflow for researchers who need extra flexibility. The ability to differentiate through native Python and NumPy functions is amazing and the JIT compilation and auto-vectorization features greatly simplify writing efficient code for massively-parallel architectures like GPUs or TPUs. What I like most about JAX, however, is its clean functional interface. Surely it’s only a matter of time before an ecosystem of mature high-level APIs will evolve around it. Stay tuned! | [
{
"code": null,
"e": 840,
"s": 172,
"text": "Since deep learning took off in the early 2010s, many frameworks were written to facilitate deep learning in both research and production. For the record, let us mention Caffe, Theano, Torch, Lasagne, Tensorflow, Keras or PyTorch. Some of these frameworks disappeared after a while. Others survived and thrive to this day, mainly PyTorch and Tensorflow. Over time, these frameworks evolved into large ecosystems with many different functionalities. On one hand, they support the training of new models including massively parallel training on many-GPU systems. On the other hand, they allow users to deploy the trained models easily in the cloud or on mobile devices."
},
{
"code": null,
"e": 1251,
"s": 840,
"text": "Unfortunately, this streamlining sometimes comes at the cost of flexibility required by machine learning researchers to test out new model ideas. It is precisely this user group that Google is targeting with its new framework called JAX. In this blog post, I will show you how JAX encourages experimentation by providing a low-level, high-performance interface to vectorized computing and gradient computation."
},
{
"code": null,
"e": 1712,
"s": 1251,
"text": "The goal of JAX is to allow the user to speed up raw Python and NumPy functions by just-in-time compilation and auto-parallelization as well as to compute gradients of these functions. In order to do this, JAX employs a functional design. Functions such as gradient computation are implemented as functional transforms (or functors) acting on user-defined Python functions. For instance, to calculate the gradient of the absolute value function, you can write:"
},
{
"code": null,
"e": 1819,
"s": 1712,
"text": "from jax import graddef abs_val(x): if x > 0: return x else: return -xabs_val_grad = grad(abs_val)"
},
{
"code": null,
"e": 1914,
"s": 1819,
"text": "As you can see, abs_val is a normal Python function, which is transformed by the functor grad."
},
{
"code": null,
"e": 2016,
"s": 1914,
"text": "In order to be able to use JAX functors, the user-defined functions have to follow some restrictions:"
},
{
"code": null,
"e": 2677,
"s": 2016,
"text": "Every function processed by JAX is required to be pure. This means that it should always return the same result when called with the same input. In functional terms, it may not have any side effects. Otherwise, correctness when using just-in-time compilation or parallelization cannot be guaranteed by JAX. Functional purity isn’t actually enforced. Although errors may be thrown sometimes, it is mainly the responsibility of the programmer to ensure this condition.Instead of in-place mutating updates such as x[i] += 1, one has to use functional alternatives in the jax.ops package.Just-In-Time (JIT) compilation has some restrictions on Python control flow."
},
{
"code": null,
"e": 3144,
"s": 2677,
"text": "Every function processed by JAX is required to be pure. This means that it should always return the same result when called with the same input. In functional terms, it may not have any side effects. Otherwise, correctness when using just-in-time compilation or parallelization cannot be guaranteed by JAX. Functional purity isn’t actually enforced. Although errors may be thrown sometimes, it is mainly the responsibility of the programmer to ensure this condition."
},
{
"code": null,
"e": 3263,
"s": 3144,
"text": "Instead of in-place mutating updates such as x[i] += 1, one has to use functional alternatives in the jax.ops package."
},
{
"code": null,
"e": 3340,
"s": 3263,
"text": "Just-In-Time (JIT) compilation has some restrictions on Python control flow."
},
{
"code": null,
"e": 3582,
"s": 3340,
"text": "In terms of philosophy, JAX is similar to what you would experience when using purely functional languages such as Haskell. In fact, the developers even use Haskell-type signatures in the documentation to explain some of the transformations."
},
{
"code": null,
"e": 3936,
"s": 3582,
"text": "One of the main features of JAX is the ability to speed up execution of Python code by JIT. Internally, JAX uses the XLA compiler to accomplish this. XLA is able to compile code not only for CPUs, but also for GPUs or even TPUs. This makes JAX very powerful and versatile. In order to compile a function using XLA, you can use the jit functor like this:"
},
{
"code": null,
"e": 4099,
"s": 3936,
"text": "from jax import jitimport jax.numpy as jnpdef selu(x, alpha=1.67, lmbda=1.05): return lmbda * jnp.where(x > 0, x, alpha * jnp.exp(x) - alpha)selu_jit = jit(selu)"
},
{
"code": null,
"e": 4185,
"s": 4099,
"text": "Alternatively, you may also use jit as a decorator on top of the function definition:"
},
{
"code": null,
"e": 4290,
"s": 4185,
"text": "@jitdef selu(x, alpha=1.67, lmbda=1.05): return lmbda * jnp.where(x > 0, x, alpha * jnp.exp(x) - alpha)"
},
{
"code": null,
"e": 4728,
"s": 4290,
"text": "The jit functor transforms the input function by returning a compiled version of it to the caller. Calling the original selu function will use the Python interpreter, while calling selu_jit will call the compiled version, which should be much faster, especially for vectorized inputs such as numpy arrays. Furthermore, the JIT compilation only occurs once and is cached thereafter, making subsequent calls of the function very efficient."
},
{
"code": null,
"e": 5181,
"s": 4728,
"text": "When training machine learning models, you are usually computing some loss for a subset of input data, then updating the model parameters. Since computing the forward function of the model for every input sequentially would be too slow, it is customary to batch together the subset of data into one batch and computing the forward function in a parallel fashion on an accelerator such as the GPU. This is accomplished in JAX by using the function vmap:"
},
{
"code": null,
"e": 5336,
"s": 5181,
"text": "def forward(input, w, b): input = jnp.dot(input, w) + b return jnp.max(input, 0)jax.vmap(forward, in_axes=(0, None, None), out_axes=0)(inputs, w, b)"
},
{
"code": null,
"e": 5752,
"s": 5336,
"text": "This code snippet takes a forward function of a fully-connected layer with ReLU activation and parallelizes its execution over a batch of inputs. The parameters in_axes and out_axes specify over which parameters and axes the parallelization occurs. In this case, (0, None, None) means that the input is parallelized over the 0-th axis while w and b are left untouched. The output is parallelized over the 0-th axis."
},
{
"code": null,
"e": 5984,
"s": 5752,
"text": "What makes JAX particularly interesting to machine learning researchers is its ability to compute gradients of arbitrary pure functions. JAX inherited this capability from autograd, a package to compute derivatives of NumPy arrays."
},
{
"code": null,
"e": 6059,
"s": 5984,
"text": "To compute the gradient of a function, simply use the grad transformation:"
},
{
"code": null,
"e": 6116,
"s": 6059,
"text": "import jax.numpy as jnpgrad(jnp.tanh))(2.0)[0.070650816]"
},
{
"code": null,
"e": 6236,
"s": 6116,
"text": "If you want to compute higher-order derivatives, you can simply chain together multiple grad transformations like this:"
},
{
"code": null,
"e": 6298,
"s": 6236,
"text": "import jax.numpy as jnpgrad(grad(jnp.tanh))(2.0)[-0.13621889]"
},
{
"code": null,
"e": 6480,
"s": 6298,
"text": "While applying grad to a function in R (the set of real numbers) will give you a single number as the output, you may also apply it to a vector-valued function to obtain a Jacobian:"
},
{
"code": null,
"e": 6740,
"s": 6480,
"text": "def f(x): return jnp.asarray( [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jnp.sin(x[0])])print(jax.jacfwd(f)(jnp.array([1., 2., 3.])))[[ 1. 0. 0. ] [ 0. 0. 5. ] [ 0. 16. -2. ] [ 1.6209 0. 0.84147]]"
},
{
"code": null,
"e": 7029,
"s": 6740,
"text": "Here, we do not use the grad transformation, since it only works on scalar-output functions. Instead, we use a similar function called jacfwd for automatic forward-mode differentiation (for a detailed discussion of forward- and backward-mode differentiation please refer to the JAX docs)."
},
{
"code": null,
"e": 7323,
"s": 7029,
"text": "Note that we may chain together the functional transformations in JAX. For instance, we may vectorize our function using vmap, calculate the gradients using grad and then compile the resulting function using jit, such as in this example of a standard mini-batch training loop in deep learning:"
},
{
"code": null,
"e": 7514,
"s": 7323,
"text": "def loss(x, y): out = net(x) cross_entropy = -y * np.log(out) - (1 - y)*np.log(1 - out) return cross_entropyloss_grad = jax.jit(jax.vmap(jax.grad(loss), in_axes=(0, 0), out_axes=0))"
},
{
"code": null,
"e": 7837,
"s": 7514,
"text": "Here, loss_grad computes the gradient of the cross-entropy loss, while paralleling over the input (x, y) and the single output (the loss). The entire function is jitted to allow for fast computation on the GPU. The resulting function is cached, allowing it to be called with different outputs without any further overhead."
},
{
"code": null,
"e": 7985,
"s": 7837,
"text": "The composition of multiple transformations makes the framework extremely powerful and gives the user great flexibility in designing the data flow."
}
] |
Python – List Elements Grouping in Matrix | When it is required to list elements grouping in a matrix, a simple iteration, the ‘pop’ method, list comprehension and ‘append’ methods are used.
Below is a demonstration of the same −
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
print("The list is :")
print(my_list)
check_list = [14, 12, 41, 62]
print("The list is :")
print(check_list)
my_result = []
while my_list:
sub_list_1 = my_list.pop()
sub_list_2 = [element for element in check_list if element not in sub_list_1]
try:
my_list.remove(sub_list_2)
my_result.append([sub_list_1, sub_list_2])
except ValueError:
my_result.append(sub_list_1)
print("The result is :")
print(my_result)
The list is :
[[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
The list is :
[14, 12, 41, 62]
The result is :
[[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]
A list of list of integers is defined and is displayed on the console.
A list of list of integers is defined and is displayed on the console.
Another list of integers is defined and displayed on the console.
Another list of integers is defined and displayed on the console.
An empty list is defined.
An empty list is defined.
A simple iteration is used, and the top most element is popped using ‘pop’ method.
A simple iteration is used, and the top most element is popped using ‘pop’ method.
This is assigned to a variable ‘sub_list_1’.
This is assigned to a variable ‘sub_list_1’.
A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’.
A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’.
The ‘try’ and ‘except’ block is used to append specific elements to the empty list.
The ‘try’ and ‘except’ block is used to append specific elements to the empty list.
This list is displayed as the output on the console.
This list is displayed as the output on the console. | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "When it is required to list elements grouping in a matrix, a simple iteration, the ‘pop’ method, list comprehension and ‘append’ methods are used."
},
{
"code": null,
"e": 1248,
"s": 1209,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1757,
"s": 1248,
"text": "my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]\n\nprint(\"The list is :\")\nprint(my_list)\n\ncheck_list = [14, 12, 41, 62]\nprint(\"The list is :\")\nprint(check_list)\n\nmy_result = []\nwhile my_list:\n\n sub_list_1 = my_list.pop()\n\n sub_list_2 = [element for element in check_list if element not in sub_list_1]\n try:\n\n my_list.remove(sub_list_2)\n\n my_result.append([sub_list_1, sub_list_2])\n except ValueError:\n\n my_result.append(sub_list_1)\n\nprint(\"The result is :\")\nprint(my_result)"
},
{
"code": null,
"e": 1922,
"s": 1757,
"text": "The list is :\n[[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]\nThe list is :\n[14, 12, 41, 62]\nThe result is :\n[[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]"
},
{
"code": null,
"e": 1993,
"s": 1922,
"text": "A list of list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 2064,
"s": 1993,
"text": "A list of list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 2130,
"s": 2064,
"text": "Another list of integers is defined and displayed on the console."
},
{
"code": null,
"e": 2196,
"s": 2130,
"text": "Another list of integers is defined and displayed on the console."
},
{
"code": null,
"e": 2222,
"s": 2196,
"text": "An empty list is defined."
},
{
"code": null,
"e": 2248,
"s": 2222,
"text": "An empty list is defined."
},
{
"code": null,
"e": 2331,
"s": 2248,
"text": "A simple iteration is used, and the top most element is popped using ‘pop’ method."
},
{
"code": null,
"e": 2414,
"s": 2331,
"text": "A simple iteration is used, and the top most element is popped using ‘pop’ method."
},
{
"code": null,
"e": 2459,
"s": 2414,
"text": "This is assigned to a variable ‘sub_list_1’."
},
{
"code": null,
"e": 2504,
"s": 2459,
"text": "This is assigned to a variable ‘sub_list_1’."
},
{
"code": null,
"e": 2617,
"s": 2504,
"text": "A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’."
},
{
"code": null,
"e": 2730,
"s": 2617,
"text": "A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’."
},
{
"code": null,
"e": 2814,
"s": 2730,
"text": "The ‘try’ and ‘except’ block is used to append specific elements to the empty list."
},
{
"code": null,
"e": 2898,
"s": 2814,
"text": "The ‘try’ and ‘except’ block is used to append specific elements to the empty list."
},
{
"code": null,
"e": 2951,
"s": 2898,
"text": "This list is displayed as the output on the console."
},
{
"code": null,
"e": 3004,
"s": 2951,
"text": "This list is displayed as the output on the console."
}
] |
How to find the sum of anti-diagonal elements in a matrix in R? | The anti-diagonal elements in a matrix are the elements that form straight line from right upper side to right bottom side. For example, if we have a matrix as shown below −
1 2 3
4 5 6
7 8 9
then the diagonal elements would be 1, 5, 9 and the anti-diagonal elements would be 3, 5, 7.
To find the sum of these anti-diagonal elements, we can use apply function.
Live Demo
M1<-matrix(1:9,ncol=3)
M1
[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
sum(diag(apply(M1,2,rev)))
[1] 15
Live Demo
M2<-matrix(1:100,nrow=10)
M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
sum(diag(apply(M2,2,rev))) [1] 505
Live Demo
M3<-matrix(sample(0:9,36,replace=TRUE),nrow=6)
M3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 8 6 1 4 2 6
[2,] 3 5 7 5 6 7
[3,] 3 2 6 9 8 2
[4,] 3 2 5 9 4 6
[5,] 7 2 8 3 6 4
[6,] 6 0 2 5 6 6
sum(diag(apply(M3,2,rev))) [1] 34
Live Demo
M4<-matrix(sample(1:10,64,replace=TRUE),nrow=8)
M4
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1, ] 6 1 2 1 3 1 7 7
[2,] 1 2 9 9 5 10 4 10
[3,] 4 2 5 4 5 8 8 10
[4,] 7 5 8 4 7 7 1 4
[5,] 10 9 1 5 6 8 2 5
[6,] 7 9 7 1 5 4 2 6
[7,] 4 9 4 5 8 9 2 9
[8,] 7 7 6 9 1 8 1 2
sum(diag(apply(M4,2,rev))) [1] 54
Live Demo
M5<-matrix(sample(1:100,81),nrow=9)
M5
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 32 34 99 73 93 65 82 50 9
[2,] 49 69 62 37 96 40 57 97 86
[3,] 11 84 22 53 87 12 95 88 100
[4,] 44 77 48 58 71 78 2 10 45
[5,] 39 66 72 23 24 20 55 59 35
[6,] 18 79 52 98 29 43 7 75 74
[7,] 80 15 70 91 13 60 61 1 38
[8,] 41 5 4 17 46 30 26 81 21
[9,] 54 51 6 25 47 89 36 85 67
sum(diag(apply(M5,2,rev))) [1] 530
Live Demo
M6<-matrix(sample(101:999,36),nrow=6)
M6
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 726 139 975 492 672 686
[2,] 501 754 818 724 547 446
[3,] 204 480 530 112 872 761
[4,] 789 165 572 899 538 298
[5,] 987 119 274 369 936 132
[6,] 306 696 448 618 951 137
sum(diag(apply(M6,2,rev))) [1] 2342
Live Demo
M7<-matrix(rpois(49,5),nrow=7)
M7
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 3 3 6 5 6 4 5
[2,] 1 9 7 4 2 5 4
[3,] 4 6 5 5 4 4 0
[4,] 6 5 5 4 5 10 1
[5,] 7 3 4 5 3 5 5
[6,] 4 4 5 2 5 2 5
[7,] 9 7 6 5 0 1 2
sum(diag(apply(M7,2,rev))) [1] 35
Live Demo
M8<-matrix(rpois(81,3),nrow=9)
M8
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 0 3 5 1 2 2 2 2 3
[2,] 2 2 0 4 3 5 3 5 5
[3,] 5 2 5 5 1 2 2 5 6
[4,] 4 4 5 3 3 3 2 1 5
[5,] 7 6 3 2 2 8 3 1 2
[6,] 5 2 3 1 5 3 1 2 1
[7,] 2 6 4 3 2 4 4 2 2
[8,] 1 3 3 3 2 1 3 1 0
[9,] 1 4 5 3 5 5 2 2 2
sum(diag(apply(M8,2,rev))) [1] 24 | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "The anti-diagonal elements in a matrix are the elements that form straight line from right upper side to right bottom side. For example, if we have a matrix as shown below −"
},
{
"code": null,
"e": 1254,
"s": 1236,
"text": "1 2 3\n4 5 6\n7 8 9"
},
{
"code": null,
"e": 1347,
"s": 1254,
"text": "then the diagonal elements would be 1, 5, 9 and the anti-diagonal elements would be 3, 5, 7."
},
{
"code": null,
"e": 1423,
"s": 1347,
"text": "To find the sum of these anti-diagonal elements, we can use apply function."
},
{
"code": null,
"e": 1434,
"s": 1423,
"text": " Live Demo"
},
{
"code": null,
"e": 1460,
"s": 1434,
"text": "M1<-matrix(1:9,ncol=3)\nM1"
},
{
"code": null,
"e": 1509,
"s": 1460,
"text": "[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9\n"
},
{
"code": null,
"e": 1536,
"s": 1509,
"text": "sum(diag(apply(M1,2,rev)))"
},
{
"code": null,
"e": 1544,
"s": 1536,
"text": "[1] 15\n"
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": " Live Demo"
},
{
"code": null,
"e": 1584,
"s": 1555,
"text": "M2<-matrix(1:100,nrow=10)\nM2"
},
{
"code": null,
"e": 2168,
"s": 1584,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] \n[1,] 1 11 21 31 41 51 61 71 81 91 \n[2,] 2 12 22 32 42 52 62 72 82 92 \n[3,] 3 13 23 33 43 53 63 73 83 93 \n[4,] 4 14 24 34 44 54 64 74 84 94 \n[5,] 5 15 25 35 45 55 65 75 85 95 \n[6,] 6 16 26 36 46 56 66 76 86 96 \n[7,] 7 17 27 37 47 57 67 77 87 97 \n[8,] 8 18 28 38 48 58 68 78 88 98 \n[9,] 9 19 29 39 49 59 69 79 89 99 \n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2203,
"s": 2168,
"text": "sum(diag(apply(M2,2,rev))) [1] 505"
},
{
"code": null,
"e": 2214,
"s": 2203,
"text": " Live Demo"
},
{
"code": null,
"e": 2264,
"s": 2214,
"text": "M3<-matrix(sample(0:9,36,replace=TRUE),nrow=6)\nM3"
},
{
"code": null,
"e": 2492,
"s": 2264,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] \n[1,] 8 6 1 4 2 6 \n[2,] 3 5 7 5 6 7 \n[3,] 3 2 6 9 8 2 \n[4,] 3 2 5 9 4 6 \n[5,] 7 2 8 3 6 4 \n[6,] 6 0 2 5 6 6"
},
{
"code": null,
"e": 2526,
"s": 2492,
"text": "sum(diag(apply(M3,2,rev))) [1] 34"
},
{
"code": null,
"e": 2537,
"s": 2526,
"text": " Live Demo"
},
{
"code": null,
"e": 2588,
"s": 2537,
"text": "M4<-matrix(sample(1:10,64,replace=TRUE),nrow=8)\nM4"
},
{
"code": null,
"e": 2939,
"s": 2588,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n [1, ] 6 1 2 1 3 1 7 7 \n[2,] 1 2 9 9 5 10 4 10 \n[3,] 4 2 5 4 5 8 8 10 \n[4,] 7 5 8 4 7 7 1 4 \n[5,] 10 9 1 5 6 8 2 5\n[6,] 7 9 7 1 5 4 2 6 \n[7,] 4 9 4 5 8 9 2 9 \n[8,] 7 7 6 9 1 8 1 2"
},
{
"code": null,
"e": 2973,
"s": 2939,
"text": "sum(diag(apply(M4,2,rev))) [1] 54"
},
{
"code": null,
"e": 2984,
"s": 2973,
"text": " Live Demo"
},
{
"code": null,
"e": 3023,
"s": 2984,
"text": "M5<-matrix(sample(1:100,81),nrow=9)\nM5"
},
{
"code": null,
"e": 3503,
"s": 3023,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] \n[1,] 32 34 99 73 93 65 82 50 9 \n[2,] 49 69 62 37 96 40 57 97 86 \n[3,] 11 84 22 53 87 12 95 88 100\n [4,] 44 77 48 58 71 78 2 10 45\n [5,] 39 66 72 23 24 20 55 59 35 \n[6,] 18 79 52 98 29 43 7 75 74\n [7,] 80 15 70 91 13 60 61 1 38 \n[8,] 41 5 4 17 46 30 26 81 21\n [9,] 54 51 6 25 47 89 36 85 67"
},
{
"code": null,
"e": 3538,
"s": 3503,
"text": "sum(diag(apply(M5,2,rev))) [1] 530"
},
{
"code": null,
"e": 3549,
"s": 3538,
"text": " Live Demo"
},
{
"code": null,
"e": 3590,
"s": 3549,
"text": "M6<-matrix(sample(101:999,36),nrow=6)\nM6"
},
{
"code": null,
"e": 3814,
"s": 3590,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] \n[1,] 726 139 975 492 672 686 \n[2,] 501 754 818 724 547 446 \n[3,] 204 480 530 112 872 761\n[4,] 789 165 572 899 538 298 \n[5,] 987 119 274 369 936 132 \n[6,] 306 696 448 618 951 137"
},
{
"code": null,
"e": 3850,
"s": 3814,
"text": "sum(diag(apply(M6,2,rev))) [1] 2342"
},
{
"code": null,
"e": 3861,
"s": 3850,
"text": " Live Demo"
},
{
"code": null,
"e": 3895,
"s": 3861,
"text": "M7<-matrix(rpois(49,5),nrow=7)\nM7"
},
{
"code": null,
"e": 4195,
"s": 3895,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] \n[1,] 3 3 6 5 6 4 5 \n[2,] 1 9 7 4 2 5 4 \n[3,] 4 6 5 5 4 4 0 \n[4,] 6 5 5 4 5 10 1 \n[5,] 7 3 4 5 3 5 5 \n[6,] 4 4 5 2 5 2 5\n [7,] 9 7 6 5 0 1 2"
},
{
"code": null,
"e": 4229,
"s": 4195,
"text": "sum(diag(apply(M7,2,rev))) [1] 35"
},
{
"code": null,
"e": 4240,
"s": 4229,
"text": " Live Demo"
},
{
"code": null,
"e": 4274,
"s": 4240,
"text": "M8<-matrix(rpois(81,3),nrow=9)\nM8"
},
{
"code": null,
"e": 4741,
"s": 4274,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] \n[1,] 0 3 5 1 2 2 2 2 3 \n[2,] 2 2 0 4 3 5 3 5 5 \n[3,] 5 2 5 5 1 2 2 5 6 \n[4,] 4 4 5 3 3 3 2 1 5 \n[5,] 7 6 3 2 2 8 3 1 2 \n[6,] 5 2 3 1 5 3 1 2 1 \n[7,] 2 6 4 3 2 4 4 2 2 \n[8,] 1 3 3 3 2 1 3 1 0 \n[9,] 1 4 5 3 5 5 2 2 2"
},
{
"code": null,
"e": 4775,
"s": 4741,
"text": "sum(diag(apply(M8,2,rev))) [1] 24"
}
] |
Pandas Cheat Sheet. A quick guide to the basics of the... | by XuanKhanh Nguyen | Towards Data Science | A quick guide to the basics of the Python data analysis library Pandas, including code samples.
My favorite professor told me that “software engineers read textbooks as a reference; we don’t memorize everything but we know how to look it up quickly.”
Being able to look up and use functions fast allows us to achieve a certain flow when conducting machine learning models. So I have created this Pandas cheat sheet of functions. This is not a comprehensive list but contains the functions I use most in building machine learning model. Let’s hop to it!
The Structure of this note:
Import dataExport dataCreate test objectsView/Inspect dataSelectionData cleaningFilter, Sort, and GroupbyStatistics
Import data
Export data
Create test objects
View/Inspect data
Selection
Data cleaning
Filter, Sort, and Groupby
Statistics
First, we need to import Pandas to get started:
import pandas as pd
Convert a CSV directly into a DataFrame using the function pd.read_csv.
Note: Another similar function also exists called pd.read_excel for excel files.
# Load data df = pd.read_csv('filename.csv') # From a CSV filedf = pd.read_excel('filename.xlsx') # From an Excel file
to_csv() dumps to the same directory as the notebook. We can save the first ten row by df[:10].to_csv(). We can also save and write a DataFrame to an Excel File or a specific Sheet in the Excel file usingdf.to_excel()
df.to_csv('filename.csv') # Write to a CSV filedf.to_excel('filename.xlsx') # Write to an Excel file
This is useful when we want to manually instantiate simple data to see changes as it flows through a pipeline.
# Build data frame from inputted datadf = pd.DataFrame(data = {'Name': ['Bob', 'Sally', 'Scott', 'Katie'], 'Physics': [68, 74, 77, 78], 'Chemistry': [84, 100, 73, 90], 'Algebra': [78, 88, 82, 87]})
# Create a series from an iterable my_listmy_list = [['Bob',78], ['Sally',91], ['Scott',62], ['Katie',78], ['John',100]]df1 = pd.Series(my_list) # Create a series from an iterable my_list
head() function displays the first n records from a DataFrame. I often print the top record of a DataFrame in my notebook so I can refer back to it if I forget what’s inside.
df.head(3) # First 3 rows of the DataFrame
tail() function is used to return the last n rows. This is useful for quickly verifying data, especially, after sorting or appending rows.
df.tail(3) # Last 3 rows of the DataFrame
To append or add a row to DataFrame, we create the new row as Series and use append() method.
In this example, the new row is initialized as a python dictionary, and append() method is used to append the row to the DataFrame.
When we are adding a python dictionary to append(), make sure we pass ignore_index=True, so that the index values are not used along the concatenation axis. The resulting axis will instead be labeled as number series0, 1, ..., n-1, which is useful when the concatenation axis does not have meaningful indexing information.
The append() method returns the DataFrame with the newly added row.
#Append row to the dataframe, missing data (np.nan)new_row = {'Name':'Max', 'Physics':67, 'Chemistry':92, 'Algebra':np.nan}df = df.append(new_row, ignore_index=True)
# List of series list_of_series = [pd.Series(['Liz', 83, 77, np.nan], index=df.columns), pd.Series(['Sam', np.nan, 94,70], index=df.columns ), pd.Series(['Mike', 79,87,90], index=df.columns), pd.Series(['Scott', np.nan,87,np.nan], index=df.columns),]# Pass a list of series to the append() to add multiple rowsdf = df.append(list_of_series , ignore_index=True)
# Adding a new column to existing DataFrame in Pandassex = ['Male','Female','Male','Female','Male','Female','Female','Male','Male']df['Sex'] = sex
info() function is useful for getting some general information like header, number of values, and datatype by column. A similar but less useful function is df.dtypes which just gives column data types.
df.info() #Index, Datatype and Memory information
# Check data type in pandas dataframedf['Chemistry'].dtypes >>> dtype('int64')# Convert Integers to Floats in Pandas DataFramedf['Chemistry'] = df['Chemistry'].astype(float) df['Chemistry'].dtypes>>> dtype('float64')# Number of rows and columnsdf.shape >>> (9, 5)
The value_counts() function is used to get a series containing counts of unique values.
# View unique values and counts of Physics columndf['Physics'].value_counts(dropna=False)
This works if we need to pull the values in columns into X and y variables so we can fit a machine learning model.
df['Chemistry'] # Returns column with label 'Chemistry' as Series
df[['Name','Algebra']] # Returns columns as a new DataFrame
df.iloc[0] # Selection by position
df.iloc[:,1] # Second column 'Name' of data frame
df.iloc[0,1] # First element of Second column>>> 68.0
rename() function is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed.
# Rename columnsdf = df.rename({'Name':'Student','Algebra':'Math'}, axis='columns')
In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed.
NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation
Pandas treat NaN as essentially interchangeable for indicating missing or null values. To facilitate this convention, there are several useful functions for detecting, removing, and replacing null values in Pandas DataFrame.
# Checks for null Values, Returns Boolean Arrraycheck_for_nan = df.isnull()
To check null values in Pandas DataFrame, we use isnull() or notnull() method. isnull() method returns DataFrame of Boolean values which are True for NaN values. In the opposite position, notnull() method returns DataFrame of Boolean values which are False for NaN values.
value = df.notnull() # Opposite of df2.isnull()
We use dropna() function to drop all rows that have any missing values.
drop_null_row = df.dropna() # Drop all rows that contain null values
Sometimes, we may just want to drop a column that has some missing values.
# Drop all columns that contain null valuesdrop_null_col = df.dropna(axis=1)
We can fill missing values by using fillna(). For example, we may want to replace ‘NaN’ with zeroes.
replace_null = df.fillna(0) # Replace all null values with 0
Or we can replace ‘NaN’ with the mean value.
# Replace all null values with the mean (mean can be replaced with almost any function from the statistics module)df = round(df.fillna(df.mean()),2)
replace() method can be used to replace values in DataFrame
one = df.replace(100,'A') # Replace all values equal to 1 with 'one'
We want to see students who get 80 or higher in Physics
fil_80 = df[df['Physics'] > 80]
What if we want to see students who receive 80 or higher grade in Chemistry but less than 90 on Math exam
fil = df[(df['Chemistry'] > 80) & (df['Math'] < 90)]
Often we want to sort Pandas DataFrame in a specific way. Typically, one may want to sort Pandas DataFrame based on the values of one or more columns or sort based on the values of row index or row names of Pandas DataFrame.
For example, we want to sort values by Student’s name in ascending order.
ascending = df.sort_values('Student')
Sorting Chemistry score in descending order.
descending = df.sort_values('Chemistry',ascending=False)
More complicated, we want to sort values by Physics scores in ascending order then Chemistry scores in descending order.
df.sort_values(['Physics','Chemistry'],ascending=[True,False])
In this case, a DataFrame will be sorted for Physics and Chemistry column respectively. We can also pass a list to the ‘ascending’ parameter to tell Pandas which column to sort how.
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It is a simple concept but it’s an extremely valuable technique that we often use. Groupby concept is important because it’s the ability to aggregate data efficiently, both in performance and the amount code is magnificent.
Let’s group the unique values from the Sex column
group_by = df.groupby(['Sex']) # Returns a groupby object for values from one columngroup_by.first() # Print the first value in each group
Calculate the average across all columns for every unique Sex group
average = df.groupby(‘Sex’).agg(np.mean)
We may be familiar with pivot tables in Excel to generate easy insights into our data. Similarly, we can create Python pivot tables using the pivot_table() function available in Pandas. The function is quite similar to the group_by() function but offers significantly more customization.
Let’s say we want to group values by Sex and calculate the mean and standard deviation of Physics and Chemistry columns. We will call the pivot_table() function and set the following arguments:
index to be 'Sex' since that is the column from df that we want to appear as a unique value in each row
values as 'Physics','Chemistry' since that's the column we want to apply some aggregate operation on
aggfunc to 'len','np.mean','np.std len will count the unique distinct values from the Sex column, np.mean and np.std will calculate the mean and standard deviation respectively.
pivot_table = df.pivot_table(index='Sex', values=['Physics','Chemistry'], aggfunc=[len, np.mean, np.std])
Note: Using len assumes we don't have NaN values in our datagram.
describe() is used to view some basic statistical details like percentile, mean, std, etc. of a DataFrame or a series of numeric values.
df.describe() # Summary statistics for numerical columns
Find the maximum value of each row and column using max()
# Get a series containing maximum value of each rowmax_row = df.max(axis=1)
# Get a series containing maximum value of each column without skipping NaNmax_col = df.max(skipna=False)
Similarly, we can use df.min() to find the minimum value of each row or column.
Other useful statistics functions:
df.sum(): Returns the sum of the values for the requested axis. By default, axis is index (axis=0).
df.mean():Returns the average value
df.median(): Returns the median of each column
df.std():Returns the standard deviation of the numerical columns.
df.corr() :Returns the correlation between columns in a DataFrame.
df.count() : Returns the number of non-null values in each column.
The code in this note is available on Github.
That’s all the good stuff. I hope this cheat sheet can be a reference guide for you. I’ll try to continuously update this as I find more useful Pandas functions. If there are any functions you can’t live without please share with me in the comments below!
It’s never too late to learn, so if you just start your Python journey, keep learning!
Lots and lots of books have been written about Python programming. I certainly didn’t cover enough information here to fill a chapter, but that doesn’t mean you can’t keep learning! Fill your mind with more awesomeness, starting with the great links below.
Pandas installationPython HandbookPandas introduction for beginnersPandas basicsHow to learn PandasWhat is the use of Pandas in Python
Pandas installation
Python Handbook
Pandas introduction for beginners
Pandas basics
How to learn Pandas
What is the use of Pandas in Python | [
{
"code": null,
"e": 143,
"s": 47,
"text": "A quick guide to the basics of the Python data analysis library Pandas, including code samples."
},
{
"code": null,
"e": 298,
"s": 143,
"text": "My favorite professor told me that “software engineers read textbooks as a reference; we don’t memorize everything but we know how to look it up quickly.”"
},
{
"code": null,
"e": 600,
"s": 298,
"text": "Being able to look up and use functions fast allows us to achieve a certain flow when conducting machine learning models. So I have created this Pandas cheat sheet of functions. This is not a comprehensive list but contains the functions I use most in building machine learning model. Let’s hop to it!"
},
{
"code": null,
"e": 628,
"s": 600,
"text": "The Structure of this note:"
},
{
"code": null,
"e": 744,
"s": 628,
"text": "Import dataExport dataCreate test objectsView/Inspect dataSelectionData cleaningFilter, Sort, and GroupbyStatistics"
},
{
"code": null,
"e": 756,
"s": 744,
"text": "Import data"
},
{
"code": null,
"e": 768,
"s": 756,
"text": "Export data"
},
{
"code": null,
"e": 788,
"s": 768,
"text": "Create test objects"
},
{
"code": null,
"e": 806,
"s": 788,
"text": "View/Inspect data"
},
{
"code": null,
"e": 816,
"s": 806,
"text": "Selection"
},
{
"code": null,
"e": 830,
"s": 816,
"text": "Data cleaning"
},
{
"code": null,
"e": 856,
"s": 830,
"text": "Filter, Sort, and Groupby"
},
{
"code": null,
"e": 867,
"s": 856,
"text": "Statistics"
},
{
"code": null,
"e": 915,
"s": 867,
"text": "First, we need to import Pandas to get started:"
},
{
"code": null,
"e": 935,
"s": 915,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1007,
"s": 935,
"text": "Convert a CSV directly into a DataFrame using the function pd.read_csv."
},
{
"code": null,
"e": 1088,
"s": 1007,
"text": "Note: Another similar function also exists called pd.read_excel for excel files."
},
{
"code": null,
"e": 1207,
"s": 1088,
"text": "# Load data df = pd.read_csv('filename.csv') # From a CSV filedf = pd.read_excel('filename.xlsx') # From an Excel file"
},
{
"code": null,
"e": 1425,
"s": 1207,
"text": "to_csv() dumps to the same directory as the notebook. We can save the first ten row by df[:10].to_csv(). We can also save and write a DataFrame to an Excel File or a specific Sheet in the Excel file usingdf.to_excel()"
},
{
"code": null,
"e": 1526,
"s": 1425,
"text": "df.to_csv('filename.csv') # Write to a CSV filedf.to_excel('filename.xlsx') # Write to an Excel file"
},
{
"code": null,
"e": 1637,
"s": 1526,
"text": "This is useful when we want to manually instantiate simple data to see changes as it flows through a pipeline."
},
{
"code": null,
"e": 1835,
"s": 1637,
"text": "# Build data frame from inputted datadf = pd.DataFrame(data = {'Name': ['Bob', 'Sally', 'Scott', 'Katie'], 'Physics': [68, 74, 77, 78], 'Chemistry': [84, 100, 73, 90], 'Algebra': [78, 88, 82, 87]})"
},
{
"code": null,
"e": 2061,
"s": 1835,
"text": "# Create a series from an iterable my_listmy_list = [['Bob',78], ['Sally',91], ['Scott',62], ['Katie',78], ['John',100]]df1 = pd.Series(my_list) # Create a series from an iterable my_list"
},
{
"code": null,
"e": 2236,
"s": 2061,
"text": "head() function displays the first n records from a DataFrame. I often print the top record of a DataFrame in my notebook so I can refer back to it if I forget what’s inside."
},
{
"code": null,
"e": 2279,
"s": 2236,
"text": "df.head(3) # First 3 rows of the DataFrame"
},
{
"code": null,
"e": 2418,
"s": 2279,
"text": "tail() function is used to return the last n rows. This is useful for quickly verifying data, especially, after sorting or appending rows."
},
{
"code": null,
"e": 2460,
"s": 2418,
"text": "df.tail(3) # Last 3 rows of the DataFrame"
},
{
"code": null,
"e": 2554,
"s": 2460,
"text": "To append or add a row to DataFrame, we create the new row as Series and use append() method."
},
{
"code": null,
"e": 2686,
"s": 2554,
"text": "In this example, the new row is initialized as a python dictionary, and append() method is used to append the row to the DataFrame."
},
{
"code": null,
"e": 3009,
"s": 2686,
"text": "When we are adding a python dictionary to append(), make sure we pass ignore_index=True, so that the index values are not used along the concatenation axis. The resulting axis will instead be labeled as number series0, 1, ..., n-1, which is useful when the concatenation axis does not have meaningful indexing information."
},
{
"code": null,
"e": 3077,
"s": 3009,
"text": "The append() method returns the DataFrame with the newly added row."
},
{
"code": null,
"e": 3243,
"s": 3077,
"text": "#Append row to the dataframe, missing data (np.nan)new_row = {'Name':'Max', 'Physics':67, 'Chemistry':92, 'Algebra':np.nan}df = df.append(new_row, ignore_index=True)"
},
{
"code": null,
"e": 3650,
"s": 3243,
"text": "# List of series list_of_series = [pd.Series(['Liz', 83, 77, np.nan], index=df.columns), pd.Series(['Sam', np.nan, 94,70], index=df.columns ), pd.Series(['Mike', 79,87,90], index=df.columns), pd.Series(['Scott', np.nan,87,np.nan], index=df.columns),]# Pass a list of series to the append() to add multiple rowsdf = df.append(list_of_series , ignore_index=True)"
},
{
"code": null,
"e": 3797,
"s": 3650,
"text": "# Adding a new column to existing DataFrame in Pandassex = ['Male','Female','Male','Female','Male','Female','Female','Male','Male']df['Sex'] = sex"
},
{
"code": null,
"e": 3999,
"s": 3797,
"text": "info() function is useful for getting some general information like header, number of values, and datatype by column. A similar but less useful function is df.dtypes which just gives column data types."
},
{
"code": null,
"e": 4049,
"s": 3999,
"text": "df.info() #Index, Datatype and Memory information"
},
{
"code": null,
"e": 4314,
"s": 4049,
"text": "# Check data type in pandas dataframedf['Chemistry'].dtypes >>> dtype('int64')# Convert Integers to Floats in Pandas DataFramedf['Chemistry'] = df['Chemistry'].astype(float) df['Chemistry'].dtypes>>> dtype('float64')# Number of rows and columnsdf.shape >>> (9, 5)"
},
{
"code": null,
"e": 4402,
"s": 4314,
"text": "The value_counts() function is used to get a series containing counts of unique values."
},
{
"code": null,
"e": 4492,
"s": 4402,
"text": "# View unique values and counts of Physics columndf['Physics'].value_counts(dropna=False)"
},
{
"code": null,
"e": 4607,
"s": 4492,
"text": "This works if we need to pull the values in columns into X and y variables so we can fit a machine learning model."
},
{
"code": null,
"e": 4673,
"s": 4607,
"text": "df['Chemistry'] # Returns column with label 'Chemistry' as Series"
},
{
"code": null,
"e": 4733,
"s": 4673,
"text": "df[['Name','Algebra']] # Returns columns as a new DataFrame"
},
{
"code": null,
"e": 4768,
"s": 4733,
"text": "df.iloc[0] # Selection by position"
},
{
"code": null,
"e": 4818,
"s": 4768,
"text": "df.iloc[:,1] # Second column 'Name' of data frame"
},
{
"code": null,
"e": 4872,
"s": 4818,
"text": "df.iloc[0,1] # First element of Second column>>> 68.0"
},
{
"code": null,
"e": 5036,
"s": 4872,
"text": "rename() function is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed."
},
{
"code": null,
"e": 5120,
"s": 5036,
"text": "# Rename columnsdf = df.rename({'Name':'Student','Algebra':'Math'}, axis='columns')"
},
{
"code": null,
"e": 5258,
"s": 5120,
"text": "In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed."
},
{
"code": null,
"e": 5410,
"s": 5258,
"text": "NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation"
},
{
"code": null,
"e": 5635,
"s": 5410,
"text": "Pandas treat NaN as essentially interchangeable for indicating missing or null values. To facilitate this convention, there are several useful functions for detecting, removing, and replacing null values in Pandas DataFrame."
},
{
"code": null,
"e": 5711,
"s": 5635,
"text": "# Checks for null Values, Returns Boolean Arrraycheck_for_nan = df.isnull()"
},
{
"code": null,
"e": 5984,
"s": 5711,
"text": "To check null values in Pandas DataFrame, we use isnull() or notnull() method. isnull() method returns DataFrame of Boolean values which are True for NaN values. In the opposite position, notnull() method returns DataFrame of Boolean values which are False for NaN values."
},
{
"code": null,
"e": 6032,
"s": 5984,
"text": "value = df.notnull() # Opposite of df2.isnull()"
},
{
"code": null,
"e": 6104,
"s": 6032,
"text": "We use dropna() function to drop all rows that have any missing values."
},
{
"code": null,
"e": 6173,
"s": 6104,
"text": "drop_null_row = df.dropna() # Drop all rows that contain null values"
},
{
"code": null,
"e": 6248,
"s": 6173,
"text": "Sometimes, we may just want to drop a column that has some missing values."
},
{
"code": null,
"e": 6325,
"s": 6248,
"text": "# Drop all columns that contain null valuesdrop_null_col = df.dropna(axis=1)"
},
{
"code": null,
"e": 6426,
"s": 6325,
"text": "We can fill missing values by using fillna(). For example, we may want to replace ‘NaN’ with zeroes."
},
{
"code": null,
"e": 6487,
"s": 6426,
"text": "replace_null = df.fillna(0) # Replace all null values with 0"
},
{
"code": null,
"e": 6532,
"s": 6487,
"text": "Or we can replace ‘NaN’ with the mean value."
},
{
"code": null,
"e": 6681,
"s": 6532,
"text": "# Replace all null values with the mean (mean can be replaced with almost any function from the statistics module)df = round(df.fillna(df.mean()),2)"
},
{
"code": null,
"e": 6741,
"s": 6681,
"text": "replace() method can be used to replace values in DataFrame"
},
{
"code": null,
"e": 6810,
"s": 6741,
"text": "one = df.replace(100,'A') # Replace all values equal to 1 with 'one'"
},
{
"code": null,
"e": 6866,
"s": 6810,
"text": "We want to see students who get 80 or higher in Physics"
},
{
"code": null,
"e": 6898,
"s": 6866,
"text": "fil_80 = df[df['Physics'] > 80]"
},
{
"code": null,
"e": 7004,
"s": 6898,
"text": "What if we want to see students who receive 80 or higher grade in Chemistry but less than 90 on Math exam"
},
{
"code": null,
"e": 7057,
"s": 7004,
"text": "fil = df[(df['Chemistry'] > 80) & (df['Math'] < 90)]"
},
{
"code": null,
"e": 7282,
"s": 7057,
"text": "Often we want to sort Pandas DataFrame in a specific way. Typically, one may want to sort Pandas DataFrame based on the values of one or more columns or sort based on the values of row index or row names of Pandas DataFrame."
},
{
"code": null,
"e": 7356,
"s": 7282,
"text": "For example, we want to sort values by Student’s name in ascending order."
},
{
"code": null,
"e": 7394,
"s": 7356,
"text": "ascending = df.sort_values('Student')"
},
{
"code": null,
"e": 7439,
"s": 7394,
"text": "Sorting Chemistry score in descending order."
},
{
"code": null,
"e": 7496,
"s": 7439,
"text": "descending = df.sort_values('Chemistry',ascending=False)"
},
{
"code": null,
"e": 7617,
"s": 7496,
"text": "More complicated, we want to sort values by Physics scores in ascending order then Chemistry scores in descending order."
},
{
"code": null,
"e": 7680,
"s": 7617,
"text": "df.sort_values(['Physics','Chemistry'],ascending=[True,False])"
},
{
"code": null,
"e": 7862,
"s": 7680,
"text": "In this case, a DataFrame will be sorted for Physics and Chemistry column respectively. We can also pass a list to the ‘ascending’ parameter to tell Pandas which column to sort how."
},
{
"code": null,
"e": 8201,
"s": 7862,
"text": "Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It is a simple concept but it’s an extremely valuable technique that we often use. Groupby concept is important because it’s the ability to aggregate data efficiently, both in performance and the amount code is magnificent."
},
{
"code": null,
"e": 8251,
"s": 8201,
"text": "Let’s group the unique values from the Sex column"
},
{
"code": null,
"e": 8390,
"s": 8251,
"text": "group_by = df.groupby(['Sex']) # Returns a groupby object for values from one columngroup_by.first() # Print the first value in each group"
},
{
"code": null,
"e": 8458,
"s": 8390,
"text": "Calculate the average across all columns for every unique Sex group"
},
{
"code": null,
"e": 8499,
"s": 8458,
"text": "average = df.groupby(‘Sex’).agg(np.mean)"
},
{
"code": null,
"e": 8787,
"s": 8499,
"text": "We may be familiar with pivot tables in Excel to generate easy insights into our data. Similarly, we can create Python pivot tables using the pivot_table() function available in Pandas. The function is quite similar to the group_by() function but offers significantly more customization."
},
{
"code": null,
"e": 8981,
"s": 8787,
"text": "Let’s say we want to group values by Sex and calculate the mean and standard deviation of Physics and Chemistry columns. We will call the pivot_table() function and set the following arguments:"
},
{
"code": null,
"e": 9085,
"s": 8981,
"text": "index to be 'Sex' since that is the column from df that we want to appear as a unique value in each row"
},
{
"code": null,
"e": 9186,
"s": 9085,
"text": "values as 'Physics','Chemistry' since that's the column we want to apply some aggregate operation on"
},
{
"code": null,
"e": 9364,
"s": 9186,
"text": "aggfunc to 'len','np.mean','np.std len will count the unique distinct values from the Sex column, np.mean and np.std will calculate the mean and standard deviation respectively."
},
{
"code": null,
"e": 9526,
"s": 9364,
"text": "pivot_table = df.pivot_table(index='Sex', values=['Physics','Chemistry'], aggfunc=[len, np.mean, np.std])"
},
{
"code": null,
"e": 9592,
"s": 9526,
"text": "Note: Using len assumes we don't have NaN values in our datagram."
},
{
"code": null,
"e": 9729,
"s": 9592,
"text": "describe() is used to view some basic statistical details like percentile, mean, std, etc. of a DataFrame or a series of numeric values."
},
{
"code": null,
"e": 9786,
"s": 9729,
"text": "df.describe() # Summary statistics for numerical columns"
},
{
"code": null,
"e": 9844,
"s": 9786,
"text": "Find the maximum value of each row and column using max()"
},
{
"code": null,
"e": 9920,
"s": 9844,
"text": "# Get a series containing maximum value of each rowmax_row = df.max(axis=1)"
},
{
"code": null,
"e": 10026,
"s": 9920,
"text": "# Get a series containing maximum value of each column without skipping NaNmax_col = df.max(skipna=False)"
},
{
"code": null,
"e": 10106,
"s": 10026,
"text": "Similarly, we can use df.min() to find the minimum value of each row or column."
},
{
"code": null,
"e": 10141,
"s": 10106,
"text": "Other useful statistics functions:"
},
{
"code": null,
"e": 10241,
"s": 10141,
"text": "df.sum(): Returns the sum of the values for the requested axis. By default, axis is index (axis=0)."
},
{
"code": null,
"e": 10277,
"s": 10241,
"text": "df.mean():Returns the average value"
},
{
"code": null,
"e": 10324,
"s": 10277,
"text": "df.median(): Returns the median of each column"
},
{
"code": null,
"e": 10390,
"s": 10324,
"text": "df.std():Returns the standard deviation of the numerical columns."
},
{
"code": null,
"e": 10457,
"s": 10390,
"text": "df.corr() :Returns the correlation between columns in a DataFrame."
},
{
"code": null,
"e": 10524,
"s": 10457,
"text": "df.count() : Returns the number of non-null values in each column."
},
{
"code": null,
"e": 10570,
"s": 10524,
"text": "The code in this note is available on Github."
},
{
"code": null,
"e": 10826,
"s": 10570,
"text": "That’s all the good stuff. I hope this cheat sheet can be a reference guide for you. I’ll try to continuously update this as I find more useful Pandas functions. If there are any functions you can’t live without please share with me in the comments below!"
},
{
"code": null,
"e": 10913,
"s": 10826,
"text": "It’s never too late to learn, so if you just start your Python journey, keep learning!"
},
{
"code": null,
"e": 11170,
"s": 10913,
"text": "Lots and lots of books have been written about Python programming. I certainly didn’t cover enough information here to fill a chapter, but that doesn’t mean you can’t keep learning! Fill your mind with more awesomeness, starting with the great links below."
},
{
"code": null,
"e": 11305,
"s": 11170,
"text": "Pandas installationPython HandbookPandas introduction for beginnersPandas basicsHow to learn PandasWhat is the use of Pandas in Python"
},
{
"code": null,
"e": 11325,
"s": 11305,
"text": "Pandas installation"
},
{
"code": null,
"e": 11341,
"s": 11325,
"text": "Python Handbook"
},
{
"code": null,
"e": 11375,
"s": 11341,
"text": "Pandas introduction for beginners"
},
{
"code": null,
"e": 11389,
"s": 11375,
"text": "Pandas basics"
},
{
"code": null,
"e": 11409,
"s": 11389,
"text": "How to learn Pandas"
}
] |
Hashtable put() Method in Java - GeeksforGeeks | 28 Jun, 2018
The java.util.Hashtable.put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
Syntax:
Hash_Table.put(key, value)
Parameters: The method takes two parameters, both are of the Object type of the Hashtable.
key: This refers to the key element that needs to be inserted into the Table for mapping.
value: This refers to the value that the above key would map into.
Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned.
Below programs are used to illustrate the working of java.util.Hashtable.put() Method:Program 1: When passing an existing key.
// Java code to illustrate the put() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting values into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial table is: " + hash_table); // Inserting existing key along with new value String returned_value = (String)hash_table.put(20, "All"); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new table System.out.println("New table is: " + hash_table); }}
Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: Geeks
New table is: {10=Geeks, 20=All, 30=You, 15=4, 25=Welcomes}
Program 2: When passing a new key.
// Java code to illustrate the put() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting values into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial table is: " + hash_table); // Inserting existing key along with new value String returned_value = (String)hash_table.put(50, "All"); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new table System.out.println("New table is: " + hash_table); }}
Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: null
New table is: {10=Geeks, 20=Geeks, 30=You, 50=All, 15=4, 25=Welcomes}
Note: The same operation can be performed with any type of variation and combination of different data types.
Java-Collections
Java-HashTable
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 23544,
"s": 23516,
"text": "\n28 Jun, 2018"
},
{
"code": null,
"e": 23882,
"s": 23544,
"text": "The java.util.Hashtable.put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole."
},
{
"code": null,
"e": 23890,
"s": 23882,
"text": "Syntax:"
},
{
"code": null,
"e": 23917,
"s": 23890,
"text": "Hash_Table.put(key, value)"
},
{
"code": null,
"e": 24008,
"s": 23917,
"text": "Parameters: The method takes two parameters, both are of the Object type of the Hashtable."
},
{
"code": null,
"e": 24098,
"s": 24008,
"text": "key: This refers to the key element that needs to be inserted into the Table for mapping."
},
{
"code": null,
"e": 24165,
"s": 24098,
"text": "value: This refers to the value that the above key would map into."
},
{
"code": null,
"e": 24295,
"s": 24165,
"text": "Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned."
},
{
"code": null,
"e": 24422,
"s": 24295,
"text": "Below programs are used to illustrate the working of java.util.Hashtable.put() Method:Program 1: When passing an existing key."
},
{
"code": "// Java code to illustrate the put() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting values into the table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"Initial table is: \" + hash_table); // Inserting existing key along with new value String returned_value = (String)hash_table.put(20, \"All\"); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displaying the new table System.out.println(\"New table is: \" + hash_table); }}",
"e": 25363,
"s": 24422,
"text": null
},
{
"code": null,
"e": 25515,
"s": 25363,
"text": "Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nReturned value is: Geeks\nNew table is: {10=Geeks, 20=All, 30=You, 15=4, 25=Welcomes}\n"
},
{
"code": null,
"e": 25550,
"s": 25515,
"text": "Program 2: When passing a new key."
},
{
"code": "// Java code to illustrate the put() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting values into the table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"Initial table is: \" + hash_table); // Inserting existing key along with new value String returned_value = (String)hash_table.put(50, \"All\"); // Verifying the returned value System.out.println(\"Returned value is: \" + returned_value); // Displaying the new table System.out.println(\"New table is: \" + hash_table); }}",
"e": 26491,
"s": 25550,
"text": null
},
{
"code": null,
"e": 26652,
"s": 26491,
"text": "Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nReturned value is: null\nNew table is: {10=Geeks, 20=Geeks, 30=You, 50=All, 15=4, 25=Welcomes}\n"
},
{
"code": null,
"e": 26762,
"s": 26652,
"text": "Note: The same operation can be performed with any type of variation and combination of different data types."
},
{
"code": null,
"e": 26779,
"s": 26762,
"text": "Java-Collections"
},
{
"code": null,
"e": 26794,
"s": 26779,
"text": "Java-HashTable"
},
{
"code": null,
"e": 26799,
"s": 26794,
"text": "Java"
},
{
"code": null,
"e": 26804,
"s": 26799,
"text": "Java"
},
{
"code": null,
"e": 26821,
"s": 26804,
"text": "Java-Collections"
},
{
"code": null,
"e": 26919,
"s": 26821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26934,
"s": 26919,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26978,
"s": 26934,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27000,
"s": 26978,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 27036,
"s": 27000,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27061,
"s": 27036,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27093,
"s": 27061,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27144,
"s": 27093,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27174,
"s": 27144,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27193,
"s": 27174,
"text": "Interfaces in Java"
}
] |
Bulma - Modal | Modal is a child window that is layered over its parent window. It display the content from a separate source that can have some interaction without leaving the parent window.
You can display the modal by using modal class along with below 3 modal classes −
modal-background − It displays the transparent overlay.
modal-background − It displays the transparent overlay.
modal-content − It includes the modal content in a horizontally and vertically centered container.
modal-content − It includes the modal content in a horizontally and vertically centered container.
modal-close − It is used to close the modal window.
modal-close − It is used to close the modal window.
The below example shows displaying of modal by using above classes in the page −
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Elements Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Simple Modal
</span>
<br>
<br>
<p>
<a class = "button is-primary modal-button" data-target = "#modal">Launch example modal</a>
</p>
<div id = "modal" class = "modal">
<div class = "modal-background"></div>
<div class = "modal-content">
<div class = "box">
<article class = "media">
<div class = "media-left">
<figure class = "image is-64x64">
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg" alt="Image">
</figure>
</div>
<div class = "media-content">
<div class = "content">
<p>
<strong>Will Smith</strong>
<small>@wsmith</small>
<small>31m</small>
<br>
This is simple text. This is simple text.
This is simple text. This is simple text.
</p>
</div>
<nav class = "level">
<div class = "level-left">
<a class = "level-item">
<span class = "icon is-small">
<i class = "fa fa-reply"></i>
</span>
</a>
<a class = "level-item">
<span class = "icon is-small">
<i class = "fa fa-retweet"></i>
</span>
</a>
</div>
</nav>
</div>
</article>
</div>
</div>
<button class = "modal-close is-large" aria-label = "close"></button>
</div>
</div>
</section>
<script>
$(".modal-button").click(function() {
var target = $(this).data("target");
$("html").addClass("is-clipped");
$(target).addClass("is-active");
});
$(".modal-close").click(function() {
$("html").removeClass("is-clipped");
$(this).parent().removeClass("is-active");
});
</script>
</body>
</html>
It displays the below output −
Launch example modal
Will Smith @wsmith 31m
This is simple text.This is simple text.This is simple text.This is simple text.
Bulma allows you to display an image in the modal by adding image class along with path of image as shown in the below example −
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Elements Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Image Modal
</span>
<br>
<br>
<p>
<a class = "button is-primary modal-button" data-target = "#modal">Launch image modal</a>
</p>
<div id = "modal" class = "modal">
<div class = "modal-background"></div>
<div class = "modal-content">
<p class = "image is-128x128">
<img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg" alt="">
</p>
</div>
<button class = "modal-close is-large" aria-label="close"></button>
</div>
</div>
</section>
<script>
$(".modal-button").click(function() {
var target = $(this).data("target");
$("html").addClass("is-clipped");
$(target).addClass("is-active");
});
$(".modal-close").click(function() {
$("html").removeClass("is-clipped");
$(this).parent().removeClass("is-active");
});
</script>
</body>
</html>
It displays the below output −
Launch image modal
Bulma uses modal card to display the content in a box for better appearance.
Let's create an example for modal card by using the modal-card class −
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Elements Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Modal Card
</span>
<br>
<br>
<p>
<a class = "button is-primary modal-button" data-target = "#modal">Launch Card modal</a>
</p>
<div id = "modal" class = "modal">
<div class = "modal-background"></div>
<div class = "modal-card">
<header class = "modal-card-head">
<p class = "modal-card-title">Modal Card</p>
<button class = "delete" aria-label = "close"></button>
</header>
<section class = "modal-card-body">
<div class = "content">
<h1>Level One</h1>
<p>
This is simple text. This is simple text.
This is simple text. This is simple text.
</p>
<h2>Level Two</h2>
<p>
This is simple text. This is simple text.
This is simple text. This is simple text.
</p>
<h3>Level Three</h3>
<blockquote>
This is simple text. This is simple text.
This is simple text. This is simple text.
</blockquote>
<h4>Level Four</h4>
<p>
This is simple text. This is simple text.
This is simple text. This is simple text.
</p>
<h5>Level Five</h5>
<p>
This is simple text. This is simple text.
This is simple text. This is simple text.
</p>
</ul>
</div>
</section>
</div>
</div>
</div>
</section>
<script>
$(".modal-button").click(function() {
var target = $(this).data("target");
$("html").addClass("is-clipped");
$(target).addClass("is-active");
});
$(".modal-close").click(function() {
$("html").removeClass("is-clipped");
$(this).parent().removeClass("is-active");
});
</script>
</body>
</html>
It displays the below output −
Launch Card modal
Modal Card
This is simple text.This is simple text.This is simple text.This is simple text.
This is simple text.This is simple text.This is simple text.This is simple text.
This is simple text.This is simple text.This is simple text.This is simple text.
This is simple text.This is simple text.This is simple text.This is simple text.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1874,
"s": 1698,
"text": "Modal is a child window that is layered over its parent window. It display the content from a separate source that can have some interaction without leaving the parent window."
},
{
"code": null,
"e": 1956,
"s": 1874,
"text": "You can display the modal by using modal class along with below 3 modal classes −"
},
{
"code": null,
"e": 2012,
"s": 1956,
"text": "modal-background − It displays the transparent overlay."
},
{
"code": null,
"e": 2068,
"s": 2012,
"text": "modal-background − It displays the transparent overlay."
},
{
"code": null,
"e": 2167,
"s": 2068,
"text": "modal-content − It includes the modal content in a horizontally and vertically centered container."
},
{
"code": null,
"e": 2266,
"s": 2167,
"text": "modal-content − It includes the modal content in a horizontally and vertically centered container."
},
{
"code": null,
"e": 2318,
"s": 2266,
"text": "modal-close − It is used to close the modal window."
},
{
"code": null,
"e": 2370,
"s": 2318,
"text": "modal-close − It is used to close the modal window."
},
{
"code": null,
"e": 2451,
"s": 2370,
"text": "The below example shows displaying of modal by using above classes in the page −"
},
{
"code": null,
"e": 5828,
"s": 2451,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Elements Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n </head>\n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Simple Modal\n </span>\n <br>\n <br>\n \n <p>\n <a class = \"button is-primary modal-button\" data-target = \"#modal\">Launch example modal</a>\n </p>\n <div id = \"modal\" class = \"modal\">\n <div class = \"modal-background\"></div>\n <div class = \"modal-content\">\n <div class = \"box\">\n <article class = \"media\">\n <div class = \"media-left\">\n <figure class = \"image is-64x64\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" alt=\"Image\">\n </figure>\n </div>\n <div class = \"media-content\">\n <div class = \"content\">\n <p>\n <strong>Will Smith</strong> \n <small>@wsmith</small> \n <small>31m</small>\n <br>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </p>\n </div>\n <nav class = \"level\">\n <div class = \"level-left\">\n <a class = \"level-item\">\n <span class = \"icon is-small\">\n <i class = \"fa fa-reply\"></i>\n </span>\n </a>\n <a class = \"level-item\">\n <span class = \"icon is-small\">\n <i class = \"fa fa-retweet\"></i>\n </span>\n </a>\n </div>\n </nav>\n \n </div>\n </article>\n </div>\n </div>\n <button class = \"modal-close is-large\" aria-label = \"close\"></button>\n </div>\n </div>\n </section>\n \n <script>\n $(\".modal-button\").click(function() {\n var target = $(this).data(\"target\");\n $(\"html\").addClass(\"is-clipped\");\n $(target).addClass(\"is-active\");\n });\n \n $(\".modal-close\").click(function() {\n $(\"html\").removeClass(\"is-clipped\");\n $(this).parent().removeClass(\"is-active\");\n });\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5859,
"s": 5828,
"text": "It displays the below output −"
},
{
"code": null,
"e": 5882,
"s": 5859,
"text": "\nLaunch example modal\n"
},
{
"code": null,
"e": 6018,
"s": 5882,
"text": "\nWill Smith @wsmith 31m\nThis is simple text.This is simple text.This is simple text.This is simple text.\n "
},
{
"code": null,
"e": 6147,
"s": 6018,
"text": "Bulma allows you to display an image in the modal by adding image class along with path of image as shown in the below example −"
},
{
"code": null,
"e": 7901,
"s": 6147,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Elements Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Image Modal\n </span>\n <br>\n <br>\n \n <p>\n <a class = \"button is-primary modal-button\" data-target = \"#modal\">Launch image modal</a>\n </p>\n <div id = \"modal\" class = \"modal\">\n <div class = \"modal-background\"></div>\n <div class = \"modal-content\">\n <p class = \"image is-128x128\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\" alt=\"\">\n </p>\n </div>\n <button class = \"modal-close is-large\" aria-label=\"close\"></button>\n </div>\n </div>\n </section>\n \n <script>\n $(\".modal-button\").click(function() {\n var target = $(this).data(\"target\");\n $(\"html\").addClass(\"is-clipped\");\n $(target).addClass(\"is-active\");\n });\n \n $(\".modal-close\").click(function() {\n $(\"html\").removeClass(\"is-clipped\");\n $(this).parent().removeClass(\"is-active\");\n });\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7932,
"s": 7901,
"text": "It displays the below output −"
},
{
"code": null,
"e": 7953,
"s": 7932,
"text": "\nLaunch image modal\n"
},
{
"code": null,
"e": 8033,
"s": 7956,
"text": "Bulma uses modal card to display the content in a box for better appearance."
},
{
"code": null,
"e": 8104,
"s": 8033,
"text": "Let's create an example for modal card by using the modal-card class −"
},
{
"code": null,
"e": 11373,
"s": 8104,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Elements Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Modal Card\n </span>\n <br>\n <br>\n \n <p>\n <a class = \"button is-primary modal-button\" data-target = \"#modal\">Launch Card modal</a>\n </p>\n \n <div id = \"modal\" class = \"modal\">\n <div class = \"modal-background\"></div>\n <div class = \"modal-card\">\n <header class = \"modal-card-head\">\n <p class = \"modal-card-title\">Modal Card</p>\n <button class = \"delete\" aria-label = \"close\"></button>\n </header>\n \n <section class = \"modal-card-body\">\n <div class = \"content\">\n <h1>Level One</h1>\n <p>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </p>\n \n <h2>Level Two</h2>\n <p>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </p>\n \n <h3>Level Three</h3>\n <blockquote>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </blockquote>\n \n <h4>Level Four</h4>\n <p>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </p>\n \n <h5>Level Five</h5>\n <p>\n This is simple text. This is simple text. \n This is simple text. This is simple text.\n </p>\n </ul>\n </div>\n </section>\n \n </div>\n </div>\n </div>\n </section>\n \n <script>\n $(\".modal-button\").click(function() {\n var target = $(this).data(\"target\");\n $(\"html\").addClass(\"is-clipped\");\n $(target).addClass(\"is-active\");\n });\n \n $(\".modal-close\").click(function() {\n $(\"html\").removeClass(\"is-clipped\");\n $(this).parent().removeClass(\"is-active\");\n });\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 11404,
"s": 11373,
"text": "It displays the below output −"
},
{
"code": null,
"e": 11424,
"s": 11404,
"text": "\nLaunch Card modal\n"
},
{
"code": null,
"e": 11435,
"s": 11424,
"text": "Modal Card"
},
{
"code": null,
"e": 11516,
"s": 11435,
"text": "This is simple text.This is simple text.This is simple text.This is simple text."
},
{
"code": null,
"e": 11597,
"s": 11516,
"text": "This is simple text.This is simple text.This is simple text.This is simple text."
},
{
"code": null,
"e": 11678,
"s": 11597,
"text": "This is simple text.This is simple text.This is simple text.This is simple text."
},
{
"code": null,
"e": 11759,
"s": 11678,
"text": "This is simple text.This is simple text.This is simple text.This is simple text."
},
{
"code": null,
"e": 11766,
"s": 11759,
"text": " Print"
},
{
"code": null,
"e": 11777,
"s": 11766,
"text": " Add Notes"
}
] |
Pytorch Model Visual Interpretation | by Himanshu Sharma | Towards Data Science | Pytorch is an open-source python library that is used to create deep learning/machine learning models, it is one of the most used library after TensorFlow. It is based on the Torch library and is mostly used for Computer Vision and NLP applications.
There are different pre-trained PyTorch models that we can use according to the application we are working on. But the question is do we really understand what comes out of this black box. Model interpretation is important because we need to understand how the model works and how we can improve the model.
Captum is an open-source python library that is used to interpret PyTorch models. It creates transparency in terms of model understanding and interpretability. It helps understand the most important features that data have and how it contributes to the output of the model.
In this article, we will create a Captum insights dashboard for PyTorch model interpretation.
Let’s get started...
We will start by installing a flask_compress and Captum using pip. The command given below will do that.
!pip install flask_compress !pip install captum
In this step, we will import the required libraries for creating a PyTorch model and a Captum dashboard for the model interpretation. In this article, I will not be covering how to create a model.
import osimport torchimport torch.nn as nnimport torchvisionimport torchvision.transforms as transformsfrom captum.insights import AttributionVisualizer, Batchfrom captum.insights.attr_vis.features import ImageFeature
For this article, I will be using a pre-trained model for creating our model.
def get_classes(): classes = [ "Plane", "Car", "Bird", "Cat", "Deer", "Dog", "Frog", "Horse", "Ship", "Truck", ] return classesdef get_pretrained_model(): class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool1 = nn.MaxPool2d(2, 2) self.pool2 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) self.relu1 = nn.ReLU() self.relu2 = nn.ReLU() self.relu3 = nn.ReLU() self.relu4 = nn.ReLU()def forward(self, x): x = self.pool1(self.relu1(self.conv1(x))) x = self.pool2(self.relu2(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = self.relu3(self.fc1(x)) x = self.relu4(self.fc2(x)) x = self.fc3(x) return xnet = Net() net.load_state_dict(torch.load("cifar_torchvision.pt")) return netdef baseline_func(input): return input * 0def formatted_data_iter(): dataset = torchvision.datasets.CIFAR10( root="data/test", train=False, download=True, transform=transforms.ToTensor() ) dataloader = iter( torch.utils.data.DataLoader(dataset, batch_size=4, shuffle=False, num_workers=2) ) while True: images, labels = next(dataloader) yield Batch(inputs=images, labels=labels)
This is the final step where will create the dashboard for model understanding and interpretation.
normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))model = get_pretrained_model()visualizer = AttributionVisualizer( models=[model], score_func=lambda o: torch.nn.functional.softmax(o, 1), classes=get_classes(), features=[ ImageFeature( "Photo", baseline_transforms=[baseline_func], input_transforms=[normalize], ) ], dataset=formatted_data_iter(),)#Visualize Modelvisualizer.render()
Here you can clearly visualize how the model is working, you can select the class that you want to interpret, similarly choose the attribution method and the arguments for that. It is clearly showing the attribution magnitude, labels, and prediction also.
Go ahead try this with different datasets and create beautiful Captum dashboards to interpret the model. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 422,
"s": 172,
"text": "Pytorch is an open-source python library that is used to create deep learning/machine learning models, it is one of the most used library after TensorFlow. It is based on the Torch library and is mostly used for Computer Vision and NLP applications."
},
{
"code": null,
"e": 729,
"s": 422,
"text": "There are different pre-trained PyTorch models that we can use according to the application we are working on. But the question is do we really understand what comes out of this black box. Model interpretation is important because we need to understand how the model works and how we can improve the model."
},
{
"code": null,
"e": 1003,
"s": 729,
"text": "Captum is an open-source python library that is used to interpret PyTorch models. It creates transparency in terms of model understanding and interpretability. It helps understand the most important features that data have and how it contributes to the output of the model."
},
{
"code": null,
"e": 1097,
"s": 1003,
"text": "In this article, we will create a Captum insights dashboard for PyTorch model interpretation."
},
{
"code": null,
"e": 1118,
"s": 1097,
"text": "Let’s get started..."
},
{
"code": null,
"e": 1223,
"s": 1118,
"text": "We will start by installing a flask_compress and Captum using pip. The command given below will do that."
},
{
"code": null,
"e": 1271,
"s": 1223,
"text": "!pip install flask_compress !pip install captum"
},
{
"code": null,
"e": 1468,
"s": 1271,
"text": "In this step, we will import the required libraries for creating a PyTorch model and a Captum dashboard for the model interpretation. In this article, I will not be covering how to create a model."
},
{
"code": null,
"e": 1686,
"s": 1468,
"text": "import osimport torchimport torch.nn as nnimport torchvisionimport torchvision.transforms as transformsfrom captum.insights import AttributionVisualizer, Batchfrom captum.insights.attr_vis.features import ImageFeature"
},
{
"code": null,
"e": 1764,
"s": 1686,
"text": "For this article, I will be using a pre-trained model for creating our model."
},
{
"code": null,
"e": 3326,
"s": 1764,
"text": "def get_classes(): classes = [ \"Plane\", \"Car\", \"Bird\", \"Cat\", \"Deer\", \"Dog\", \"Frog\", \"Horse\", \"Ship\", \"Truck\", ] return classesdef get_pretrained_model(): class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool1 = nn.MaxPool2d(2, 2) self.pool2 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) self.relu1 = nn.ReLU() self.relu2 = nn.ReLU() self.relu3 = nn.ReLU() self.relu4 = nn.ReLU()def forward(self, x): x = self.pool1(self.relu1(self.conv1(x))) x = self.pool2(self.relu2(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = self.relu3(self.fc1(x)) x = self.relu4(self.fc2(x)) x = self.fc3(x) return xnet = Net() net.load_state_dict(torch.load(\"cifar_torchvision.pt\")) return netdef baseline_func(input): return input * 0def formatted_data_iter(): dataset = torchvision.datasets.CIFAR10( root=\"data/test\", train=False, download=True, transform=transforms.ToTensor() ) dataloader = iter( torch.utils.data.DataLoader(dataset, batch_size=4, shuffle=False, num_workers=2) ) while True: images, labels = next(dataloader) yield Batch(inputs=images, labels=labels)"
},
{
"code": null,
"e": 3425,
"s": 3326,
"text": "This is the final step where will create the dashboard for model understanding and interpretation."
},
{
"code": null,
"e": 3890,
"s": 3425,
"text": "normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))model = get_pretrained_model()visualizer = AttributionVisualizer( models=[model], score_func=lambda o: torch.nn.functional.softmax(o, 1), classes=get_classes(), features=[ ImageFeature( \"Photo\", baseline_transforms=[baseline_func], input_transforms=[normalize], ) ], dataset=formatted_data_iter(),)#Visualize Modelvisualizer.render()"
},
{
"code": null,
"e": 4146,
"s": 3890,
"text": "Here you can clearly visualize how the model is working, you can select the class that you want to interpret, similarly choose the attribution method and the arguments for that. It is clearly showing the attribution magnitude, labels, and prediction also."
},
{
"code": null,
"e": 4327,
"s": 4146,
"text": "Go ahead try this with different datasets and create beautiful Captum dashboards to interpret the model. In case you find any difficulty please let me know in the response section."
},
{
"code": null,
"e": 4380,
"s": 4327,
"text": "This article is in collaboration with Piyush Ingale."
}
] |
Impala - Environment | This chapter explains the prerequisites for installing Impala, how to download, install and set up Impala in your system.
Similar to Hadoop and its ecosystem software, we need to install Impala on Linux operating system. Since cloudera shipped Impala, it is available with Cloudera Quick Start VM.
This chapter describes how to download Cloudera Quick Start VM and start Impala.
Follow the steps given below to download the latest version of Cloudera QuickStartVM.
Open the homepage of cloudera website http://www.cloudera.com/. You will get the page as shown below.
Click the Sign in link on the cloudera homepage, which will redirect you to the Sign in page as shown below.
If you haven’t registered yet, click the Register Now link which will give you Account Registration form. Register there and sign in to cloudera account.
After signing in, open the download page of cloudera website by clicking on the Downloads link highlighted in the following snapshot.
Download the cloudera QuickStartVM by clicking on the Download Now button, as highlighted in the following snapshot
This will redirect you to the download page of QuickStart VM.
Click the Get ONE NOW button, accept the license agreement, and click the submit button as shown below.
Cloudera provides its VM compatible VMware, KVM and VIRTUALBOX. Select the required version. Here in our tutorial, we are demonstrating the Cloudera QuickStartVM setup using virtual box, therefore click the VIRTUALBOX DOWNLOAD button, as shown in the snapshot given below.
This will start downloading a file named cloudera-quickstart-vm-5.5.0-0-virtualbox.ovf which is a virtual box image file.
After downloading the cloudera-quickstart-vm-5.5.0-0-virtualbox.ovf file, we need to import it using virtual box. For that, first of all, you need to install virtual box in your system. Follow the steps given below to import the downloaded image file.
Download virtual box from the following link and install it https://www.virtualbox.org/
Open the virtual box software. Click File and choose Import Appliance, as shown below.
On clicking Import Appliance, you will get the Import Virtual Appliance window. Select the location of the downloaded image file as shown below.
After importing Cloudera QuickStartVM image, start the virtual machine. This virtual machine has Hadoop, cloudera Impala, and all the required software installed. The snapshot of the VM is shown below.
To start Impala, open the terminal and execute the following command.
[cloudera@quickstart ~] $ impala-shell
This will start the Impala Shell, displaying the following message.
Starting Impala Shell without Kerberos authentication
Connected to quickstart.cloudera:21000
Server version: impalad version 2.3.0-cdh5.5.0 RELEASE (build
0c891d79aa38f297d244855a32f1e17280e2129b)
********************************************************************************
Welcome to the Impala shell. Copyright (c) 2015 Cloudera, Inc. All rights reserved.
(Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9 12:18:12 PST 2015)
Press TAB twice to see a list of available commands.
********************************************************************************
[quickstart.cloudera:21000] >
Note − We will discuss all the impala-shell commands in later chapters.
In addition to Impala shell, you can communicate with Impala using the Hue browser. After installing CDH5 and starting Impala, if you open your browser, you will get the cloudera homepage as shown below.
Now, click the bookmark Hue to open the Hue browser. On clicking, you can see the login page of the Hue Browser, logging with the credentials cloudera and cloudera.
As soon as you log on to the Hue browser, you can see the Quick Start Wizard of Hue browser as shown below.
On clicking the Query Editors drop-down menu, you will get the list of editors Impala supports as shown in the following screenshot.
On clicking Impala in the drop-down menu, you will get the Impala query editor as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2407,
"s": 2285,
"text": "This chapter explains the prerequisites for installing Impala, how to download, install and set up Impala in your system."
},
{
"code": null,
"e": 2583,
"s": 2407,
"text": "Similar to Hadoop and its ecosystem software, we need to install Impala on Linux operating system. Since cloudera shipped Impala, it is available with Cloudera Quick Start VM."
},
{
"code": null,
"e": 2664,
"s": 2583,
"text": "This chapter describes how to download Cloudera Quick Start VM and start Impala."
},
{
"code": null,
"e": 2750,
"s": 2664,
"text": "Follow the steps given below to download the latest version of Cloudera QuickStartVM."
},
{
"code": null,
"e": 2852,
"s": 2750,
"text": "Open the homepage of cloudera website http://www.cloudera.com/. You will get the page as shown below."
},
{
"code": null,
"e": 2961,
"s": 2852,
"text": "Click the Sign in link on the cloudera homepage, which will redirect you to the Sign in page as shown below."
},
{
"code": null,
"e": 3115,
"s": 2961,
"text": "If you haven’t registered yet, click the Register Now link which will give you Account Registration form. Register there and sign in to cloudera account."
},
{
"code": null,
"e": 3249,
"s": 3115,
"text": "After signing in, open the download page of cloudera website by clicking on the Downloads link highlighted in the following snapshot."
},
{
"code": null,
"e": 3365,
"s": 3249,
"text": "Download the cloudera QuickStartVM by clicking on the Download Now button, as highlighted in the following snapshot"
},
{
"code": null,
"e": 3427,
"s": 3365,
"text": "This will redirect you to the download page of QuickStart VM."
},
{
"code": null,
"e": 3531,
"s": 3427,
"text": "Click the Get ONE NOW button, accept the license agreement, and click the submit button as shown below."
},
{
"code": null,
"e": 3804,
"s": 3531,
"text": "Cloudera provides its VM compatible VMware, KVM and VIRTUALBOX. Select the required version. Here in our tutorial, we are demonstrating the Cloudera QuickStartVM setup using virtual box, therefore click the VIRTUALBOX DOWNLOAD button, as shown in the snapshot given below."
},
{
"code": null,
"e": 3926,
"s": 3804,
"text": "This will start downloading a file named cloudera-quickstart-vm-5.5.0-0-virtualbox.ovf which is a virtual box image file."
},
{
"code": null,
"e": 4178,
"s": 3926,
"text": "After downloading the cloudera-quickstart-vm-5.5.0-0-virtualbox.ovf file, we need to import it using virtual box. For that, first of all, you need to install virtual box in your system. Follow the steps given below to import the downloaded image file."
},
{
"code": null,
"e": 4266,
"s": 4178,
"text": "Download virtual box from the following link and install it https://www.virtualbox.org/"
},
{
"code": null,
"e": 4353,
"s": 4266,
"text": "Open the virtual box software. Click File and choose Import Appliance, as shown below."
},
{
"code": null,
"e": 4498,
"s": 4353,
"text": "On clicking Import Appliance, you will get the Import Virtual Appliance window. Select the location of the downloaded image file as shown below."
},
{
"code": null,
"e": 4700,
"s": 4498,
"text": "After importing Cloudera QuickStartVM image, start the virtual machine. This virtual machine has Hadoop, cloudera Impala, and all the required software installed. The snapshot of the VM is shown below."
},
{
"code": null,
"e": 4770,
"s": 4700,
"text": "To start Impala, open the terminal and execute the following command."
},
{
"code": null,
"e": 4810,
"s": 4770,
"text": "[cloudera@quickstart ~] $ impala-shell\n"
},
{
"code": null,
"e": 4878,
"s": 4810,
"text": "This will start the Impala Shell, displaying the following message."
},
{
"code": null,
"e": 5492,
"s": 4878,
"text": "Starting Impala Shell without Kerberos authentication \nConnected to quickstart.cloudera:21000 \nServer version: impalad version 2.3.0-cdh5.5.0 RELEASE (build\n0c891d79aa38f297d244855a32f1e17280e2129b) \n********************************************************************************\n Welcome to the Impala shell. Copyright (c) 2015 Cloudera, Inc. All rights reserved. \n(Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9 12:18:12 PST 2015)\n \nPress TAB twice to see a list of available commands. \n******************************************************************************** \n[quickstart.cloudera:21000] >\n"
},
{
"code": null,
"e": 5564,
"s": 5492,
"text": "Note − We will discuss all the impala-shell commands in later chapters."
},
{
"code": null,
"e": 5768,
"s": 5564,
"text": "In addition to Impala shell, you can communicate with Impala using the Hue browser. After installing CDH5 and starting Impala, if you open your browser, you will get the cloudera homepage as shown below."
},
{
"code": null,
"e": 5933,
"s": 5768,
"text": "Now, click the bookmark Hue to open the Hue browser. On clicking, you can see the login page of the Hue Browser, logging with the credentials cloudera and cloudera."
},
{
"code": null,
"e": 6041,
"s": 5933,
"text": "As soon as you log on to the Hue browser, you can see the Quick Start Wizard of Hue browser as shown below."
},
{
"code": null,
"e": 6174,
"s": 6041,
"text": "On clicking the Query Editors drop-down menu, you will get the list of editors Impala supports as shown in the following screenshot."
},
{
"code": null,
"e": 6269,
"s": 6174,
"text": "On clicking Impala in the drop-down menu, you will get the Impala query editor as shown below."
},
{
"code": null,
"e": 6276,
"s": 6269,
"text": " Print"
},
{
"code": null,
"e": 6287,
"s": 6276,
"text": " Add Notes"
}
] |
How to position text to bottom right on an image with CSS | To position text to bottom left, use the bottom and right property. You can try to run the following code to position text to bottom right on an image:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: relative;
}
img {
width: 100%;
height: auto;
opacity: 0.6;
}
.direction {
position: absolute;
bottom: 10px;
right: 19px;
font-size: 13px;
}
</style>
</head>
<body>
<h1>Heading One</h1>
<p>Below image has text in the bottom right:</p>
<div class = "box">
<img src = "https://www.tutorialspoint.com/python/images/python_data_science.jpg" alt = "Tutorial" width = "800" height = "400">
<div class = "direction">Bottom Right Corner</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "To position text to bottom left, use the bottom and right property. You can try to run the following code to position text to bottom right on an image:"
},
{
"code": null,
"e": 1224,
"s": 1214,
"text": "Live Demo"
},
{
"code": null,
"e": 1952,
"s": 1224,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .box {\n position: relative;\n }\n img {\n width: 100%;\n height: auto;\n opacity: 0.6;\n }\n .direction {\n position: absolute;\n bottom: 10px;\n right: 19px;\n font-size: 13px;\n }\n </style>\n </head>\n <body>\n <h1>Heading One</h1>\n <p>Below image has text in the bottom right:</p>\n <div class = \"box\">\n <img src = \"https://www.tutorialspoint.com/python/images/python_data_science.jpg\" alt = \"Tutorial\" width = \"800\" height = \"400\">\n <div class = \"direction\">Bottom Right Corner</div>\n </div>\n </body>\n</html>"
}
] |
Pagination in streamlit. Using session states to implement... | by Vinayak Nayak | Towards Data Science | This post is aimed toward demonstrating the use of session state in Streamlitfor storing info about certain variables and prevent them from updating across runs. But what is Streamlit ?
Streamlit is a python library which is aimed to make the process of building web applications to showcase your work very easy for python developers. Until the arrival of this package Flask and Djangowere the goto libraries which developers chose to use in order to develop and deploy their application over the web; however both these frameworks required the user to write HTML/CSS code to render their work as a web-app. Streamlit abstracts all this and provides an easy pythonic interface for adding custom components like sliders, dropdowns, forms, textboxes etc. while also allowing people to add their own custom HTML/CSS components. If you’re new to Streamlit, their official documentation is very good to get you started with the same.
In this post, I am going to be discussing how we could build a component which could help implement pagination support as it is not something that is provided out of the box and needs a small hack of SessionStates.
Wikipedia defines pagination as process of dividing a document into discrete pages, either electronic pages or printed pages.
So basically if you have a lot of content which you want to display on your app/web-page, you can break them into a number of component pages which could be shown one by one and the trigger to switch between pages could be a button like a Next button or a Previous button.
On many web pages you can see pagination pay a key role for eg.
On any e-commerce site where there’s a lot of products to display, they’re typically showed in a page-wise fashion.
The search results for Google Search of a given query are always visible in pages and not all at once.
Streamlit’s current version doesn’t provide out of the box support to tackle this use-case but in this post we’re going to talk about a hack which will enable us to perform pagination in a neat manner.
If we look at a simple demo Streamlit code for displaying a dataframe to our screen, we can see the code is as follows:
The issue that we face here is that if we want to do pagination, we will have to define a page number and if we initialize it in here.
Next we need to create a button called Next and Previous which will move across the next or previous entries in the dataframe. But when we link to the variable page_number to these buttons, every time page number is clicked or there’s any component’s state change in the session, the variable gets re-initialised to it’s starting value and we never end up dynamically moving across pages. So, suppose we had a code like this
We have created a button next and a button previous which when clicked change the page number based on some conditional checks (i.e. don’t overshoot in case of first and last pages; roll back to the last/first pages respectively as case be). If we use this code as is and display the dataframe in the app, our output would be as follows:
When we click on next, the page number gets reinitialised to 0. That’s why we are never able to move ahead of page 1. The page number reinitialises to 0, gets incremented by 1 and that’s it, that happens in a loop.
Similarly when we click on previous, page number gets reinitialised to 0 and then decrements to the last page and this keeps happening perpetually!
There’s this piece of code which is generously lent to the users of streamlit by Thiago Teixeira who is the co-founder of streamlit that allows us to create objects which we can track in a session by not overwriting/reinitializing them over and again.
You basically copy the code given in the piece of code above to a file called SessionState.py and keep it in the same work directory as the application file. Next you just have to wrap the variable who you want to stop from getting re-initialised inside a Session State object by using the get method of the same as shown below.
In case you have more variables to keep track of you could write
import SessionStatess = SessionState.get(page_number = 0, var_1 = True, var_2 = "Streamlit demo!")
And it would also work fine. But a caveat here is that
You can only have one session state object per application
This is important to note because otherwise if you’re gonna try to initialize multiple states with multiple variables/attributes, that will end up not working and throw an error. So you have to be cautious about which variables to track dynamically and which ones to track via sessions and encircle the latter inside of the one and only SessionState object that you’re gonna create. The result of the above code works perfectly and looks as follows
If you liked what you read above, you may be interested in other articles authored by me. You can find them here.
Here’s one which helps you build your own video background blur functionality using Pytorch
https://towardsdatascience.com/semantic-image-segmentation-with-deeplabv3-pytorch-989319a9a4fb
Github link for source code of this appDataset reference — auto-mpg.csv from Kaggle
Github link for source code of this app
Dataset reference — auto-mpg.csv from Kaggle | [
{
"code": null,
"e": 357,
"s": 171,
"text": "This post is aimed toward demonstrating the use of session state in Streamlitfor storing info about certain variables and prevent them from updating across runs. But what is Streamlit ?"
},
{
"code": null,
"e": 1100,
"s": 357,
"text": "Streamlit is a python library which is aimed to make the process of building web applications to showcase your work very easy for python developers. Until the arrival of this package Flask and Djangowere the goto libraries which developers chose to use in order to develop and deploy their application over the web; however both these frameworks required the user to write HTML/CSS code to render their work as a web-app. Streamlit abstracts all this and provides an easy pythonic interface for adding custom components like sliders, dropdowns, forms, textboxes etc. while also allowing people to add their own custom HTML/CSS components. If you’re new to Streamlit, their official documentation is very good to get you started with the same."
},
{
"code": null,
"e": 1315,
"s": 1100,
"text": "In this post, I am going to be discussing how we could build a component which could help implement pagination support as it is not something that is provided out of the box and needs a small hack of SessionStates."
},
{
"code": null,
"e": 1441,
"s": 1315,
"text": "Wikipedia defines pagination as process of dividing a document into discrete pages, either electronic pages or printed pages."
},
{
"code": null,
"e": 1714,
"s": 1441,
"text": "So basically if you have a lot of content which you want to display on your app/web-page, you can break them into a number of component pages which could be shown one by one and the trigger to switch between pages could be a button like a Next button or a Previous button."
},
{
"code": null,
"e": 1778,
"s": 1714,
"text": "On many web pages you can see pagination pay a key role for eg."
},
{
"code": null,
"e": 1894,
"s": 1778,
"text": "On any e-commerce site where there’s a lot of products to display, they’re typically showed in a page-wise fashion."
},
{
"code": null,
"e": 1997,
"s": 1894,
"text": "The search results for Google Search of a given query are always visible in pages and not all at once."
},
{
"code": null,
"e": 2199,
"s": 1997,
"text": "Streamlit’s current version doesn’t provide out of the box support to tackle this use-case but in this post we’re going to talk about a hack which will enable us to perform pagination in a neat manner."
},
{
"code": null,
"e": 2319,
"s": 2199,
"text": "If we look at a simple demo Streamlit code for displaying a dataframe to our screen, we can see the code is as follows:"
},
{
"code": null,
"e": 2454,
"s": 2319,
"text": "The issue that we face here is that if we want to do pagination, we will have to define a page number and if we initialize it in here."
},
{
"code": null,
"e": 2879,
"s": 2454,
"text": "Next we need to create a button called Next and Previous which will move across the next or previous entries in the dataframe. But when we link to the variable page_number to these buttons, every time page number is clicked or there’s any component’s state change in the session, the variable gets re-initialised to it’s starting value and we never end up dynamically moving across pages. So, suppose we had a code like this"
},
{
"code": null,
"e": 3217,
"s": 2879,
"text": "We have created a button next and a button previous which when clicked change the page number based on some conditional checks (i.e. don’t overshoot in case of first and last pages; roll back to the last/first pages respectively as case be). If we use this code as is and display the dataframe in the app, our output would be as follows:"
},
{
"code": null,
"e": 3432,
"s": 3217,
"text": "When we click on next, the page number gets reinitialised to 0. That’s why we are never able to move ahead of page 1. The page number reinitialises to 0, gets incremented by 1 and that’s it, that happens in a loop."
},
{
"code": null,
"e": 3580,
"s": 3432,
"text": "Similarly when we click on previous, page number gets reinitialised to 0 and then decrements to the last page and this keeps happening perpetually!"
},
{
"code": null,
"e": 3832,
"s": 3580,
"text": "There’s this piece of code which is generously lent to the users of streamlit by Thiago Teixeira who is the co-founder of streamlit that allows us to create objects which we can track in a session by not overwriting/reinitializing them over and again."
},
{
"code": null,
"e": 4161,
"s": 3832,
"text": "You basically copy the code given in the piece of code above to a file called SessionState.py and keep it in the same work directory as the application file. Next you just have to wrap the variable who you want to stop from getting re-initialised inside a Session State object by using the get method of the same as shown below."
},
{
"code": null,
"e": 4226,
"s": 4161,
"text": "In case you have more variables to keep track of you could write"
},
{
"code": null,
"e": 4325,
"s": 4226,
"text": "import SessionStatess = SessionState.get(page_number = 0, var_1 = True, var_2 = \"Streamlit demo!\")"
},
{
"code": null,
"e": 4380,
"s": 4325,
"text": "And it would also work fine. But a caveat here is that"
},
{
"code": null,
"e": 4439,
"s": 4380,
"text": "You can only have one session state object per application"
},
{
"code": null,
"e": 4888,
"s": 4439,
"text": "This is important to note because otherwise if you’re gonna try to initialize multiple states with multiple variables/attributes, that will end up not working and throw an error. So you have to be cautious about which variables to track dynamically and which ones to track via sessions and encircle the latter inside of the one and only SessionState object that you’re gonna create. The result of the above code works perfectly and looks as follows"
},
{
"code": null,
"e": 5002,
"s": 4888,
"text": "If you liked what you read above, you may be interested in other articles authored by me. You can find them here."
},
{
"code": null,
"e": 5094,
"s": 5002,
"text": "Here’s one which helps you build your own video background blur functionality using Pytorch"
},
{
"code": null,
"e": 5189,
"s": 5094,
"text": "https://towardsdatascience.com/semantic-image-segmentation-with-deeplabv3-pytorch-989319a9a4fb"
},
{
"code": null,
"e": 5273,
"s": 5189,
"text": "Github link for source code of this appDataset reference — auto-mpg.csv from Kaggle"
},
{
"code": null,
"e": 5313,
"s": 5273,
"text": "Github link for source code of this app"
}
] |
Price Impact of Order Book Imbalance in Cryptocurrency Markets | by Vasili Shichou | Towards Data Science | We investigate whether imbalanced order books lead to price changes towards the thinner side of the book. That is, by this hypothesis prices decrease when limit order books have large volumes posted at the ask side relative to the bid side, and if order books are more heavy on the bid side then prices increase. We test this hypothesis and assess whether order book imbalance information can be exploited to profitably predict price movements in the ETHUSD market.
We follow the literature, e.g., Cartea et al. (2015), and define the order book imbalance as
where t indexes the time, V stands for volume at either the bid (superscript b) or ask (superscript a), and L is the depth level of the order book considered to calculate ρ. Figure 1 shows an example how to calculate the imbalance ρ for a given order book.
A ρ-value close to -1 is obtained when market makers post a large volume at the ask relative to the bid volume. A ρ-value close to 1 means there is a large volume at the bid side of the order book relative to the ask side. With an imbalance of zero the order book is perfectly balanced at the given level L. The hypothesis suggests that low imbalance numbers (<0) imply negative returns, high imbalance numbers (>0) imply positive returns, i.e., the price moves into the direction of the imbalance ρ.
Cont et al. (2014) use US stock data to show that there is a price impact of order flow imbalance and a linear relationship between “order flow imbalance” and price changes. The authors define order flow imbalance as the imbalance between supply and demand, measured by aggregating incoming orders over a given period. Their linear model has an R2 of around 70%. The study considers the past order flows (that result in an imbalance measure) and compares it to the price change over the same period. Hence, the conclusion is not that order flow imbalances predict future prices, but rather that the order flow imbalances computed over a historic period explains the price change over the same period. So this study reveals no direct insights on current order flow imbalances on future prices. Silantyev (2018) confirms the finding of this study using BTC-USD order book data in his Medium article.
Lipton et al. (2013), us the imbalance measure ρ with L=1 and find that the price change until the next tick can be well approximated by a linear function of the order book imbalance but note that (1) the change is well below the bid-ask spread, and (2) the method “does not by itself offer an opportunity for a straightforward statistical arbitrage”.
Cartea et al. (2018) find that a higher order book imbalance measured by ρ is followed by an increased amount of market orders and that the imbalance helps to predict price changes immediately after the arrival of a market order.
In their book, Cartea et al. (2015) present for one particular stock that correlations of past imbalances and price changes are decent (about 25% for a 10-second interval).
Stoikov (2017) defines a mid-price adjustment that incorporatesorder book imbalances and bid-ask spreads. He finds that the resultingprice (mid-price plus adjustment) is a better predictor for short-term movements of mid-prices than mid-prices and volume-weighted mid-prices. In this study, the order book imbalance slightly differs from ours, specifically Equation (1) would be adjusted by removing the ask volume from the nominator and fixing the level L to 1. The method estimates the expectation of the future mid-price conditional on current information and is horizon independent. Empirically horizons for which the forecasts are most accurate range from 3 to 10 seconds for the stocks assessed. The adjusted mid-price lives between the bid and the ask for the data presented which indicates that the method by itself does not present a method for statistical arbitrage, but as the author notes can be used to improve upon algorithms.
These studies consider tick-level data at the best bid-ask price (L=1),we look at longer horizons and delve into a depth of 5 to calculate the orderimbalance. The data in these studies uses stock market data, with thenotable exception of Silantyev (2018), whereas we look into cryptocurrency order books.
Order book data can be queried via public API from crypto-exchanges. Historical data other than candle data is not generally available. Hence I collected order book data for ETHUSD from Coinbase in 10 second intervals up to a depth of 5 levels from May to December 2019 (2019–05–21 01:46:37 to 2019–12–18 18:40:59). This amounts to 1,920,617 observations. There are some gaps in the data, e.g., due to system downtimes, which we account for in our analysis. We count 592 gaps where the timestamp difference between two subsequent order book observations is larger than 11 seconds. The timestamp between two order books is not exactly 10 seconds in the data since I collected the data using repeated REST requests, rather than, e.g., a continuous Websocket stream.
Before looking at the relationship between price changes and the order book imbalance, we look at the distribution of the imbalance for different order book levels.
We calculate the order book imbalance ρ for all observations and the 5 different levels according to Equation 1 and find the following properties.
At L=1 the imbalances are often very pronounced or not existent at all. The higher L, the more frequent are balanced order books (i.e., more observations for ρ≈0).The imbalance is autocorrelated. The deeper the level L, the higher the autocorrelation
At L=1 the imbalances are often very pronounced or not existent at all. The higher L, the more frequent are balanced order books (i.e., more observations for ρ≈0).
The imbalance is autocorrelated. The deeper the level L, the higher the autocorrelation
We present the first finding in Figures 2 and 3 and the second in Figure 4.
Figure 2 shows a histogram of order book imbalances for level 1. We observe that at this level, the order book is mostly balanced (close to 0), or highly imbalanced (close to -1 or 1).
As we increase the order book depth to calculate the imbalance, the order books become more balanced, as we see in Figure 3.
Figure 4 shows the autocorrelation function (ACF). Consistent with Cuartea et al. (2015) we find that imbalances are highly autocorrelated. The correlation for a given lag tends to be higher, the larger the order book depth L for the calculation of the imbalance.
We now investigate the correlation of ρ and future mid-prices. Mid-prices are defined as the average of highest bid price and the lowest ask price.
We first calculate the p-period ahead log-return of the mid-price for each observation of order book imbalance. We then calculate the correlation between these returns and the order imbalances observed at the beginning of the period. We remove observations where the p-periods are on average longer than 11 seconds (1 period ≈ 10 seconds).
Figure 5 and 6 show the correlations of future returns and imbalances as a function of the period over which the return is measured. We conclude as follows.
The correlations are low. E.g., Cont et al. (2014) report an R2 of about 70% between the price-impact and their measure of order flow imbalance over the same period. For a linear univariate regression model this R2 implies a correlation of sqrt(0.70)=0.84. However, the authors measure the price increase over the same period as the order flow imbalance, hence this method does not offer price forecastsThe imbalance measure ρ is more predictive for prices closer to the imbalance observation (the correlation decreases as p increases)The higher the depth level L of the order book considered to calculate the imbalance, the more the imbalance measure correlates with future price movements
The correlations are low. E.g., Cont et al. (2014) report an R2 of about 70% between the price-impact and their measure of order flow imbalance over the same period. For a linear univariate regression model this R2 implies a correlation of sqrt(0.70)=0.84. However, the authors measure the price increase over the same period as the order flow imbalance, hence this method does not offer price forecasts
The imbalance measure ρ is more predictive for prices closer to the imbalance observation (the correlation decreases as p increases)
The higher the depth level L of the order book considered to calculate the imbalance, the more the imbalance measure correlates with future price movements
The corresponding plots for depths L=2 to 4 which I don’t show for brevity are consistent with these findings. For Python code for these plots see Appendix A2.
The correlations presented above showed that imbalances calculated with higher L correlates better with price increases than imbalances calculated with lower L. More near-term prices have a higher correlation with ρ. Based on this we continue the analysis with only one-period ahead forecasts (≈10s).
Correlation is an average measure, what about the uncertainty of the mid-price moves?
Figure 7 and 8 plot the 1-period log-return against the imbalance observed at the beginning of the period for L=1 and L=5 respectively. The level 1 imbalance plot (Figure 7) looks as if there was a higher variation of log-returns when the imbalance is large (close to -1 or close to 1) or 0, which we don’t observe for level 5 imbalances (Figure 8). However, this seemingly larger variation in the plot stems from the fact that we have more observations for L=1 at the boundaries and at zero (seen in the histograms in Figures 2 and 3) — calculating the standard deviation of returns does not confirm higher variances at the extremes as we see in the next paragraph.
We follow Cartea et al. (2018) and bucket our imbalance measure into five regimes chosen to be equally spaced along the points
θ = {-1, -0.6, -0.2, 0.2, 0.6, 1}.
That is, regime 0 has price imbalances between -1 and -0.6, regime 1 from -0.6 to -0.2 and so on. Table 1 shows the standard deviation of 1-period ahead price returns for all 5 regimes.
Table 1 addresses the question from the previous paragraph: the mid-price variance at extreme imbalances (regime 0 and regime 4) is not higher for order book depth level L=1 than for level 5.
Now we take this analysis further and estimate probabilistic bounds for the expected mid-price return in a given regime by constructing confidence intervals. I provide details on this calculation in Appendix A1.
Figure 9 presents confidence intervals for the expected mid-price return in a given regime. We can see that indeed the returns are on average negative for low imbalance numbers (regime 0 and 1) and positive for high imbalance numbers (regime 3 and 4). The means move more into the order imbalance direction when the imbalance is constructed with a higher level, e.g., in regime 4 the mean of the 1-period ahead return when the imbalance is calculated with L=1 (dark line) is smaller than when performing the calculations at a depth of level L=5 (bright line). Note that the confidence intervals shown reflect the uncertainty in the expected value. The standard deviations of Table 1 inform us about the uncertainty of the returns around this expected value.
This analysis confirms the findings from the correlation analysis: there is positive but weak correlation between imbalances and 1-period ahead returns, and the deeper level (L) results in a slightly more predictive imbalance measure.
What is the probability that the next period mid-price will go up, stay flat, or go down knowing in which imbalance regime we are?
To see this, we bucket every order imbalance into a regime 0-4 and then count the number of negative returns, zero returns, and positive 1-period returns and divide the count by the number of observation to have an estimate for the probabilities of mid-price moves.
Figures 10 and 11 present the empirical probabilities for imbalances computed for L=1 and L=5 respectively. The figures confirm our initial hypothesis:
There is a higher probability of mid-price decreases in regimes with low values of order book imbalance, and vice versa.
We see qualitatively no difference in the empirical probabilities when calculating the imbalances with only 1 level (Figure 10) or 5 levels (Figure 11). We observe that the probabilities for higher levels L=5 are more discriminatory than for L=1, which is a desired property.
In Appendix A3 we also show the probabilities conditional on observing a non-zero price move. We find that if the price moves, the level 5 imbalance is a slightly better predictor than the level 1 imbalance.
Many crypto exchanges have trading fees in the order of 10bps (and we would execute 2 trades). We see from the confidence intervals (Figure 9) that mid-price returns are below 10 basis points for the 10 second periods considered. So from judging by the expected return without considering variances, we can conclude that order imbalances do not directly imply a profitable strategy on its own without even investigating the bid-ask spreads.
To affirm this finding, we look at profitability from another angle and calculate the empirical probabilities of price moves larger than 10 basis points, similar to figures 10 and 11. That is, we count all movements that are in absolute terms below 10 basis points as flat. Table 3 shows that for imbalance calculations with order book levels of both 1 and 5, most trades would end up below an absolute return of 10 basis points in all regimes. This confirms the strategy does not allow for statistical arbitrage on its own.
Our analysis for ETHUSD order books and mid-price movements is consistent with the findings in the literature on order book imbalances for stock markets:
When the imbalance is close to -1 there is a selling pressure and the mid-price is more likely to go down in the near term, when the imbalance is close to 1 there is a buying pressure and the mid-price is more likely to move up.
The price impact of the imbalance measure is short-lived and quickly deteriorates with the time horizon.
The imbalance measure itself cannot directly be used for statistical arbitrage, however, it can be used to improve upon algorithms.
In addition to what the literature cited on order book imbalances, I have also analyzed the order book imbalance calculated using up to 5 levels and found that the correlation of the imbalance measure with future price moves increases with the level (for the 5 levels assessed). From the expected values and its confidence intervals in Figure 9, however, we see that higher levels do only marginally improve the return direction and we observed that empirical probabilities are only slightly more discriminatory when working with higher levels of order book depths. Therefore, the added value from deeper levels (L>1) does probably not justify the higher complexity (handling deeper levels is typically more time consuming for high frequency algorithms).
Finally, we found the strongest relationship between imbalance and price movements to be within the shortest period (10 seconds) available in the data. Therefore, I conclude that looking into tick data could reveal more insights, as opposed to the 10 second period length examined in this article.
Cartea, A., R. Donnelly, and S. Jaimungal (2018). Enhancing trading strategies with order book signals. Applied Mathematical Finance 25 (1), 1-35.
Cartea, u0013A., S. Jaimungal, and J. Penalva (2015). Algorithmic and high-frequency trading. Cambridge University Press.
Cont, R., A. Kukanov, and S. Stoikov (2014). The price impact of order book events. Journal of financial econometrics 12 (1), 47-88.
Lipton, A., U. Pesavento, and M. G. Sotiropoulos (2013). Trade arrival dynamics and quote imbalance in a limit order book. arXiv preprint arXiv:1312.0514 .
Paolella, M. S. (2007). Intermediate probability: A computational approach. John Wiley & Sons.
Silantyev, E. (2018). Order-flow-analysis-of-cryptocurrency-markets. Medium.
Stoikov, S. (2017). The micro-price: A high frequency estimator of future prices. Available at SSRN 2970694 .
We are interested in the mean of the log-returns conditional on being in a given regime. We construct confidence intervals that allow us to estimate probabilistic bounds for the expected mid-price return in a given regime. The method we present here is standard, see e.g., Paollela 2017.
By the central limit theorem, the sample mean
of i.i.d. random variables Xi are normal:
where Xi represent the i=1,...,n observations drawn from a distribution with mean μ and standard deviation σ, the arrow with superscript d denotes convergence in distribution and N(0,1) represents the standard normal distribution. We can express Equation A.2. informally as
that leads to the estimates of mean and variance
where s is the sample standard deviation. Now, the confidence interval for a level (1-α) is given by
z(α) represents the point on the x -axis of the standard normal density curve such that the probability of observing a value greater than z(α) or smaller than -z(α) is equal to α.
To apply this form of the central limit theorem, the mid-price returns have to be i.i.d.. The autocorrelation of mid-price returns are below 1% (see also A2) and there is no indication that they should stem from different distributions or have another dependency that is not reflected in the correlation, so we can assume the i.i.d. property holds and use Equation A.4.
import scipy.stats as stimport numpy as npdef estimate_confidence(shifted_return, vol_binned, volume_regime_num, alpha=0.1): """ Estimate confidence interval for given alpha :param shifted_return: array of returns for which we calculate the confidence interval of its mean, can contain NaN :type shifted_return: float array of length n :param vol_binned: volume regimes. Entry i corresponds to the volume regime associated with shifted_return[i] :type vol_binned: float array of length n :param volume_regime_num: equals np.max(vol_binned)+1 :type volume_regime_num: int :return: confidence intervals for mean of the returns per regime :rtype: float array of size volume_regime_num x 2 """ confidence_interval = np.zeros((volume_regime_num, 2)) z = st.norm.ppf(1-alpha) for regime_num in range(0, volume_regime_num): m = np.nanmean(shifted_return[vol_binned == regime_num]) s = np.nanstd(shifted_return[vol_binned == regime_num]) sqrt_n = np.sqrt(np.sum(vol_binned == regime_num)) confidence_interval[regime_num, :] = [m - z * s/sqrt_n, m + z * s/sqrt_n] return confidence_interval
The Python code-snippet below calculates autocorrelations and plots. The calculation accounts for (hard-coded) gaps in the time-series that are greater than 11 seconds.
import numpy as npfrom datetime import datetimeimport plotly.express as pxdef shift_array(v, num_shift): ''' Shift array left (num_shift<0) or right num_shift>0 :param v: float array to be shifted :type v: array 1d :param num_shift: number of shifts :type num_shift: int :return: float array of same length as original array, shifted by num_shifts elements, np.nan entries at boundaries :rtype: array ''' v_shift = np.roll(v, num_shift) if num_shift > 0: v_shift[:num_shift] = np.nan else: v_shift[num_shift:] = np.nan return v_shiftdef plot_acf(v, max_lag, timestamp): ''' Create figure to plot autocorrelation function :param max_lag: when to stop the autocorrelation calculations (up to max_lag lags) :param timestamp: timestamp array of length n with entry i corresponding to timestamp of entry i in v, used to remove time-jumps v: array with n observation :return: plotly-figure ''' corr_vec = np.zeros(max_lag, dtype=float) for k in range(max_lag): v_lag = shift_array(v, -k-1) timestamp_lag = shift_array(timestamp, -k-1) dT = (timestamp - timestamp_lag) / (k+1) msk_time_gap = dT > 11000.0 mask = ~np.isnan(v) & ~np.isnan(v_lag) & ~msk_time_gap corr_vec[k] = np.corrcoef(v[mask], v_lag[mask])[0, 1] fig_acf = px.bar(x=range(1, max_lag+1), y=corr_vec) fig_acf.update_layout(yaxis_range=[0, 1]) fig_acf.update_xaxes(title="Lag") fig_acf.update_yaxes(title="ACF") return fig_acf
Figures A1 and A2 show the empirical probabilities of a mid-price up move/down move conditional on observing a non-zero return. Level 5 imbalances show a better discriminatory power, that is, in regimes 0 and 5 the probabilities are more extreme than at level 1.
If the mid-price moves, the imbalance with L=5 is a better indicator of the price direction than the imbalance of L=1.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. | [
{
"code": null,
"e": 637,
"s": 171,
"text": "We investigate whether imbalanced order books lead to price changes towards the thinner side of the book. That is, by this hypothesis prices decrease when limit order books have large volumes posted at the ask side relative to the bid side, and if order books are more heavy on the bid side then prices increase. We test this hypothesis and assess whether order book imbalance information can be exploited to profitably predict price movements in the ETHUSD market."
},
{
"code": null,
"e": 730,
"s": 637,
"text": "We follow the literature, e.g., Cartea et al. (2015), and define the order book imbalance as"
},
{
"code": null,
"e": 987,
"s": 730,
"text": "where t indexes the time, V stands for volume at either the bid (superscript b) or ask (superscript a), and L is the depth level of the order book considered to calculate ρ. Figure 1 shows an example how to calculate the imbalance ρ for a given order book."
},
{
"code": null,
"e": 1488,
"s": 987,
"text": "A ρ-value close to -1 is obtained when market makers post a large volume at the ask relative to the bid volume. A ρ-value close to 1 means there is a large volume at the bid side of the order book relative to the ask side. With an imbalance of zero the order book is perfectly balanced at the given level L. The hypothesis suggests that low imbalance numbers (<0) imply negative returns, high imbalance numbers (>0) imply positive returns, i.e., the price moves into the direction of the imbalance ρ."
},
{
"code": null,
"e": 2386,
"s": 1488,
"text": "Cont et al. (2014) use US stock data to show that there is a price impact of order flow imbalance and a linear relationship between “order flow imbalance” and price changes. The authors define order flow imbalance as the imbalance between supply and demand, measured by aggregating incoming orders over a given period. Their linear model has an R2 of around 70%. The study considers the past order flows (that result in an imbalance measure) and compares it to the price change over the same period. Hence, the conclusion is not that order flow imbalances predict future prices, but rather that the order flow imbalances computed over a historic period explains the price change over the same period. So this study reveals no direct insights on current order flow imbalances on future prices. Silantyev (2018) confirms the finding of this study using BTC-USD order book data in his Medium article."
},
{
"code": null,
"e": 2738,
"s": 2386,
"text": "Lipton et al. (2013), us the imbalance measure ρ with L=1 and find that the price change until the next tick can be well approximated by a linear function of the order book imbalance but note that (1) the change is well below the bid-ask spread, and (2) the method “does not by itself offer an opportunity for a straightforward statistical arbitrage”."
},
{
"code": null,
"e": 2968,
"s": 2738,
"text": "Cartea et al. (2018) find that a higher order book imbalance measured by ρ is followed by an increased amount of market orders and that the imbalance helps to predict price changes immediately after the arrival of a market order."
},
{
"code": null,
"e": 3141,
"s": 2968,
"text": "In their book, Cartea et al. (2015) present for one particular stock that correlations of past imbalances and price changes are decent (about 25% for a 10-second interval)."
},
{
"code": null,
"e": 4082,
"s": 3141,
"text": "Stoikov (2017) defines a mid-price adjustment that incorporatesorder book imbalances and bid-ask spreads. He finds that the resultingprice (mid-price plus adjustment) is a better predictor for short-term movements of mid-prices than mid-prices and volume-weighted mid-prices. In this study, the order book imbalance slightly differs from ours, specifically Equation (1) would be adjusted by removing the ask volume from the nominator and fixing the level L to 1. The method estimates the expectation of the future mid-price conditional on current information and is horizon independent. Empirically horizons for which the forecasts are most accurate range from 3 to 10 seconds for the stocks assessed. The adjusted mid-price lives between the bid and the ask for the data presented which indicates that the method by itself does not present a method for statistical arbitrage, but as the author notes can be used to improve upon algorithms."
},
{
"code": null,
"e": 4387,
"s": 4082,
"text": "These studies consider tick-level data at the best bid-ask price (L=1),we look at longer horizons and delve into a depth of 5 to calculate the orderimbalance. The data in these studies uses stock market data, with thenotable exception of Silantyev (2018), whereas we look into cryptocurrency order books."
},
{
"code": null,
"e": 5151,
"s": 4387,
"text": "Order book data can be queried via public API from crypto-exchanges. Historical data other than candle data is not generally available. Hence I collected order book data for ETHUSD from Coinbase in 10 second intervals up to a depth of 5 levels from May to December 2019 (2019–05–21 01:46:37 to 2019–12–18 18:40:59). This amounts to 1,920,617 observations. There are some gaps in the data, e.g., due to system downtimes, which we account for in our analysis. We count 592 gaps where the timestamp difference between two subsequent order book observations is larger than 11 seconds. The timestamp between two order books is not exactly 10 seconds in the data since I collected the data using repeated REST requests, rather than, e.g., a continuous Websocket stream."
},
{
"code": null,
"e": 5316,
"s": 5151,
"text": "Before looking at the relationship between price changes and the order book imbalance, we look at the distribution of the imbalance for different order book levels."
},
{
"code": null,
"e": 5463,
"s": 5316,
"text": "We calculate the order book imbalance ρ for all observations and the 5 different levels according to Equation 1 and find the following properties."
},
{
"code": null,
"e": 5714,
"s": 5463,
"text": "At L=1 the imbalances are often very pronounced or not existent at all. The higher L, the more frequent are balanced order books (i.e., more observations for ρ≈0).The imbalance is autocorrelated. The deeper the level L, the higher the autocorrelation"
},
{
"code": null,
"e": 5878,
"s": 5714,
"text": "At L=1 the imbalances are often very pronounced or not existent at all. The higher L, the more frequent are balanced order books (i.e., more observations for ρ≈0)."
},
{
"code": null,
"e": 5966,
"s": 5878,
"text": "The imbalance is autocorrelated. The deeper the level L, the higher the autocorrelation"
},
{
"code": null,
"e": 6042,
"s": 5966,
"text": "We present the first finding in Figures 2 and 3 and the second in Figure 4."
},
{
"code": null,
"e": 6227,
"s": 6042,
"text": "Figure 2 shows a histogram of order book imbalances for level 1. We observe that at this level, the order book is mostly balanced (close to 0), or highly imbalanced (close to -1 or 1)."
},
{
"code": null,
"e": 6352,
"s": 6227,
"text": "As we increase the order book depth to calculate the imbalance, the order books become more balanced, as we see in Figure 3."
},
{
"code": null,
"e": 6616,
"s": 6352,
"text": "Figure 4 shows the autocorrelation function (ACF). Consistent with Cuartea et al. (2015) we find that imbalances are highly autocorrelated. The correlation for a given lag tends to be higher, the larger the order book depth L for the calculation of the imbalance."
},
{
"code": null,
"e": 6764,
"s": 6616,
"text": "We now investigate the correlation of ρ and future mid-prices. Mid-prices are defined as the average of highest bid price and the lowest ask price."
},
{
"code": null,
"e": 7104,
"s": 6764,
"text": "We first calculate the p-period ahead log-return of the mid-price for each observation of order book imbalance. We then calculate the correlation between these returns and the order imbalances observed at the beginning of the period. We remove observations where the p-periods are on average longer than 11 seconds (1 period ≈ 10 seconds)."
},
{
"code": null,
"e": 7261,
"s": 7104,
"text": "Figure 5 and 6 show the correlations of future returns and imbalances as a function of the period over which the return is measured. We conclude as follows."
},
{
"code": null,
"e": 7952,
"s": 7261,
"text": "The correlations are low. E.g., Cont et al. (2014) report an R2 of about 70% between the price-impact and their measure of order flow imbalance over the same period. For a linear univariate regression model this R2 implies a correlation of sqrt(0.70)=0.84. However, the authors measure the price increase over the same period as the order flow imbalance, hence this method does not offer price forecastsThe imbalance measure ρ is more predictive for prices closer to the imbalance observation (the correlation decreases as p increases)The higher the depth level L of the order book considered to calculate the imbalance, the more the imbalance measure correlates with future price movements"
},
{
"code": null,
"e": 8356,
"s": 7952,
"text": "The correlations are low. E.g., Cont et al. (2014) report an R2 of about 70% between the price-impact and their measure of order flow imbalance over the same period. For a linear univariate regression model this R2 implies a correlation of sqrt(0.70)=0.84. However, the authors measure the price increase over the same period as the order flow imbalance, hence this method does not offer price forecasts"
},
{
"code": null,
"e": 8489,
"s": 8356,
"text": "The imbalance measure ρ is more predictive for prices closer to the imbalance observation (the correlation decreases as p increases)"
},
{
"code": null,
"e": 8645,
"s": 8489,
"text": "The higher the depth level L of the order book considered to calculate the imbalance, the more the imbalance measure correlates with future price movements"
},
{
"code": null,
"e": 8805,
"s": 8645,
"text": "The corresponding plots for depths L=2 to 4 which I don’t show for brevity are consistent with these findings. For Python code for these plots see Appendix A2."
},
{
"code": null,
"e": 9106,
"s": 8805,
"text": "The correlations presented above showed that imbalances calculated with higher L correlates better with price increases than imbalances calculated with lower L. More near-term prices have a higher correlation with ρ. Based on this we continue the analysis with only one-period ahead forecasts (≈10s)."
},
{
"code": null,
"e": 9192,
"s": 9106,
"text": "Correlation is an average measure, what about the uncertainty of the mid-price moves?"
},
{
"code": null,
"e": 9859,
"s": 9192,
"text": "Figure 7 and 8 plot the 1-period log-return against the imbalance observed at the beginning of the period for L=1 and L=5 respectively. The level 1 imbalance plot (Figure 7) looks as if there was a higher variation of log-returns when the imbalance is large (close to -1 or close to 1) or 0, which we don’t observe for level 5 imbalances (Figure 8). However, this seemingly larger variation in the plot stems from the fact that we have more observations for L=1 at the boundaries and at zero (seen in the histograms in Figures 2 and 3) — calculating the standard deviation of returns does not confirm higher variances at the extremes as we see in the next paragraph."
},
{
"code": null,
"e": 9986,
"s": 9859,
"text": "We follow Cartea et al. (2018) and bucket our imbalance measure into five regimes chosen to be equally spaced along the points"
},
{
"code": null,
"e": 10021,
"s": 9986,
"text": "θ = {-1, -0.6, -0.2, 0.2, 0.6, 1}."
},
{
"code": null,
"e": 10207,
"s": 10021,
"text": "That is, regime 0 has price imbalances between -1 and -0.6, regime 1 from -0.6 to -0.2 and so on. Table 1 shows the standard deviation of 1-period ahead price returns for all 5 regimes."
},
{
"code": null,
"e": 10399,
"s": 10207,
"text": "Table 1 addresses the question from the previous paragraph: the mid-price variance at extreme imbalances (regime 0 and regime 4) is not higher for order book depth level L=1 than for level 5."
},
{
"code": null,
"e": 10611,
"s": 10399,
"text": "Now we take this analysis further and estimate probabilistic bounds for the expected mid-price return in a given regime by constructing confidence intervals. I provide details on this calculation in Appendix A1."
},
{
"code": null,
"e": 11369,
"s": 10611,
"text": "Figure 9 presents confidence intervals for the expected mid-price return in a given regime. We can see that indeed the returns are on average negative for low imbalance numbers (regime 0 and 1) and positive for high imbalance numbers (regime 3 and 4). The means move more into the order imbalance direction when the imbalance is constructed with a higher level, e.g., in regime 4 the mean of the 1-period ahead return when the imbalance is calculated with L=1 (dark line) is smaller than when performing the calculations at a depth of level L=5 (bright line). Note that the confidence intervals shown reflect the uncertainty in the expected value. The standard deviations of Table 1 inform us about the uncertainty of the returns around this expected value."
},
{
"code": null,
"e": 11604,
"s": 11369,
"text": "This analysis confirms the findings from the correlation analysis: there is positive but weak correlation between imbalances and 1-period ahead returns, and the deeper level (L) results in a slightly more predictive imbalance measure."
},
{
"code": null,
"e": 11735,
"s": 11604,
"text": "What is the probability that the next period mid-price will go up, stay flat, or go down knowing in which imbalance regime we are?"
},
{
"code": null,
"e": 12001,
"s": 11735,
"text": "To see this, we bucket every order imbalance into a regime 0-4 and then count the number of negative returns, zero returns, and positive 1-period returns and divide the count by the number of observation to have an estimate for the probabilities of mid-price moves."
},
{
"code": null,
"e": 12153,
"s": 12001,
"text": "Figures 10 and 11 present the empirical probabilities for imbalances computed for L=1 and L=5 respectively. The figures confirm our initial hypothesis:"
},
{
"code": null,
"e": 12274,
"s": 12153,
"text": "There is a higher probability of mid-price decreases in regimes with low values of order book imbalance, and vice versa."
},
{
"code": null,
"e": 12550,
"s": 12274,
"text": "We see qualitatively no difference in the empirical probabilities when calculating the imbalances with only 1 level (Figure 10) or 5 levels (Figure 11). We observe that the probabilities for higher levels L=5 are more discriminatory than for L=1, which is a desired property."
},
{
"code": null,
"e": 12758,
"s": 12550,
"text": "In Appendix A3 we also show the probabilities conditional on observing a non-zero price move. We find that if the price moves, the level 5 imbalance is a slightly better predictor than the level 1 imbalance."
},
{
"code": null,
"e": 13199,
"s": 12758,
"text": "Many crypto exchanges have trading fees in the order of 10bps (and we would execute 2 trades). We see from the confidence intervals (Figure 9) that mid-price returns are below 10 basis points for the 10 second periods considered. So from judging by the expected return without considering variances, we can conclude that order imbalances do not directly imply a profitable strategy on its own without even investigating the bid-ask spreads."
},
{
"code": null,
"e": 13724,
"s": 13199,
"text": "To affirm this finding, we look at profitability from another angle and calculate the empirical probabilities of price moves larger than 10 basis points, similar to figures 10 and 11. That is, we count all movements that are in absolute terms below 10 basis points as flat. Table 3 shows that for imbalance calculations with order book levels of both 1 and 5, most trades would end up below an absolute return of 10 basis points in all regimes. This confirms the strategy does not allow for statistical arbitrage on its own."
},
{
"code": null,
"e": 13878,
"s": 13724,
"text": "Our analysis for ETHUSD order books and mid-price movements is consistent with the findings in the literature on order book imbalances for stock markets:"
},
{
"code": null,
"e": 14107,
"s": 13878,
"text": "When the imbalance is close to -1 there is a selling pressure and the mid-price is more likely to go down in the near term, when the imbalance is close to 1 there is a buying pressure and the mid-price is more likely to move up."
},
{
"code": null,
"e": 14212,
"s": 14107,
"text": "The price impact of the imbalance measure is short-lived and quickly deteriorates with the time horizon."
},
{
"code": null,
"e": 14344,
"s": 14212,
"text": "The imbalance measure itself cannot directly be used for statistical arbitrage, however, it can be used to improve upon algorithms."
},
{
"code": null,
"e": 15099,
"s": 14344,
"text": "In addition to what the literature cited on order book imbalances, I have also analyzed the order book imbalance calculated using up to 5 levels and found that the correlation of the imbalance measure with future price moves increases with the level (for the 5 levels assessed). From the expected values and its confidence intervals in Figure 9, however, we see that higher levels do only marginally improve the return direction and we observed that empirical probabilities are only slightly more discriminatory when working with higher levels of order book depths. Therefore, the added value from deeper levels (L>1) does probably not justify the higher complexity (handling deeper levels is typically more time consuming for high frequency algorithms)."
},
{
"code": null,
"e": 15397,
"s": 15099,
"text": "Finally, we found the strongest relationship between imbalance and price movements to be within the shortest period (10 seconds) available in the data. Therefore, I conclude that looking into tick data could reveal more insights, as opposed to the 10 second period length examined in this article."
},
{
"code": null,
"e": 15544,
"s": 15397,
"text": "Cartea, A., R. Donnelly, and S. Jaimungal (2018). Enhancing trading strategies with order book signals. Applied Mathematical Finance 25 (1), 1-35."
},
{
"code": null,
"e": 15666,
"s": 15544,
"text": "Cartea, u0013A., S. Jaimungal, and J. Penalva (2015). Algorithmic and high-frequency trading. Cambridge University Press."
},
{
"code": null,
"e": 15799,
"s": 15666,
"text": "Cont, R., A. Kukanov, and S. Stoikov (2014). The price impact of order book events. Journal of financial econometrics 12 (1), 47-88."
},
{
"code": null,
"e": 15955,
"s": 15799,
"text": "Lipton, A., U. Pesavento, and M. G. Sotiropoulos (2013). Trade arrival dynamics and quote imbalance in a limit order book. arXiv preprint arXiv:1312.0514 ."
},
{
"code": null,
"e": 16050,
"s": 15955,
"text": "Paolella, M. S. (2007). Intermediate probability: A computational approach. John Wiley & Sons."
},
{
"code": null,
"e": 16127,
"s": 16050,
"text": "Silantyev, E. (2018). Order-flow-analysis-of-cryptocurrency-markets. Medium."
},
{
"code": null,
"e": 16237,
"s": 16127,
"text": "Stoikov, S. (2017). The micro-price: A high frequency estimator of future prices. Available at SSRN 2970694 ."
},
{
"code": null,
"e": 16525,
"s": 16237,
"text": "We are interested in the mean of the log-returns conditional on being in a given regime. We construct confidence intervals that allow us to estimate probabilistic bounds for the expected mid-price return in a given regime. The method we present here is standard, see e.g., Paollela 2017."
},
{
"code": null,
"e": 16571,
"s": 16525,
"text": "By the central limit theorem, the sample mean"
},
{
"code": null,
"e": 16613,
"s": 16571,
"text": "of i.i.d. random variables Xi are normal:"
},
{
"code": null,
"e": 16887,
"s": 16613,
"text": "where Xi represent the i=1,...,n observations drawn from a distribution with mean μ and standard deviation σ, the arrow with superscript d denotes convergence in distribution and N(0,1) represents the standard normal distribution. We can express Equation A.2. informally as"
},
{
"code": null,
"e": 16936,
"s": 16887,
"text": "that leads to the estimates of mean and variance"
},
{
"code": null,
"e": 17037,
"s": 16936,
"text": "where s is the sample standard deviation. Now, the confidence interval for a level (1-α) is given by"
},
{
"code": null,
"e": 17217,
"s": 17037,
"text": "z(α) represents the point on the x -axis of the standard normal density curve such that the probability of observing a value greater than z(α) or smaller than -z(α) is equal to α."
},
{
"code": null,
"e": 17587,
"s": 17217,
"text": "To apply this form of the central limit theorem, the mid-price returns have to be i.i.d.. The autocorrelation of mid-price returns are below 1% (see also A2) and there is no indication that they should stem from different distributions or have another dependency that is not reflected in the correlation, so we can assume the i.i.d. property holds and use Equation A.4."
},
{
"code": null,
"e": 18979,
"s": 17587,
"text": "import scipy.stats as stimport numpy as npdef estimate_confidence(shifted_return, vol_binned, volume_regime_num, alpha=0.1): \"\"\" Estimate confidence interval for given alpha :param shifted_return: array of returns for which we calculate the confidence interval of its mean, can contain NaN :type shifted_return: float array of length n :param vol_binned: volume regimes. Entry i corresponds to the volume regime associated with shifted_return[i] :type vol_binned: float array of length n :param volume_regime_num: equals np.max(vol_binned)+1 :type volume_regime_num: int :return: confidence intervals for mean of the returns per regime :rtype: float array of size volume_regime_num x 2 \"\"\" confidence_interval = np.zeros((volume_regime_num, 2)) z = st.norm.ppf(1-alpha) for regime_num in range(0, volume_regime_num): m = np.nanmean(shifted_return[vol_binned == regime_num]) s = np.nanstd(shifted_return[vol_binned == regime_num]) sqrt_n = np.sqrt(np.sum(vol_binned == regime_num)) confidence_interval[regime_num, :] = [m - z * s/sqrt_n, m + z * s/sqrt_n] return confidence_interval"
},
{
"code": null,
"e": 19148,
"s": 18979,
"text": "The Python code-snippet below calculates autocorrelations and plots. The calculation accounts for (hard-coded) gaps in the time-series that are greater than 11 seconds."
},
{
"code": null,
"e": 20734,
"s": 19148,
"text": "import numpy as npfrom datetime import datetimeimport plotly.express as pxdef shift_array(v, num_shift): ''' Shift array left (num_shift<0) or right num_shift>0 :param v: float array to be shifted :type v: array 1d :param num_shift: number of shifts :type num_shift: int :return: float array of same length as original array, shifted by num_shifts elements, np.nan entries at boundaries :rtype: array ''' v_shift = np.roll(v, num_shift) if num_shift > 0: v_shift[:num_shift] = np.nan else: v_shift[num_shift:] = np.nan return v_shiftdef plot_acf(v, max_lag, timestamp): ''' Create figure to plot autocorrelation function :param max_lag: when to stop the autocorrelation calculations (up to max_lag lags) :param timestamp: timestamp array of length n with entry i corresponding to timestamp of entry i in v, used to remove time-jumps v: array with n observation :return: plotly-figure ''' corr_vec = np.zeros(max_lag, dtype=float) for k in range(max_lag): v_lag = shift_array(v, -k-1) timestamp_lag = shift_array(timestamp, -k-1) dT = (timestamp - timestamp_lag) / (k+1) msk_time_gap = dT > 11000.0 mask = ~np.isnan(v) & ~np.isnan(v_lag) & ~msk_time_gap corr_vec[k] = np.corrcoef(v[mask], v_lag[mask])[0, 1] fig_acf = px.bar(x=range(1, max_lag+1), y=corr_vec) fig_acf.update_layout(yaxis_range=[0, 1]) fig_acf.update_xaxes(title=\"Lag\") fig_acf.update_yaxes(title=\"ACF\") return fig_acf"
},
{
"code": null,
"e": 20997,
"s": 20734,
"text": "Figures A1 and A2 show the empirical probabilities of a mid-price up move/down move conditional on observing a non-zero return. Level 5 imbalances show a better discriminatory power, that is, in regimes 0 and 5 the probabilities are more extreme than at level 1."
},
{
"code": null,
"e": 21116,
"s": 20997,
"text": "If the mid-price moves, the imbalance with L=5 is a better indicator of the price direction than the imbalance of L=1."
}
] |
Java 16 - Sealed Classes | Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Java 16 provides some minor enhancements and keep this feature as Preview. Following are salient points to consider for a sealed class −
Sealed class is declared using sealed keyword.
Sealed class is declared using sealed keyword.
Sealed classes allow to declare which class can be a subtype using permits keyword.
Sealed classes allow to declare which class can be a subtype using permits keyword.
A class extending sealed class must be declared as either sealed, non-sealed or final.
A class extending sealed class must be declared as either sealed, non-sealed or final.
Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
Consider the following example −
ApiTester.java
public class APITester {
public static void main(String[] args) {
Person manager = new Manager(23, "Robert");
manager.name = "Robert";
System.out.println(getId(manager));
}
public static int getId(Person person) {
if (person instanceof Employee) {
return ((Employee) person).getEmployeeId();
}
else if (person instanceof Manager) {
return ((Manager) person).getManagerId();
}
return -1;
}
}
abstract sealed class Person permits Employee, Manager {
String name;
String getName() {
return name;
}
}
final class Employee extends Person {
String name;
int id;
Employee(int id, String name){
this.id = id;
this.name = name;
}
int getEmployeeId() {
return id;
}
}
non-sealed class Manager extends Person {
int id;
Manager(int id, String name){
this.id = id;
this.name = name;
}
int getManagerId() {
return id;
}
}
$javac -Xlint:preview --enable-preview -source 16 APITester.java
$java --enable-preview APITester
23
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": 2338,
"s": 2090,
"text": "Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Java 16 provides some minor enhancements and keep this feature as Preview. Following are salient points to consider for a sealed class −"
},
{
"code": null,
"e": 2385,
"s": 2338,
"text": "Sealed class is declared using sealed keyword."
},
{
"code": null,
"e": 2432,
"s": 2385,
"text": "Sealed class is declared using sealed keyword."
},
{
"code": null,
"e": 2516,
"s": 2432,
"text": "Sealed classes allow to declare which class can be a subtype using permits keyword."
},
{
"code": null,
"e": 2600,
"s": 2516,
"text": "Sealed classes allow to declare which class can be a subtype using permits keyword."
},
{
"code": null,
"e": 2687,
"s": 2600,
"text": "A class extending sealed class must be declared as either sealed, non-sealed or final."
},
{
"code": null,
"e": 2774,
"s": 2687,
"text": "A class extending sealed class must be declared as either sealed, non-sealed or final."
},
{
"code": null,
"e": 2869,
"s": 2774,
"text": "Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance."
},
{
"code": null,
"e": 2964,
"s": 2869,
"text": "Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance."
},
{
"code": null,
"e": 2997,
"s": 2964,
"text": "Consider the following example −"
},
{
"code": null,
"e": 3012,
"s": 2997,
"text": "ApiTester.java"
},
{
"code": null,
"e": 3983,
"s": 3012,
"text": "public class APITester {\n public static void main(String[] args) {\n Person manager = new Manager(23, \"Robert\");\n manager.name = \"Robert\";\n System.out.println(getId(manager));\n }\n public static int getId(Person person) {\n if (person instanceof Employee) {\n return ((Employee) person).getEmployeeId();\n } \n else if (person instanceof Manager) {\n return ((Manager) person).getManagerId();\n }\n return -1;\n }\n}\nabstract sealed class Person permits Employee, Manager {\n String name;\n String getName() {\n return name;\n }\n}\nfinal class Employee extends Person {\n String name;\n int id;\n Employee(int id, String name){\n this.id = id;\n this.name = name;\n }\n int getEmployeeId() {\n return id;\n }\n}\nnon-sealed class Manager extends Person {\n int id;\n Manager(int id, String name){\n this.id = id;\n this.name = name;\n }\n int getManagerId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 4082,
"s": 3983,
"text": "$javac -Xlint:preview --enable-preview -source 16 APITester.java\n$java --enable-preview APITester\n"
},
{
"code": null,
"e": 4086,
"s": 4082,
"text": "23\n"
},
{
"code": null,
"e": 4119,
"s": 4086,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4135,
"s": 4119,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4168,
"s": 4135,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4184,
"s": 4168,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4219,
"s": 4184,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4233,
"s": 4219,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4267,
"s": 4233,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4281,
"s": 4267,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4318,
"s": 4281,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4333,
"s": 4318,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4366,
"s": 4333,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4385,
"s": 4366,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4392,
"s": 4385,
"text": " Print"
},
{
"code": null,
"e": 4403,
"s": 4392,
"text": " Add Notes"
}
] |
15 Tips and Tricks to Use Jupyter Notebook More Efficiently | by Julia Kho | Towards Data Science | In the data science community, Jupyter notebook is a popular tool with strong adoption. This article is meant to share cool tips and tricks to help you become more efficient while utilizing Jupyter notebook. Learn how to execute terminal commands from Jupyter, speed up your notebook by hiding outputs, add additional functionality to your notebook, and more!
Knowing these shortcuts can help you save time. I’ve highlighted in yellow the ones that I commonly used and find to be very helpful. If you forget the shortcut, you can always go to Command Mode and press H to see the full list. Jupyter notebook also allows you to create your own shortcut if you want. Click on the Edit Shortcut button to design your own hot keys.
Jupyter notebook only shows one output at a time as shown below. In the example, only the last variable’s output is shown.
However, you can add this code below to show all outputs in the cell. Notice now that both variables are shown.
If you wanted to insert an image, you will have to first change the cell type from Code to Markdown. You can do this in the dropdown box at the top of the page, or go to Command Mode and press M. Once the cell is a Markdown, simply just drag and drop the picture into the cell.
Once you’ve dropped the image into the cell, some code should appear. Run the cell (Shift + Enter) to see the image.
Rather than leaving Jupyter notebook to execute shell commands, you can use the exclamation point (!) at the beginning of your command. For example, you can install a package.
!pip install matplotlib-venn
Magic commands are special commands that help with productivity.
You might be most familiar with this magic command below, which lets your plots render in the notebook itself.
%matplotlib inline
Here are some other useful magic commands:
%pwd #print the current working directory%cd #change working directory%ls #show contents in the current directory%load [insert Python filename here] #load code into the Jupyter notebook%store [insert variable here] #this lets you pass variables between Jupyter Notebooks%who #use this to list all variables
For %who, you can specify the variable type as well. For example, the code below will list variables of all int type.
%who int
For the full list of magic commands:
%lsmagic #show all magic commands
Use %%time to get the wall time for your whole cell.
Let’s say you have multiple lines of code like below and you want to delete all the numbers in each line of the code. Rather than deleting each digit line by line, you can do it all at once!
Hold down the Alt key and select the entire cell content. Press the left arrow and you will see that there are now multiple cursors (black line in snippet below), one on each line. From here, you can then delete all the digits in one click of the delete key. Use the right arrow key if you want to move the cursor to the end.
If you have code that will take a while to run, you can add code to have Python tell you when it has finished running.
import winsoundduration = 1000 #millisecondsfreq = 440 #Hzwinsound.Beep(freq, duration)
This will sound an alarm when the code has completed.
import osos.system('say "your program has finished"')
Source: https://stackoverflow.com/questions/16573051/sound-alarm-when-code-finishes/16573339#16573339
Jupyter notebook extensions are neat tools to provide you with even more functionality.
Below is a list of configurable extensions you can enable. Some of the useful ones for me are collapsible headings, codefolding, scratchpad and spellchecker.
I recommend checking out the extensions and finding what’s useful for your work.
For help installing Jupyter Notebook Extensions to your computer, check out this link. https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html#
If you forget the parameters for a particular method, use Shift + Tab to get the documentation for that method. Click on the + arrow on the top right to expand the documentation.
There are a limited number of rows and columns that are shown in a pandas table, but you can customize the limit to your liking.
Here, I’ve set the max output of rows and columns to 500.
import pandas as pdpd.set_option('display.max_rows', 500)pd.set_option('display.max_columns', 500)
To make the important pieces of your outputs stand out, you can add bold font and/or color. I haven’t tried this one yet, but I thought it was a really cool trick provided by Stas Bekman. See snippet below.
Do you find your Jupyter Notebook lagging? That might possibly be because you have a lot of graphs that are being rendered.
Hover on the area to the left of your chart (see red rectangle below) and double click on the area to hide the output. This should speed up your notebook tremendously!
When you create a plot, you might get see this text "<matplotlib.collections.PathCollection at 0x9fae910>" right above the chart (highlighted yellow below).
I personally find that annoying, so to hide that line of text, you can add a semicolon to the end of the code.
With the markdown cells, it is easy to document your work. You can create a font hierarchy to organize your notebook by using the ‘#’ symbol as shown below.
Once the above is executed, this is what the font hierarchy looks like.
If you create these different headings and combine it with the collapsible headings Extension mentioned in Tip #9, it’s super useful to hide a large chunk of cells as well as being able to quickly navigate and move sections around.
Thanks for reading! If you have any favorite tip and tricks not listed in the article, I’d love to hear them in the comments.
Matplotlib Guide For People In A Hurry
Pandas for People In A Hurry
Numpy Guide for People In a Hurry
If you would like to download the Jupyter Notebook, you can find it here. | [
{
"code": null,
"e": 532,
"s": 172,
"text": "In the data science community, Jupyter notebook is a popular tool with strong adoption. This article is meant to share cool tips and tricks to help you become more efficient while utilizing Jupyter notebook. Learn how to execute terminal commands from Jupyter, speed up your notebook by hiding outputs, add additional functionality to your notebook, and more!"
},
{
"code": null,
"e": 899,
"s": 532,
"text": "Knowing these shortcuts can help you save time. I’ve highlighted in yellow the ones that I commonly used and find to be very helpful. If you forget the shortcut, you can always go to Command Mode and press H to see the full list. Jupyter notebook also allows you to create your own shortcut if you want. Click on the Edit Shortcut button to design your own hot keys."
},
{
"code": null,
"e": 1022,
"s": 899,
"text": "Jupyter notebook only shows one output at a time as shown below. In the example, only the last variable’s output is shown."
},
{
"code": null,
"e": 1134,
"s": 1022,
"text": "However, you can add this code below to show all outputs in the cell. Notice now that both variables are shown."
},
{
"code": null,
"e": 1412,
"s": 1134,
"text": "If you wanted to insert an image, you will have to first change the cell type from Code to Markdown. You can do this in the dropdown box at the top of the page, or go to Command Mode and press M. Once the cell is a Markdown, simply just drag and drop the picture into the cell."
},
{
"code": null,
"e": 1529,
"s": 1412,
"text": "Once you’ve dropped the image into the cell, some code should appear. Run the cell (Shift + Enter) to see the image."
},
{
"code": null,
"e": 1705,
"s": 1529,
"text": "Rather than leaving Jupyter notebook to execute shell commands, you can use the exclamation point (!) at the beginning of your command. For example, you can install a package."
},
{
"code": null,
"e": 1734,
"s": 1705,
"text": "!pip install matplotlib-venn"
},
{
"code": null,
"e": 1799,
"s": 1734,
"text": "Magic commands are special commands that help with productivity."
},
{
"code": null,
"e": 1910,
"s": 1799,
"text": "You might be most familiar with this magic command below, which lets your plots render in the notebook itself."
},
{
"code": null,
"e": 1929,
"s": 1910,
"text": "%matplotlib inline"
},
{
"code": null,
"e": 1972,
"s": 1929,
"text": "Here are some other useful magic commands:"
},
{
"code": null,
"e": 2279,
"s": 1972,
"text": "%pwd #print the current working directory%cd #change working directory%ls #show contents in the current directory%load [insert Python filename here] #load code into the Jupyter notebook%store [insert variable here] #this lets you pass variables between Jupyter Notebooks%who #use this to list all variables"
},
{
"code": null,
"e": 2397,
"s": 2279,
"text": "For %who, you can specify the variable type as well. For example, the code below will list variables of all int type."
},
{
"code": null,
"e": 2406,
"s": 2397,
"text": "%who int"
},
{
"code": null,
"e": 2443,
"s": 2406,
"text": "For the full list of magic commands:"
},
{
"code": null,
"e": 2477,
"s": 2443,
"text": "%lsmagic #show all magic commands"
},
{
"code": null,
"e": 2530,
"s": 2477,
"text": "Use %%time to get the wall time for your whole cell."
},
{
"code": null,
"e": 2721,
"s": 2530,
"text": "Let’s say you have multiple lines of code like below and you want to delete all the numbers in each line of the code. Rather than deleting each digit line by line, you can do it all at once!"
},
{
"code": null,
"e": 3047,
"s": 2721,
"text": "Hold down the Alt key and select the entire cell content. Press the left arrow and you will see that there are now multiple cursors (black line in snippet below), one on each line. From here, you can then delete all the digits in one click of the delete key. Use the right arrow key if you want to move the cursor to the end."
},
{
"code": null,
"e": 3166,
"s": 3047,
"text": "If you have code that will take a while to run, you can add code to have Python tell you when it has finished running."
},
{
"code": null,
"e": 3256,
"s": 3166,
"text": "import winsoundduration = 1000 #millisecondsfreq = 440 #Hzwinsound.Beep(freq, duration)"
},
{
"code": null,
"e": 3310,
"s": 3256,
"text": "This will sound an alarm when the code has completed."
},
{
"code": null,
"e": 3364,
"s": 3310,
"text": "import osos.system('say \"your program has finished\"')"
},
{
"code": null,
"e": 3466,
"s": 3364,
"text": "Source: https://stackoverflow.com/questions/16573051/sound-alarm-when-code-finishes/16573339#16573339"
},
{
"code": null,
"e": 3554,
"s": 3466,
"text": "Jupyter notebook extensions are neat tools to provide you with even more functionality."
},
{
"code": null,
"e": 3712,
"s": 3554,
"text": "Below is a list of configurable extensions you can enable. Some of the useful ones for me are collapsible headings, codefolding, scratchpad and spellchecker."
},
{
"code": null,
"e": 3793,
"s": 3712,
"text": "I recommend checking out the extensions and finding what’s useful for your work."
},
{
"code": null,
"e": 3956,
"s": 3793,
"text": "For help installing Jupyter Notebook Extensions to your computer, check out this link. https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html#"
},
{
"code": null,
"e": 4135,
"s": 3956,
"text": "If you forget the parameters for a particular method, use Shift + Tab to get the documentation for that method. Click on the + arrow on the top right to expand the documentation."
},
{
"code": null,
"e": 4264,
"s": 4135,
"text": "There are a limited number of rows and columns that are shown in a pandas table, but you can customize the limit to your liking."
},
{
"code": null,
"e": 4322,
"s": 4264,
"text": "Here, I’ve set the max output of rows and columns to 500."
},
{
"code": null,
"e": 4421,
"s": 4322,
"text": "import pandas as pdpd.set_option('display.max_rows', 500)pd.set_option('display.max_columns', 500)"
},
{
"code": null,
"e": 4628,
"s": 4421,
"text": "To make the important pieces of your outputs stand out, you can add bold font and/or color. I haven’t tried this one yet, but I thought it was a really cool trick provided by Stas Bekman. See snippet below."
},
{
"code": null,
"e": 4752,
"s": 4628,
"text": "Do you find your Jupyter Notebook lagging? That might possibly be because you have a lot of graphs that are being rendered."
},
{
"code": null,
"e": 4920,
"s": 4752,
"text": "Hover on the area to the left of your chart (see red rectangle below) and double click on the area to hide the output. This should speed up your notebook tremendously!"
},
{
"code": null,
"e": 5077,
"s": 4920,
"text": "When you create a plot, you might get see this text \"<matplotlib.collections.PathCollection at 0x9fae910>\" right above the chart (highlighted yellow below)."
},
{
"code": null,
"e": 5188,
"s": 5077,
"text": "I personally find that annoying, so to hide that line of text, you can add a semicolon to the end of the code."
},
{
"code": null,
"e": 5345,
"s": 5188,
"text": "With the markdown cells, it is easy to document your work. You can create a font hierarchy to organize your notebook by using the ‘#’ symbol as shown below."
},
{
"code": null,
"e": 5417,
"s": 5345,
"text": "Once the above is executed, this is what the font hierarchy looks like."
},
{
"code": null,
"e": 5649,
"s": 5417,
"text": "If you create these different headings and combine it with the collapsible headings Extension mentioned in Tip #9, it’s super useful to hide a large chunk of cells as well as being able to quickly navigate and move sections around."
},
{
"code": null,
"e": 5775,
"s": 5649,
"text": "Thanks for reading! If you have any favorite tip and tricks not listed in the article, I’d love to hear them in the comments."
},
{
"code": null,
"e": 5814,
"s": 5775,
"text": "Matplotlib Guide For People In A Hurry"
},
{
"code": null,
"e": 5843,
"s": 5814,
"text": "Pandas for People In A Hurry"
},
{
"code": null,
"e": 5877,
"s": 5843,
"text": "Numpy Guide for People In a Hurry"
}
] |
On/Off Toggle Button Switch in Tkinter | Tkinter provides features for adding different kinds of widgets necessary for an
application. Some of these widgets are: Button widget, Entry Widget, Text Box, Slider,
etc. In this article, we will see how we can create an application with a button such that it can either be on or off.
In this example, we will use these two buttons for demonstration,
Switch On
Switch On
Switch Off
Switch Off
# Import tkinter in the notebook
from tkinter import *
# Create an instance of window of frame
win =Tk()
# set Title
win.title('On/Off Demonstration')
# Set the Geometry
win.geometry("600x400")
win.resizable(0,0)
#Create a variable to turn on the button initially
is_on = True
# Create Label to display the message
label = Label(win,text = "Night Mode is On",bg= "white",fg ="black",font =("Poppins bold", 22))
label.pack(pady = 20)
# Define our switch function
def button_mode():
global is_on
#Determine it is on or off
if is_on:
on_.config(image=off)
label.config(text ="Day Mode is On",bg ="white", fg= "black")
is_on = False
else:
on_.config(image = on)
label.config(text ="Night Mode is On", fg="black")
is_on = True
# Define Our Images
on = PhotoImage(file ="on.png")
off = PhotoImage(file ="off.png")
# Create A Button
on_= Button(win,image =on,bd =0,command = button_mode)
on_.pack(pady = 50)
#Keep Running the window
win.mainloop()
Running the above code will create a Button to operate on/off mode.
If you click the button, it will change as follows − | [
{
"code": null,
"e": 1349,
"s": 1062,
"text": "Tkinter provides features for adding different kinds of widgets necessary for an\napplication. Some of these widgets are: Button widget, Entry Widget, Text Box, Slider,\netc. In this article, we will see how we can create an application with a button such that it can either be on or off."
},
{
"code": null,
"e": 1415,
"s": 1349,
"text": "In this example, we will use these two buttons for demonstration,"
},
{
"code": null,
"e": 1425,
"s": 1415,
"text": "Switch On"
},
{
"code": null,
"e": 1435,
"s": 1425,
"text": "Switch On"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": "Switch Off"
},
{
"code": null,
"e": 1457,
"s": 1446,
"text": "Switch Off"
},
{
"code": null,
"e": 2458,
"s": 1457,
"text": "# Import tkinter in the notebook\nfrom tkinter import *\n\n# Create an instance of window of frame\nwin =Tk()\n\n# set Title\nwin.title('On/Off Demonstration')\n\n# Set the Geometry\nwin.geometry(\"600x400\")\nwin.resizable(0,0)\n#Create a variable to turn on the button initially\nis_on = True\n\n# Create Label to display the message\nlabel = Label(win,text = \"Night Mode is On\",bg= \"white\",fg =\"black\",font =(\"Poppins bold\", 22))\nlabel.pack(pady = 20)\n\n# Define our switch function\ndef button_mode():\n global is_on\n \n #Determine it is on or off\n if is_on:\n on_.config(image=off)\n label.config(text =\"Day Mode is On\",bg =\"white\", fg= \"black\")\n is_on = False\n else:\n on_.config(image = on)\n label.config(text =\"Night Mode is On\", fg=\"black\")\n is_on = True\n\n# Define Our Images\non = PhotoImage(file =\"on.png\")\noff = PhotoImage(file =\"off.png\")\n\n# Create A Button\non_= Button(win,image =on,bd =0,command = button_mode)\non_.pack(pady = 50)\n\n#Keep Running the window\nwin.mainloop()"
},
{
"code": null,
"e": 2526,
"s": 2458,
"text": "Running the above code will create a Button to operate on/off mode."
},
{
"code": null,
"e": 2579,
"s": 2526,
"text": "If you click the button, it will change as follows −"
}
] |
Add week to current date using Calendar.add() method in Java | Import the following package for Calendar class in Java
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the weeks using the calendar.add() method and Calendar.WEEK_OF_YEAR constant.
calendar.add(Calendar.WEEK_OF_YEAR, 2);
The following is an example
Live Demo
import java.util.Calendar;
public class Demo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date = " + calendar.getTime());
// Adding 2 weeks
calendar.add(Calendar.WEEK_OF_YEAR, 2);
System.out.println("Updated Date = " + calendar.getTime());
}
}
Current Date = Thu Nov 22 18:13:38 UTC 2018
Updated Date = Thu Dec 06 18:13:38 UTC 2018 | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Import the following package for Calendar class in Java"
},
{
"code": null,
"e": 1145,
"s": 1118,
"text": "import java.util.Calendar;"
},
{
"code": null,
"e": 1217,
"s": 1145,
"text": "Firstly, create a Calendar object and display the current date and time"
},
{
"code": null,
"e": 1330,
"s": 1217,
"text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(\"Current Date and Time = \" + calendar.getTime());"
},
{
"code": null,
"e": 1430,
"s": 1330,
"text": "Now, let us increment the weeks using the calendar.add() method and Calendar.WEEK_OF_YEAR constant."
},
{
"code": null,
"e": 1470,
"s": 1430,
"text": "calendar.add(Calendar.WEEK_OF_YEAR, 2);"
},
{
"code": null,
"e": 1498,
"s": 1470,
"text": "The following is an example"
},
{
"code": null,
"e": 1509,
"s": 1498,
"text": " Live Demo"
},
{
"code": null,
"e": 1859,
"s": 1509,
"text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(\"Current Date = \" + calendar.getTime());\n // Adding 2 weeks\n calendar.add(Calendar.WEEK_OF_YEAR, 2);\n System.out.println(\"Updated Date = \" + calendar.getTime());\n }\n}"
},
{
"code": null,
"e": 1947,
"s": 1859,
"text": "Current Date = Thu Nov 22 18:13:38 UTC 2018\nUpdated Date = Thu Dec 06 18:13:38 UTC 2018"
}
] |
Generate Simulated Dataset for Linear Model in R | by Raden Aurelius Andhika Viadinugroho | Towards Data Science | In these recent years, research about Machine Learning (ML) has increased along with the increased computation capability. As a result, there is much development in some of the ML models — if not inventing a new model — that performs better than the traditional model.
One of the main problems that the researchers usually encountered when trying to implement the proposed model is the lack of the proper real-world dataset that follows the model’s assumptions. Or in the other case, the real-world dataset exists, but the dataset itself is very expensive and hard to collect.
To overcome those problems, the researchers usually generate a simulated dataset that follows the model’s assumptions. This simulated dataset can be used as a benchmark for the model or real-world dataset replacement in the modeling process, where the simulated dataset is cost-effective than the real-world dataset. This article will explain how to generate a simulated dataset for a linear model using R.
The process of generating a simulated dataset can be explained as follows. First, we specify the model that we want to simulate. Next, we determine each independent variable’s coefficient, then simulate the independent variable and error that follows a probability distribution. And finally, compute the dependent variable based on the simulated independent variable (and its predetermined coefficient) and error.
To understand more about this process in practice, here I will give some implementations of generating a simulated dataset for a linear model using R.
For the first example, suppose that we want to simulate the following linear regression model
where x_1 follows Normal distribution with mean 50 and variance 9, x_2 follows Normal distribution with mean 200 and variance 64, and the error follows Normal distribution with mean 0 and variance 16. Suppose too that b0, b1, and b2 are 150, -4, and 2.5, respectively. We can simulate it by writing these lines of code as follows (Note that the result might different with different seeds).
> summary(m1)Call:lm(formula = y1 ~ x1 + x2)Residuals: Min 1Q Median 3Q Max -41.782 -12.913 -0.179 10.802 53.316Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 154.23621 10.71954 14.39 <2e-16 ***x1 -3.98515 0.19636 -20.30 <2e-16 ***x2 2.47327 0.02714 91.14 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 17.96 on 97 degrees of freedomMultiple R-squared: 0.9885, Adjusted R-squared: 0.9883 F-statistic: 4179 on 2 and 97 DF, p-value: < 2.2e-16
From the model m1 , we can see that the model is significant (based on the p-value of the overall test) and every independent variable (x_1 and x_2) and the constant are significant (based on the p-value in each variable). We can see too that the estimated coefficients are pretty close to the predetermined value of each coefficient.
Now, for the second example, suppose that we want to simulate the following linear regression model
where x_1 and x_2 (and its coefficients), error, and b0 are the same as the first example, but x_3 is a binary categorical variable that follows Binomial distribution with probability of success (in R will be denoted as 1) is 0.7 and b3 is 5. Using the same seed as before, we can simulate it by writing these lines of code as follows.
> summary(m2)Call:lm(formula = y2 ~ x1 + x2 + x3)Residuals: Min 1Q Median 3Q Max -41.914 -12.804 -0.065 10.671 53.178Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 153.84275 11.32094 13.589 <2e-16 ***x1 -3.98432 0.19751 -20.173 <2e-16 ***x2 2.47330 0.02728 90.671 <2e-16 ***x3 5.46641 4.11890 1.327 0.188 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 18.05 on 96 degrees of freedomMultiple R-squared: 0.9885, Adjusted R-squared: 0.9882 F-statistic: 2758 on 3 and 96 DF, p-value: < 2.2e-16
From the model m2 , we can see that the model is significant, and every independent variable (except x_3) and the constant are significant (based on the p-value in each variable).
For the final example, suppose that we want to simulate the following count linear model (Poisson regression model, to be specific)
where x_1 follows Normal distribution with mean 2 and variance 1, x_2 follows Normal distribution with mean 1 and variance 1, and b0, b1, and b2 is 5, -4, and 2.5, respectively. The difference with the first two examples is, we need to calculate the logarithm of lambda first using the equation above, and exponentiate it to compute the dependent variable. We can simulate it by writing these lines of code as follows.
> summary(m3)Call:glm(formula = y3 ~ x1 + x2, family = poisson(link = "log"))Deviance Residuals: Min 1Q Median 3Q Max -1.99481 -0.58807 -0.14819 0.00079 2.08933Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 5.02212 0.03389 148.2 <2e-16 ***x1 -3.96326 0.02871 -138.0 <2e-16 ***x2 2.48380 0.02950 84.2 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 1)Null deviance: 90503.729 on 99 degrees of freedomResidual deviance: 69.329 on 97 degrees of freedomAIC: 283.21Number of Fisher Scoring iterations: 4
From the model m3 , we can see that the variables and the model constant are significant, and we can see that the estimated coefficients are pretty close too compared with the predetermined value of each coefficient.
And that’s it! You have learned how to generate a simulated dataset for the linear model in R. The examples in this article are just some of a simple implementation of how this simulated dataset generating process is conducted. In a real-world application, you can generate a more complex simulated dataset and use it for some linear models with interaction effects or some advanced ML models.
As usual, feel free to ask and/or discuss if you have any questions! See you in my next article!
LinkedIn: Raden Aurelius Andhika Viadinugroho
Medium: https://medium.com/@radenaurelius
[1] Ross, S. M. (2013). Simulation, 5th ed. Elsevier.
[2] https://bookdown.org/rdpeng/rprogdatascience/simulation.html#simulating-a-linear-model
[3] Baraldi, P., Mangili, F., and Zio, E. (2013). Investigation of uncertainty treatment capability of model-based and data-driven prognostic methods using simulated data. Reliability Engineering & System Safety, vol. 112, pp. 94–108.
[4] Ortiz-Barrios, M. A., Lundström, J., Synnott, J., Järpe, E., and Sant’Anna, A. (2020). Complementing real datasets with simulated data: a regression-based approach. Multimedia Tools and Applications, vol. 79, pp. 34301–34324. | [
{
"code": null,
"e": 316,
"s": 47,
"text": "In these recent years, research about Machine Learning (ML) has increased along with the increased computation capability. As a result, there is much development in some of the ML models — if not inventing a new model — that performs better than the traditional model."
},
{
"code": null,
"e": 624,
"s": 316,
"text": "One of the main problems that the researchers usually encountered when trying to implement the proposed model is the lack of the proper real-world dataset that follows the model’s assumptions. Or in the other case, the real-world dataset exists, but the dataset itself is very expensive and hard to collect."
},
{
"code": null,
"e": 1031,
"s": 624,
"text": "To overcome those problems, the researchers usually generate a simulated dataset that follows the model’s assumptions. This simulated dataset can be used as a benchmark for the model or real-world dataset replacement in the modeling process, where the simulated dataset is cost-effective than the real-world dataset. This article will explain how to generate a simulated dataset for a linear model using R."
},
{
"code": null,
"e": 1445,
"s": 1031,
"text": "The process of generating a simulated dataset can be explained as follows. First, we specify the model that we want to simulate. Next, we determine each independent variable’s coefficient, then simulate the independent variable and error that follows a probability distribution. And finally, compute the dependent variable based on the simulated independent variable (and its predetermined coefficient) and error."
},
{
"code": null,
"e": 1596,
"s": 1445,
"text": "To understand more about this process in practice, here I will give some implementations of generating a simulated dataset for a linear model using R."
},
{
"code": null,
"e": 1690,
"s": 1596,
"text": "For the first example, suppose that we want to simulate the following linear regression model"
},
{
"code": null,
"e": 2081,
"s": 1690,
"text": "where x_1 follows Normal distribution with mean 50 and variance 9, x_2 follows Normal distribution with mean 200 and variance 64, and the error follows Normal distribution with mean 0 and variance 16. Suppose too that b0, b1, and b2 are 150, -4, and 2.5, respectively. We can simulate it by writing these lines of code as follows (Note that the result might different with different seeds)."
},
{
"code": null,
"e": 2671,
"s": 2081,
"text": "> summary(m1)Call:lm(formula = y1 ~ x1 + x2)Residuals: Min 1Q Median 3Q Max -41.782 -12.913 -0.179 10.802 53.316Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 154.23621 10.71954 14.39 <2e-16 ***x1 -3.98515 0.19636 -20.30 <2e-16 ***x2 2.47327 0.02714 91.14 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 17.96 on 97 degrees of freedomMultiple R-squared: 0.9885, Adjusted R-squared: 0.9883 F-statistic: 4179 on 2 and 97 DF, p-value: < 2.2e-16"
},
{
"code": null,
"e": 3006,
"s": 2671,
"text": "From the model m1 , we can see that the model is significant (based on the p-value of the overall test) and every independent variable (x_1 and x_2) and the constant are significant (based on the p-value in each variable). We can see too that the estimated coefficients are pretty close to the predetermined value of each coefficient."
},
{
"code": null,
"e": 3106,
"s": 3006,
"text": "Now, for the second example, suppose that we want to simulate the following linear regression model"
},
{
"code": null,
"e": 3442,
"s": 3106,
"text": "where x_1 and x_2 (and its coefficients), error, and b0 are the same as the first example, but x_3 is a binary categorical variable that follows Binomial distribution with probability of success (in R will be denoted as 1) is 0.7 and b3 is 5. Using the same seed as before, we can simulate it by writing these lines of code as follows."
},
{
"code": null,
"e": 4090,
"s": 3442,
"text": "> summary(m2)Call:lm(formula = y2 ~ x1 + x2 + x3)Residuals: Min 1Q Median 3Q Max -41.914 -12.804 -0.065 10.671 53.178Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 153.84275 11.32094 13.589 <2e-16 ***x1 -3.98432 0.19751 -20.173 <2e-16 ***x2 2.47330 0.02728 90.671 <2e-16 ***x3 5.46641 4.11890 1.327 0.188 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 18.05 on 96 degrees of freedomMultiple R-squared: 0.9885, Adjusted R-squared: 0.9882 F-statistic: 2758 on 3 and 96 DF, p-value: < 2.2e-16"
},
{
"code": null,
"e": 4270,
"s": 4090,
"text": "From the model m2 , we can see that the model is significant, and every independent variable (except x_3) and the constant are significant (based on the p-value in each variable)."
},
{
"code": null,
"e": 4402,
"s": 4270,
"text": "For the final example, suppose that we want to simulate the following count linear model (Poisson regression model, to be specific)"
},
{
"code": null,
"e": 4821,
"s": 4402,
"text": "where x_1 follows Normal distribution with mean 2 and variance 1, x_2 follows Normal distribution with mean 1 and variance 1, and b0, b1, and b2 is 5, -4, and 2.5, respectively. The difference with the first two examples is, we need to calculate the logarithm of lambda first using the equation above, and exponentiate it to compute the dependent variable. We can simulate it by writing these lines of code as follows."
},
{
"code": null,
"e": 5513,
"s": 4821,
"text": "> summary(m3)Call:glm(formula = y3 ~ x1 + x2, family = poisson(link = \"log\"))Deviance Residuals: Min 1Q Median 3Q Max -1.99481 -0.58807 -0.14819 0.00079 2.08933Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 5.02212 0.03389 148.2 <2e-16 ***x1 -3.96326 0.02871 -138.0 <2e-16 ***x2 2.48380 0.02950 84.2 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 1)Null deviance: 90503.729 on 99 degrees of freedomResidual deviance: 69.329 on 97 degrees of freedomAIC: 283.21Number of Fisher Scoring iterations: 4"
},
{
"code": null,
"e": 5730,
"s": 5513,
"text": "From the model m3 , we can see that the variables and the model constant are significant, and we can see that the estimated coefficients are pretty close too compared with the predetermined value of each coefficient."
},
{
"code": null,
"e": 6124,
"s": 5730,
"text": "And that’s it! You have learned how to generate a simulated dataset for the linear model in R. The examples in this article are just some of a simple implementation of how this simulated dataset generating process is conducted. In a real-world application, you can generate a more complex simulated dataset and use it for some linear models with interaction effects or some advanced ML models."
},
{
"code": null,
"e": 6221,
"s": 6124,
"text": "As usual, feel free to ask and/or discuss if you have any questions! See you in my next article!"
},
{
"code": null,
"e": 6267,
"s": 6221,
"text": "LinkedIn: Raden Aurelius Andhika Viadinugroho"
},
{
"code": null,
"e": 6309,
"s": 6267,
"text": "Medium: https://medium.com/@radenaurelius"
},
{
"code": null,
"e": 6363,
"s": 6309,
"text": "[1] Ross, S. M. (2013). Simulation, 5th ed. Elsevier."
},
{
"code": null,
"e": 6454,
"s": 6363,
"text": "[2] https://bookdown.org/rdpeng/rprogdatascience/simulation.html#simulating-a-linear-model"
},
{
"code": null,
"e": 6689,
"s": 6454,
"text": "[3] Baraldi, P., Mangili, F., and Zio, E. (2013). Investigation of uncertainty treatment capability of model-based and data-driven prognostic methods using simulated data. Reliability Engineering & System Safety, vol. 112, pp. 94–108."
}
] |
How to make two histograms have the same bin width in Matplotlib? | To make two histograms having same bin width, we can compute the histogram of a set of data.
Create random data, a, and normal distribution, b.
Create random data, a, and normal distribution, b.
Initialize a variable, bins, for the same bin width.
Initialize a variable, bins, for the same bin width.
Plot a and bins using hist() method.
Plot a and bins using hist() method.
Plot b and bins using hist() method.
Plot b and bins using hist() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
a = np.random.random(100) * 0.5
b = 1 - np.random.normal(size=100) * 0.1
bins = 10
bins = np.histogram(np.hstack((a, b)), bins=bins)[1]
plt.hist(a, bins, edgecolor='black')
plt.hist(b, bins, edgecolor='black')
plt.show() | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To make two histograms having same bin width, we can compute the histogram of a set of data."
},
{
"code": null,
"e": 1206,
"s": 1155,
"text": "Create random data, a, and normal distribution, b."
},
{
"code": null,
"e": 1257,
"s": 1206,
"text": "Create random data, a, and normal distribution, b."
},
{
"code": null,
"e": 1310,
"s": 1257,
"text": "Initialize a variable, bins, for the same bin width."
},
{
"code": null,
"e": 1363,
"s": 1310,
"text": "Initialize a variable, bins, for the same bin width."
},
{
"code": null,
"e": 1400,
"s": 1363,
"text": "Plot a and bins using hist() method."
},
{
"code": null,
"e": 1437,
"s": 1400,
"text": "Plot a and bins using hist() method."
},
{
"code": null,
"e": 1474,
"s": 1437,
"text": "Plot b and bins using hist() method."
},
{
"code": null,
"e": 1511,
"s": 1474,
"text": "Plot b and bins using hist() method."
},
{
"code": null,
"e": 1553,
"s": 1511,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1595,
"s": 1553,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1959,
"s": 1595,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\na = np.random.random(100) * 0.5\nb = 1 - np.random.normal(size=100) * 0.1\nbins = 10\nbins = np.histogram(np.hstack((a, b)), bins=bins)[1]\nplt.hist(a, bins, edgecolor='black')\nplt.hist(b, bins, edgecolor='black')\nplt.show()"
}
] |
Aptitude - Percentages Online Quiz | Following quiz provides Multiple Choice Questions (MCQs) related to Percentages. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - Half of 1% written as a decimal is :
A - 0.005
B - 5
C - 0.5
D - 0.005
Half of 1% = (1⁄2 x 1⁄100)
= 0.5⁄100 = 0.005 %
Q 2 - If 120 is 20% of a number, then 120% of that number will be?
A - 120
B - 620
C - 720
D - 20
let z be the number.
Then, 20% of z = 120 i.e (20⁄100 x z) = 120
Therefore, z = 600
120% of z = (120⁄100 x 600) = 720
Q 3 - A batsman scored 110 runs which included 3 boundaries and 8 sixes. What percent of his total score did he make by running between the wickets?
A - 5⁄11%
B - 45%
C - 11 5⁄45%
D - 45 5⁄11%
Number of runs made by running = 110 - (3 x 4 + 8 x 6) = 50
Therefore, percentage = (50⁄100 x 100)% = 45 5⁄11%
Q 4 - If A = p% of q and B = q% of p, then which of the following is true?
A - A is smaller than B
B - A is greater than B
C - Relationship between A and B cannot be determined
D - A = B
p% of q = (p⁄100 x q) = (q⁄100 x p) = q% of p
→ A = B
Q 5 - The wheat production of a farmer increased from 180 quintals to 190 quintals. Find the percentage increase in production.
A - 4.56%
B - 5.00%
C - 5.50%
D - 5.56%
Increase =190-180=10
%Increase=(10/180)*100 = 5.56%
Q 6 - In a recent survey 40% houses contained 2 or more people. Of those houses containing only one person, 25% were having only a male. What is the percentage of all the houses which contain exactly one females and no males?
A - 75
B - 40
C - 15
D - 45
As per question, 40% houses contain two or more people.
i.e. 60% houses have only one person. O these houses 25% have male.
∴ 75% of 60% of the total houses have only one female and no males.
= .75 * 60% = 45%
Q 7 - 50% of a number when added to 50, is equal to a number .the number is
A - 100
B - 125
C - 140
D - 150
50 + 50% of x =x
x - 1/2x = 50
x=100
Q 8 - The population of a town is 176400. It increases annually at the rate of 5% p.a. What was it 2 years ago?
A - 160000
B - 260000
C - 360000
D - 460000
Population 2 years ago = 176400/(1+5/100)2 =(176400*20/21*20/21)=160000.
Q 9 - (9% of 386) * (6.5% of 144) = ?
A - 328.0
B - 333.3
C - 340.1
D - 253.8
(9% of 386) * (6.5% of 144) = 347.4 - 93.6 = 253.8
Q 10 - The population of a city increases at the rate of 4% per annum. There is additional annual increase of 1% due to influx of job seekers. The percentage increase in population after two years is:
A - 10
B - 10.25
C - 10.50
D - 10.75
Let the initial population be 100.
Total percentage change = 4 + 1 = 5%
∴ Population after 2 years = 100(1 + 5/100)2
= 100(21/20)2
= 441/4 = 110.25
∴ Percentage increase = 110.25 � 100 = 10.25%
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4217,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Percentages. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4260,
"s": 4217,
"text": "Q 1 - Half of 1% written as a decimal is :"
},
{
"code": null,
"e": 4270,
"s": 4260,
"text": "A - 0.005"
},
{
"code": null,
"e": 4276,
"s": 4270,
"text": "B - 5"
},
{
"code": null,
"e": 4284,
"s": 4276,
"text": "C - 0.5"
},
{
"code": null,
"e": 4294,
"s": 4284,
"text": "D - 0.005"
},
{
"code": null,
"e": 4341,
"s": 4294,
"text": "Half of 1% = (1⁄2 x 1⁄100)\n= 0.5⁄100 = 0.005 %"
},
{
"code": null,
"e": 4408,
"s": 4341,
"text": "Q 2 - If 120 is 20% of a number, then 120% of that number will be?"
},
{
"code": null,
"e": 4416,
"s": 4408,
"text": "A - 120"
},
{
"code": null,
"e": 4424,
"s": 4416,
"text": "B - 620"
},
{
"code": null,
"e": 4432,
"s": 4424,
"text": "C - 720"
},
{
"code": null,
"e": 4439,
"s": 4432,
"text": "D - 20"
},
{
"code": null,
"e": 4557,
"s": 4439,
"text": "let z be the number.\nThen, 20% of z = 120 i.e (20⁄100 x z) = 120\nTherefore, z = 600\n120% of z = (120⁄100 x 600) = 720"
},
{
"code": null,
"e": 4706,
"s": 4557,
"text": "Q 3 - A batsman scored 110 runs which included 3 boundaries and 8 sixes. What percent of his total score did he make by running between the wickets?"
},
{
"code": null,
"e": 4716,
"s": 4706,
"text": "A - 5⁄11%"
},
{
"code": null,
"e": 4724,
"s": 4716,
"text": "B - 45%"
},
{
"code": null,
"e": 4737,
"s": 4724,
"text": "C - 11 5⁄45%"
},
{
"code": null,
"e": 4750,
"s": 4737,
"text": "D - 45 5⁄11%"
},
{
"code": null,
"e": 4861,
"s": 4750,
"text": "Number of runs made by running = 110 - (3 x 4 + 8 x 6) = 50\nTherefore, percentage = (50⁄100 x 100)% = 45 5⁄11%"
},
{
"code": null,
"e": 4936,
"s": 4861,
"text": "Q 4 - If A = p% of q and B = q% of p, then which of the following is true?"
},
{
"code": null,
"e": 4960,
"s": 4936,
"text": "A - A is smaller than B"
},
{
"code": null,
"e": 4984,
"s": 4960,
"text": "B - A is greater than B"
},
{
"code": null,
"e": 5038,
"s": 4984,
"text": "C - Relationship between A and B cannot be determined"
},
{
"code": null,
"e": 5048,
"s": 5038,
"text": "D - A = B"
},
{
"code": null,
"e": 5102,
"s": 5048,
"text": "p% of q = (p⁄100 x q) = (q⁄100 x p) = q% of p\n→ A = B"
},
{
"code": null,
"e": 5230,
"s": 5102,
"text": "Q 5 - The wheat production of a farmer increased from 180 quintals to 190 quintals. Find the percentage increase in production."
},
{
"code": null,
"e": 5240,
"s": 5230,
"text": "A - 4.56%"
},
{
"code": null,
"e": 5250,
"s": 5240,
"text": "B - 5.00%"
},
{
"code": null,
"e": 5260,
"s": 5250,
"text": "C - 5.50%"
},
{
"code": null,
"e": 5270,
"s": 5260,
"text": "D - 5.56%"
},
{
"code": null,
"e": 5322,
"s": 5270,
"text": "Increase =190-180=10\n%Increase=(10/180)*100 = 5.56%"
},
{
"code": null,
"e": 5548,
"s": 5322,
"text": "Q 6 - In a recent survey 40% houses contained 2 or more people. Of those houses containing only one person, 25% were having only a male. What is the percentage of all the houses which contain exactly one females and no males?"
},
{
"code": null,
"e": 5555,
"s": 5548,
"text": "A - 75"
},
{
"code": null,
"e": 5562,
"s": 5555,
"text": "B - 40"
},
{
"code": null,
"e": 5569,
"s": 5562,
"text": "C - 15"
},
{
"code": null,
"e": 5576,
"s": 5569,
"text": "D - 45"
},
{
"code": null,
"e": 5787,
"s": 5576,
"text": "As per question, 40% houses contain two or more people.\ni.e. 60% houses have only one person. O these houses 25% have male.\n∴ 75% of 60% of the total houses have only one female and no males.\n = .75 * 60% = 45%"
},
{
"code": null,
"e": 5864,
"s": 5787,
"text": "Q 7 - 50% of a number when added to 50, is equal to a number .the number is "
},
{
"code": null,
"e": 5872,
"s": 5864,
"text": "A - 100"
},
{
"code": null,
"e": 5880,
"s": 5872,
"text": "B - 125"
},
{
"code": null,
"e": 5888,
"s": 5880,
"text": "C - 140"
},
{
"code": null,
"e": 5896,
"s": 5888,
"text": "D - 150"
},
{
"code": null,
"e": 5933,
"s": 5896,
"text": "50 + 50% of x =x\nx - 1/2x = 50\nx=100"
},
{
"code": null,
"e": 6045,
"s": 5933,
"text": "Q 8 - The population of a town is 176400. It increases annually at the rate of 5% p.a. What was it 2 years ago?"
},
{
"code": null,
"e": 6056,
"s": 6045,
"text": "A - 160000"
},
{
"code": null,
"e": 6067,
"s": 6056,
"text": "B - 260000"
},
{
"code": null,
"e": 6078,
"s": 6067,
"text": "C - 360000"
},
{
"code": null,
"e": 6089,
"s": 6078,
"text": "D - 460000"
},
{
"code": null,
"e": 6162,
"s": 6089,
"text": "Population 2 years ago = 176400/(1+5/100)2 =(176400*20/21*20/21)=160000."
},
{
"code": null,
"e": 6201,
"s": 6162,
"text": "Q 9 - (9% of 386) * (6.5% of 144) = ?"
},
{
"code": null,
"e": 6211,
"s": 6201,
"text": "A - 328.0"
},
{
"code": null,
"e": 6221,
"s": 6211,
"text": "B - 333.3"
},
{
"code": null,
"e": 6231,
"s": 6221,
"text": "C - 340.1"
},
{
"code": null,
"e": 6241,
"s": 6231,
"text": "D - 253.8"
},
{
"code": null,
"e": 6293,
"s": 6241,
"text": "(9% of 386) * (6.5% of 144) = 347.4 - 93.6 = 253.8"
},
{
"code": null,
"e": 6494,
"s": 6293,
"text": "Q 10 - The population of a city increases at the rate of 4% per annum. There is additional annual increase of 1% due to influx of job seekers. The percentage increase in population after two years is:"
},
{
"code": null,
"e": 6501,
"s": 6494,
"text": "A - 10"
},
{
"code": null,
"e": 6511,
"s": 6501,
"text": "B - 10.25"
},
{
"code": null,
"e": 6521,
"s": 6511,
"text": "C - 10.50"
},
{
"code": null,
"e": 6531,
"s": 6521,
"text": "D - 10.75"
},
{
"code": null,
"e": 6725,
"s": 6531,
"text": "Let the initial population be 100.\nTotal percentage change = 4 + 1 = 5%\n∴ Population after 2 years = 100(1 + 5/100)2\n= 100(21/20)2\n= 441/4 = 110.25\n∴ Percentage increase = 110.25 � 100 = 10.25%"
},
{
"code": null,
"e": 6761,
"s": 6725,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 6779,
"s": 6761,
"text": " Programming Line"
},
{
"code": null,
"e": 6786,
"s": 6779,
"text": " Print"
},
{
"code": null,
"e": 6797,
"s": 6786,
"text": " Add Notes"
}
] |
Azure Data Studio or SSMS — which should I use? | by Nikola Ilic | Towards Data Science | Question from the title already became extremely popular and it will become more and more as time passes by. Since Microsoft made Azure Data Studio generally available in September 2018 and investing heavily in this tool improvement in the meantime, it looks like good old SQL Server Management Studio is destined to go into (well-deserved) retirement...
But, is it like that?
As a SQL Developer, who is writing queries on a day-to-day basis, I will try to give some observations based on what I discovered so far, with special emphasis on Azure Data Studio, since I believe that most of us are more than familiar with SSMS already.
Short intro before I dive deeper into some cool features of the “new kid on the block”. When I heard the name of the new tool, I wasn’t planning to test it deeply, because the “Azure” part didn’t wake special interest in me. However, after I heard Ben Weissman speaking at SQL Saturday Vienna this January when he explained that “Azure” word doesn’t necessarily mean that you need to use this tool in conjunction with Azure palette of products, I decided to give it a try.
So, my first impression is: Microsoft named this IDE quite misleading! Why calling it “Azure Data Studio“, when connecting to Azure is just one of the options? You can also connect to the on-prem SQL Server database, as previously with SSMS, but you can also connect to Big Data Clusters (the latest feature of SQL Server, introduced in 2019 edition).
The main advantage of Azure Data Studio is its portability — while SSMS can work only on the Windows platform, ADS can run on Linux and macOS as well. That’s a huge step forward and going in line with Microsoft’s general expansion to non-Windows world.
Another huge difference to SSMS is that you can use notebooks, and writing SQL, Python, Spark, or Scala scripts within them. I can’t elaborate more on this since I’m still not using this feature (I’m a traditional SQL guy), but it definitely gives more flexibility for more sophisticated usage, comparing to SSMS.
Ok, enough with generic descriptions of the features and differences between ADS and SSMS. I will try to bold some neat features that Azure Data Studio offers:
When I write queries, I often need to check database object definitions. For example, to see if the underlying data type is DATETIME or DATETIME2. Of course, that can be achieved in SSMS using some 3rd party add-ons (by the way, I like SSMS Boost), but it’s quite straightforward in ADS:
Simply mark the object you want to check, right-click, and under Peek, select Peek Definition. You will immediately see the definition of the selected object:
As far as I know, SSMS still lacks dark mode, and I know a lot of developers are craving this. In ADS, dark mode is there!
Go to File->Preferences->Color Theme and choose the layout you want:
Looks pretty cool, ha?
This can be really useful and I’m using it extensively when working with Azure Data Studio. It can give you a brief overview of data returned by your query, so you can perform quick data profiling straight away and check how many NULLs are there, if there are some outliers, etc.
After I ran this query, I can choose a chart icon on the right and visualize my results immediately:
Moreover, as you can notice in the picture above, I can define the whole set of parameters and adjust the visual appearance of the results.
Azure Data Studio comes with a Git source control manager (SCM), so source control becomes one of the greatest advantages comparing to SSMS! More details on how to perform source control of your code can be found in official Azure Data Studio documentation.
In many cases, you need to provide your users with quick results of the queries. Now, no need to copy/paste query results or using some external add-ons for processing these simple requests. With literally one click, you are good to go!
On the right side, you simply choose if you want to export your results as CSV, Excel, JSON, XML or to visualize them (as in the previous tip).
This one could easily take first place, but I intentionally left it for the end. Imagine that you can have all relevant measures in one place, such as the number of currently running queries, deadlocks, index fragmentation, etc.!
I will demonstrate how you can create a dashboard for index fragmentation check, but you can easily expand your dashboard with queries you may find relevant for your monitoring.
SELECT st.index_id ,name AS indexName ,avg_fragmentation_in_percent AS frgPrct ,fragment_count AS frgCnt , avg_fragment_size_in_pages AS frgPagesFROM sys.dm_db_index_physical_stats (DB_ID('StackOverflow2013'), NULL, NULL, NULL, NULL) AS stINNER JOIN sys.indexes AS i ON st.object_id = i.object_id AND st.index_id = i.index_idORDER BY avg_fragmentation_in_percent DESC
Once I execute this query, I select Chart icon on the right:
I will save this query on Desktop (you can save it in whatever folder you like). Then, I choose the Table chart type and click on Create Insight above the result set:
Once I do this, the JSON code will be generated. After that, go to View tab, choose Command Palette and then Preference: Open User Settings.
Search for Dashboard.Database.Widgets and select to Edit in settings.json.
In “dashboard.database.widgets” key, paste JSON code created in one of the previous steps.
Save this settings.json file, navigate to StackOverflow2013 database, right-click on it and choose Manage. As you can see, our newly created widget is pinned to a dashboard and we can easily monitor what is going on with our indexes fragmentation.
You can create multiple different widgets and pin them to a dashboard, so you get a quick overview of key metrics for your database.
Despite being a truly an awesome tool, Azure Data Studio still lacks some key features in order to be considered as a direct substitute for SSMS. That’s especially true for DBAs tasks, where SSMS as a mature tool offers many more options.
As far as I see it, both tools are here to stay, at least for some time in the future!
Microsoft constantly upgrades Azure Data Studio, and I will dedicate separate articles to some recently added features, such as SQL Agent jobs, or more common tasks, such as using estimated and actual query execution plans to tune your queries.
Honestly, I still use SSMS more frequently than ADS (maybe just because I’m more accustomed to it), but I believe that every developer should give at least a try to an Azure Data Studio.
Become a member and read every story on Medium!
Subscribe here to get more insightful data articles! | [
{
"code": null,
"e": 527,
"s": 172,
"text": "Question from the title already became extremely popular and it will become more and more as time passes by. Since Microsoft made Azure Data Studio generally available in September 2018 and investing heavily in this tool improvement in the meantime, it looks like good old SQL Server Management Studio is destined to go into (well-deserved) retirement..."
},
{
"code": null,
"e": 549,
"s": 527,
"text": "But, is it like that?"
},
{
"code": null,
"e": 805,
"s": 549,
"text": "As a SQL Developer, who is writing queries on a day-to-day basis, I will try to give some observations based on what I discovered so far, with special emphasis on Azure Data Studio, since I believe that most of us are more than familiar with SSMS already."
},
{
"code": null,
"e": 1278,
"s": 805,
"text": "Short intro before I dive deeper into some cool features of the “new kid on the block”. When I heard the name of the new tool, I wasn’t planning to test it deeply, because the “Azure” part didn’t wake special interest in me. However, after I heard Ben Weissman speaking at SQL Saturday Vienna this January when he explained that “Azure” word doesn’t necessarily mean that you need to use this tool in conjunction with Azure palette of products, I decided to give it a try."
},
{
"code": null,
"e": 1630,
"s": 1278,
"text": "So, my first impression is: Microsoft named this IDE quite misleading! Why calling it “Azure Data Studio“, when connecting to Azure is just one of the options? You can also connect to the on-prem SQL Server database, as previously with SSMS, but you can also connect to Big Data Clusters (the latest feature of SQL Server, introduced in 2019 edition)."
},
{
"code": null,
"e": 1883,
"s": 1630,
"text": "The main advantage of Azure Data Studio is its portability — while SSMS can work only on the Windows platform, ADS can run on Linux and macOS as well. That’s a huge step forward and going in line with Microsoft’s general expansion to non-Windows world."
},
{
"code": null,
"e": 2197,
"s": 1883,
"text": "Another huge difference to SSMS is that you can use notebooks, and writing SQL, Python, Spark, or Scala scripts within them. I can’t elaborate more on this since I’m still not using this feature (I’m a traditional SQL guy), but it definitely gives more flexibility for more sophisticated usage, comparing to SSMS."
},
{
"code": null,
"e": 2357,
"s": 2197,
"text": "Ok, enough with generic descriptions of the features and differences between ADS and SSMS. I will try to bold some neat features that Azure Data Studio offers:"
},
{
"code": null,
"e": 2645,
"s": 2357,
"text": "When I write queries, I often need to check database object definitions. For example, to see if the underlying data type is DATETIME or DATETIME2. Of course, that can be achieved in SSMS using some 3rd party add-ons (by the way, I like SSMS Boost), but it’s quite straightforward in ADS:"
},
{
"code": null,
"e": 2804,
"s": 2645,
"text": "Simply mark the object you want to check, right-click, and under Peek, select Peek Definition. You will immediately see the definition of the selected object:"
},
{
"code": null,
"e": 2927,
"s": 2804,
"text": "As far as I know, SSMS still lacks dark mode, and I know a lot of developers are craving this. In ADS, dark mode is there!"
},
{
"code": null,
"e": 2996,
"s": 2927,
"text": "Go to File->Preferences->Color Theme and choose the layout you want:"
},
{
"code": null,
"e": 3019,
"s": 2996,
"text": "Looks pretty cool, ha?"
},
{
"code": null,
"e": 3299,
"s": 3019,
"text": "This can be really useful and I’m using it extensively when working with Azure Data Studio. It can give you a brief overview of data returned by your query, so you can perform quick data profiling straight away and check how many NULLs are there, if there are some outliers, etc."
},
{
"code": null,
"e": 3400,
"s": 3299,
"text": "After I ran this query, I can choose a chart icon on the right and visualize my results immediately:"
},
{
"code": null,
"e": 3540,
"s": 3400,
"text": "Moreover, as you can notice in the picture above, I can define the whole set of parameters and adjust the visual appearance of the results."
},
{
"code": null,
"e": 3798,
"s": 3540,
"text": "Azure Data Studio comes with a Git source control manager (SCM), so source control becomes one of the greatest advantages comparing to SSMS! More details on how to perform source control of your code can be found in official Azure Data Studio documentation."
},
{
"code": null,
"e": 4035,
"s": 3798,
"text": "In many cases, you need to provide your users with quick results of the queries. Now, no need to copy/paste query results or using some external add-ons for processing these simple requests. With literally one click, you are good to go!"
},
{
"code": null,
"e": 4179,
"s": 4035,
"text": "On the right side, you simply choose if you want to export your results as CSV, Excel, JSON, XML or to visualize them (as in the previous tip)."
},
{
"code": null,
"e": 4409,
"s": 4179,
"text": "This one could easily take first place, but I intentionally left it for the end. Imagine that you can have all relevant measures in one place, such as the number of currently running queries, deadlocks, index fragmentation, etc.!"
},
{
"code": null,
"e": 4587,
"s": 4409,
"text": "I will demonstrate how you can create a dashboard for index fragmentation check, but you can easily expand your dashboard with queries you may find relevant for your monitoring."
},
{
"code": null,
"e": 4995,
"s": 4587,
"text": "SELECT st.index_id ,name AS indexName ,avg_fragmentation_in_percent AS frgPrct ,fragment_count AS frgCnt , avg_fragment_size_in_pages AS frgPagesFROM sys.dm_db_index_physical_stats (DB_ID('StackOverflow2013'), NULL, NULL, NULL, NULL) AS stINNER JOIN sys.indexes AS i ON st.object_id = i.object_id AND st.index_id = i.index_idORDER BY avg_fragmentation_in_percent DESC"
},
{
"code": null,
"e": 5056,
"s": 4995,
"text": "Once I execute this query, I select Chart icon on the right:"
},
{
"code": null,
"e": 5223,
"s": 5056,
"text": "I will save this query on Desktop (you can save it in whatever folder you like). Then, I choose the Table chart type and click on Create Insight above the result set:"
},
{
"code": null,
"e": 5364,
"s": 5223,
"text": "Once I do this, the JSON code will be generated. After that, go to View tab, choose Command Palette and then Preference: Open User Settings."
},
{
"code": null,
"e": 5439,
"s": 5364,
"text": "Search for Dashboard.Database.Widgets and select to Edit in settings.json."
},
{
"code": null,
"e": 5530,
"s": 5439,
"text": "In “dashboard.database.widgets” key, paste JSON code created in one of the previous steps."
},
{
"code": null,
"e": 5778,
"s": 5530,
"text": "Save this settings.json file, navigate to StackOverflow2013 database, right-click on it and choose Manage. As you can see, our newly created widget is pinned to a dashboard and we can easily monitor what is going on with our indexes fragmentation."
},
{
"code": null,
"e": 5911,
"s": 5778,
"text": "You can create multiple different widgets and pin them to a dashboard, so you get a quick overview of key metrics for your database."
},
{
"code": null,
"e": 6150,
"s": 5911,
"text": "Despite being a truly an awesome tool, Azure Data Studio still lacks some key features in order to be considered as a direct substitute for SSMS. That’s especially true for DBAs tasks, where SSMS as a mature tool offers many more options."
},
{
"code": null,
"e": 6237,
"s": 6150,
"text": "As far as I see it, both tools are here to stay, at least for some time in the future!"
},
{
"code": null,
"e": 6482,
"s": 6237,
"text": "Microsoft constantly upgrades Azure Data Studio, and I will dedicate separate articles to some recently added features, such as SQL Agent jobs, or more common tasks, such as using estimated and actual query execution plans to tune your queries."
},
{
"code": null,
"e": 6669,
"s": 6482,
"text": "Honestly, I still use SSMS more frequently than ADS (maybe just because I’m more accustomed to it), but I believe that every developer should give at least a try to an Azure Data Studio."
},
{
"code": null,
"e": 6717,
"s": 6669,
"text": "Become a member and read every story on Medium!"
}
] |
How to use the CAST function in a MySQL SELECT statement? | The CAST() function in MySQL converts a value of any type into a value that has a specified
type. Let us first create a table −
mysql> create table castFunctionDemo
-> (
-> ShippingDate date
-> );
Query OK, 0 rows affected (0.74 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into castFunctionDemo values('2019-01-31');
Query OK, 1 row affected (0.20 sec)
mysql> insert into castFunctionDemo values('2018-07-12');
Query OK, 1 row affected (0.16 sec)
mysql> insert into castFunctionDemo values('2016-12-06');
Query OK, 1 row affected (0.16 sec)
mysql> insert into castFunctionDemo values('2017-08-25');
Query OK, 1 row affected (0.19 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from castFunctionDemo;
This will produce the following output −
+--------------+
| ShippingDate |
+--------------+
| 2019-01-31 |
| 2018-07-12 |
| 2016-12-06 |
| 2017-08-25 |
+--------------+
4 rows in set (0.00 sec)
Here is the query to use the cast() function correctly in a MySQL select statement −
mysql> select CAST(ShippingDate AS CHAR(12)) as Conversion FROM castFunctionDemo;
This will produce the following output −
+------------+
| Conversion |
+------------+
| 2019-01-31 |
| 2018-07-12 |
| 2016-12-06 |
| 2017-08-25 |
+------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "The CAST() function in MySQL converts a value of any type into a value that has a specified\ntype. Let us first create a table −"
},
{
"code": null,
"e": 1305,
"s": 1190,
"text": "mysql> create table castFunctionDemo\n -> (\n -> ShippingDate date\n -> );\nQuery OK, 0 rows affected (0.74 sec)"
},
{
"code": null,
"e": 1387,
"s": 1305,
"text": "Following is the query to insert some records in the table using insert command −"
},
{
"code": null,
"e": 1766,
"s": 1387,
"text": "mysql> insert into castFunctionDemo values('2019-01-31');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into castFunctionDemo values('2018-07-12');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into castFunctionDemo values('2016-12-06');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into castFunctionDemo values('2017-08-25');\nQuery OK, 1 row affected (0.19 sec)"
},
{
"code": null,
"e": 1852,
"s": 1766,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 1891,
"s": 1852,
"text": "mysql> select * from castFunctionDemo;"
},
{
"code": null,
"e": 1932,
"s": 1891,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2093,
"s": 1932,
"text": "+--------------+\n| ShippingDate |\n+--------------+\n| 2019-01-31 |\n| 2018-07-12 |\n| 2016-12-06 |\n| 2017-08-25 |\n+--------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2178,
"s": 2093,
"text": "Here is the query to use the cast() function correctly in a MySQL select statement −"
},
{
"code": null,
"e": 2260,
"s": 2178,
"text": "mysql> select CAST(ShippingDate AS CHAR(12)) as Conversion FROM castFunctionDemo;"
},
{
"code": null,
"e": 2301,
"s": 2260,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2446,
"s": 2301,
"text": "+------------+\n| Conversion |\n+------------+\n| 2019-01-31 |\n| 2018-07-12 |\n| 2016-12-06 |\n| 2017-08-25 |\n+------------+\n4 rows in set (0.00 sec)"
}
] |
HTTP headers | Host - GeeksforGeeks | 20 Nov, 2019
The HTTP Host represents the domain name of the server. It may also represent the Transmission Control Protocol (TCP) port number which the server uses. Defining the port number is optional, the default value is considered. For example, “80” is assigned as the port number for an HTTP URL when there is no port number specified. The HTTP Host header is a request type header. The host header field must be sent in all HTTP/1.1 request messages. If a request message does not have any header field or more than one header field, a 400 Bad Request is sent.
Syntax :
Host: <host>:<port>
Directives: The HTTP header Host accepts two directives mentioned above and described below:
<host>: This directive represents the domain name of the server.
<port>: This directive is an optional one. It represents the TCP port number in which the server is working.Note: You can check any website hoster in this link.Examples:Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.orgHost for GeeksforGeeks home page.Host: www.geeksforgeeks.orgSupported Browsers: The browsers compatible with HTTP Host header are listed below:Google ChromeInternet ExplorerEdgeMozilla FirefoxOperaSafariMy Personal Notes
arrow_drop_upSave
Note: You can check any website hoster in this link.Examples:
Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.org
Host: www.cdn.geeksforgeeks.org
Host for GeeksforGeeks home page.Host: www.geeksforgeeks.org
Host: www.geeksforgeeks.org
Supported Browsers: The browsers compatible with HTTP Host header are listed below:
Google Chrome
Internet Explorer
Edge
Mozilla Firefox
Opera
Safari
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 24672,
"s": 24644,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 25227,
"s": 24672,
"text": "The HTTP Host represents the domain name of the server. It may also represent the Transmission Control Protocol (TCP) port number which the server uses. Defining the port number is optional, the default value is considered. For example, “80” is assigned as the port number for an HTTP URL when there is no port number specified. The HTTP Host header is a request type header. The host header field must be sent in all HTTP/1.1 request messages. If a request message does not have any header field or more than one header field, a 400 Bad Request is sent."
},
{
"code": null,
"e": 25236,
"s": 25227,
"text": "Syntax :"
},
{
"code": null,
"e": 25256,
"s": 25236,
"text": "Host: <host>:<port>"
},
{
"code": null,
"e": 25349,
"s": 25256,
"text": "Directives: The HTTP header Host accepts two directives mentioned above and described below:"
},
{
"code": null,
"e": 25414,
"s": 25349,
"text": "<host>: This directive represents the domain name of the server."
},
{
"code": null,
"e": 25885,
"s": 25414,
"text": "<port>: This directive is an optional one. It represents the TCP port number in which the server is working.Note: You can check any website hoster in this link.Examples:Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.orgHost for GeeksforGeeks home page.Host: www.geeksforgeeks.orgSupported Browsers: The browsers compatible with HTTP Host header are listed below:Google ChromeInternet ExplorerEdgeMozilla FirefoxOperaSafariMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 25947,
"s": 25885,
"text": "Note: You can check any website hoster in this link.Examples:"
},
{
"code": null,
"e": 26011,
"s": 25947,
"text": "Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.org"
},
{
"code": null,
"e": 26043,
"s": 26011,
"text": "Host: www.cdn.geeksforgeeks.org"
},
{
"code": null,
"e": 26104,
"s": 26043,
"text": "Host for GeeksforGeeks home page.Host: www.geeksforgeeks.org"
},
{
"code": null,
"e": 26132,
"s": 26104,
"text": "Host: www.geeksforgeeks.org"
},
{
"code": null,
"e": 26216,
"s": 26132,
"text": "Supported Browsers: The browsers compatible with HTTP Host header are listed below:"
},
{
"code": null,
"e": 26230,
"s": 26216,
"text": "Google Chrome"
},
{
"code": null,
"e": 26248,
"s": 26230,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26253,
"s": 26248,
"text": "Edge"
},
{
"code": null,
"e": 26269,
"s": 26253,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 26275,
"s": 26269,
"text": "Opera"
},
{
"code": null,
"e": 26282,
"s": 26275,
"text": "Safari"
},
{
"code": null,
"e": 26295,
"s": 26282,
"text": "HTTP-headers"
},
{
"code": null,
"e": 26302,
"s": 26295,
"text": "Picked"
},
{
"code": null,
"e": 26321,
"s": 26302,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26338,
"s": 26321,
"text": "Web Technologies"
},
{
"code": null,
"e": 26436,
"s": 26338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26445,
"s": 26436,
"text": "Comments"
},
{
"code": null,
"e": 26458,
"s": 26445,
"text": "Old Comments"
},
{
"code": null,
"e": 26500,
"s": 26458,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26533,
"s": 26500,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26576,
"s": 26533,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26638,
"s": 26576,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26688,
"s": 26638,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26733,
"s": 26688,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26802,
"s": 26733,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 26863,
"s": 26802,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26935,
"s": 26863,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Difference between concatenation of strings using (str += s) and (str = str + s) - GeeksforGeeks | 02 Mar, 2022
A string is a collection of characters. For example, “GeeksforGeeks” is a string. C++ provides primitive data types to create a string. The string can also be initialized at the time of declaration.
Syntax:
string str;
string str = “GeeksforGeeks”
Here, “GeeksforGeeks” is a string literal.
This article shows the difference between the concatenation of the strings using the addition assignment operator (+=) and the addition (+) operator used with strings. Concatenation is the process of joining end-to-end.
Addition assignment (+=) operator
In C++, a string addition assignment operator is used to concatenate one string to the end of another string.
Syntax:
str += value
Here, value is a string to be concatenated with str.
It appends the value (literal) at the end of the string, without any reassignment.
Example: Below is the C++ program to demonstrate the addition assignment operator.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = "Geeks"; // String to be concatenated string str1 = "forGeeks"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the string cout << str; return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Driver codepublic static void main(String[] args){ // Declaring an empty String String str = "Geeks"; // String to be concatenated String str1 = "forGeeks"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the String System.out.print(str);}} // This code is contributed by 29AjayKumar
# Python code for the above approach# Driver code # Declaring an empty stringstr = "Geeks"; # String to be concatenatedstr1 = "forGeeks"; # Concatenate str and str1# using addition assignment operatorstr += str1; # Print the stringprint(str); # This code is contributed by gfgking
// C# program to implement// the above approachusing System; public class GFG{ // Driver codepublic static void Main(String[] args){ // Declaring an empty String String str = "Geeks"; // String to be concatenated String str1 = "forGeeks"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the String Console.Write(str);}} // This code is contributed by 29AjayKumar
<script> // JavaScript code for the above approach // Driver code // Declaring an empty string let str = "Geeks"; // String to be concatenated let str1 = "forGeeks"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the string document.write(str); // This code is contributed by Potta Lokesh </script>
GeeksforGeeks
Addition(+) operator
In C++, a string addition operator is used to concatenate one string to the end of another string. But in this case the after the concatenation of strings, the modified string gets assigned to the string.
Syntax:
str = str + value
Here, value is a string to be concatenated with str.
It firstly appends the value (literal) at the end of the string and then reassigns it to str.
Example: Below is the C+ program to demonstrate the above approach.
C++
Java
C#
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = "Geeks"; // String to be concatenated string str1 = "forGeeks"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the string cout << str; return 0;}
// Java program to implement// the above approach class GFG{ // Driver codepublic static void main(String[] args){ // Declaring an empty String String str = "Geeks"; // String to be concatenated String str1 = "forGeeks"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the String System.out.print(str);}} // This code is contributed by 29AjayKumar
// C# program to implement// the above approachusing System;public class GFG { // Driver code public static void Main(String[] args) { // Declaring an empty String String str = "Geeks"; // String to be concatenated String str1 = "forGeeks"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the String Console.Write(str); }} // This code is contributed by umadevi9616
GeeksforGeeks
Although both operators when used with strings can be used for the concatenation of strings, there are some differences between them:
Factor 1: Assignment of the modified string:
The addition assignment operator (+=) concatenates two strings by appending one string at the end of another string.
The addition operator(+) concatenates two strings by appending one string at the end of the original string and then assigning the modified string to the original string.
Example: Below is the C++ program to demonstrate the above approach.
C++
#include <iostream>using namespace std; int main(){ // Declaring an empty string string str = "Geeks"; // String to be concatenated string str1 = "forGeeks"; // Concatenate str and str1 // using addition assignment operator // Concatenate str1 at the end of str str += str1; // Print the string cout << "Resultant string using += " << str << '\n'; str = "Geeks"; // Concatenate str and str1 // using addition operator // Concatenate str and str1 // and assign the result to str again str = str + str1; // Print the string cout << "Resultant string using + " << str; return 0;}
Resultant string using += GeeksforGeeks
Resultant string using + GeeksforGeeks
Factor 2: Operator overloaded functions used:
The addition assignment operator (+=) concatenates two strings because the operator is overloaded internally.
In this case, also, the addition operator (+) concatenates two strings because the operator is overloaded internally.
Factor 3: Number of strings concatenated:
The addition assignment operator (+=) can concatenate two strings at a time in a single statement.
The addition operator (+) can concatenate multiple strings by using multiple addition (+) operators between the string in a single statement. For example, str = str1 + str2 + str3 + ... + strn
Example: In this program, three different statements are required to concatenate three strings; str, str1, str2, and str3 using the assignment addition operator (+=) and a single statement is required to concatenate three strings; str, str1, str2, and str3 using the addition operator (+).
C++
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = "GeeksforGeeks"; // String to be concatenated string str1 = " GeeksforGeeks"; // String to be concatenated string str2 = " GeeksforGeeks"; // String to be concatenated string str3 = " GeeksforGeeks"; // Concatenate str, str1, str2 and str3 // using addition assignment operator // in multiple statements str += str1; str += str2; str += str3; // Print the string cout << "Resultant string using +=" << str << '\n'; str = "GeeksforGeeks"; // Concatenate str, str1, str and str3 // using addition operator // in a single statement str = str + str1 + str2 + str3; // Print the string cout << "Resultant string using + " << str; return 0;}
Resultant string using +=GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks
Resultant string using + GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks
Factor 4: Performance:
The addition assignment operator (+=) when used for the concatenation of strings gives better efficiency as compared to the addition(+) operator. This is because no reassignment of strings takes place in this case.
The addition operator (+) when used for the concatenation of strings, is less efficient as compared to the addition (+=) operator. This is because the assignment of strings takes place in this case.
Example: Below is the program to demonstrate the performance of the += string concatenation method.
C++
// C++ program to calculate// performance of +=#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialize a n empty string string str = ""; // concatenate the characters // from 'a' to 'z' for (int i = 0; i < 26; i++) { char c = 'a' + i; str += c; }} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;}
Time taken by program is : 0.000046 sec
Example: Below is the program to demonstrate the performance of the + string concatenation method.
C++
// C++ program to calculate// performance of +#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialize a n empty string string str = ""; // concatenate the characters // from 'a' to 'z' for (int i = 0; i < 26; i++) { char c = 'a' + i; str = str + c; }} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;}
Time taken by program is : 0.000034 sec
lokeshpotta20
varshagumber28
gfgking
29AjayKumar
umadevi9616
C++
Difference Between
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing | [
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 24297,
"s": 24098,
"text": "A string is a collection of characters. For example, “GeeksforGeeks” is a string. C++ provides primitive data types to create a string. The string can also be initialized at the time of declaration."
},
{
"code": null,
"e": 24305,
"s": 24297,
"text": "Syntax:"
},
{
"code": null,
"e": 24317,
"s": 24305,
"text": "string str;"
},
{
"code": null,
"e": 24346,
"s": 24317,
"text": "string str = “GeeksforGeeks”"
},
{
"code": null,
"e": 24389,
"s": 24346,
"text": "Here, “GeeksforGeeks” is a string literal."
},
{
"code": null,
"e": 24609,
"s": 24389,
"text": "This article shows the difference between the concatenation of the strings using the addition assignment operator (+=) and the addition (+) operator used with strings. Concatenation is the process of joining end-to-end."
},
{
"code": null,
"e": 24643,
"s": 24609,
"text": "Addition assignment (+=) operator"
},
{
"code": null,
"e": 24753,
"s": 24643,
"text": "In C++, a string addition assignment operator is used to concatenate one string to the end of another string."
},
{
"code": null,
"e": 24762,
"s": 24753,
"text": " Syntax:"
},
{
"code": null,
"e": 24775,
"s": 24762,
"text": "str += value"
},
{
"code": null,
"e": 24828,
"s": 24775,
"text": "Here, value is a string to be concatenated with str."
},
{
"code": null,
"e": 24911,
"s": 24828,
"text": "It appends the value (literal) at the end of the string, without any reassignment."
},
{
"code": null,
"e": 24994,
"s": 24911,
"text": "Example: Below is the C++ program to demonstrate the addition assignment operator."
},
{
"code": null,
"e": 24998,
"s": 24994,
"text": "C++"
},
{
"code": null,
"e": 25003,
"s": 24998,
"text": "Java"
},
{
"code": null,
"e": 25011,
"s": 25003,
"text": "Python3"
},
{
"code": null,
"e": 25014,
"s": 25011,
"text": "C#"
},
{
"code": null,
"e": 25025,
"s": 25014,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = \"Geeks\"; // String to be concatenated string str1 = \"forGeeks\"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the string cout << str; return 0;}",
"e": 25402,
"s": 25025,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Driver codepublic static void main(String[] args){ // Declaring an empty String String str = \"Geeks\"; // String to be concatenated String str1 = \"forGeeks\"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the String System.out.print(str);}} // This code is contributed by 29AjayKumar",
"e": 25839,
"s": 25402,
"text": null
},
{
"code": "# Python code for the above approach# Driver code # Declaring an empty stringstr = \"Geeks\"; # String to be concatenatedstr1 = \"forGeeks\"; # Concatenate str and str1# using addition assignment operatorstr += str1; # Print the stringprint(str); # This code is contributed by gfgking",
"e": 26120,
"s": 25839,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; public class GFG{ // Driver codepublic static void Main(String[] args){ // Declaring an empty String String str = \"Geeks\"; // String to be concatenated String str1 = \"forGeeks\"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the String Console.Write(str);}} // This code is contributed by 29AjayKumar",
"e": 26554,
"s": 26120,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Driver code // Declaring an empty string let str = \"Geeks\"; // String to be concatenated let str1 = \"forGeeks\"; // Concatenate str and str1 // using addition assignment operator str += str1; // Print the string document.write(str); // This code is contributed by Potta Lokesh </script>",
"e": 26980,
"s": 26554,
"text": null
},
{
"code": null,
"e": 26994,
"s": 26980,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 27015,
"s": 26994,
"text": "Addition(+) operator"
},
{
"code": null,
"e": 27220,
"s": 27015,
"text": "In C++, a string addition operator is used to concatenate one string to the end of another string. But in this case the after the concatenation of strings, the modified string gets assigned to the string."
},
{
"code": null,
"e": 27228,
"s": 27220,
"text": "Syntax:"
},
{
"code": null,
"e": 27246,
"s": 27228,
"text": "str = str + value"
},
{
"code": null,
"e": 27299,
"s": 27246,
"text": "Here, value is a string to be concatenated with str."
},
{
"code": null,
"e": 27393,
"s": 27299,
"text": "It firstly appends the value (literal) at the end of the string and then reassigns it to str."
},
{
"code": null,
"e": 27461,
"s": 27393,
"text": "Example: Below is the C+ program to demonstrate the above approach."
},
{
"code": null,
"e": 27465,
"s": 27461,
"text": "C++"
},
{
"code": null,
"e": 27470,
"s": 27465,
"text": "Java"
},
{
"code": null,
"e": 27473,
"s": 27470,
"text": "C#"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = \"Geeks\"; // String to be concatenated string str1 = \"forGeeks\"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the string cout << str; return 0;}",
"e": 27844,
"s": 27473,
"text": null
},
{
"code": "// Java program to implement// the above approach class GFG{ // Driver codepublic static void main(String[] args){ // Declaring an empty String String str = \"Geeks\"; // String to be concatenated String str1 = \"forGeeks\"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the String System.out.print(str);}} // This code is contributed by 29AjayKumar",
"e": 28257,
"s": 27844,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;public class GFG { // Driver code public static void Main(String[] args) { // Declaring an empty String String str = \"Geeks\"; // String to be concatenated String str1 = \"forGeeks\"; // Concatenate str and str1 // using addition operator str = str + str1; // Print the String Console.Write(str); }} // This code is contributed by umadevi9616",
"e": 28692,
"s": 28257,
"text": null
},
{
"code": null,
"e": 28706,
"s": 28692,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 28840,
"s": 28706,
"text": "Although both operators when used with strings can be used for the concatenation of strings, there are some differences between them:"
},
{
"code": null,
"e": 28885,
"s": 28840,
"text": "Factor 1: Assignment of the modified string:"
},
{
"code": null,
"e": 29002,
"s": 28885,
"text": "The addition assignment operator (+=) concatenates two strings by appending one string at the end of another string."
},
{
"code": null,
"e": 29173,
"s": 29002,
"text": "The addition operator(+) concatenates two strings by appending one string at the end of the original string and then assigning the modified string to the original string."
},
{
"code": null,
"e": 29242,
"s": 29173,
"text": "Example: Below is the C++ program to demonstrate the above approach."
},
{
"code": null,
"e": 29246,
"s": 29242,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ // Declaring an empty string string str = \"Geeks\"; // String to be concatenated string str1 = \"forGeeks\"; // Concatenate str and str1 // using addition assignment operator // Concatenate str1 at the end of str str += str1; // Print the string cout << \"Resultant string using += \" << str << '\\n'; str = \"Geeks\"; // Concatenate str and str1 // using addition operator // Concatenate str and str1 // and assign the result to str again str = str + str1; // Print the string cout << \"Resultant string using + \" << str; return 0;}",
"e": 29903,
"s": 29246,
"text": null
},
{
"code": null,
"e": 29982,
"s": 29903,
"text": "Resultant string using += GeeksforGeeks\nResultant string using + GeeksforGeeks"
},
{
"code": null,
"e": 30028,
"s": 29982,
"text": "Factor 2: Operator overloaded functions used:"
},
{
"code": null,
"e": 30138,
"s": 30028,
"text": "The addition assignment operator (+=) concatenates two strings because the operator is overloaded internally."
},
{
"code": null,
"e": 30256,
"s": 30138,
"text": "In this case, also, the addition operator (+) concatenates two strings because the operator is overloaded internally."
},
{
"code": null,
"e": 30298,
"s": 30256,
"text": "Factor 3: Number of strings concatenated:"
},
{
"code": null,
"e": 30397,
"s": 30298,
"text": "The addition assignment operator (+=) can concatenate two strings at a time in a single statement."
},
{
"code": null,
"e": 30590,
"s": 30397,
"text": "The addition operator (+) can concatenate multiple strings by using multiple addition (+) operators between the string in a single statement. For example, str = str1 + str2 + str3 + ... + strn"
},
{
"code": null,
"e": 30881,
"s": 30590,
"text": "Example: In this program, three different statements are required to concatenate three strings; str, str1, str2, and str3 using the assignment addition operator (+=) and a single statement is required to concatenate three strings; str, str1, str2, and str3 using the addition operator (+). "
},
{
"code": null,
"e": 30885,
"s": 30881,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Declaring an empty string string str = \"GeeksforGeeks\"; // String to be concatenated string str1 = \" GeeksforGeeks\"; // String to be concatenated string str2 = \" GeeksforGeeks\"; // String to be concatenated string str3 = \" GeeksforGeeks\"; // Concatenate str, str1, str2 and str3 // using addition assignment operator // in multiple statements str += str1; str += str2; str += str3; // Print the string cout << \"Resultant string using +=\" << str << '\\n'; str = \"GeeksforGeeks\"; // Concatenate str, str1, str and str3 // using addition operator // in a single statement str = str + str1 + str2 + str3; // Print the string cout << \"Resultant string using + \" << str; return 0;}",
"e": 31776,
"s": 30885,
"text": null
},
{
"code": null,
"e": 31938,
"s": 31776,
"text": "Resultant string using +=GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks\nResultant string using + GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks"
},
{
"code": null,
"e": 31961,
"s": 31938,
"text": "Factor 4: Performance:"
},
{
"code": null,
"e": 32176,
"s": 31961,
"text": "The addition assignment operator (+=) when used for the concatenation of strings gives better efficiency as compared to the addition(+) operator. This is because no reassignment of strings takes place in this case."
},
{
"code": null,
"e": 32376,
"s": 32176,
"text": "The addition operator (+) when used for the concatenation of strings, is less efficient as compared to the addition (+=) operator. This is because the assignment of strings takes place in this case."
},
{
"code": null,
"e": 32476,
"s": 32376,
"text": "Example: Below is the program to demonstrate the performance of the += string concatenation method."
},
{
"code": null,
"e": 32480,
"s": 32476,
"text": "C++"
},
{
"code": "// C++ program to calculate// performance of +=#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialize a n empty string string str = \"\"; // concatenate the characters // from 'a' to 'z' for (int i = 0; i < 26; i++) { char c = 'a' + i; str += c; }} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}",
"e": 33583,
"s": 32480,
"text": null
},
{
"code": null,
"e": 33623,
"s": 33583,
"text": "Time taken by program is : 0.000046 sec"
},
{
"code": null,
"e": 33722,
"s": 33623,
"text": "Example: Below is the program to demonstrate the performance of the + string concatenation method."
},
{
"code": null,
"e": 33726,
"s": 33722,
"text": "C++"
},
{
"code": "// C++ program to calculate// performance of +#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialize a n empty string string str = \"\"; // concatenate the characters // from 'a' to 'z' for (int i = 0; i < 26; i++) { char c = 'a' + i; str = str + c; }} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}",
"e": 34834,
"s": 33726,
"text": null
},
{
"code": null,
"e": 34874,
"s": 34834,
"text": "Time taken by program is : 0.000034 sec"
},
{
"code": null,
"e": 34888,
"s": 34874,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34903,
"s": 34888,
"text": "varshagumber28"
},
{
"code": null,
"e": 34911,
"s": 34903,
"text": "gfgking"
},
{
"code": null,
"e": 34923,
"s": 34911,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34935,
"s": 34923,
"text": "umadevi9616"
},
{
"code": null,
"e": 34939,
"s": 34935,
"text": "C++"
},
{
"code": null,
"e": 34958,
"s": 34939,
"text": "Difference Between"
},
{
"code": null,
"e": 34966,
"s": 34958,
"text": "Strings"
},
{
"code": null,
"e": 34974,
"s": 34966,
"text": "Strings"
},
{
"code": null,
"e": 34978,
"s": 34974,
"text": "CPP"
},
{
"code": null,
"e": 35076,
"s": 34978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35085,
"s": 35076,
"text": "Comments"
},
{
"code": null,
"e": 35098,
"s": 35085,
"text": "Old Comments"
},
{
"code": null,
"e": 35126,
"s": 35098,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 35146,
"s": 35126,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 35179,
"s": 35146,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 35203,
"s": 35179,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 35224,
"s": 35203,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 35255,
"s": 35224,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 35295,
"s": 35255,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 35327,
"s": 35295,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 35388,
"s": 35327,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Difference between Definition and Declaration in Java. | For the difference between definition and declaration, one should consider their literal meaning first which includes Declare means to announce or proclaim while Define means to describe some entity.
The following are the important differences between the Definition and the Declaration.
JavaTester.java
Live Demo
public class JavaTester{
public static void main(String args[]){
int a; // declaration of variable
a=10; // definition of variable
functionA(a); // declaration of function
}
public static void functionA(int a){
System.out.println("value of a is " + a); // definition of function
}
}
value of a is 10 | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "For the difference between definition and declaration, one should consider their literal meaning first which includes Declare means to announce or proclaim while Define means to describe some entity."
},
{
"code": null,
"e": 1350,
"s": 1262,
"text": "The following are the important differences between the Definition and the Declaration."
},
{
"code": null,
"e": 1366,
"s": 1350,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1377,
"s": 1366,
"text": " Live Demo"
},
{
"code": null,
"e": 1696,
"s": 1377,
"text": "public class JavaTester{\n public static void main(String args[]){\n int a; // declaration of variable\n a=10; // definition of variable\n functionA(a); // declaration of function\n }\n public static void functionA(int a){\n System.out.println(\"value of a is \" + a); // definition of function\n }\n}"
},
{
"code": null,
"e": 1713,
"s": 1696,
"text": "value of a is 10"
}
] |
How to get the size of an array within a nested JSON in Rest Assured? | We can get the size of an array within a nested JSON in Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string.
Finally, to obtain JSON array size, we have to use the size method. We shall send a GET request via Postman on a mock API, and observe the Response.
Using Rest Assured, let us get the size of the Location array within the nested JSON response. The size should be three since it contains information about three locations - Michigan, Indiana, and New York.
Code Implementation
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class NewTest {
@Test
public void jsonArySize() {
//base URI with Rest Assured class
RestAssured.baseURI = "https://run.mocky.io/v3";
//obtain Response from GET request
Response res = given()
.when()
.get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7");
//convert JSON to string
JsonPath j = new JsonPath(res.asString());
//length of JSON Location array
int s = j.getInt("Location.size()");
System.out.println("Array size of Location: " +s);
}
} | [
{
"code": null,
"e": 1238,
"s": 1062,
"text": "We can get the size of an array within a nested JSON in Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string."
},
{
"code": null,
"e": 1387,
"s": 1238,
"text": "Finally, to obtain JSON array size, we have to use the size method. We shall send a GET request via Postman on a mock API, and observe the Response."
},
{
"code": null,
"e": 1594,
"s": 1387,
"text": "Using Rest Assured, let us get the size of the Location array within the nested JSON response. The size should be three since it contains information about three locations - Michigan, Indiana, and New York."
},
{
"code": null,
"e": 1614,
"s": 1594,
"text": "Code Implementation"
},
{
"code": null,
"e": 2341,
"s": 1614,
"text": "import static io.restassured.RestAssured.given;\nimport org.testng.annotations.Test;\nimport io.restassured.RestAssured;\nimport io.restassured.path.json.JsonPath;\nimport io.restassured.response.Response;\npublic class NewTest {\n @Test\n public void jsonArySize() {\n\n //base URI with Rest Assured class\n RestAssured.baseURI = \"https://run.mocky.io/v3\";\n\n //obtain Response from GET request\n Response res = given()\n .when()\n .get(\"/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7\");\n\n //convert JSON to string\n JsonPath j = new JsonPath(res.asString());\n\n //length of JSON Location array\n int s = j.getInt(\"Location.size()\");\n System.out.println(\"Array size of Location: \" +s);\n }\n}"
}
] |
How to count the total number of frames in OpenCV using C++? | We will learn how to calculate the total number of frames in OpenCV. Using OpenCV, it is elementary to count and show the total number of frames of a video. However, you have to store one thing in mind that we cannot count the total number of real-time video frames. Because a real-time video does not have a specific number of frames.
The following program counts the number of total frames and shows it in the console window.
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main() {
int frame_Number;//Declaring an integervariable to store the number of total frames//
VideoCapture cap("video.mp4");//Declaring an object to capture stream of frames from default camera//
frame_Number = cap.get(CAP_PROP_FRAME_COUNT);//Getting the total number of frames//
cout << "Total Number of frames are:" << frame_Number << endl;//Showing the number in console window//
system("pause");//Pausing the system to see the result//
cap.release();//Releasing the buffer memory//
return 0;
}
As the output, we will get an integer value. | [
{
"code": null,
"e": 1398,
"s": 1062,
"text": "We will learn how to calculate the total number of frames in OpenCV. Using OpenCV, it is elementary to count and show the total number of frames of a video. However, you have to store one thing in mind that we cannot count the total number of real-time video frames. Because a real-time video does not have a specific number of frames."
},
{
"code": null,
"e": 1490,
"s": 1398,
"text": "The following program counts the number of total frames and shows it in the console window."
},
{
"code": null,
"e": 2103,
"s": 1490,
"text": "#include<opencv2/opencv.hpp>\n#include<iostream>\nusing namespace std;\nusing namespace cv;\nint main() {\n int frame_Number;//Declaring an integervariable to store the number of total frames//\n VideoCapture cap(\"video.mp4\");//Declaring an object to capture stream of frames from default camera//\n frame_Number = cap.get(CAP_PROP_FRAME_COUNT);//Getting the total number of frames//\n cout << \"Total Number of frames are:\" << frame_Number << endl;//Showing the number in console window//\n system(\"pause\");//Pausing the system to see the result//\n cap.release();//Releasing the buffer memory//\n return 0;\n}"
},
{
"code": null,
"e": 2148,
"s": 2103,
"text": "As the output, we will get an integer value."
}
] |
Introducing Google Guava. Guava is an open-source “Collection... | by Mohit Sharma | Towards Data Science | It provides utilities for working with Java collections. As you dive deep into Guava you’ll notice how it reduces coding errors, facilitates standard coding practices and boost productivity by making code concise and easy to read.
I’ve decided to break down the Guava tutorial in a series of posts. We’ll cover a lot of Guava concepts — Guava utility classes, functional programming, working with collections, and Event bus.
In this post, you’ll learn about:1. Adding Guava to your Java project.2. Basic utilities in Guava — Splitter, MapSplitter, Joiner, MapJoiner, and Precondition class
Guava comes in two flavors
One for use on a Java 8+ JavaRuntimeEnvironment.Another for use on a Java 7 or Android Platform.
One for use on a Java 8+ JavaRuntimeEnvironment.
Another for use on a Java 7 or Android Platform.
If you’re using Maven, add the following snippet to <dependencies>...</dependencies> section
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>version</version></dependency>
If you’re using Gradle, add mavenCentral() to repositories
repositories { mavenCentral()}
And then add the following snippet to dependencies section of build.gradle file.
dependencies { compile group:'com.google.guava’, name:'guava', version:version}
Check out link for more information on version.
For people who are not using any project management tool like Maven or Gradle —
Download JAR of Google Guava from here.If you’re using IDE, add JAR file as an external library.If you’re using text editor, add JAR file to your class-path.
Download JAR of Google Guava from here.
If you’re using IDE, add JAR file as an external library.
If you’re using text editor, add JAR file to your class-path.
2.1 Joiner ClassIt takes arbitrary strings and concatenate them together with some delimiter token. The result is built by calling Object.toString() for each element.
Typically you’d do something like
public String concatenateStringsWithDelimiter(List<String> strList, String delimiter) { StringBuilder builder = new StringBuilder(); for (String str: strList) if (str != null) builder.append(str).append(delimiter); // To remove the delimiter from the end builder.setLength(builder.length() - delimiter.length()); return builder.toString();}
But with the help of Joiner Class, code equivalent to above can be written as
Joiner.on(delimiter).skipNulls().join(strList);
So as you can see, the code becomes concise and maintainable. Also finding bugs is relatively easy with Guava.Now what if you want to add a replacement for null strings? Well, Joiner class takes care of this situation too.
Joiner.on(delimiter).useForNull(replacement).join(strList);
You might be thinking that maybe Joiner class is limited to working with Strings only but this is not the case. Since it is implemented as Generic class, you could pass an array, iterable or varargs of any object too.Joiner class is immutable once it is created. So, it is thread-safe and can be used as static final variable.
public static final Joiner jnr = Joiner.on(delimiter).skipNulls();String result = jnr.append(strList);
2.2 Joiner.MapJoiner ClassIt works same as the Joiner Class with the only difference that it joins the given string as key-value pair with specified key-value separator.
public void DemoMapJoiner() { // Initialising Guava LinkedHashMap Collection Map<String, String> myMap = Maps.newLinkedHashMap(); myMap.put(“India”, “Hockey”); myMap.put(“England”, “Cricket”); String delimiter = “#”; String separator = “=”; String result = Joiner.on(delimiter).withKeyValueSeperator(separator).join(myMap); String expected = “India=Hocket#England=Cricket”; assertThat(result, expected);}
2.3 Splitter ClassSplitter class does opposite of what Joiner class does. It takes a string with some delimiter (a character, a string or even a regex pattern) and split that string on delimiter and obtain an array of the parts.
Typically you’d do something like
String test = “alpha,beta,gamma,,delta,,”;String[] parts = test.split(“,”);// parts = {“alpha”, “beta”, “gamma”, “”, “delta”, “”};
Can you notice the issue? You don’t want empty strings to be part of my result. So, split() method is leaving something to be desired.
But with the help of Splitter Class, code equivalent to above can be written as
Splitter splitter = Splitter.on(“,”);String[] parts = splitter.split(test);
split() method returns an iterable object containing individual string parts from test string. trimResults() method can be used to remove leading and trailing whitespaces from results.
Just like Joiner class, Splitter class also is immutable once it is created. So, it is thread-safe and can be used as static final variable.
2.4 MapSplitter ClassSplitter class is accompanied by MapSplitter. It takes in a string in which key-value pairs are delimited by some delimiter (a character, a string or even a regex pattern) and returns Map instance with key-value pair in same order as in original string.
public void DemoMapSplitter() { String test = “India=Hocket#England=Cricket”; // Initialising Guava LinkedHashMap Collection Map<String, String> myTestMap = Maps.newLinkedHashMap(); myMap.put(“India”, “Hockey”); myMap.put(“England”, “Cricket”); String delimiter = “#”; String seperator = “=”; Splitter.MapSplitter mapSplitter = Splitter.on(delimiter).withKeyValueSeperator(seperator); Map<String, String> myExpectedMap = mapSplitter.split(test); assertThat(myTestMap, myExpectedMap);}
2.5 Precondition ClassPrecondition class provides collection of static methods to check the state of our code. Preconditions are important because they guarantee out expectations for successful code are met.
For example:1. Checking for null conditions. You can always write
if (testObj == null) throw new IllegalArgumentException(“testObj is null”);
Using Precondition class makes it more concise and easy-to-use
checkNotNull(testObj, “testObj is null”);
2. Checking for valid arguments.
public void demoPrecondition { private int age; public demoPrecondition(int age) { checkArgument(age > 0, “Invalid Age”); this.age = age; }}
checkArgument(exp, msg) evaluates state of variable passed as parameter to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false.
3. Checking state of an object
public void demoPrecondition { private String name; public demoPrecondition(String name) { this.name = checkNotNull(name, “Anonamous”); } public void Capitalize() { checkState(validate(), “Empty Name”); } private bool validate() { this.name.length() > 0; } }
checkState(exp, msg) evaluates state of object not argument passed to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false.
4. Checking valid element index
public void demoPrecondition { int size; private int [] price; public demoPrecondition(int size) { this.size = checkArgument(size > 0, “size must be greater than 0”); this.price = new int[this.size]; } public void updateItem(int index, int value) { int indexToBeUpdated = checkElementIndex(index, this.size, “Illegal Index Access”); } }
Thanks for the read. In the next post, we’ll talk about Functional Programming in Guava. | [
{
"code": null,
"e": 403,
"s": 172,
"text": "It provides utilities for working with Java collections. As you dive deep into Guava you’ll notice how it reduces coding errors, facilitates standard coding practices and boost productivity by making code concise and easy to read."
},
{
"code": null,
"e": 597,
"s": 403,
"text": "I’ve decided to break down the Guava tutorial in a series of posts. We’ll cover a lot of Guava concepts — Guava utility classes, functional programming, working with collections, and Event bus."
},
{
"code": null,
"e": 762,
"s": 597,
"text": "In this post, you’ll learn about:1. Adding Guava to your Java project.2. Basic utilities in Guava — Splitter, MapSplitter, Joiner, MapJoiner, and Precondition class"
},
{
"code": null,
"e": 789,
"s": 762,
"text": "Guava comes in two flavors"
},
{
"code": null,
"e": 886,
"s": 789,
"text": "One for use on a Java 8+ JavaRuntimeEnvironment.Another for use on a Java 7 or Android Platform."
},
{
"code": null,
"e": 935,
"s": 886,
"text": "One for use on a Java 8+ JavaRuntimeEnvironment."
},
{
"code": null,
"e": 984,
"s": 935,
"text": "Another for use on a Java 7 or Android Platform."
},
{
"code": null,
"e": 1077,
"s": 984,
"text": "If you’re using Maven, add the following snippet to <dependencies>...</dependencies> section"
},
{
"code": null,
"e": 1206,
"s": 1077,
"text": "<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>version</version></dependency>"
},
{
"code": null,
"e": 1265,
"s": 1206,
"text": "If you’re using Gradle, add mavenCentral() to repositories"
},
{
"code": null,
"e": 1299,
"s": 1265,
"text": "repositories { mavenCentral()}"
},
{
"code": null,
"e": 1380,
"s": 1299,
"text": "And then add the following snippet to dependencies section of build.gradle file."
},
{
"code": null,
"e": 1463,
"s": 1380,
"text": "dependencies { compile group:'com.google.guava’, name:'guava', version:version}"
},
{
"code": null,
"e": 1511,
"s": 1463,
"text": "Check out link for more information on version."
},
{
"code": null,
"e": 1591,
"s": 1511,
"text": "For people who are not using any project management tool like Maven or Gradle —"
},
{
"code": null,
"e": 1749,
"s": 1591,
"text": "Download JAR of Google Guava from here.If you’re using IDE, add JAR file as an external library.If you’re using text editor, add JAR file to your class-path."
},
{
"code": null,
"e": 1789,
"s": 1749,
"text": "Download JAR of Google Guava from here."
},
{
"code": null,
"e": 1847,
"s": 1789,
"text": "If you’re using IDE, add JAR file as an external library."
},
{
"code": null,
"e": 1909,
"s": 1847,
"text": "If you’re using text editor, add JAR file to your class-path."
},
{
"code": null,
"e": 2076,
"s": 1909,
"text": "2.1 Joiner ClassIt takes arbitrary strings and concatenate them together with some delimiter token. The result is built by calling Object.toString() for each element."
},
{
"code": null,
"e": 2110,
"s": 2076,
"text": "Typically you’d do something like"
},
{
"code": null,
"e": 2486,
"s": 2110,
"text": "public String concatenateStringsWithDelimiter(List<String> strList, String delimiter) { StringBuilder builder = new StringBuilder(); for (String str: strList) if (str != null) builder.append(str).append(delimiter); // To remove the delimiter from the end builder.setLength(builder.length() - delimiter.length()); return builder.toString();}"
},
{
"code": null,
"e": 2564,
"s": 2486,
"text": "But with the help of Joiner Class, code equivalent to above can be written as"
},
{
"code": null,
"e": 2612,
"s": 2564,
"text": "Joiner.on(delimiter).skipNulls().join(strList);"
},
{
"code": null,
"e": 2835,
"s": 2612,
"text": "So as you can see, the code becomes concise and maintainable. Also finding bugs is relatively easy with Guava.Now what if you want to add a replacement for null strings? Well, Joiner class takes care of this situation too."
},
{
"code": null,
"e": 2895,
"s": 2835,
"text": "Joiner.on(delimiter).useForNull(replacement).join(strList);"
},
{
"code": null,
"e": 3222,
"s": 2895,
"text": "You might be thinking that maybe Joiner class is limited to working with Strings only but this is not the case. Since it is implemented as Generic class, you could pass an array, iterable or varargs of any object too.Joiner class is immutable once it is created. So, it is thread-safe and can be used as static final variable."
},
{
"code": null,
"e": 3325,
"s": 3222,
"text": "public static final Joiner jnr = Joiner.on(delimiter).skipNulls();String result = jnr.append(strList);"
},
{
"code": null,
"e": 3495,
"s": 3325,
"text": "2.2 Joiner.MapJoiner ClassIt works same as the Joiner Class with the only difference that it joins the given string as key-value pair with specified key-value separator."
},
{
"code": null,
"e": 3927,
"s": 3495,
"text": "public void DemoMapJoiner() { // Initialising Guava LinkedHashMap Collection Map<String, String> myMap = Maps.newLinkedHashMap(); myMap.put(“India”, “Hockey”); myMap.put(“England”, “Cricket”); String delimiter = “#”; String separator = “=”; String result = Joiner.on(delimiter).withKeyValueSeperator(separator).join(myMap); String expected = “India=Hocket#England=Cricket”; assertThat(result, expected);}"
},
{
"code": null,
"e": 4156,
"s": 3927,
"text": "2.3 Splitter ClassSplitter class does opposite of what Joiner class does. It takes a string with some delimiter (a character, a string or even a regex pattern) and split that string on delimiter and obtain an array of the parts."
},
{
"code": null,
"e": 4190,
"s": 4156,
"text": "Typically you’d do something like"
},
{
"code": null,
"e": 4321,
"s": 4190,
"text": "String test = “alpha,beta,gamma,,delta,,”;String[] parts = test.split(“,”);// parts = {“alpha”, “beta”, “gamma”, “”, “delta”, “”};"
},
{
"code": null,
"e": 4456,
"s": 4321,
"text": "Can you notice the issue? You don’t want empty strings to be part of my result. So, split() method is leaving something to be desired."
},
{
"code": null,
"e": 4536,
"s": 4456,
"text": "But with the help of Splitter Class, code equivalent to above can be written as"
},
{
"code": null,
"e": 4612,
"s": 4536,
"text": "Splitter splitter = Splitter.on(“,”);String[] parts = splitter.split(test);"
},
{
"code": null,
"e": 4797,
"s": 4612,
"text": "split() method returns an iterable object containing individual string parts from test string. trimResults() method can be used to remove leading and trailing whitespaces from results."
},
{
"code": null,
"e": 4938,
"s": 4797,
"text": "Just like Joiner class, Splitter class also is immutable once it is created. So, it is thread-safe and can be used as static final variable."
},
{
"code": null,
"e": 5213,
"s": 4938,
"text": "2.4 MapSplitter ClassSplitter class is accompanied by MapSplitter. It takes in a string in which key-value pairs are delimited by some delimiter (a character, a string or even a regex pattern) and returns Map instance with key-value pair in same order as in original string."
},
{
"code": null,
"e": 5729,
"s": 5213,
"text": "public void DemoMapSplitter() { String test = “India=Hocket#England=Cricket”; // Initialising Guava LinkedHashMap Collection Map<String, String> myTestMap = Maps.newLinkedHashMap(); myMap.put(“India”, “Hockey”); myMap.put(“England”, “Cricket”); String delimiter = “#”; String seperator = “=”; Splitter.MapSplitter mapSplitter = Splitter.on(delimiter).withKeyValueSeperator(seperator); Map<String, String> myExpectedMap = mapSplitter.split(test); assertThat(myTestMap, myExpectedMap);}"
},
{
"code": null,
"e": 5937,
"s": 5729,
"text": "2.5 Precondition ClassPrecondition class provides collection of static methods to check the state of our code. Preconditions are important because they guarantee out expectations for successful code are met."
},
{
"code": null,
"e": 6003,
"s": 5937,
"text": "For example:1. Checking for null conditions. You can always write"
},
{
"code": null,
"e": 6086,
"s": 6003,
"text": "if (testObj == null) throw new IllegalArgumentException(“testObj is null”);"
},
{
"code": null,
"e": 6149,
"s": 6086,
"text": "Using Precondition class makes it more concise and easy-to-use"
},
{
"code": null,
"e": 6191,
"s": 6149,
"text": "checkNotNull(testObj, “testObj is null”);"
},
{
"code": null,
"e": 6224,
"s": 6191,
"text": "2. Checking for valid arguments."
},
{
"code": null,
"e": 6384,
"s": 6224,
"text": "public void demoPrecondition { private int age; public demoPrecondition(int age) { checkArgument(age > 0, “Invalid Age”); this.age = age; }}"
},
{
"code": null,
"e": 6577,
"s": 6384,
"text": "checkArgument(exp, msg) evaluates state of variable passed as parameter to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false."
},
{
"code": null,
"e": 6608,
"s": 6577,
"text": "3. Checking state of an object"
},
{
"code": null,
"e": 6946,
"s": 6608,
"text": "public void demoPrecondition { private String name; public demoPrecondition(String name) { this.name = checkNotNull(name, “Anonamous”); } public void Capitalize() { checkState(validate(), “Empty Name”); } private bool validate() { this.name.length() > 0; } }"
},
{
"code": null,
"e": 7134,
"s": 6946,
"text": "checkState(exp, msg) evaluates state of object not argument passed to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false."
},
{
"code": null,
"e": 7166,
"s": 7134,
"text": "4. Checking valid element index"
},
{
"code": null,
"e": 7588,
"s": 7166,
"text": "public void demoPrecondition { int size; private int [] price; public demoPrecondition(int size) { this.size = checkArgument(size > 0, “size must be greater than 0”); this.price = new int[this.size]; } public void updateItem(int index, int value) { int indexToBeUpdated = checkElementIndex(index, this.size, “Illegal Index Access”); } }"
}
] |
Dart Programming - Async | An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.
Let’s take an example to understand this concept. Here, the program accepts user input using the IO library.
import 'dart:io';
void main() {
print("Enter your name :");
// prompt for user input
String name = stdin.readLineSync();
// this is a synchronous method that reads user input
print("Hello Mr. ${name}");
print("End of main");
}
The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution.
The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input.
The above example will result in the following output −
Enter your name :
Tom
// reads user input
Hello Mr. Tom
End of main
In computing, we say something is synchronous when it waits for an event to happen before continuing. A disadvantage in this approach is that if a part of the code takes too long to execute, the subsequent blocks, though unrelated, will be blocked from executing. Consider a webserver that must respond to multiple requests for a resource.
A synchronous execution model will block every other user’s request till it finishes processing the current request. In such a case, like that of a web server, every request must be independent of the others. This means, the webserver should not wait for the current request to finish executing before it responds to request from other users.
Simply put, it should accept requests from new users before necessarily completing the requests of previous users. This is termed as asynchronous. Asynchronous programming basically means no waiting or non-blocking programming model. The dart:async package facilitates implementing asynchronous programming blocks in a Dart script.
The following example better illustrates the functioning of an asynchronous block.
Step 1 − Create a contact.txt file as given below and save it in the data folder in the current project.
1, Tom
2, John
3, Tim
4, Jane
Step 2 − Write a program which will read the file without blocking other parts of the application.
import "dart:async";
import "dart:io";
void main(){
File file = new File( Directory.current.path+"\\data\\contact.txt");
Future<String> f = file.readAsString();
// returns a futrue, this is Async method
f.then((data)=>print(data));
// once file is read , call back method is invoked
print("End of main");
// this get printed first, showing fileReading is non blocking or async
}
The output of this program will be as follows −
End of main
1, Tom
2, John
3, Tim
4, Jan
The "end of main" executes first while the script continues reading the file. The Future class, part of dart:async, is used for getting the result of a computation after an asynchronous task has completed. This Future value is then used to do something after the computation finishes.
Once the read operation is completed, the execution control is transferred within "then()". This is because the reading operation can take more time and so it doesn’t want to block other part of program.
The Dart community defines a Future as "a means for getting a value sometime in the future." Simply put, Future objects are a mechanism to represent values returned by an expression whose execution will complete at a later point in time. Several of Dart’s built-in classes return a Future when an asynchronous method is called.
Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes.
Asynchronous operations let your program run without getting blocked. Dart uses Future objects to represent asynchronous operations.
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2779,
"s": 2525,
"text": "An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task."
},
{
"code": null,
"e": 2888,
"s": 2779,
"text": "Let’s take an example to understand this concept. Here, the program accepts user input using the IO library."
},
{
"code": null,
"e": 3162,
"s": 2888,
"text": "import 'dart:io'; \nvoid main() { \n print(\"Enter your name :\"); \n \n // prompt for user input \n String name = stdin.readLineSync(); \n \n // this is a synchronous method that reads user input \n print(\"Hello Mr. ${name}\"); \n print(\"End of main\"); \n} "
},
{
"code": null,
"e": 3368,
"s": 3162,
"text": "The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution."
},
{
"code": null,
"e": 3500,
"s": 3368,
"text": "The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input."
},
{
"code": null,
"e": 3556,
"s": 3500,
"text": "The above example will result in the following output −"
},
{
"code": null,
"e": 3653,
"s": 3556,
"text": "Enter your name : \nTom \n\n// reads user input \nHello Mr. Tom \nEnd of main\n"
},
{
"code": null,
"e": 3994,
"s": 3653,
"text": "In computing, we say something is synchronous when it waits for an event to happen before continuing. A disadvantage in this approach is that if a part of the code takes too long to execute, the subsequent blocks, though unrelated, will be blocked from executing. Consider a webserver that must respond to multiple requests for a resource."
},
{
"code": null,
"e": 4337,
"s": 3994,
"text": "A synchronous execution model will block every other user’s request till it finishes processing the current request. In such a case, like that of a web server, every request must be independent of the others. This means, the webserver should not wait for the current request to finish executing before it responds to request from other users."
},
{
"code": null,
"e": 4670,
"s": 4337,
"text": "Simply put, it should accept requests from new users before necessarily completing the requests of previous users. This is termed as asynchronous. Asynchronous programming basically means no waiting or non-blocking programming model. The dart:async package facilitates implementing asynchronous programming blocks in a Dart script."
},
{
"code": null,
"e": 4753,
"s": 4670,
"text": "The following example better illustrates the functioning of an asynchronous block."
},
{
"code": null,
"e": 4858,
"s": 4753,
"text": "Step 1 − Create a contact.txt file as given below and save it in the data folder in the current project."
},
{
"code": null,
"e": 4893,
"s": 4858,
"text": "1, Tom \n2, John \n3, Tim \n4, Jane \n"
},
{
"code": null,
"e": 4992,
"s": 4893,
"text": "Step 2 − Write a program which will read the file without blocking other parts of the application."
},
{
"code": null,
"e": 5415,
"s": 4992,
"text": "import \"dart:async\"; \nimport \"dart:io\"; \n\nvoid main(){ \n File file = new File( Directory.current.path+\"\\\\data\\\\contact.txt\"); \n Future<String> f = file.readAsString(); \n \n // returns a futrue, this is Async method \n f.then((data)=>print(data)); \n \n // once file is read , call back method is invoked \n print(\"End of main\"); \n // this get printed first, showing fileReading is non blocking or async \n}"
},
{
"code": null,
"e": 5463,
"s": 5415,
"text": "The output of this program will be as follows −"
},
{
"code": null,
"e": 5509,
"s": 5463,
"text": "End of main \n1, Tom \n2, John \n3, Tim \n4, Jan\n"
},
{
"code": null,
"e": 5794,
"s": 5509,
"text": "The \"end of main\" executes first while the script continues reading the file. The Future class, part of dart:async, is used for getting the result of a computation after an asynchronous task has completed. This Future value is then used to do something after the computation finishes."
},
{
"code": null,
"e": 5998,
"s": 5794,
"text": "Once the read operation is completed, the execution control is transferred within \"then()\". This is because the reading operation can take more time and so it doesn’t want to block other part of program."
},
{
"code": null,
"e": 6326,
"s": 5998,
"text": "The Dart community defines a Future as \"a means for getting a value sometime in the future.\" Simply put, Future objects are a mechanism to represent values returned by an expression whose execution will complete at a later point in time. Several of Dart’s built-in classes return a Future when an asynchronous method is called."
},
{
"code": null,
"e": 6527,
"s": 6326,
"text": "Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes."
},
{
"code": null,
"e": 6660,
"s": 6527,
"text": "Asynchronous operations let your program run without getting blocked. Dart uses Future objects to represent asynchronous operations."
},
{
"code": null,
"e": 6695,
"s": 6660,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6715,
"s": 6695,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 6748,
"s": 6715,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6768,
"s": 6748,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 6801,
"s": 6768,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6818,
"s": 6801,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6853,
"s": 6818,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6870,
"s": 6853,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6905,
"s": 6870,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6925,
"s": 6905,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6958,
"s": 6925,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6978,
"s": 6958,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6985,
"s": 6978,
"text": " Print"
},
{
"code": null,
"e": 6996,
"s": 6985,
"text": " Add Notes"
}
] |
Simulating Text With Markov Chains in Python | by b | Towards Data Science | In my last post, I introduced Markov chains in the context of Markov chain Monte Carlo methods. This post is a small addendum to that one, demonstrating one fun thing you can do with Markov chains: simulate text.
A Markov chain is a simulated sequence of events. Each event in the sequence comes from a set of outcomes that depend on one another. In particular, each outcome determines which outcomes are likely to occur next. In a Markov chain, all of the information needed to predict the next event is contained in the most recent event. That means that knowing the full history of a Markov chain doesn’t help you predict the next outcome any better than only knowing what the last outcome was.
Markov chains aren’t generally reliable predictors of events in the near term, since most processes in the real world are more complex than Markov chains allow. Markov chains are, however, used to examine the long-run behavior of a series of events that are related to one another by fixed probabilities.
For any sequence of non-independent events in the world, and where a limited number of outcomes can occur, conditional probabilities can be computed relating each outcome to one another. Often this simply takes the form of counting how often certain outcomes follow one another in an observed sequence.
To generate a simulation based on a certain text, count up every word that is used. Then, for every word, store the words that are used next. This is the distribution of words in that text conditional on the preceding word.
In order to simulate some text from Donald Trump, let’s use a collection of his speeches from the 2016 campaign available here.
First import numpy and the text file containing Trump’s speeches:
import numpy as nptrump = open('speeches.txt', encoding='utf8').read()
Then, split the text file into single words. Note we’re keeping all the punctuation in, so our simulated text has punctuation:
corpus = trump.split()
Then, we define a function to give us all the pairs of words in the speeches. We’re using lazy evaluation, and yielding a generator object instead of actually filling up our memory with every pair of words:
def make_pairs(corpus): for i in range(len(corpus)-1): yield (corpus[i], corpus[i+1]) pairs = make_pairs(corpus)
Then we instantiate an empty dictionary, and fill it words from our pairs. If the first word of the pair is already a key in the dictionary, simply append the next word to the list of words that follow that word. Otherwise, initialize a new entry in the dictionary with the key equal to the first word and the value a list of length one:
word_dict = {}for word_1, word_2 in pairs: if word_1 in word_dict.keys(): word_dict[word_1].append(word_2) else: word_dict[word_1] = [word_2]
Finally we pick some random word to kick off the chain, and choose the number of words we want to simulate:
first_word = np.random.choice(corpus)chain = [first_word]n_words = 30
After the first word, every word in the chain is sampled randomly from the list of words which have followed that word in Trump’s actual speeches:
for i in range(n_words): chain.append(np.random.choice(word_dict[chain[-1]]))
The final join command returns the chain as a string:
' '.join(chain)
When I run this code, my first result is:
'I will be able to vote. Got them back. We’re going to make a total lie, proven out right after. "During the opposite. We have some turnout. My patients are really'
The nice thing here is that we’re using a dictionary to actually look up the next word in the chain. Of course, you can wrap this all up in a function, which I leave as an exercise to the reader.
There are a lot of tools are there to ‘Markovify’ text, and I encourage you to look them up. But for someone just learning Markov chains, the code here is an easy place to start. But there are endless possibilities for improvement. For example, you might require the first word to be capitalized, so your text doesn’t begin mid-sentence:
while first_word.islower(): first_word = np.random.choice(corpus)
I hope this is helpful for those of you getting started in the wide world of Markov chains. If this code can be improved without sacrificing clarity, leave a comment! | [
{
"code": null,
"e": 385,
"s": 172,
"text": "In my last post, I introduced Markov chains in the context of Markov chain Monte Carlo methods. This post is a small addendum to that one, demonstrating one fun thing you can do with Markov chains: simulate text."
},
{
"code": null,
"e": 870,
"s": 385,
"text": "A Markov chain is a simulated sequence of events. Each event in the sequence comes from a set of outcomes that depend on one another. In particular, each outcome determines which outcomes are likely to occur next. In a Markov chain, all of the information needed to predict the next event is contained in the most recent event. That means that knowing the full history of a Markov chain doesn’t help you predict the next outcome any better than only knowing what the last outcome was."
},
{
"code": null,
"e": 1175,
"s": 870,
"text": "Markov chains aren’t generally reliable predictors of events in the near term, since most processes in the real world are more complex than Markov chains allow. Markov chains are, however, used to examine the long-run behavior of a series of events that are related to one another by fixed probabilities."
},
{
"code": null,
"e": 1478,
"s": 1175,
"text": "For any sequence of non-independent events in the world, and where a limited number of outcomes can occur, conditional probabilities can be computed relating each outcome to one another. Often this simply takes the form of counting how often certain outcomes follow one another in an observed sequence."
},
{
"code": null,
"e": 1702,
"s": 1478,
"text": "To generate a simulation based on a certain text, count up every word that is used. Then, for every word, store the words that are used next. This is the distribution of words in that text conditional on the preceding word."
},
{
"code": null,
"e": 1830,
"s": 1702,
"text": "In order to simulate some text from Donald Trump, let’s use a collection of his speeches from the 2016 campaign available here."
},
{
"code": null,
"e": 1896,
"s": 1830,
"text": "First import numpy and the text file containing Trump’s speeches:"
},
{
"code": null,
"e": 1967,
"s": 1896,
"text": "import numpy as nptrump = open('speeches.txt', encoding='utf8').read()"
},
{
"code": null,
"e": 2094,
"s": 1967,
"text": "Then, split the text file into single words. Note we’re keeping all the punctuation in, so our simulated text has punctuation:"
},
{
"code": null,
"e": 2117,
"s": 2094,
"text": "corpus = trump.split()"
},
{
"code": null,
"e": 2324,
"s": 2117,
"text": "Then, we define a function to give us all the pairs of words in the speeches. We’re using lazy evaluation, and yielding a generator object instead of actually filling up our memory with every pair of words:"
},
{
"code": null,
"e": 2454,
"s": 2324,
"text": "def make_pairs(corpus): for i in range(len(corpus)-1): yield (corpus[i], corpus[i+1]) pairs = make_pairs(corpus)"
},
{
"code": null,
"e": 2792,
"s": 2454,
"text": "Then we instantiate an empty dictionary, and fill it words from our pairs. If the first word of the pair is already a key in the dictionary, simply append the next word to the list of words that follow that word. Otherwise, initialize a new entry in the dictionary with the key equal to the first word and the value a list of length one:"
},
{
"code": null,
"e": 2954,
"s": 2792,
"text": "word_dict = {}for word_1, word_2 in pairs: if word_1 in word_dict.keys(): word_dict[word_1].append(word_2) else: word_dict[word_1] = [word_2]"
},
{
"code": null,
"e": 3062,
"s": 2954,
"text": "Finally we pick some random word to kick off the chain, and choose the number of words we want to simulate:"
},
{
"code": null,
"e": 3132,
"s": 3062,
"text": "first_word = np.random.choice(corpus)chain = [first_word]n_words = 30"
},
{
"code": null,
"e": 3279,
"s": 3132,
"text": "After the first word, every word in the chain is sampled randomly from the list of words which have followed that word in Trump’s actual speeches:"
},
{
"code": null,
"e": 3360,
"s": 3279,
"text": "for i in range(n_words): chain.append(np.random.choice(word_dict[chain[-1]]))"
},
{
"code": null,
"e": 3414,
"s": 3360,
"text": "The final join command returns the chain as a string:"
},
{
"code": null,
"e": 3430,
"s": 3414,
"text": "' '.join(chain)"
},
{
"code": null,
"e": 3472,
"s": 3430,
"text": "When I run this code, my first result is:"
},
{
"code": null,
"e": 3637,
"s": 3472,
"text": "'I will be able to vote. Got them back. We’re going to make a total lie, proven out right after. \"During the opposite. We have some turnout. My patients are really'"
},
{
"code": null,
"e": 3833,
"s": 3637,
"text": "The nice thing here is that we’re using a dictionary to actually look up the next word in the chain. Of course, you can wrap this all up in a function, which I leave as an exercise to the reader."
},
{
"code": null,
"e": 4171,
"s": 3833,
"text": "There are a lot of tools are there to ‘Markovify’ text, and I encourage you to look them up. But for someone just learning Markov chains, the code here is an easy place to start. But there are endless possibilities for improvement. For example, you might require the first word to be capitalized, so your text doesn’t begin mid-sentence:"
},
{
"code": null,
"e": 4240,
"s": 4171,
"text": "while first_word.islower(): first_word = np.random.choice(corpus)"
}
] |
AWK - Basic Examples | This chapter describes several useful AWK commands and their appropriate examples. Consider a text file marks.txt to be processed with the following content −
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
You can instruct AWK to print only certain columns from the input field. The following example demonstrates this −
[jerry]$ awk '{print $3 "\t" $4}' marks.txt
On executing this code, you get the following result −
Physics 80
Maths 90
Biology 87
English 85
History 89
In the file marks.txt, the third column contains the subject name and the fourth column contains the marks obtained in a particular subject. Let us print these two columns using AWK print command. In the above example, $3 and $4 represent the third and the fourth fields respectively from the input record.
By default, AWK prints all the lines that match pattern.
[jerry]$ awk '/a/ {print $0}' marks.txt
On executing this code, you get the following result −
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
In the above example, we are searching form pattern a. When a pattern match succeeds, it executes a command from the body block. In the absence of a body block − default action is taken which is print the record. Hence, the following command produces the same result −
[jerry]$ awk '/a/' marks.txt
When a pattern match succeeds, AWK prints the entire record by default. But you can instruct AWK to print only certain fields. For instance, the following example prints the third and fourth field when a pattern match succeeds.
[jerry]$ awk '/a/ {print $3 "\t" $4}' marks.txt
On executing this code, you get the following result −
Maths 90
Biology 87
English 85
History 89
You can print columns in any order. For instance, the following example prints the fourth column followed by the third column.
[jerry]$ awk '/a/ {print $4 "\t" $3}' marks.txt
On executing the above code, you get the following result −
90 Maths
87 Biology
85 English
89 History
Let us see an example where you can count and print the number of lines for which a pattern match succeeded.
[jerry]$ awk '/a/{++cnt} END {print "Count = ", cnt}' marks.txt
On executing this code, you get the following result −
Count = 4
In this example, we increment the value of counter when a pattern match succeeds and we print this value in the END block. Note that unlike other programming languages, there is no need to declare a variable before using it.
Let us print only those lines that contain more than 18 characters.
[jerry]$ awk 'length($0) > 18' marks.txt
On executing this code, you get the following result −
3) Shyam Biology 87
4) Kedar English 85
AWK provides a built-in length function that returns the length of the string. $0 variable stores the entire line and in the absence of a body block, default action is taken, i.e., the print action. Hence, if a line has more than 18 characters, then the comparison results true and the line gets printed.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2016,
"s": 1857,
"text": "This chapter describes several useful AWK commands and their appropriate examples. Consider a text file marks.txt to be processed with the following content −"
},
{
"code": null,
"e": 2142,
"s": 2016,
"text": "1) Amit Physics 80\n2) Rahul Maths 90\n3) Shyam Biology 87\n4) Kedar English 85\n5) Hari History 89\n"
},
{
"code": null,
"e": 2257,
"s": 2142,
"text": "You can instruct AWK to print only certain columns from the input field. The following example demonstrates this −"
},
{
"code": null,
"e": 2301,
"s": 2257,
"text": "[jerry]$ awk '{print $3 \"\\t\" $4}' marks.txt"
},
{
"code": null,
"e": 2356,
"s": 2301,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2422,
"s": 2356,
"text": "Physics 80\nMaths 90\nBiology 87\nEnglish 85\nHistory 89\n"
},
{
"code": null,
"e": 2729,
"s": 2422,
"text": "In the file marks.txt, the third column contains the subject name and the fourth column contains the marks obtained in a particular subject. Let us print these two columns using AWK print command. In the above example, $3 and $4 represent the third and the fourth fields respectively from the input record."
},
{
"code": null,
"e": 2786,
"s": 2729,
"text": "By default, AWK prints all the lines that match pattern."
},
{
"code": null,
"e": 2826,
"s": 2786,
"text": "[jerry]$ awk '/a/ {print $0}' marks.txt"
},
{
"code": null,
"e": 2881,
"s": 2826,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2982,
"s": 2881,
"text": "2) Rahul Maths 90\n3) Shyam Biology 87\n4) Kedar English 85\n5) Hari History 89\n"
},
{
"code": null,
"e": 3251,
"s": 2982,
"text": "In the above example, we are searching form pattern a. When a pattern match succeeds, it executes a command from the body block. In the absence of a body block − default action is taken which is print the record. Hence, the following command produces the same result −"
},
{
"code": null,
"e": 3280,
"s": 3251,
"text": "[jerry]$ awk '/a/' marks.txt"
},
{
"code": null,
"e": 3508,
"s": 3280,
"text": "When a pattern match succeeds, AWK prints the entire record by default. But you can instruct AWK to print only certain fields. For instance, the following example prints the third and fourth field when a pattern match succeeds."
},
{
"code": null,
"e": 3556,
"s": 3508,
"text": "[jerry]$ awk '/a/ {print $3 \"\\t\" $4}' marks.txt"
},
{
"code": null,
"e": 3611,
"s": 3556,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3660,
"s": 3611,
"text": "Maths 90\nBiology 87\nEnglish 85\nHistory 89\n"
},
{
"code": null,
"e": 3787,
"s": 3660,
"text": "You can print columns in any order. For instance, the following example prints the fourth column followed by the third column."
},
{
"code": null,
"e": 3835,
"s": 3787,
"text": "[jerry]$ awk '/a/ {print $4 \"\\t\" $3}' marks.txt"
},
{
"code": null,
"e": 3895,
"s": 3835,
"text": "On executing the above code, you get the following result −"
},
{
"code": null,
"e": 3946,
"s": 3895,
"text": "90 Maths\n87 Biology\n85 English\n89 History\n"
},
{
"code": null,
"e": 4055,
"s": 3946,
"text": "Let us see an example where you can count and print the number of lines for which a pattern match succeeded."
},
{
"code": null,
"e": 4119,
"s": 4055,
"text": "[jerry]$ awk '/a/{++cnt} END {print \"Count = \", cnt}' marks.txt"
},
{
"code": null,
"e": 4174,
"s": 4119,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4185,
"s": 4174,
"text": "Count = 4\n"
},
{
"code": null,
"e": 4410,
"s": 4185,
"text": "In this example, we increment the value of counter when a pattern match succeeds and we print this value in the END block. Note that unlike other programming languages, there is no need to declare a variable before using it."
},
{
"code": null,
"e": 4478,
"s": 4410,
"text": "Let us print only those lines that contain more than 18 characters."
},
{
"code": null,
"e": 4519,
"s": 4478,
"text": "[jerry]$ awk 'length($0) > 18' marks.txt"
},
{
"code": null,
"e": 4574,
"s": 4519,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4623,
"s": 4574,
"text": "3) Shyam Biology 87\n4) Kedar English 85\n"
},
{
"code": null,
"e": 4929,
"s": 4623,
"text": "AWK provides a built-in length function that returns the length of the string. $0 variable stores the entire line and in the absence of a body block, default action is taken, i.e., the print action. Hence, if a line has more than 18 characters, then the comparison results true and the line gets printed."
},
{
"code": null,
"e": 4936,
"s": 4929,
"text": " Print"
},
{
"code": null,
"e": 4947,
"s": 4936,
"text": " Add Notes"
}
] |
Customize your Jupyter Notebook Theme in 2 lines of code | by Satyam Kumar | Towards Data Science | The interface themes define the appearance of the windows, buttons, toolbar, cells, and all visual elements of the user interface. By default, Jupyter Notebook uses the light theme. Some of the programmers or data scientists like to use some dark themes or other themes on different platform such as PyCharm, Spyder, etc.
Jupyter Notebook does not come up with an inbuilt option to change the theme of the notebook. In this article, you can read how to change the theme of your jupyter notebook, enable/disable toolbars, and customize your notebook according to your need.
Jupyter themes is an open-source library developed by Kyle Dunovan used to change themes, plotting style, fonts in the jupyter notebook. You can install Jupiter themes using pip:
# install jupyterthemespip install jupyterthemes# upgrade to latest versionpip install --upgrade jupyterthemes
By default, Jupyter Notebook uses a light theme as mentioned in the below image. Notebook themes are customizable along with toolbars, text and code fonts, and other elements of the user interface. To view the list of available themes in jupyterthemes package use command line usage !jt -l:
Command-line statement to change the theme of the notebook:
!jt -t [theme name]
To restore the default theme of the notebook, run the command line statement as !jt -r
When the theme of the notebook is changed to the above-mentioned themes, the toolbar, filename, kernel logo, is hidden by default. You can enable these options by changing the command line statement.
Enable the toolbar: !jt -t [theme name] -T
Enable the filename and logo: !jt -t [theme name] -N
Enable the kernel logo: !jt -t [theme name] -kl
To change the theme and enable the toolbar, filename, logo, kernel logo in same command line statement: !jt -t [theme name] -T -N -kl
Jupyter themes provide features to change code font, code font size, notebook font, notebook font size, pandas data frame font size, etc.
Command Line Usage: !jt [arg] [FONT or FONTSIZE]
!jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-altmd] [-altout] [-P] [-T] [-N] [-r] [-dfonts]
jtplot.style() makes changes to matplotlib library rcParams dictionary so that figure aesthetics match with the chosen jupyter themes. In addition to setting the color scheme, jtplot.style() allows controlling various figure properties such as spines, grid, font scale, etc. as well as the plotting "context".
Note:jtplot style commands need to run just once in the notebook, not every time before generating the plot
Jupyter themes library is used to customize the visual elements of the user interface. It can be used to modify plots created through matplotlib. With the jupyterthemes library, you can take your visualization to the next level.
[1] Jupyter Themes GitHub repo: https://github.com/dunovank/jupyter-themes
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you.
satyam-kumar.medium.com
Thank You for Reading | [
{
"code": null,
"e": 494,
"s": 172,
"text": "The interface themes define the appearance of the windows, buttons, toolbar, cells, and all visual elements of the user interface. By default, Jupyter Notebook uses the light theme. Some of the programmers or data scientists like to use some dark themes or other themes on different platform such as PyCharm, Spyder, etc."
},
{
"code": null,
"e": 745,
"s": 494,
"text": "Jupyter Notebook does not come up with an inbuilt option to change the theme of the notebook. In this article, you can read how to change the theme of your jupyter notebook, enable/disable toolbars, and customize your notebook according to your need."
},
{
"code": null,
"e": 924,
"s": 745,
"text": "Jupyter themes is an open-source library developed by Kyle Dunovan used to change themes, plotting style, fonts in the jupyter notebook. You can install Jupiter themes using pip:"
},
{
"code": null,
"e": 1035,
"s": 924,
"text": "# install jupyterthemespip install jupyterthemes# upgrade to latest versionpip install --upgrade jupyterthemes"
},
{
"code": null,
"e": 1326,
"s": 1035,
"text": "By default, Jupyter Notebook uses a light theme as mentioned in the below image. Notebook themes are customizable along with toolbars, text and code fonts, and other elements of the user interface. To view the list of available themes in jupyterthemes package use command line usage !jt -l:"
},
{
"code": null,
"e": 1386,
"s": 1326,
"text": "Command-line statement to change the theme of the notebook:"
},
{
"code": null,
"e": 1406,
"s": 1386,
"text": "!jt -t [theme name]"
},
{
"code": null,
"e": 1493,
"s": 1406,
"text": "To restore the default theme of the notebook, run the command line statement as !jt -r"
},
{
"code": null,
"e": 1693,
"s": 1493,
"text": "When the theme of the notebook is changed to the above-mentioned themes, the toolbar, filename, kernel logo, is hidden by default. You can enable these options by changing the command line statement."
},
{
"code": null,
"e": 1736,
"s": 1693,
"text": "Enable the toolbar: !jt -t [theme name] -T"
},
{
"code": null,
"e": 1789,
"s": 1736,
"text": "Enable the filename and logo: !jt -t [theme name] -N"
},
{
"code": null,
"e": 1837,
"s": 1789,
"text": "Enable the kernel logo: !jt -t [theme name] -kl"
},
{
"code": null,
"e": 1971,
"s": 1837,
"text": "To change the theme and enable the toolbar, filename, logo, kernel logo in same command line statement: !jt -t [theme name] -T -N -kl"
},
{
"code": null,
"e": 2109,
"s": 1971,
"text": "Jupyter themes provide features to change code font, code font size, notebook font, notebook font size, pandas data frame font size, etc."
},
{
"code": null,
"e": 2158,
"s": 2109,
"text": "Command Line Usage: !jt [arg] [FONT or FONTSIZE]"
},
{
"code": null,
"e": 2469,
"s": 2158,
"text": "!jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE] [-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim] [-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-altmd] [-altout] [-P] [-T] [-N] [-r] [-dfonts]"
},
{
"code": null,
"e": 2779,
"s": 2469,
"text": "jtplot.style() makes changes to matplotlib library rcParams dictionary so that figure aesthetics match with the chosen jupyter themes. In addition to setting the color scheme, jtplot.style() allows controlling various figure properties such as spines, grid, font scale, etc. as well as the plotting \"context\"."
},
{
"code": null,
"e": 2887,
"s": 2779,
"text": "Note:jtplot style commands need to run just once in the notebook, not every time before generating the plot"
},
{
"code": null,
"e": 3116,
"s": 2887,
"text": "Jupyter themes library is used to customize the visual elements of the user interface. It can be used to modify plots created through matplotlib. With the jupyterthemes library, you can take your visualization to the next level."
},
{
"code": null,
"e": 3191,
"s": 3116,
"text": "[1] Jupyter Themes GitHub repo: https://github.com/dunovank/jupyter-themes"
},
{
"code": null,
"e": 3380,
"s": 3191,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 3404,
"s": 3380,
"text": "satyam-kumar.medium.com"
}
] |
Format date with DateFormat.SHORT in Java | DateFormat.SHORT is a constant for short style pattern.
Firstly, we will create date object
Date dt = new Date();
DateFormat dateFormat;
Let us format date for different locale with DateFormat.SHORT
// FRENCH
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);
// GERMANY
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
The following is an example −
Live Demo
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Demo {
public static void main(String args[]) {
Date dt = new Date();
DateFormat dateFormat;
// Date Format SHORT constant
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);
System.out.println("Locale FRENCH = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
System.out.println("Locale GERMANY = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINESE);
System.out.println("Locale CHINESE = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CANADA);
System.out.println("Locale CANADA = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ITALY);
System.out.println("Locale ITALY = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.TAIWAN);
System.out.println("Locale TAIWAN = " + dateFormat.format(dt));
}
}
Locale FRENCH = 22/11/18
Locale GERMANY = 22.11.18
Locale CHINESE = 18-11-22
Locale CANADA = 22/11/18
Locale ITALY = 22/11/18
Locale TAIWAN = 2018/11/22 | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "DateFormat.SHORT is a constant for short style pattern."
},
{
"code": null,
"e": 1154,
"s": 1118,
"text": "Firstly, we will create date object"
},
{
"code": null,
"e": 1199,
"s": 1154,
"text": "Date dt = new Date();\nDateFormat dateFormat;"
},
{
"code": null,
"e": 1261,
"s": 1199,
"text": "Let us format date for different locale with DateFormat.SHORT"
},
{
"code": null,
"e": 1431,
"s": 1261,
"text": "// FRENCH\ndateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);\n// GERMANY\ndateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);"
},
{
"code": null,
"e": 1461,
"s": 1431,
"text": "The following is an example −"
},
{
"code": null,
"e": 1472,
"s": 1461,
"text": " Live Demo"
},
{
"code": null,
"e": 2609,
"s": 1472,
"text": "import java.text.DateFormat;\nimport java.util.Date;\nimport java.util.Locale;\npublic class Demo {\n public static void main(String args[]) {\n Date dt = new Date();\n DateFormat dateFormat;\n// Date Format SHORT constant\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);\n System.out.println(\"Locale FRENCH = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);\n System.out.println(\"Locale GERMANY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINESE);\n System.out.println(\"Locale CHINESE = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CANADA);\n System.out.println(\"Locale CANADA = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ITALY);\n System.out.println(\"Locale ITALY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.TAIWAN);\n System.out.println(\"Locale TAIWAN = \" + dateFormat.format(dt));\n }\n}"
},
{
"code": null,
"e": 2762,
"s": 2609,
"text": "Locale FRENCH = 22/11/18\nLocale GERMANY = 22.11.18\nLocale CHINESE = 18-11-22\nLocale CANADA = 22/11/18\nLocale ITALY = 22/11/18\nLocale TAIWAN = 2018/11/22"
}
] |
Downloading Datasets into Google Drive via Google Colab | by Kevin Luk | Towards Data Science | Update: (Coming Soon) TensorFlow 2.0 will be launching new distribution strategy for Keras so that you can use the same code to distribute your model on TPUs. Google Colab can directly access Google Cloud TPUs after the release! Watch TF Dev Summit ’19 for more information.
If you are working on an old MacBook Pro like me (Late 2013, with 120GB HD), limited storage will be my greatest hurdle in working on data science project. For those who are also working on data science project with large dataset, I am sure that saving the dataset and training the model on the cloud will definitely ease your mind.
In this tutorial, I will share with you my experience in:
Mounting the Google Drive to Google ColabDownloading the dataset directly to Google Drive via Google Colab
Mounting the Google Drive to Google Colab
Downloading the dataset directly to Google Drive via Google Colab
with the use of Kaggle API;
from competition website which username and password is required while requesting to download
BONUS: One click to enable FREE GPU support in Google Colab to train with Tensorflow.
First, go to your Google Colab then type the below:
from google.colab import drivedrive.mount('/content/gdrive')
The cell will return the following and your needs to go to the link to retrieve the authorization code. Then you are good to go!
If you are able to access Google Drive, your google drive files should be all under:
/content/gdrive/My Drive/
while your current directory will be /content/
For your easy usage, just save the below code snippet and paste it into the Google Colab and you can mount your Google Drive to the notebook easily.
In this section I will share with you my experience in downloading dataset from Kaggle and other competition.
Downloading Kaggle datasets via Kaggle API
Visit www.kaggle.com ⇨ login ⇨ My Account ⇨ Create New API Token
The “kaggle.json” file will be auto downloaded.
Use these code snippets in Google Colab for the task:
from google.colab import filesfiles.upload() #this will prompt you to upload the kaggle.json
The below will create the necessary folder path.
!pip install -q kaggle!mkdir -p ~/.kaggle!cp kaggle.json ~/.kaggle/!ls ~/.kaggle!chmod 600 /root/.kaggle/kaggle.json # set permission
Simply download the required dataset with the syntax:
!kaggle competitions download -c ‘name_of_competition’ -p “target_colab_dir”
!kaggle competitions download -c histopathologic-cancer-detection -p /content/gdrive/My\ Drive/kaggle/cancer
Bonus: please see the git gist below for searching Kaggle dataset
For dataset with multiple zip files like the example, I tend to change directory to the designated folder and unzip them one by one.
!unzip -q file[.zip] -d [exdir]
-q suppress the printing of the file names being extracted-d [exdir] optional directory to which to extract files
import osos.chdir('gdrive/My Drive/kaggle/cancer') #change dir!mkdir train #create a directory named train/!mkdir test #create a directory named test/!unzip -q train.zip -d train/ #unzip data in train/!unzip -q test.zip -d test/ #unzip data in test/!unzip sample_submission.csv.zip!unzip train_labels.csv.zip
Go to here to read more from Kaggle API docs.
For competition like ICIAR2018, you will need to provide the username and password while downloading the dataset.
To do this in Google Colab, first you can change your current directory to the folder you wish to save your dataset. Then, use wget instead of using curl command.
!wget --user=your_username --password=your_password http://cdn1.i3s.up.pt/digitalpathology/ICIAR2018_BACH_Challenge.zip
After downloading, you can unzip the file using the same approach above.
After you mounted your Google Drive to Google Colab and downloaded the required dataset, let’s enable GPU in your Colab notebook and train your model.
From task bar: Runtime ⇨ Change runtime type
Hardware accelerator: None ⇨ GPU
Hope you find this tutorial useful and happy cloud computing!
Thanks for Matt Gleeson, Finlay Macrae suggestions to make the content better. | [
{
"code": null,
"e": 447,
"s": 172,
"text": "Update: (Coming Soon) TensorFlow 2.0 will be launching new distribution strategy for Keras so that you can use the same code to distribute your model on TPUs. Google Colab can directly access Google Cloud TPUs after the release! Watch TF Dev Summit ’19 for more information."
},
{
"code": null,
"e": 780,
"s": 447,
"text": "If you are working on an old MacBook Pro like me (Late 2013, with 120GB HD), limited storage will be my greatest hurdle in working on data science project. For those who are also working on data science project with large dataset, I am sure that saving the dataset and training the model on the cloud will definitely ease your mind."
},
{
"code": null,
"e": 838,
"s": 780,
"text": "In this tutorial, I will share with you my experience in:"
},
{
"code": null,
"e": 945,
"s": 838,
"text": "Mounting the Google Drive to Google ColabDownloading the dataset directly to Google Drive via Google Colab"
},
{
"code": null,
"e": 987,
"s": 945,
"text": "Mounting the Google Drive to Google Colab"
},
{
"code": null,
"e": 1053,
"s": 987,
"text": "Downloading the dataset directly to Google Drive via Google Colab"
},
{
"code": null,
"e": 1081,
"s": 1053,
"text": "with the use of Kaggle API;"
},
{
"code": null,
"e": 1175,
"s": 1081,
"text": "from competition website which username and password is required while requesting to download"
},
{
"code": null,
"e": 1261,
"s": 1175,
"text": "BONUS: One click to enable FREE GPU support in Google Colab to train with Tensorflow."
},
{
"code": null,
"e": 1313,
"s": 1261,
"text": "First, go to your Google Colab then type the below:"
},
{
"code": null,
"e": 1374,
"s": 1313,
"text": "from google.colab import drivedrive.mount('/content/gdrive')"
},
{
"code": null,
"e": 1503,
"s": 1374,
"text": "The cell will return the following and your needs to go to the link to retrieve the authorization code. Then you are good to go!"
},
{
"code": null,
"e": 1588,
"s": 1503,
"text": "If you are able to access Google Drive, your google drive files should be all under:"
},
{
"code": null,
"e": 1614,
"s": 1588,
"text": "/content/gdrive/My Drive/"
},
{
"code": null,
"e": 1661,
"s": 1614,
"text": "while your current directory will be /content/"
},
{
"code": null,
"e": 1810,
"s": 1661,
"text": "For your easy usage, just save the below code snippet and paste it into the Google Colab and you can mount your Google Drive to the notebook easily."
},
{
"code": null,
"e": 1920,
"s": 1810,
"text": "In this section I will share with you my experience in downloading dataset from Kaggle and other competition."
},
{
"code": null,
"e": 1963,
"s": 1920,
"text": "Downloading Kaggle datasets via Kaggle API"
},
{
"code": null,
"e": 2028,
"s": 1963,
"text": "Visit www.kaggle.com ⇨ login ⇨ My Account ⇨ Create New API Token"
},
{
"code": null,
"e": 2076,
"s": 2028,
"text": "The “kaggle.json” file will be auto downloaded."
},
{
"code": null,
"e": 2130,
"s": 2076,
"text": "Use these code snippets in Google Colab for the task:"
},
{
"code": null,
"e": 2224,
"s": 2130,
"text": "from google.colab import filesfiles.upload() #this will prompt you to upload the kaggle.json"
},
{
"code": null,
"e": 2273,
"s": 2224,
"text": "The below will create the necessary folder path."
},
{
"code": null,
"e": 2408,
"s": 2273,
"text": "!pip install -q kaggle!mkdir -p ~/.kaggle!cp kaggle.json ~/.kaggle/!ls ~/.kaggle!chmod 600 /root/.kaggle/kaggle.json # set permission"
},
{
"code": null,
"e": 2462,
"s": 2408,
"text": "Simply download the required dataset with the syntax:"
},
{
"code": null,
"e": 2539,
"s": 2462,
"text": "!kaggle competitions download -c ‘name_of_competition’ -p “target_colab_dir”"
},
{
"code": null,
"e": 2648,
"s": 2539,
"text": "!kaggle competitions download -c histopathologic-cancer-detection -p /content/gdrive/My\\ Drive/kaggle/cancer"
},
{
"code": null,
"e": 2714,
"s": 2648,
"text": "Bonus: please see the git gist below for searching Kaggle dataset"
},
{
"code": null,
"e": 2847,
"s": 2714,
"text": "For dataset with multiple zip files like the example, I tend to change directory to the designated folder and unzip them one by one."
},
{
"code": null,
"e": 2879,
"s": 2847,
"text": "!unzip -q file[.zip] -d [exdir]"
},
{
"code": null,
"e": 2993,
"s": 2879,
"text": "-q suppress the printing of the file names being extracted-d [exdir] optional directory to which to extract files"
},
{
"code": null,
"e": 3307,
"s": 2993,
"text": "import osos.chdir('gdrive/My Drive/kaggle/cancer') #change dir!mkdir train #create a directory named train/!mkdir test #create a directory named test/!unzip -q train.zip -d train/ #unzip data in train/!unzip -q test.zip -d test/ #unzip data in test/!unzip sample_submission.csv.zip!unzip train_labels.csv.zip"
},
{
"code": null,
"e": 3353,
"s": 3307,
"text": "Go to here to read more from Kaggle API docs."
},
{
"code": null,
"e": 3467,
"s": 3353,
"text": "For competition like ICIAR2018, you will need to provide the username and password while downloading the dataset."
},
{
"code": null,
"e": 3630,
"s": 3467,
"text": "To do this in Google Colab, first you can change your current directory to the folder you wish to save your dataset. Then, use wget instead of using curl command."
},
{
"code": null,
"e": 3750,
"s": 3630,
"text": "!wget --user=your_username --password=your_password http://cdn1.i3s.up.pt/digitalpathology/ICIAR2018_BACH_Challenge.zip"
},
{
"code": null,
"e": 3823,
"s": 3750,
"text": "After downloading, you can unzip the file using the same approach above."
},
{
"code": null,
"e": 3974,
"s": 3823,
"text": "After you mounted your Google Drive to Google Colab and downloaded the required dataset, let’s enable GPU in your Colab notebook and train your model."
},
{
"code": null,
"e": 4019,
"s": 3974,
"text": "From task bar: Runtime ⇨ Change runtime type"
},
{
"code": null,
"e": 4052,
"s": 4019,
"text": "Hardware accelerator: None ⇨ GPU"
},
{
"code": null,
"e": 4114,
"s": 4052,
"text": "Hope you find this tutorial useful and happy cloud computing!"
}
] |
Asking the Right Questions: Training a T5 Transformer Model on a New task | by Thilina Rajapakse | Towards Data Science | I’ve been itching to try the T5 (Text-To-Text Transfer Transformer) ever since it came out way, way back in October 2019 (it’s been a long couple of months). I messed around with open-sourced code from Google a couple of times, but I never managed to get it to work properly. Some of it went a little over my head (Tensorflow 😫 ) so I figured I’ll wait for Hugging Face to ride to the rescue! As always, the Transformers implementation is much easier to work with and I adapted it for use with Simple Transformers.
Before we get to the good stuff, a quick word on what the T5 model is and why it’s so exciting. According to the article on T5 in the Google AI Blog, the model is a result of a large-scale study (paper link) on transfer learning techniques to see which works best. The T5 model was pre-trained on C4 (Colossal Clean Crawled Corpus), a new, absolutely massive dataset, released along with the model.
Pre-training is the first step of transfer learning in which a model is trained on a self-supervised task on huge amounts of unlabeled text data. After this, the model is fine-tuned (trained) on smaller labelled datasets tailored to specific tasks, yielding far superior performance compared to simply training on the small, labelled datasets without pre-training. Further information on pre-training language models can be found in my post below.
towardsdatascience.com
A key difference in the T5 model is that all NLP tasks are presented in a text-to-text format. On the other hand, BERT-like models take a text sequence as an input and output a single class label or a span of text from the input. A BERT model is retrofitted for a particular task by adding a relevant output layer on top of the transformer model. For example, a simple linear classification layer is added for classification tasks. T5, however, eschews this approach and instead reframes any NLP task such that both the input and the output are text sequences. This means that the same T5 model can be used for any NLP task, without any aftermarket changes to the architecture. The task to be performed can be specified via a simple prefix (again a text sequence) prepended to the input as demonstrated below.
The T5 paper explores many of the recent developments in NLP transfer learning. It is well worth a read!
However, the focus of this article on adapting the T5 model to perform new NLP tasks. Thanks to the unified text-to-text approach, this turns out to be (surprisingly) easy. So, let’s get to the aforementioned good stuff!
The T5 model is trained on a wide variety of NLP tasks including text classification, question answering, machine translation, and abstractive summarization. The task we will be teaching our T5 model is question generation.
Specifically, the model will be tasked with asking relevant questions when given a context.
You can find all the scripts used in this guide in the examples directory of the Simple Transformers repo.
We will be using the Amazon Review Data (2018) dataset which contains (among other things) descriptions of the various products on Amazon and question-answer pairs related to those products.
The descriptions and the question-answer pairs must be downloaded separately. You can either download the data manually by following the instructions in the Descriptions and Question-Answer Pairs below, or you can use the provided shell script. The list of categories used in this study is given below.
Go to reviews URL.Download the metadata files (json.gz) from the links on the page. Note that it might be better to download from the Per-category data links (e.g. http://deepyeti.ucsd.edu/jianmo/amazon/metaFiles/meta_AMAZON_FASHION.json.gz) rather than downloading the full metadata for all products. The full metadata is a 24 GB archive and you will need a lot of RAM to process it.Rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file.
Go to reviews URL.
Download the metadata files (json.gz) from the links on the page. Note that it might be better to download from the Per-category data links (e.g. http://deepyeti.ucsd.edu/jianmo/amazon/metaFiles/meta_AMAZON_FASHION.json.gz) rather than downloading the full metadata for all products. The full metadata is a 24 GB archive and you will need a lot of RAM to process it.
Rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file.
Go to the qa URL.Download the Per-category files. Note that I am using the question-answer pairs without multiple answers.
Go to the qa URL.
Download the Per-category files. Note that I am using the question-answer pairs without multiple answers.
Alternatively, the shell script below should download all the necessary files by reading the links from the two text files also given below (place the text files in the same directory data/ as the shell script). It will also rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file.
With the data files in place, we can start training our model!
We will be using the Simple Transformers library (based on the Hugging Face Transformers) to train the T5 model.
The instructions given below will install all the requirements.
Install Anaconda or Miniconda Package Manager from here.Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersconda install pytorch cudatoolkit=10.1 -c pytorchInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers
Install Anaconda or Miniconda Package Manager from here.
Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersconda install pytorch cudatoolkit=10.1 -c pytorch
Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)
Install simpletransformers.pip install simpletransformers
See installation docs
We can process the data files and save them in a convenient format using the script given below. This will also split the data into train and evaluation sets.
Adapted from the helpful scripts given in the Amazon Review Data page.
Check whether you have the train_df.tsv and eval_df.tsv files in your data/ directory.
The input data to a T5 model should be a Pandas DataFrame containing 3 columns as shown below.
prefix: A string indicating the task to perform.
input_text: The input text sequence.
target_text: The target sequence.
Internally, Simple Transformers will build the properly formatted input and target sequences (shown below) from the Pandas DataFrame.
The input to a T5 model has the following pattern;
"<prefix>: <input_text> </s>"
The target sequence has the following pattern;
"<target_sequence> </s>"
The prefix value specifies the task we want the T5 model to perform. To train a T5 model to perform a new task, we simply train the model while specifying an appropriate prefix. In this case, we will be using the prefix ask_question. I.e. All the rows in our DataFrame will have the value ask_question in the prefix column.
Training the model is quite straightforward with Simple Transformers.
As you might observe from the training script, we are using the t5-large pre-trained model. Using these parameters with the t5-large model takes about 12 hours of training with a single Titan RTX GPU. Depending on your GPU resources, you can either increase the train_batch_size to speed up training or you can decrease it to fit a GPU with less VRAM (Titan RTX has 24 GB).
Note that you can offset the effect of a small batch size by increasing the gradient_accumulation_steps. The effective batch size is roughly equal to train_batch_size * gradient_accumulation_steps.
You can also significantly improve the training speed and GPU memory consumption by opting for the t5-base model. This will likely result in comparatively worse (but by no means poor) model.
This training script will also automatically log the training progress using the Weights & Biases framework. You can see my logs here.
Evaluating a language generation model is a little more complicated than evaluating something like a classification model. This is because there is no right answer you can compare against like you could with a classification model. The evaluation dataset contains descriptions and the questions that people have asked about those products, but that doesn’t mean that those are the only right questions you can ask.
Therefore, one of the best ways to evaluate a language generation model is to generate text and have it evaluated by an actual person (or several people).
Speaking of generating text, impressive developments in decoding algorithms over the past few years has led to models capable of generating quite realistic text sequences. (Decoding algorithms are used to generate text)
The following section gives a brief overview of the popular decoding algorithms currently in use.
This section is based heavily on the Hugging Face notebook on text generation. I highly recommend going through that notebook to gain a more in-depth understanding of decoding algorithms as it does an excellent job of explaining the algorithms and showing how they can be used.
Greedy search — Selects the word with the highest probability as the next word at each timestep. The T5 paper uses this algorithm for short sequence generation (e.g. classification).Beam search — Tracks the n most likely hypotheses (based on word probability) at each timestep and finally chooses the hypothesis with the highest overall probability. ( n is the number of beams)Top-K sampling — Randomly samples a word from the K most likely next words at each time step. The number of possible words to choose from at each step is fixed.Top-p sampling — Samples a word from the smallest possible set of words whose cumulative probability (sum of probabilities for each word) exceeds the probability p at each timestep. The number of possible words to choose from at each step is dynamic.
Greedy search — Selects the word with the highest probability as the next word at each timestep. The T5 paper uses this algorithm for short sequence generation (e.g. classification).
Beam search — Tracks the n most likely hypotheses (based on word probability) at each timestep and finally chooses the hypothesis with the highest overall probability. ( n is the number of beams)
Top-K sampling — Randomly samples a word from the K most likely next words at each time step. The number of possible words to choose from at each step is fixed.
Top-p sampling — Samples a word from the smallest possible set of words whose cumulative probability (sum of probabilities for each word) exceeds the probability p at each timestep. The number of possible words to choose from at each step is dynamic.
We will be using a combination of both Top-K and Top-p sampling techniques to generate questions with our T5 model. This strategy typically leads to more natural-looking text.
The predict() method of a Simple Transformers T5 model is used to generate the predictions or, in our case, the questions.
Here, we are generating 3 questions for each description in the eval_df dataset.
Let’s take a look at some of the samples.
Just for fun, I’ve shuffled the generated questions with the actual question from the dataset. There are 4 questions for each description, 3 of which are generated and one is the original. See if you can tell which is which! I would love to see your guesses in the comments. 😉
Description:
The Smart Solar San Rafael II Solar Mission Lantern will provide elegant ambiance to any outdoor setting and is ideal for your patio, deck or garden: made from all-weather poly-plastic with a seeded glass effect, the 15-inch lantern sits on any surface, or can be hung using the integrated hanging loop. The Rafael II is illuminated by two warm white LEDs in the top with a pillar candle inside the lantern that has an amber LED for a warm glowing effect. Powered by an integral mono-crystalline solar panel and rechargeable Ni-MH battery, the Rafael II requires no wiring or operating costs. The lantern automatically turns on at dusk and off at dawn. Smart Living Home & Garden offers a 1 year limited manufacturers warranty from the original date of purchase on full products bought from authorized distributors and retailers. Established in 2002, Smart Solar offers a wide selection of exclusively solar powered products. We design, manufacture, and customize all of our own items for your patio and garden. Enjoy our solar powered, energy efficient, and environmental friendly lighting solutions, water features, and outdoor decor. We are confident you will love solar living — that’s why we’ve been creating solar products and growing the solar lifestyle for nearly 15 years.
Questions:
what is the height from the ground to the LED bulb? thanks
What kind of battery does the pillar candle use?
What size bulbs does it take?
Are they heavy? We get a lot of wind and they will be on tables
Description:
Durable dog ball with treat hole
Questions:
will it be safe for a pug to play with it?
does it squeak or not?
will it pop when the dog chews on it
What is the weight of this item?
Description:
Petco River Rock Shallow Creek Aquarium GravelPetco Aquarium Gravel is ideal for freshwater and safe for marine aquariums. This high quality gravel has colorful, durable coatings specifically developed for their permanence and non-toxicity. The gravel is processed to remove potentially harmful debris and materials. It will not affect the water’s chemistry, nor harm any fish, invertebrates or plants. Can be used in aquariums, ponds, water gardens and terrariums.
Questions:
I have a betta fish with very delicate fins. I want to make sure I get gravel that’s not going to scratch or tear them. Would this stuff work?
Has anyone tried this in saltwater, if so how does it hold up?
What are the dimensions of the bag and the plastic/stuff it comes in?
Is this gravel good for growing algae in aquariums?
Description:
Enter a world of building fun with the LEGO City Starter Set featuring 3 iconic vehicles. Catch the robber with the policeman on his motorcycle! Put out the fire with the firemans speedy fire truck. Then race to help the fallen skater boy in the ambulance. Create endless play possibilities with all the inspiration a young builder needs to explore fun ways of saving the day! Includes 5 minifigures with accessories: robber, policeman, fireman, rescuer and a skater boy. 272 pcs. Ages 5 yrs. +.’, “Enter a world of building fun with the LEGO City Starter Set featuring 3 iconic vehicles. Catch the robber with the policeman on his motorcycle. Put out the fire with the fireman’s speedy fire truck. Then race to help the fallen skater boy in the ambulance. Create endless play possibilities with all the inspiration a young builder needs to explore fun ways of saving the day. Includes 5 minifigures with accessories: robber, policeman, fireman, rescuer and a skater boy.
Questions:
How much space in the box will the starter set take up when all the pieces are in the set?
What size are the blocks themselves?
Can Lego minifigures be made to fit on the LEGO HOMES?
What color is the set? The picture is not clear and looks dark.
Description:
Elegant and sleek, this TV Stand a new look to your home. Finished in a dark Espresso color. Two sliding doors. Four Sections for storage.
Questions:
Is there any way to adjust the height in this unit or does the width need to adjust itself if my TV is not 32"?
How tall are the shelves? I have a tall receiver and want to be sure it will fit.
What are the dimensions of the two storage compartments? Thanks!
Can the drawers be removed or are they fixed?
Description:
Did we say cotton? You bet we did. The Men’s Charged Cotton Longsleeve T-shirt may feel like a regular cotton T-shirt, but it’s anything but ordinary. Its unique fabrication combines the classic comfort of cotton with the built-in water-resistance of all-weather gear to create the world’s first true performance cotton T-shirt. It feels soft but dries faster than regular cotton, so you’ll never be weighed down. Lightweight comfort. Stretchable mobility. This is the most powerful cotton T-shirt you’ll ever put on. After all, it is Under Armour.
Questions:
can you get a large in this for me?
will this work for running/doing sprints? i have small arms and not alot of flexibility but do alot of sprinting. would a vrs2 look ok on me
what is the shirt size for a 12 year old boy?
Size large is what chest size in inches?
Description:
Connect the Dotters!’, “Connect the Dotters! Dotters, our 10 happy-faced Dalmatian dog, is made of our super-soft Pluffies material that’s not only cuddly, but machine washable!
Question:
can you eat this?
👀
You can also test your model on other product descriptions. The script below uses a random description I found on eBay.
And the generated questions:
what size are the globes?
What is the color of this lamp?
Could I purchase more globes for this lamp?
For me, the most intriguing aspect of the T5 model is the ability to train it for an entirely new task by merely changing the prefix. In this article, we’ve trained the model to generate questions by looking at product descriptions. However, it is entirely possible to have this same model trained on other tasks and switch between the different tasks by simply changing the prefix.
This flexibility opens up a whole new world of possibilities and applications for a T5 model. I can’t wait to see what comes next!
You can also significantly improve the training speed and GPU memory consumption by opting for the t5-base model. This will likely result in comparatively poorer (but by no means poor) performance. | [
{
"code": null,
"e": 687,
"s": 172,
"text": "I’ve been itching to try the T5 (Text-To-Text Transfer Transformer) ever since it came out way, way back in October 2019 (it’s been a long couple of months). I messed around with open-sourced code from Google a couple of times, but I never managed to get it to work properly. Some of it went a little over my head (Tensorflow 😫 ) so I figured I’ll wait for Hugging Face to ride to the rescue! As always, the Transformers implementation is much easier to work with and I adapted it for use with Simple Transformers."
},
{
"code": null,
"e": 1086,
"s": 687,
"text": "Before we get to the good stuff, a quick word on what the T5 model is and why it’s so exciting. According to the article on T5 in the Google AI Blog, the model is a result of a large-scale study (paper link) on transfer learning techniques to see which works best. The T5 model was pre-trained on C4 (Colossal Clean Crawled Corpus), a new, absolutely massive dataset, released along with the model."
},
{
"code": null,
"e": 1534,
"s": 1086,
"text": "Pre-training is the first step of transfer learning in which a model is trained on a self-supervised task on huge amounts of unlabeled text data. After this, the model is fine-tuned (trained) on smaller labelled datasets tailored to specific tasks, yielding far superior performance compared to simply training on the small, labelled datasets without pre-training. Further information on pre-training language models can be found in my post below."
},
{
"code": null,
"e": 1557,
"s": 1534,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2367,
"s": 1557,
"text": "A key difference in the T5 model is that all NLP tasks are presented in a text-to-text format. On the other hand, BERT-like models take a text sequence as an input and output a single class label or a span of text from the input. A BERT model is retrofitted for a particular task by adding a relevant output layer on top of the transformer model. For example, a simple linear classification layer is added for classification tasks. T5, however, eschews this approach and instead reframes any NLP task such that both the input and the output are text sequences. This means that the same T5 model can be used for any NLP task, without any aftermarket changes to the architecture. The task to be performed can be specified via a simple prefix (again a text sequence) prepended to the input as demonstrated below."
},
{
"code": null,
"e": 2472,
"s": 2367,
"text": "The T5 paper explores many of the recent developments in NLP transfer learning. It is well worth a read!"
},
{
"code": null,
"e": 2693,
"s": 2472,
"text": "However, the focus of this article on adapting the T5 model to perform new NLP tasks. Thanks to the unified text-to-text approach, this turns out to be (surprisingly) easy. So, let’s get to the aforementioned good stuff!"
},
{
"code": null,
"e": 2917,
"s": 2693,
"text": "The T5 model is trained on a wide variety of NLP tasks including text classification, question answering, machine translation, and abstractive summarization. The task we will be teaching our T5 model is question generation."
},
{
"code": null,
"e": 3009,
"s": 2917,
"text": "Specifically, the model will be tasked with asking relevant questions when given a context."
},
{
"code": null,
"e": 3116,
"s": 3009,
"text": "You can find all the scripts used in this guide in the examples directory of the Simple Transformers repo."
},
{
"code": null,
"e": 3307,
"s": 3116,
"text": "We will be using the Amazon Review Data (2018) dataset which contains (among other things) descriptions of the various products on Amazon and question-answer pairs related to those products."
},
{
"code": null,
"e": 3610,
"s": 3307,
"text": "The descriptions and the question-answer pairs must be downloaded separately. You can either download the data manually by following the instructions in the Descriptions and Question-Answer Pairs below, or you can use the provided shell script. The list of categories used in this study is given below."
},
{
"code": null,
"e": 4095,
"s": 3610,
"text": "Go to reviews URL.Download the metadata files (json.gz) from the links on the page. Note that it might be better to download from the Per-category data links (e.g. http://deepyeti.ucsd.edu/jianmo/amazon/metaFiles/meta_AMAZON_FASHION.json.gz) rather than downloading the full metadata for all products. The full metadata is a 24 GB archive and you will need a lot of RAM to process it.Rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file."
},
{
"code": null,
"e": 4114,
"s": 4095,
"text": "Go to reviews URL."
},
{
"code": null,
"e": 4481,
"s": 4114,
"text": "Download the metadata files (json.gz) from the links on the page. Note that it might be better to download from the Per-category data links (e.g. http://deepyeti.ucsd.edu/jianmo/amazon/metaFiles/meta_AMAZON_FASHION.json.gz) rather than downloading the full metadata for all products. The full metadata is a 24 GB archive and you will need a lot of RAM to process it."
},
{
"code": null,
"e": 4582,
"s": 4481,
"text": "Rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file."
},
{
"code": null,
"e": 4705,
"s": 4582,
"text": "Go to the qa URL.Download the Per-category files. Note that I am using the question-answer pairs without multiple answers."
},
{
"code": null,
"e": 4723,
"s": 4705,
"text": "Go to the qa URL."
},
{
"code": null,
"e": 4829,
"s": 4723,
"text": "Download the Per-category files. Note that I am using the question-answer pairs without multiple answers."
},
{
"code": null,
"e": 5155,
"s": 4829,
"text": "Alternatively, the shell script below should download all the necessary files by reading the links from the two text files also given below (place the text files in the same directory data/ as the shell script). It will also rename meta_ALL_Beauty.json.gz to meta_Beauty.json.gz to match the name in the question-answer file."
},
{
"code": null,
"e": 5218,
"s": 5155,
"text": "With the data files in place, we can start training our model!"
},
{
"code": null,
"e": 5331,
"s": 5218,
"text": "We will be using the Simple Transformers library (based on the Hugging Face Transformers) to train the T5 model."
},
{
"code": null,
"e": 5395,
"s": 5331,
"text": "The instructions given below will install all the requirements."
},
{
"code": null,
"e": 5844,
"s": 5395,
"text": "Install Anaconda or Miniconda Package Manager from here.Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersconda install pytorch cudatoolkit=10.1 -c pytorchInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 5901,
"s": 5844,
"text": "Install Anaconda or Miniconda Package Manager from here."
},
{
"code": null,
"e": 6091,
"s": 5901,
"text": "Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersconda install pytorch cudatoolkit=10.1 -c pytorch"
},
{
"code": null,
"e": 6238,
"s": 6091,
"text": "Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)"
},
{
"code": null,
"e": 6296,
"s": 6238,
"text": "Install simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 6318,
"s": 6296,
"text": "See installation docs"
},
{
"code": null,
"e": 6477,
"s": 6318,
"text": "We can process the data files and save them in a convenient format using the script given below. This will also split the data into train and evaluation sets."
},
{
"code": null,
"e": 6548,
"s": 6477,
"text": "Adapted from the helpful scripts given in the Amazon Review Data page."
},
{
"code": null,
"e": 6635,
"s": 6548,
"text": "Check whether you have the train_df.tsv and eval_df.tsv files in your data/ directory."
},
{
"code": null,
"e": 6730,
"s": 6635,
"text": "The input data to a T5 model should be a Pandas DataFrame containing 3 columns as shown below."
},
{
"code": null,
"e": 6779,
"s": 6730,
"text": "prefix: A string indicating the task to perform."
},
{
"code": null,
"e": 6816,
"s": 6779,
"text": "input_text: The input text sequence."
},
{
"code": null,
"e": 6850,
"s": 6816,
"text": "target_text: The target sequence."
},
{
"code": null,
"e": 6984,
"s": 6850,
"text": "Internally, Simple Transformers will build the properly formatted input and target sequences (shown below) from the Pandas DataFrame."
},
{
"code": null,
"e": 7035,
"s": 6984,
"text": "The input to a T5 model has the following pattern;"
},
{
"code": null,
"e": 7065,
"s": 7035,
"text": "\"<prefix>: <input_text> </s>\""
},
{
"code": null,
"e": 7112,
"s": 7065,
"text": "The target sequence has the following pattern;"
},
{
"code": null,
"e": 7137,
"s": 7112,
"text": "\"<target_sequence> </s>\""
},
{
"code": null,
"e": 7461,
"s": 7137,
"text": "The prefix value specifies the task we want the T5 model to perform. To train a T5 model to perform a new task, we simply train the model while specifying an appropriate prefix. In this case, we will be using the prefix ask_question. I.e. All the rows in our DataFrame will have the value ask_question in the prefix column."
},
{
"code": null,
"e": 7531,
"s": 7461,
"text": "Training the model is quite straightforward with Simple Transformers."
},
{
"code": null,
"e": 7905,
"s": 7531,
"text": "As you might observe from the training script, we are using the t5-large pre-trained model. Using these parameters with the t5-large model takes about 12 hours of training with a single Titan RTX GPU. Depending on your GPU resources, you can either increase the train_batch_size to speed up training or you can decrease it to fit a GPU with less VRAM (Titan RTX has 24 GB)."
},
{
"code": null,
"e": 8103,
"s": 7905,
"text": "Note that you can offset the effect of a small batch size by increasing the gradient_accumulation_steps. The effective batch size is roughly equal to train_batch_size * gradient_accumulation_steps."
},
{
"code": null,
"e": 8294,
"s": 8103,
"text": "You can also significantly improve the training speed and GPU memory consumption by opting for the t5-base model. This will likely result in comparatively worse (but by no means poor) model."
},
{
"code": null,
"e": 8429,
"s": 8294,
"text": "This training script will also automatically log the training progress using the Weights & Biases framework. You can see my logs here."
},
{
"code": null,
"e": 8844,
"s": 8429,
"text": "Evaluating a language generation model is a little more complicated than evaluating something like a classification model. This is because there is no right answer you can compare against like you could with a classification model. The evaluation dataset contains descriptions and the questions that people have asked about those products, but that doesn’t mean that those are the only right questions you can ask."
},
{
"code": null,
"e": 8999,
"s": 8844,
"text": "Therefore, one of the best ways to evaluate a language generation model is to generate text and have it evaluated by an actual person (or several people)."
},
{
"code": null,
"e": 9219,
"s": 8999,
"text": "Speaking of generating text, impressive developments in decoding algorithms over the past few years has led to models capable of generating quite realistic text sequences. (Decoding algorithms are used to generate text)"
},
{
"code": null,
"e": 9317,
"s": 9219,
"text": "The following section gives a brief overview of the popular decoding algorithms currently in use."
},
{
"code": null,
"e": 9595,
"s": 9317,
"text": "This section is based heavily on the Hugging Face notebook on text generation. I highly recommend going through that notebook to gain a more in-depth understanding of decoding algorithms as it does an excellent job of explaining the algorithms and showing how they can be used."
},
{
"code": null,
"e": 10383,
"s": 9595,
"text": "Greedy search — Selects the word with the highest probability as the next word at each timestep. The T5 paper uses this algorithm for short sequence generation (e.g. classification).Beam search — Tracks the n most likely hypotheses (based on word probability) at each timestep and finally chooses the hypothesis with the highest overall probability. ( n is the number of beams)Top-K sampling — Randomly samples a word from the K most likely next words at each time step. The number of possible words to choose from at each step is fixed.Top-p sampling — Samples a word from the smallest possible set of words whose cumulative probability (sum of probabilities for each word) exceeds the probability p at each timestep. The number of possible words to choose from at each step is dynamic."
},
{
"code": null,
"e": 10566,
"s": 10383,
"text": "Greedy search — Selects the word with the highest probability as the next word at each timestep. The T5 paper uses this algorithm for short sequence generation (e.g. classification)."
},
{
"code": null,
"e": 10762,
"s": 10566,
"text": "Beam search — Tracks the n most likely hypotheses (based on word probability) at each timestep and finally chooses the hypothesis with the highest overall probability. ( n is the number of beams)"
},
{
"code": null,
"e": 10923,
"s": 10762,
"text": "Top-K sampling — Randomly samples a word from the K most likely next words at each time step. The number of possible words to choose from at each step is fixed."
},
{
"code": null,
"e": 11174,
"s": 10923,
"text": "Top-p sampling — Samples a word from the smallest possible set of words whose cumulative probability (sum of probabilities for each word) exceeds the probability p at each timestep. The number of possible words to choose from at each step is dynamic."
},
{
"code": null,
"e": 11350,
"s": 11174,
"text": "We will be using a combination of both Top-K and Top-p sampling techniques to generate questions with our T5 model. This strategy typically leads to more natural-looking text."
},
{
"code": null,
"e": 11473,
"s": 11350,
"text": "The predict() method of a Simple Transformers T5 model is used to generate the predictions or, in our case, the questions."
},
{
"code": null,
"e": 11554,
"s": 11473,
"text": "Here, we are generating 3 questions for each description in the eval_df dataset."
},
{
"code": null,
"e": 11596,
"s": 11554,
"text": "Let’s take a look at some of the samples."
},
{
"code": null,
"e": 11873,
"s": 11596,
"text": "Just for fun, I’ve shuffled the generated questions with the actual question from the dataset. There are 4 questions for each description, 3 of which are generated and one is the original. See if you can tell which is which! I would love to see your guesses in the comments. 😉"
},
{
"code": null,
"e": 11886,
"s": 11873,
"text": "Description:"
},
{
"code": null,
"e": 13168,
"s": 11886,
"text": "The Smart Solar San Rafael II Solar Mission Lantern will provide elegant ambiance to any outdoor setting and is ideal for your patio, deck or garden: made from all-weather poly-plastic with a seeded glass effect, the 15-inch lantern sits on any surface, or can be hung using the integrated hanging loop. The Rafael II is illuminated by two warm white LEDs in the top with a pillar candle inside the lantern that has an amber LED for a warm glowing effect. Powered by an integral mono-crystalline solar panel and rechargeable Ni-MH battery, the Rafael II requires no wiring or operating costs. The lantern automatically turns on at dusk and off at dawn. Smart Living Home & Garden offers a 1 year limited manufacturers warranty from the original date of purchase on full products bought from authorized distributors and retailers. Established in 2002, Smart Solar offers a wide selection of exclusively solar powered products. We design, manufacture, and customize all of our own items for your patio and garden. Enjoy our solar powered, energy efficient, and environmental friendly lighting solutions, water features, and outdoor decor. We are confident you will love solar living — that’s why we’ve been creating solar products and growing the solar lifestyle for nearly 15 years."
},
{
"code": null,
"e": 13179,
"s": 13168,
"text": "Questions:"
},
{
"code": null,
"e": 13238,
"s": 13179,
"text": "what is the height from the ground to the LED bulb? thanks"
},
{
"code": null,
"e": 13287,
"s": 13238,
"text": "What kind of battery does the pillar candle use?"
},
{
"code": null,
"e": 13317,
"s": 13287,
"text": "What size bulbs does it take?"
},
{
"code": null,
"e": 13381,
"s": 13317,
"text": "Are they heavy? We get a lot of wind and they will be on tables"
},
{
"code": null,
"e": 13394,
"s": 13381,
"text": "Description:"
},
{
"code": null,
"e": 13427,
"s": 13394,
"text": "Durable dog ball with treat hole"
},
{
"code": null,
"e": 13438,
"s": 13427,
"text": "Questions:"
},
{
"code": null,
"e": 13481,
"s": 13438,
"text": "will it be safe for a pug to play with it?"
},
{
"code": null,
"e": 13504,
"s": 13481,
"text": "does it squeak or not?"
},
{
"code": null,
"e": 13541,
"s": 13504,
"text": "will it pop when the dog chews on it"
},
{
"code": null,
"e": 13574,
"s": 13541,
"text": "What is the weight of this item?"
},
{
"code": null,
"e": 13587,
"s": 13574,
"text": "Description:"
},
{
"code": null,
"e": 14053,
"s": 13587,
"text": "Petco River Rock Shallow Creek Aquarium GravelPetco Aquarium Gravel is ideal for freshwater and safe for marine aquariums. This high quality gravel has colorful, durable coatings specifically developed for their permanence and non-toxicity. The gravel is processed to remove potentially harmful debris and materials. It will not affect the water’s chemistry, nor harm any fish, invertebrates or plants. Can be used in aquariums, ponds, water gardens and terrariums."
},
{
"code": null,
"e": 14064,
"s": 14053,
"text": "Questions:"
},
{
"code": null,
"e": 14207,
"s": 14064,
"text": "I have a betta fish with very delicate fins. I want to make sure I get gravel that’s not going to scratch or tear them. Would this stuff work?"
},
{
"code": null,
"e": 14270,
"s": 14207,
"text": "Has anyone tried this in saltwater, if so how does it hold up?"
},
{
"code": null,
"e": 14340,
"s": 14270,
"text": "What are the dimensions of the bag and the plastic/stuff it comes in?"
},
{
"code": null,
"e": 14392,
"s": 14340,
"text": "Is this gravel good for growing algae in aquariums?"
},
{
"code": null,
"e": 14405,
"s": 14392,
"text": "Description:"
},
{
"code": null,
"e": 15377,
"s": 14405,
"text": "Enter a world of building fun with the LEGO City Starter Set featuring 3 iconic vehicles. Catch the robber with the policeman on his motorcycle! Put out the fire with the firemans speedy fire truck. Then race to help the fallen skater boy in the ambulance. Create endless play possibilities with all the inspiration a young builder needs to explore fun ways of saving the day! Includes 5 minifigures with accessories: robber, policeman, fireman, rescuer and a skater boy. 272 pcs. Ages 5 yrs. +.’, “Enter a world of building fun with the LEGO City Starter Set featuring 3 iconic vehicles. Catch the robber with the policeman on his motorcycle. Put out the fire with the fireman’s speedy fire truck. Then race to help the fallen skater boy in the ambulance. Create endless play possibilities with all the inspiration a young builder needs to explore fun ways of saving the day. Includes 5 minifigures with accessories: robber, policeman, fireman, rescuer and a skater boy."
},
{
"code": null,
"e": 15388,
"s": 15377,
"text": "Questions:"
},
{
"code": null,
"e": 15479,
"s": 15388,
"text": "How much space in the box will the starter set take up when all the pieces are in the set?"
},
{
"code": null,
"e": 15516,
"s": 15479,
"text": "What size are the blocks themselves?"
},
{
"code": null,
"e": 15571,
"s": 15516,
"text": "Can Lego minifigures be made to fit on the LEGO HOMES?"
},
{
"code": null,
"e": 15635,
"s": 15571,
"text": "What color is the set? The picture is not clear and looks dark."
},
{
"code": null,
"e": 15648,
"s": 15635,
"text": "Description:"
},
{
"code": null,
"e": 15787,
"s": 15648,
"text": "Elegant and sleek, this TV Stand a new look to your home. Finished in a dark Espresso color. Two sliding doors. Four Sections for storage."
},
{
"code": null,
"e": 15798,
"s": 15787,
"text": "Questions:"
},
{
"code": null,
"e": 15910,
"s": 15798,
"text": "Is there any way to adjust the height in this unit or does the width need to adjust itself if my TV is not 32\"?"
},
{
"code": null,
"e": 15992,
"s": 15910,
"text": "How tall are the shelves? I have a tall receiver and want to be sure it will fit."
},
{
"code": null,
"e": 16057,
"s": 15992,
"text": "What are the dimensions of the two storage compartments? Thanks!"
},
{
"code": null,
"e": 16103,
"s": 16057,
"text": "Can the drawers be removed or are they fixed?"
},
{
"code": null,
"e": 16116,
"s": 16103,
"text": "Description:"
},
{
"code": null,
"e": 16665,
"s": 16116,
"text": "Did we say cotton? You bet we did. The Men’s Charged Cotton Longsleeve T-shirt may feel like a regular cotton T-shirt, but it’s anything but ordinary. Its unique fabrication combines the classic comfort of cotton with the built-in water-resistance of all-weather gear to create the world’s first true performance cotton T-shirt. It feels soft but dries faster than regular cotton, so you’ll never be weighed down. Lightweight comfort. Stretchable mobility. This is the most powerful cotton T-shirt you’ll ever put on. After all, it is Under Armour."
},
{
"code": null,
"e": 16676,
"s": 16665,
"text": "Questions:"
},
{
"code": null,
"e": 16712,
"s": 16676,
"text": "can you get a large in this for me?"
},
{
"code": null,
"e": 16853,
"s": 16712,
"text": "will this work for running/doing sprints? i have small arms and not alot of flexibility but do alot of sprinting. would a vrs2 look ok on me"
},
{
"code": null,
"e": 16899,
"s": 16853,
"text": "what is the shirt size for a 12 year old boy?"
},
{
"code": null,
"e": 16940,
"s": 16899,
"text": "Size large is what chest size in inches?"
},
{
"code": null,
"e": 16953,
"s": 16940,
"text": "Description:"
},
{
"code": null,
"e": 17131,
"s": 16953,
"text": "Connect the Dotters!’, “Connect the Dotters! Dotters, our 10 happy-faced Dalmatian dog, is made of our super-soft Pluffies material that’s not only cuddly, but machine washable!"
},
{
"code": null,
"e": 17141,
"s": 17131,
"text": "Question:"
},
{
"code": null,
"e": 17159,
"s": 17141,
"text": "can you eat this?"
},
{
"code": null,
"e": 17161,
"s": 17159,
"text": "👀"
},
{
"code": null,
"e": 17281,
"s": 17161,
"text": "You can also test your model on other product descriptions. The script below uses a random description I found on eBay."
},
{
"code": null,
"e": 17310,
"s": 17281,
"text": "And the generated questions:"
},
{
"code": null,
"e": 17336,
"s": 17310,
"text": "what size are the globes?"
},
{
"code": null,
"e": 17368,
"s": 17336,
"text": "What is the color of this lamp?"
},
{
"code": null,
"e": 17412,
"s": 17368,
"text": "Could I purchase more globes for this lamp?"
},
{
"code": null,
"e": 17795,
"s": 17412,
"text": "For me, the most intriguing aspect of the T5 model is the ability to train it for an entirely new task by merely changing the prefix. In this article, we’ve trained the model to generate questions by looking at product descriptions. However, it is entirely possible to have this same model trained on other tasks and switch between the different tasks by simply changing the prefix."
},
{
"code": null,
"e": 17926,
"s": 17795,
"text": "This flexibility opens up a whole new world of possibilities and applications for a T5 model. I can’t wait to see what comes next!"
}
] |
Jupyter and Markdown. Making your Notebooks look good | by Alan Jones | Towards Data Science | You can put comments in your Jupyter Notebook code to help the reader to understand what you are up to. But longer commentary is better in text cells separate from the code.
Text cells in Jupyter support the Markdown language and we are going to take a look at the facilities that it offers. Markdown is a set of simple markup codes that are easily transformed into HTML for rendering in a browser. Markdown is nowhere near as sophisticated, or complex, as HTML but is perfectly adequate for documenting a notebook (although can also embed HTML if you need more control over the look or layout).
This article was initially written in Markdown (there is a link to the original at the end of this article) and the first paragraph and the two headings looks like this:
# Jupyter and Markdown## Making your Notebooks look goodWhether you are sharing your Jupyter Notebooks with friends and colleagues or publishing them more widely, they will be better appreciated if they are well layed out and formatted.
Very simple. The # precedes a heading equivalent to <h1> in HTML, two of them means a secondary heading, <h2>. The more # symbols, the smaller the heading.
So the following Markdown code will display a list of headings gradually reducing in size.
# heading 1## heading 2### heading 3#### heading 4##### heading 5###### heading 6
Markdown supports the most common styling such as bold and italic, you can construct lists both numbered and unnumbered. You can embed code within a paragraph or display a complete code block. Hyperlinks are included and you can insert images, too. Tables can be constructed with left and right justified columns with very simple syntax.
Markdown ignores single line breaks, so to separate paragraphs, you need to insert two line breaks.
Below we are going to go through some examples of the Markdown code. For each example I’ll show you the Markdown code and then follow it with the way that it will look after being rendered.
First we’ll take a look at some simple inline markup.
Here is the code and below it is the rendered version:
This is a paragraph that illustrates some of the Markdown features.This is a new paragraph that includes some code: `print(123)` you can see that it is enclosed in single back ticks. Other simple markup is *italic which is enclosed in asterisks* and **bold which is enclosed in double asterisks**.
You can use single or double underscores to make text italic or bold. So, by mixing underscores and stars you can have text that is both italic and
You can also use an _underscore to make things italic_, or two of them for __bold__. This means you can have both _**italic and bold**_ text.
Block quotes are preceded by a chevron.
> To include a block quote you precede it with a `>`
If you want to include a code block use three backticks or ~ characters to enclose the code like this:
~~~pythonfor i in (1,2,3): print(i)~~~
or this
```pythonfor i in (1,2,3): print(i)```
and you’ll get a block of code which will probably be colour coded:
Note that the use of the name a programming language is optional and, although it is not part of the Markdown specification, colour coding is included in most renderers.
There are both ordered and unordered lists. The items in an unordered list are preceded by a star, minus or a plus:
+ item- item* item
This looks like
item
item
item
Sublists are just indented with a space:
+ item + item + item+ item
Numbered lists begin with — you guessed it — a number, followed by a dot. And you can mix and match ordered, unordered and sub-lists.
1. item2. item3. item + item + item4. item
Images are referenced by their path or URI. To include an image the line starts with an exclamation mark followed by a pair of square brackets where the alt-text goes then a pair of braces containing image path and a string which will be displayed when you hover over the image.

Links look similar to images except the text in the square brackets is the actual link text.
Here is a link to [Google’s](https://www.google.com “Google’s Homepage”) home page.
Which is rendered as:
Here is a link to Google’s home page.
In a table the columns are separated with the pipe character(|) and the header is followed by a row of dashes, then the rest of the data follows row by row, like this:
Col1 |Col2 |Col3-----|-----|----- Data1|Data2|Data3Data1|Data2|Data3Data1|Data2|Data3Data1|Data2|Data3
You can also align columns by placing colons in the header underline. A colon of the right means right aligned, on the left means left aligned and one on each side is centered. Here’s an example:
Left aligned column | Centered column | Right aligned column:-------------------|:---------------:|--------------------:**Bold data** | *Italic data* | Normal data
And, as you see, the entries in the table can be made bold or italicised.
The layout of the code does not have to be neat, Markdown will sort it out. This messy version of the table above is rendered exactly the same.
Left aligned column | Centered column | Right aligned column:-|:-:|-:**Bold data**|*Italic data*| Normal data
You can add whatever HTML you want, if Markdown doesn’t do exactly what you want.
Here’s a bit of Markdown text. Can you see the difference between**Markdown bold** and <b>HTML bold</b>?No, you can’t because it’s the same!
Here’s a bit of Markdown text. Can you see the difference between Markdown bold and HTML bold?
No, you can’t because it’s the same!
And to finish off here is a horizontal line. Just type three dashes on a line by itself
---
(There is no horizontal line in the Medium editor but I’m sure you can imagine one!)
That’s plenty enough to make your Jupyter Notebooks into attractive readable documents, I think.
Since Medium doesn’t support all of the stuff that Markdown can do, I’ve relied to a considerable extent on images. But if you would like to see the original version of this notebook you can view it, or download it, here.
And if you would like to be informed about future articles please subscribe to my free Technofile newsletter. | [
{
"code": null,
"e": 346,
"s": 172,
"text": "You can put comments in your Jupyter Notebook code to help the reader to understand what you are up to. But longer commentary is better in text cells separate from the code."
},
{
"code": null,
"e": 768,
"s": 346,
"text": "Text cells in Jupyter support the Markdown language and we are going to take a look at the facilities that it offers. Markdown is a set of simple markup codes that are easily transformed into HTML for rendering in a browser. Markdown is nowhere near as sophisticated, or complex, as HTML but is perfectly adequate for documenting a notebook (although can also embed HTML if you need more control over the look or layout)."
},
{
"code": null,
"e": 938,
"s": 768,
"text": "This article was initially written in Markdown (there is a link to the original at the end of this article) and the first paragraph and the two headings looks like this:"
},
{
"code": null,
"e": 1175,
"s": 938,
"text": "# Jupyter and Markdown## Making your Notebooks look goodWhether you are sharing your Jupyter Notebooks with friends and colleagues or publishing them more widely, they will be better appreciated if they are well layed out and formatted."
},
{
"code": null,
"e": 1331,
"s": 1175,
"text": "Very simple. The # precedes a heading equivalent to <h1> in HTML, two of them means a secondary heading, <h2>. The more # symbols, the smaller the heading."
},
{
"code": null,
"e": 1422,
"s": 1331,
"text": "So the following Markdown code will display a list of headings gradually reducing in size."
},
{
"code": null,
"e": 1504,
"s": 1422,
"text": "# heading 1## heading 2### heading 3#### heading 4##### heading 5###### heading 6"
},
{
"code": null,
"e": 1842,
"s": 1504,
"text": "Markdown supports the most common styling such as bold and italic, you can construct lists both numbered and unnumbered. You can embed code within a paragraph or display a complete code block. Hyperlinks are included and you can insert images, too. Tables can be constructed with left and right justified columns with very simple syntax."
},
{
"code": null,
"e": 1942,
"s": 1842,
"text": "Markdown ignores single line breaks, so to separate paragraphs, you need to insert two line breaks."
},
{
"code": null,
"e": 2132,
"s": 1942,
"text": "Below we are going to go through some examples of the Markdown code. For each example I’ll show you the Markdown code and then follow it with the way that it will look after being rendered."
},
{
"code": null,
"e": 2186,
"s": 2132,
"text": "First we’ll take a look at some simple inline markup."
},
{
"code": null,
"e": 2241,
"s": 2186,
"text": "Here is the code and below it is the rendered version:"
},
{
"code": null,
"e": 2539,
"s": 2241,
"text": "This is a paragraph that illustrates some of the Markdown features.This is a new paragraph that includes some code: `print(123)` you can see that it is enclosed in single back ticks. Other simple markup is *italic which is enclosed in asterisks* and **bold which is enclosed in double asterisks**."
},
{
"code": null,
"e": 2687,
"s": 2539,
"text": "You can use single or double underscores to make text italic or bold. So, by mixing underscores and stars you can have text that is both italic and"
},
{
"code": null,
"e": 2829,
"s": 2687,
"text": "You can also use an _underscore to make things italic_, or two of them for __bold__. This means you can have both _**italic and bold**_ text."
},
{
"code": null,
"e": 2869,
"s": 2829,
"text": "Block quotes are preceded by a chevron."
},
{
"code": null,
"e": 2922,
"s": 2869,
"text": "> To include a block quote you precede it with a `>`"
},
{
"code": null,
"e": 3025,
"s": 2922,
"text": "If you want to include a code block use three backticks or ~ characters to enclose the code like this:"
},
{
"code": null,
"e": 3066,
"s": 3025,
"text": "~~~pythonfor i in (1,2,3): print(i)~~~"
},
{
"code": null,
"e": 3074,
"s": 3066,
"text": "or this"
},
{
"code": null,
"e": 3115,
"s": 3074,
"text": "```pythonfor i in (1,2,3): print(i)```"
},
{
"code": null,
"e": 3183,
"s": 3115,
"text": "and you’ll get a block of code which will probably be colour coded:"
},
{
"code": null,
"e": 3353,
"s": 3183,
"text": "Note that the use of the name a programming language is optional and, although it is not part of the Markdown specification, colour coding is included in most renderers."
},
{
"code": null,
"e": 3469,
"s": 3353,
"text": "There are both ordered and unordered lists. The items in an unordered list are preceded by a star, minus or a plus:"
},
{
"code": null,
"e": 3488,
"s": 3469,
"text": "+ item- item* item"
},
{
"code": null,
"e": 3504,
"s": 3488,
"text": "This looks like"
},
{
"code": null,
"e": 3509,
"s": 3504,
"text": "item"
},
{
"code": null,
"e": 3514,
"s": 3509,
"text": "item"
},
{
"code": null,
"e": 3519,
"s": 3514,
"text": "item"
},
{
"code": null,
"e": 3560,
"s": 3519,
"text": "Sublists are just indented with a space:"
},
{
"code": null,
"e": 3587,
"s": 3560,
"text": "+ item + item + item+ item"
},
{
"code": null,
"e": 3721,
"s": 3587,
"text": "Numbered lists begin with — you guessed it — a number, followed by a dot. And you can mix and match ordered, unordered and sub-lists."
},
{
"code": null,
"e": 3764,
"s": 3721,
"text": "1. item2. item3. item + item + item4. item"
},
{
"code": null,
"e": 4043,
"s": 3764,
"text": "Images are referenced by their path or URI. To include an image the line starts with an exclamation mark followed by a pair of square brackets where the alt-text goes then a pair of braces containing image path and a string which will be displayed when you hover over the image."
},
{
"code": null,
"e": 4152,
"s": 4043,
"text": ""
},
{
"code": null,
"e": 4245,
"s": 4152,
"text": "Links look similar to images except the text in the square brackets is the actual link text."
},
{
"code": null,
"e": 4329,
"s": 4245,
"text": "Here is a link to [Google’s](https://www.google.com “Google’s Homepage”) home page."
},
{
"code": null,
"e": 4351,
"s": 4329,
"text": "Which is rendered as:"
},
{
"code": null,
"e": 4389,
"s": 4351,
"text": "Here is a link to Google’s home page."
},
{
"code": null,
"e": 4557,
"s": 4389,
"text": "In a table the columns are separated with the pipe character(|) and the header is followed by a row of dashes, then the rest of the data follows row by row, like this:"
},
{
"code": null,
"e": 4660,
"s": 4557,
"text": "Col1 |Col2 |Col3-----|-----|----- Data1|Data2|Data3Data1|Data2|Data3Data1|Data2|Data3Data1|Data2|Data3"
},
{
"code": null,
"e": 4856,
"s": 4660,
"text": "You can also align columns by placing colons in the header underline. A colon of the right means right aligned, on the left means left aligned and one on each side is centered. Here’s an example:"
},
{
"code": null,
"e": 5028,
"s": 4856,
"text": "Left aligned column | Centered column | Right aligned column:-------------------|:---------------:|--------------------:**Bold data** | *Italic data* | Normal data"
},
{
"code": null,
"e": 5102,
"s": 5028,
"text": "And, as you see, the entries in the table can be made bold or italicised."
},
{
"code": null,
"e": 5246,
"s": 5102,
"text": "The layout of the code does not have to be neat, Markdown will sort it out. This messy version of the table above is rendered exactly the same."
},
{
"code": null,
"e": 5356,
"s": 5246,
"text": "Left aligned column | Centered column | Right aligned column:-|:-:|-:**Bold data**|*Italic data*| Normal data"
},
{
"code": null,
"e": 5438,
"s": 5356,
"text": "You can add whatever HTML you want, if Markdown doesn’t do exactly what you want."
},
{
"code": null,
"e": 5579,
"s": 5438,
"text": "Here’s a bit of Markdown text. Can you see the difference between**Markdown bold** and <b>HTML bold</b>?No, you can’t because it’s the same!"
},
{
"code": null,
"e": 5674,
"s": 5579,
"text": "Here’s a bit of Markdown text. Can you see the difference between Markdown bold and HTML bold?"
},
{
"code": null,
"e": 5711,
"s": 5674,
"text": "No, you can’t because it’s the same!"
},
{
"code": null,
"e": 5799,
"s": 5711,
"text": "And to finish off here is a horizontal line. Just type three dashes on a line by itself"
},
{
"code": null,
"e": 5803,
"s": 5799,
"text": "---"
},
{
"code": null,
"e": 5888,
"s": 5803,
"text": "(There is no horizontal line in the Medium editor but I’m sure you can imagine one!)"
},
{
"code": null,
"e": 5985,
"s": 5888,
"text": "That’s plenty enough to make your Jupyter Notebooks into attractive readable documents, I think."
},
{
"code": null,
"e": 6207,
"s": 5985,
"text": "Since Medium doesn’t support all of the stuff that Markdown can do, I’ve relied to a considerable extent on images. But if you would like to see the original version of this notebook you can view it, or download it, here."
}
] |
Count set bits in an integer using Lookup Table - GeeksforGeeks | 13 Apr, 2022
Write an efficient program to count number of 1s in binary representation of an integer.Examples
Input : n = 6
Output : 2
Binary representation of 6 is 110
and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 11 is 1101
and has 3 set bits
In the previous post we had seen different method that solved this problem in O(log n) time. In this post we solve in O(1) using lookup table. Here we assume that the size of INT is 32-bits. It’s hard to count all 32 bits in one go using lookup table (” because it’s infeasible to create lookup table of size 232-1 “). So we break 32 bits into 8 bits of chunks( How lookup table of size (28-1 ) index : 0-255 ).LookUp Table In lookup tale, we store count of set_bit of every number that are in a range (0-255) LookupTable[0] = 0 | binary 00000000 CountSetBits 0 LookupTable[1] = 1 | binary 00000001 CountSetBits 1 LookupTable[2] = 1 | binary 00000010 CountSetBits 1 LookupTable[3] = 2 | binary 00000011 CountSetBits 2 LookupTable[4] = 1 | binary 00000100 CountSetBits 1 and so...on upto LookupTable[255].Let’s take an Example How lookup table work.
Let's number be : 354
in Binary : 0000000000000000000000101100010
Split it into 8 bits chunks :
In Binary : 00000000 | 00000000 | 00000001 | 01100010
In decimal : 0 0 1 98
Now Count Set_bits using LookupTable
LookupTable[0] = 0
LookupTable[1] = 1
LookupTable[98] = 3
so Total bits count : 4
CPP
// c++ count to count number of set bits// using lookup table in O(1) time #include <iostream>using namespace std; // Generate a lookup table for 32 bit integers#define B2(n) n, n + 1, n + 1, n + 2#define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)#define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2) // Lookup table that store the reverse of each tableunsigned int lookuptable[256] = { B6(0), B6(1), B6(1), B6(2) }; // function countset Bits Using lookup table// ans return set bits countunsigned int countSetBits(int N){ // first chunk of 8 bits from right unsigned int count = lookuptable[N & 0xff] + // second chunk from right lookuptable[(N >> 8) & 0xff] + // third and fourth chunks lookuptable[(N >> 16) & 0xff] + lookuptable[(N >> 24) & 0xff]; return count;} int main(){ unsigned int N = 354; cout << countSetBits(N) << endl; return 0;}
Output:
4
Time Complexity : O(1)
avtarkumar719
shobhitvjain
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Bit Tricks for Competitive Programming
Write an Efficient Method to Check if a Number is Multiple of 3
Check for Integer Overflow
Convert decimal fraction to binary number
Reverse actual bits of the given number
Builtin functions of GCC compiler
Hamming code Implementation in C/C++
Check if a Number is Odd or Even using Bitwise Operators | [
{
"code": null,
"e": 24932,
"s": 24904,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 25031,
"s": 24932,
"text": "Write an efficient program to count number of 1s in binary representation of an integer.Examples "
},
{
"code": null,
"e": 25193,
"s": 25031,
"text": "Input : n = 6\nOutput : 2\nBinary representation of 6 is 110 \nand has 2 set bits\n\nInput : n = 13\nOutput : 3\nBinary representation of 11 is 1101 \nand has 3 set bits"
},
{
"code": null,
"e": 26045,
"s": 25195,
"text": "In the previous post we had seen different method that solved this problem in O(log n) time. In this post we solve in O(1) using lookup table. Here we assume that the size of INT is 32-bits. It’s hard to count all 32 bits in one go using lookup table (” because it’s infeasible to create lookup table of size 232-1 “). So we break 32 bits into 8 bits of chunks( How lookup table of size (28-1 ) index : 0-255 ).LookUp Table In lookup tale, we store count of set_bit of every number that are in a range (0-255) LookupTable[0] = 0 | binary 00000000 CountSetBits 0 LookupTable[1] = 1 | binary 00000001 CountSetBits 1 LookupTable[2] = 1 | binary 00000010 CountSetBits 1 LookupTable[3] = 2 | binary 00000011 CountSetBits 2 LookupTable[4] = 1 | binary 00000100 CountSetBits 1 and so...on upto LookupTable[255].Let’s take an Example How lookup table work. "
},
{
"code": null,
"e": 26374,
"s": 26045,
"text": "Let's number be : 354 \nin Binary : 0000000000000000000000101100010\n\nSplit it into 8 bits chunks :\nIn Binary : 00000000 | 00000000 | 00000001 | 01100010\nIn decimal : 0 0 1 98\n\nNow Count Set_bits using LookupTable\nLookupTable[0] = 0\nLookupTable[1] = 1\nLookupTable[98] = 3\n\nso Total bits count : 4 "
},
{
"code": null,
"e": 26380,
"s": 26376,
"text": "CPP"
},
{
"code": "// c++ count to count number of set bits// using lookup table in O(1) time #include <iostream>using namespace std; // Generate a lookup table for 32 bit integers#define B2(n) n, n + 1, n + 1, n + 2#define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)#define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2) // Lookup table that store the reverse of each tableunsigned int lookuptable[256] = { B6(0), B6(1), B6(1), B6(2) }; // function countset Bits Using lookup table// ans return set bits countunsigned int countSetBits(int N){ // first chunk of 8 bits from right unsigned int count = lookuptable[N & 0xff] + // second chunk from right lookuptable[(N >> 8) & 0xff] + // third and fourth chunks lookuptable[(N >> 16) & 0xff] + lookuptable[(N >> 24) & 0xff]; return count;} int main(){ unsigned int N = 354; cout << countSetBits(N) << endl; return 0;}",
"e": 27393,
"s": 26380,
"text": null
},
{
"code": null,
"e": 27403,
"s": 27393,
"text": "Output: "
},
{
"code": null,
"e": 27406,
"s": 27403,
"text": "4 "
},
{
"code": null,
"e": 27430,
"s": 27406,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 27444,
"s": 27430,
"text": "avtarkumar719"
},
{
"code": null,
"e": 27457,
"s": 27444,
"text": "shobhitvjain"
},
{
"code": null,
"e": 27467,
"s": 27457,
"text": "Bit Magic"
},
{
"code": null,
"e": 27477,
"s": 27467,
"text": "Bit Magic"
},
{
"code": null,
"e": 27575,
"s": 27477,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27584,
"s": 27575,
"text": "Comments"
},
{
"code": null,
"e": 27597,
"s": 27584,
"text": "Old Comments"
},
{
"code": null,
"e": 27648,
"s": 27597,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 27671,
"s": 27648,
"text": "Program to find parity"
},
{
"code": null,
"e": 27710,
"s": 27671,
"text": "Bit Tricks for Competitive Programming"
},
{
"code": null,
"e": 27774,
"s": 27710,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 27801,
"s": 27774,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 27843,
"s": 27801,
"text": "Convert decimal fraction to binary number"
},
{
"code": null,
"e": 27883,
"s": 27843,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 27917,
"s": 27883,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 27954,
"s": 27917,
"text": "Hamming code Implementation in C/C++"
}
] |
Python | Element repetition in list - GeeksforGeeks | 26 Jan, 2019
Sometimes we require to add a duplicate value in the list for several different utilities. This type of application is sometimes required in day-day programming. Let’s discuss certain ways in which we add a clone of a number to its next position.
Method #1 : Using list comprehensionIn this method, we just iterate the loop twice for each value and add to the desired new list. This is just a shorthand alternative to the naive method.
# Python3 code to demonstrate # to perform element duplication# using list comprehension # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension# to perform element duplicationres = [i for i in test_list for x in (0, 1)] # printing result print ("The list after element duplication " + str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
Method #2 : Using reduce() + addWe can also use the reduce function to act the the function to perform the addition of a pair of similar numbers simultaneously in the list.
# Python3 code to demonstrate # to perform element duplication# using reduce() + addfrom operator import add # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # using reduce() + add# to perform element duplicationres = list(reduce(add, [(i, i) for i in test_list])) # printing result print ("The list after element duplication " + str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
Method #3 : Using itertools.chain().from_iterable()from_iterable function can also be used to perform this task of adding a duplicate. It just makes the pair of each iterated element and inserts it successively.
# Python3 code to demonstrate # to perform element duplication# using itertools.chain.from_iterable()import itertools # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # using itertools.chain.from_iterable()# to perform element duplicationres = list(itertools.chain.from_iterable([i, i] for i in test_list)) # printing result print ("The list after element duplication " + str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24025,
"s": 23997,
"text": "\n26 Jan, 2019"
},
{
"code": null,
"e": 24272,
"s": 24025,
"text": "Sometimes we require to add a duplicate value in the list for several different utilities. This type of application is sometimes required in day-day programming. Let’s discuss certain ways in which we add a clone of a number to its next position."
},
{
"code": null,
"e": 24461,
"s": 24272,
"text": "Method #1 : Using list comprehensionIn this method, we just iterate the loop twice for each value and add to the desired new list. This is just a shorthand alternative to the naive method."
},
{
"code": "# Python3 code to demonstrate # to perform element duplication# using list comprehension # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # using list comprehension# to perform element duplicationres = [i for i in test_list for x in (0, 1)] # printing result print (\"The list after element duplication \" + str(res))",
"e": 24857,
"s": 24461,
"text": null
},
{
"code": null,
"e": 24866,
"s": 24857,
"text": "Output :"
},
{
"code": null,
"e": 24972,
"s": 24866,
"text": "The original list is : [4, 5, 6, 3, 9]\nThe list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]\n"
},
{
"code": null,
"e": 25147,
"s": 24974,
"text": "Method #2 : Using reduce() + addWe can also use the reduce function to act the the function to perform the addition of a pair of similar numbers simultaneously in the list."
},
{
"code": "# Python3 code to demonstrate # to perform element duplication# using reduce() + addfrom operator import add # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # using reduce() + add# to perform element duplicationres = list(reduce(add, [(i, i) for i in test_list])) # printing result print (\"The list after element duplication \" + str(res))",
"e": 25567,
"s": 25147,
"text": null
},
{
"code": null,
"e": 25576,
"s": 25567,
"text": "Output :"
},
{
"code": null,
"e": 25682,
"s": 25576,
"text": "The original list is : [4, 5, 6, 3, 9]\nThe list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]\n"
},
{
"code": null,
"e": 25896,
"s": 25684,
"text": "Method #3 : Using itertools.chain().from_iterable()from_iterable function can also be used to perform this task of adding a duplicate. It just makes the pair of each iterated element and inserts it successively."
},
{
"code": "# Python3 code to demonstrate # to perform element duplication# using itertools.chain.from_iterable()import itertools # initializing list test_list = [4, 5, 6, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # using itertools.chain.from_iterable()# to perform element duplicationres = list(itertools.chain.from_iterable([i, i] for i in test_list)) # printing result print (\"The list after element duplication \" + str(res))",
"e": 26358,
"s": 25896,
"text": null
},
{
"code": null,
"e": 26367,
"s": 26358,
"text": "Output :"
},
{
"code": null,
"e": 26473,
"s": 26367,
"text": "The original list is : [4, 5, 6, 3, 9]\nThe list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]\n"
},
{
"code": null,
"e": 26494,
"s": 26473,
"text": "Python list-programs"
},
{
"code": null,
"e": 26506,
"s": 26494,
"text": "python-list"
},
{
"code": null,
"e": 26513,
"s": 26506,
"text": "Python"
},
{
"code": null,
"e": 26525,
"s": 26513,
"text": "python-list"
},
{
"code": null,
"e": 26623,
"s": 26525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26632,
"s": 26623,
"text": "Comments"
},
{
"code": null,
"e": 26645,
"s": 26632,
"text": "Old Comments"
},
{
"code": null,
"e": 26663,
"s": 26645,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26698,
"s": 26663,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26730,
"s": 26698,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26772,
"s": 26730,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26798,
"s": 26772,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26841,
"s": 26798,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26885,
"s": 26841,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26910,
"s": 26885,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26947,
"s": 26910,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Horizontal stacked bar chart in Matplotlib | To plot stacked bar chart in Matplotlib, we can use barh() methods
Set the figure size and adjust the padding between and around the subplots.
Create a list of years, issues_addressed and issues_pending, in accordance with years.
Plot horizontal bars with years and issues_addressed data.
To make stacked horizontal bars, use barh() method with years, issues_pending and issues_addressed data
Place the legend on the plot.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
year = [2014, 2015, 2016, 2017, 2018, 2019]
issues_addressed = [10, 14, 0, 10, 15, 15]
issues_pending = [5, 10, 50, 2, 0, 10]
b1 = plt.barh(year, issues_addressed, color="red")
b2 = plt.barh(year, issues_pending, left=issues_addressed, color="yellow")
plt.legend([b1, b2], ["Completed", "Pending"], title="Issues", loc="upper right")
plt.show() | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To plot stacked bar chart in Matplotlib, we can use barh() methods"
},
{
"code": null,
"e": 1205,
"s": 1129,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1292,
"s": 1205,
"text": "Create a list of years, issues_addressed and issues_pending, in accordance with years."
},
{
"code": null,
"e": 1351,
"s": 1292,
"text": "Plot horizontal bars with years and issues_addressed data."
},
{
"code": null,
"e": 1455,
"s": 1351,
"text": "To make stacked horizontal bars, use barh() method with years, issues_pending and issues_addressed data"
},
{
"code": null,
"e": 1485,
"s": 1455,
"text": "Place the legend on the plot."
},
{
"code": null,
"e": 1527,
"s": 1485,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2001,
"s": 1527,
"text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nyear = [2014, 2015, 2016, 2017, 2018, 2019]\nissues_addressed = [10, 14, 0, 10, 15, 15]\nissues_pending = [5, 10, 50, 2, 0, 10]\n\nb1 = plt.barh(year, issues_addressed, color=\"red\")\n\nb2 = plt.barh(year, issues_pending, left=issues_addressed, color=\"yellow\")\n\nplt.legend([b1, b2], [\"Completed\", \"Pending\"], title=\"Issues\", loc=\"upper right\")\n\nplt.show()"
}
] |
Convert the number from International system to Indian system - GeeksforGeeks | 05 Nov, 2020
Given string str which represents a number with separators(, ) in the International number system, the task is to convert this string representation into the Indian Numeric System. Examples:
Input: str = “123, 456, 789” Output: 12, 34, 56, 789 Explanation: The given string represents a number in the international system. It is converted to the Indian system. Input: str = “90, 050, 000, 000” Output: 90, 05, 00, 00, 000
International Numeric System: The International numbering system is used outside the Indian subcontinent to express large numbers. It follows the following schema:
Indian Numeric System: The Indian numbering system is used in the Indian subcontinent to express large numbers. It follows the following schema:
Approach: From the above representations, the idea is to first obtain the number without any separators. Therefore:
Remove all the separators(, ) from the string.Reverse the string.Process the string and put a separator(, ) after the third number.Now put a separator(, ) after every second number. This converts the number into the Indian Numeric System.Reverse the string again and print it.
Remove all the separators(, ) from the string.
Reverse the string.
Process the string and put a separator(, ) after the third number.
Now put a separator(, ) after every second number. This converts the number into the Indian Numeric System.
Reverse the string again and print it.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to convert the number// from International system// to Indian system #include <bits/stdc++.h>using namespace std; // Function to convert a number represented// in International numeric system to// Indian numeric system.string convert(string input){ // Find the length of the // input string int len = input.length(); // Removing all the separators(, ) // from the input string for (int i = 0; i < len;) { if (input[i] == ', ') { input.erase(input.begin() + i); len--; i--; } else if (input[i] == ' ') { input.erase(input.begin() + i); len--; i--; } else { i++; } } // Reverse the input string reverse(input.begin(), input.end()); // Declaring the output string string output; // Process the input string for (int i = 0; i < len; i++) { // Add a separator(, ) after the // third number if (i == 2) { output += input[i]; output += ", "; } // Then add a separator(, ) after // every second number else if (i > 2 && i % 2 == 0 && i + 1 < len) { output += input[i]; output += ", "; } else { output += input[i]; } } // Reverse the output string reverse(output.begin(), output.end()); // Return the output string back // to the main function return output;} // Driver codeint main(){ string input1 = "123, 456, 789"; string input2 = "90, 050, 000, 000"; cout << convert(input1) << endl; cout << convert(input2);}
// Java program to convert the number// from International system// to Indian systemimport java.util.*;class GFG{ // Function to convert a number represented// in International numeric system to// Indian numeric system.static String convert(String input){ StringBuilder sbInput = new StringBuilder(input); // Find the length of the // sbInput int len = sbInput.length(); // Removing all the separators(, ) // from the sbInput for (int i = 0; i < len;) { if (sbInput.charAt(i) == ',') { sbInput.deleteCharAt(i); len--; i--; } else if (sbInput.charAt(i) == ' ') { sbInput.deleteCharAt(i); len--; i--; } else { i++; } } // Reverse the sbInput StringBuilder sbInputReverse = sbInput.reverse(); // Declaring the output StringBuilder output = new StringBuilder(); // Process the sbInput for (int i = 0; i < len; i++) { // Add a separator(, ) after the // third number if (i == 2) { output.append(sbInputReverse.charAt(i)); output.append(" ,"); } // Then add a separator(, ) after // every second number else if (i > 2 && i % 2 == 0 && i + 1 < len) { output.append(sbInputReverse.charAt(i)); output.append(" ,"); } else { output.append(sbInputReverse.charAt(i)); } } // Reverse the output StringBuilder reverseOutput = output.reverse(); // Return the output string back // to the main function return reverseOutput.toString();} // Driver codepublic static void main(String[] args){ String input1 = "123, 456, 789"; String input2 = "90, 050, 000, 000"; System.out.println(convert(input1)); System.out.println(convert(input2));}} // This code is contributed by offbeat
# Python3 program to convert# the number from International# system to Indian system # Function to convert a number# represented in International# numeric system to Indian numeric# system.def convert(input): # Find the length of the # input string Len = len(input) # Removing all the separators(, ) # from the input string i = 0 while(i < Len): if(input[i] == ","): input = input[:i] + input[i + 1:] Len -= 1 i -= 1 elif(input[i] == " "): input=input[:i] + input[i + 1:] Len -= 1 i -= 1 else: i += 1 # Reverse the input string input=input[::-1] # Declaring the output string output = "" # Process the input string for i in range(Len): # Add a separator(, ) after the # third number if(i == 2): output += input[i] output += " ," # Then add a separator(, ) after # every second number elif(i > 2 and i % 2 == 0 and i + 1 < Len): output += input[i] output += " ," else: output += input[i] # Reverse the output string output=output[::-1] # Return the output string back # to the main function return output # Driver codeinput1 = "123, 456, 789"input2 = "90, 050, 000, 000"print(convert(input1))print(convert(input2)) # This code is contributed by avanitrachhadiya2155
12, 34, 56, 789
90, 05, 00, 00, 000
offbeat
avanitrachhadiya2155
Mathematical
School Programming
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 25350,
"s": 25322,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 25542,
"s": 25350,
"text": "Given string str which represents a number with separators(, ) in the International number system, the task is to convert this string representation into the Indian Numeric System. Examples: "
},
{
"code": null,
"e": 25774,
"s": 25542,
"text": "Input: str = “123, 456, 789” Output: 12, 34, 56, 789 Explanation: The given string represents a number in the international system. It is converted to the Indian system. Input: str = “90, 050, 000, 000” Output: 90, 05, 00, 00, 000 "
},
{
"code": null,
"e": 25938,
"s": 25774,
"text": "International Numeric System: The International numbering system is used outside the Indian subcontinent to express large numbers. It follows the following schema:"
},
{
"code": null,
"e": 26083,
"s": 25938,
"text": "Indian Numeric System: The Indian numbering system is used in the Indian subcontinent to express large numbers. It follows the following schema:"
},
{
"code": null,
"e": 26200,
"s": 26083,
"text": "Approach: From the above representations, the idea is to first obtain the number without any separators. Therefore: "
},
{
"code": null,
"e": 26477,
"s": 26200,
"text": "Remove all the separators(, ) from the string.Reverse the string.Process the string and put a separator(, ) after the third number.Now put a separator(, ) after every second number. This converts the number into the Indian Numeric System.Reverse the string again and print it."
},
{
"code": null,
"e": 26524,
"s": 26477,
"text": "Remove all the separators(, ) from the string."
},
{
"code": null,
"e": 26544,
"s": 26524,
"text": "Reverse the string."
},
{
"code": null,
"e": 26611,
"s": 26544,
"text": "Process the string and put a separator(, ) after the third number."
},
{
"code": null,
"e": 26719,
"s": 26611,
"text": "Now put a separator(, ) after every second number. This converts the number into the Indian Numeric System."
},
{
"code": null,
"e": 26758,
"s": 26719,
"text": "Reverse the string again and print it."
},
{
"code": null,
"e": 26810,
"s": 26758,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26814,
"s": 26810,
"text": "C++"
},
{
"code": null,
"e": 26819,
"s": 26814,
"text": "Java"
},
{
"code": null,
"e": 26827,
"s": 26819,
"text": "Python3"
},
{
"code": "// C++ program to convert the number// from International system// to Indian system #include <bits/stdc++.h>using namespace std; // Function to convert a number represented// in International numeric system to// Indian numeric system.string convert(string input){ // Find the length of the // input string int len = input.length(); // Removing all the separators(, ) // from the input string for (int i = 0; i < len;) { if (input[i] == ', ') { input.erase(input.begin() + i); len--; i--; } else if (input[i] == ' ') { input.erase(input.begin() + i); len--; i--; } else { i++; } } // Reverse the input string reverse(input.begin(), input.end()); // Declaring the output string string output; // Process the input string for (int i = 0; i < len; i++) { // Add a separator(, ) after the // third number if (i == 2) { output += input[i]; output += \", \"; } // Then add a separator(, ) after // every second number else if (i > 2 && i % 2 == 0 && i + 1 < len) { output += input[i]; output += \", \"; } else { output += input[i]; } } // Reverse the output string reverse(output.begin(), output.end()); // Return the output string back // to the main function return output;} // Driver codeint main(){ string input1 = \"123, 456, 789\"; string input2 = \"90, 050, 000, 000\"; cout << convert(input1) << endl; cout << convert(input2);}",
"e": 28486,
"s": 26827,
"text": null
},
{
"code": "// Java program to convert the number// from International system// to Indian systemimport java.util.*;class GFG{ // Function to convert a number represented// in International numeric system to// Indian numeric system.static String convert(String input){ StringBuilder sbInput = new StringBuilder(input); // Find the length of the // sbInput int len = sbInput.length(); // Removing all the separators(, ) // from the sbInput for (int i = 0; i < len;) { if (sbInput.charAt(i) == ',') { sbInput.deleteCharAt(i); len--; i--; } else if (sbInput.charAt(i) == ' ') { sbInput.deleteCharAt(i); len--; i--; } else { i++; } } // Reverse the sbInput StringBuilder sbInputReverse = sbInput.reverse(); // Declaring the output StringBuilder output = new StringBuilder(); // Process the sbInput for (int i = 0; i < len; i++) { // Add a separator(, ) after the // third number if (i == 2) { output.append(sbInputReverse.charAt(i)); output.append(\" ,\"); } // Then add a separator(, ) after // every second number else if (i > 2 && i % 2 == 0 && i + 1 < len) { output.append(sbInputReverse.charAt(i)); output.append(\" ,\"); } else { output.append(sbInputReverse.charAt(i)); } } // Reverse the output StringBuilder reverseOutput = output.reverse(); // Return the output string back // to the main function return reverseOutput.toString();} // Driver codepublic static void main(String[] args){ String input1 = \"123, 456, 789\"; String input2 = \"90, 050, 000, 000\"; System.out.println(convert(input1)); System.out.println(convert(input2));}} // This code is contributed by offbeat",
"e": 30420,
"s": 28486,
"text": null
},
{
"code": "# Python3 program to convert# the number from International# system to Indian system # Function to convert a number# represented in International# numeric system to Indian numeric# system.def convert(input): # Find the length of the # input string Len = len(input) # Removing all the separators(, ) # from the input string i = 0 while(i < Len): if(input[i] == \",\"): input = input[:i] + input[i + 1:] Len -= 1 i -= 1 elif(input[i] == \" \"): input=input[:i] + input[i + 1:] Len -= 1 i -= 1 else: i += 1 # Reverse the input string input=input[::-1] # Declaring the output string output = \"\" # Process the input string for i in range(Len): # Add a separator(, ) after the # third number if(i == 2): output += input[i] output += \" ,\" # Then add a separator(, ) after # every second number elif(i > 2 and i % 2 == 0 and i + 1 < Len): output += input[i] output += \" ,\" else: output += input[i] # Reverse the output string output=output[::-1] # Return the output string back # to the main function return output # Driver codeinput1 = \"123, 456, 789\"input2 = \"90, 050, 000, 000\"print(convert(input1))print(convert(input2)) # This code is contributed by avanitrachhadiya2155",
"e": 31872,
"s": 30420,
"text": null
},
{
"code": null,
"e": 31910,
"s": 31872,
"text": "12, 34, 56, 789\n90, 05, 00, 00, 000\n\n"
},
{
"code": null,
"e": 31920,
"s": 31912,
"text": "offbeat"
},
{
"code": null,
"e": 31941,
"s": 31920,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 31954,
"s": 31941,
"text": "Mathematical"
},
{
"code": null,
"e": 31973,
"s": 31954,
"text": "School Programming"
},
{
"code": null,
"e": 31981,
"s": 31973,
"text": "Strings"
},
{
"code": null,
"e": 31989,
"s": 31981,
"text": "Strings"
},
{
"code": null,
"e": 32002,
"s": 31989,
"text": "Mathematical"
},
{
"code": null,
"e": 32100,
"s": 32002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32109,
"s": 32100,
"text": "Comments"
},
{
"code": null,
"e": 32122,
"s": 32109,
"text": "Old Comments"
},
{
"code": null,
"e": 32165,
"s": 32122,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32207,
"s": 32165,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32231,
"s": 32207,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32245,
"s": 32231,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32294,
"s": 32245,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32312,
"s": 32294,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32328,
"s": 32312,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32347,
"s": 32328,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32372,
"s": 32347,
"text": "Reverse a string in Java"
}
] |
Cryptocurrency Analysis with Python — Log Returns | by Roman Orac | Towards Data Science | In the previous post, we analyzed raw price changes of cryptocurrencies. The problem with that approach is that prices of different cryptocurrencies are not normalized and we cannot use comparable metrics.
In this post, we describe the benefits of using log returns for analysis of price changes. You can download this Jupyter Notebook and the data.
In case you’ve missed my other articles about this topic:
romanorac.medium.com
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
SciPy — scientific and numerical tools for Python
For other requirements, see my first blog post of this series.
import pandas as pddf_btc = pd.read_csv('BTC_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df_eth = pd.read_csv('ETH_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df_ltc = pd.read_csv('LTC_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df = pd.DataFrame({'BTC': df_btc.close, 'ETH': df_eth.close, 'LTC': df_ltc.close})df.index = df.index.map(pd.to_datetime)df = df.sort_index()df.head()
The benefit of using returns, versus prices, is normalization: measuring all variables in a comparable metric, thus enabling evaluation of analytic relationships amongst two or more variables despite originating from price series of unequal values (for details, see Why Log Returns).
Let’s define return as:
Author of Why Log Returns outlines several benefits of using log returns instead of returns so we transform returns equation to log returns equation:
Now, we apply the log returns equation to closing prices of cryptocurrencies:
import numpy as np# shift moves dates back by 1df_change = df.apply(lambda x: np.log(x) - np.log(x.shift(1)))df_change.head()
We plot normalized changes of closing prices for last 50 hours. Log differences can be interpreted as the percentage change.
df_change[:50].plot(figsize=(15, 10)).axhline(color='black', linewidth=2)
If we assume that prices are distributed log-normally, then log(1+ri) is conveniently normally distributed (for details, see Why Log Returns)
On the chart below, we plot the distribution of LTC hourly closing prices. We also estimate parameters for log-normal distribution and plot estimated log-normal distribution with a red line.
from scipy.stats import lognormimport matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(10, 6))values = df['LTC']shape, loc, scale = stats.lognorm.fit(values) x = np.linspace(values.min(), values.max(), len(values))pdf = stats.lognorm.pdf(x, shape, loc=loc, scale=scale) label = 'mean=%.4f, std=%.4f, shape=%.4f' % (loc, scale, shape)ax.hist(values, bins=30, normed=True)ax.plot(x, pdf, 'r-', lw=2, label=label)ax.legend(loc='best')
On the chart below, we plot the distribution of LTC log returns. We also estimate parameters for normal distribution and plot estimated normal distribution with a red line.
import pandas as pdimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as pltvalues = df_change['LTC'][1:] # skip first NA valuex = np.linspace(values.min(), values.max(), len(values))loc, scale = stats.norm.fit(values)param_density = stats.norm.pdf(x, loc=loc, scale=scale)label = 'mean=%.4f, std=%.4f' % (loc, scale)fig, ax = plt.subplots(figsize=(10, 6))ax.hist(values, bins=30, normed=True)ax.plot(x, param_density, 'r-', label=label)ax.legend(loc='best')
We calculate the Pearson Correlation from log returns. The correlation matrix below has similar values as the one at Sifr Data. There are differences because:
we don’t calculate volume-weighted average daily prices
different time period (hourly and daily),
different data sources (Coinbase and Poloniex).
Observations
BTC and ETH have a moderate positive relationship,
LTC and ETH have a strong positive relationship.
import seaborn as snsimport matplotlib.pyplot as plt# Compute the correlation matrixcorr = df_change.corr()# Generate a mask for the upper trianglemask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True# Set up the matplotlib figuref, ax = plt.subplots(figsize=(10, 10))# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, annot=True, fmt = '.4f', mask=mask, center=0, square=True, linewidths=.5)
We showed how to calculate log returns from raw prices with a practical example. This way we normalized prices, which simplifies further analysis. We also showed how to estimate parameters for normal and log-normal distributions.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 378,
"s": 172,
"text": "In the previous post, we analyzed raw price changes of cryptocurrencies. The problem with that approach is that prices of different cryptocurrencies are not normalized and we cannot use comparable metrics."
},
{
"code": null,
"e": 522,
"s": 378,
"text": "In this post, we describe the benefits of using log returns for analysis of price changes. You can download this Jupyter Notebook and the data."
},
{
"code": null,
"e": 580,
"s": 522,
"text": "In case you’ve missed my other articles about this topic:"
},
{
"code": null,
"e": 601,
"s": 580,
"text": "romanorac.medium.com"
},
{
"code": null,
"e": 647,
"s": 601,
"text": "Here are a few links that might interest you:"
},
{
"code": null,
"e": 977,
"s": 647,
"text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 1214,
"s": 977,
"text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases."
},
{
"code": null,
"e": 1264,
"s": 1214,
"text": "SciPy — scientific and numerical tools for Python"
},
{
"code": null,
"e": 1327,
"s": 1264,
"text": "For other requirements, see my first blog post of this series."
},
{
"code": null,
"e": 1779,
"s": 1327,
"text": "import pandas as pddf_btc = pd.read_csv('BTC_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df_eth = pd.read_csv('ETH_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df_ltc = pd.read_csv('LTC_USD_Coinbase_hour_2017-12-24.csv', index_col='datetime')df = pd.DataFrame({'BTC': df_btc.close, 'ETH': df_eth.close, 'LTC': df_ltc.close})df.index = df.index.map(pd.to_datetime)df = df.sort_index()df.head()"
},
{
"code": null,
"e": 2063,
"s": 1779,
"text": "The benefit of using returns, versus prices, is normalization: measuring all variables in a comparable metric, thus enabling evaluation of analytic relationships amongst two or more variables despite originating from price series of unequal values (for details, see Why Log Returns)."
},
{
"code": null,
"e": 2087,
"s": 2063,
"text": "Let’s define return as:"
},
{
"code": null,
"e": 2237,
"s": 2087,
"text": "Author of Why Log Returns outlines several benefits of using log returns instead of returns so we transform returns equation to log returns equation:"
},
{
"code": null,
"e": 2315,
"s": 2237,
"text": "Now, we apply the log returns equation to closing prices of cryptocurrencies:"
},
{
"code": null,
"e": 2441,
"s": 2315,
"text": "import numpy as np# shift moves dates back by 1df_change = df.apply(lambda x: np.log(x) - np.log(x.shift(1)))df_change.head()"
},
{
"code": null,
"e": 2566,
"s": 2441,
"text": "We plot normalized changes of closing prices for last 50 hours. Log differences can be interpreted as the percentage change."
},
{
"code": null,
"e": 2640,
"s": 2566,
"text": "df_change[:50].plot(figsize=(15, 10)).axhline(color='black', linewidth=2)"
},
{
"code": null,
"e": 2782,
"s": 2640,
"text": "If we assume that prices are distributed log-normally, then log(1+ri) is conveniently normally distributed (for details, see Why Log Returns)"
},
{
"code": null,
"e": 2973,
"s": 2782,
"text": "On the chart below, we plot the distribution of LTC hourly closing prices. We also estimate parameters for log-normal distribution and plot estimated log-normal distribution with a red line."
},
{
"code": null,
"e": 3412,
"s": 2973,
"text": "from scipy.stats import lognormimport matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(10, 6))values = df['LTC']shape, loc, scale = stats.lognorm.fit(values) x = np.linspace(values.min(), values.max(), len(values))pdf = stats.lognorm.pdf(x, shape, loc=loc, scale=scale) label = 'mean=%.4f, std=%.4f, shape=%.4f' % (loc, scale, shape)ax.hist(values, bins=30, normed=True)ax.plot(x, pdf, 'r-', lw=2, label=label)ax.legend(loc='best')"
},
{
"code": null,
"e": 3585,
"s": 3412,
"text": "On the chart below, we plot the distribution of LTC log returns. We also estimate parameters for normal distribution and plot estimated normal distribution with a red line."
},
{
"code": null,
"e": 4064,
"s": 3585,
"text": "import pandas as pdimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as pltvalues = df_change['LTC'][1:] # skip first NA valuex = np.linspace(values.min(), values.max(), len(values))loc, scale = stats.norm.fit(values)param_density = stats.norm.pdf(x, loc=loc, scale=scale)label = 'mean=%.4f, std=%.4f' % (loc, scale)fig, ax = plt.subplots(figsize=(10, 6))ax.hist(values, bins=30, normed=True)ax.plot(x, param_density, 'r-', label=label)ax.legend(loc='best')"
},
{
"code": null,
"e": 4223,
"s": 4064,
"text": "We calculate the Pearson Correlation from log returns. The correlation matrix below has similar values as the one at Sifr Data. There are differences because:"
},
{
"code": null,
"e": 4279,
"s": 4223,
"text": "we don’t calculate volume-weighted average daily prices"
},
{
"code": null,
"e": 4321,
"s": 4279,
"text": "different time period (hourly and daily),"
},
{
"code": null,
"e": 4369,
"s": 4321,
"text": "different data sources (Coinbase and Poloniex)."
},
{
"code": null,
"e": 4382,
"s": 4369,
"text": "Observations"
},
{
"code": null,
"e": 4433,
"s": 4382,
"text": "BTC and ETH have a moderate positive relationship,"
},
{
"code": null,
"e": 4482,
"s": 4433,
"text": "LTC and ETH have a strong positive relationship."
},
{
"code": null,
"e": 4926,
"s": 4482,
"text": "import seaborn as snsimport matplotlib.pyplot as plt# Compute the correlation matrixcorr = df_change.corr()# Generate a mask for the upper trianglemask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True# Set up the matplotlib figuref, ax = plt.subplots(figsize=(10, 10))# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, annot=True, fmt = '.4f', mask=mask, center=0, square=True, linewidths=.5)"
},
{
"code": null,
"e": 5156,
"s": 4926,
"text": "We showed how to calculate log returns from raw prices with a practical example. This way we normalized prices, which simplifies further analysis. We also showed how to estimate parameters for normal and log-normal distributions."
}
] |
Python 3 -File close() Method | The method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed. Calling close() more than once is allowed.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
Following is the syntax for close() method −
fileObject.close()
NA
This method does not return any value.
The following example shows the usage of close() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file: foo.txt
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2586,
"s": 2340,
"text": "The method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed. Calling close() more than once is allowed."
},
{
"code": null,
"e": 2753,
"s": 2586,
"text": "Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file."
},
{
"code": null,
"e": 2798,
"s": 2753,
"text": "Following is the syntax for close() method −"
},
{
"code": null,
"e": 2818,
"s": 2798,
"text": "fileObject.close()\n"
},
{
"code": null,
"e": 2821,
"s": 2818,
"text": "NA"
},
{
"code": null,
"e": 2860,
"s": 2821,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2917,
"s": 2860,
"text": "The following example shows the usage of close() method."
},
{
"code": null,
"e": 3048,
"s": 2917,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint (\"Name of the file: \", fo.name)\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 3114,
"s": 3048,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3142,
"s": 3114,
"text": "Name of the file: foo.txt\n"
},
{
"code": null,
"e": 3179,
"s": 3142,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3195,
"s": 3179,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3228,
"s": 3195,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3247,
"s": 3228,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3282,
"s": 3247,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3304,
"s": 3282,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3338,
"s": 3304,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3366,
"s": 3338,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3401,
"s": 3366,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3415,
"s": 3401,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3448,
"s": 3415,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3465,
"s": 3448,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3472,
"s": 3465,
"text": " Print"
},
{
"code": null,
"e": 3483,
"s": 3472,
"text": " Add Notes"
}
] |
inheritance(is-a) v/s composition (has-a) relationship in Java | IS-A is a way of saying − This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.
public class Animal {
}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, if we consider the IS-A relationship, we can say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Live Demo
class Animal {
} class Mammal extends Animal {
} class Reptile extends Animal {
} public class Dog extends Mammal {
public static void main(String args[]) {
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This will produce the following result −
true
true
true
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Let's look into an example −
public class Vehicle{ }
public class Speed{ }
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action. | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "IS-A is a way of saying − This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. "
},
{
"code": null,
"e": 1333,
"s": 1194,
"text": "public class Animal {\n}\npublic class Mammal extends Animal {\n}\npublic class Reptile extends Animal {\n}\npublic class Dog extends Mammal {\n}"
},
{
"code": null,
"e": 1389,
"s": 1333,
"text": "Now, if we consider the IS-A relationship, we can say −"
},
{
"code": null,
"e": 1408,
"s": 1389,
"text": "Mammal IS-A Animal"
},
{
"code": null,
"e": 1428,
"s": 1408,
"text": "Reptile IS-A Animal"
},
{
"code": null,
"e": 1444,
"s": 1428,
"text": "Dog IS-A Mammal"
},
{
"code": null,
"e": 1475,
"s": 1444,
"text": "Hence: Dog IS-A Animal as well"
},
{
"code": null,
"e": 1641,
"s": 1475,
"text": "With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass."
},
{
"code": null,
"e": 1728,
"s": 1641,
"text": "We can assure that Mammal is actually an Animal with the use of the instance operator."
},
{
"code": null,
"e": 1738,
"s": 1728,
"text": "Live Demo"
},
{
"code": null,
"e": 2134,
"s": 1738,
"text": "class Animal {\n} class Mammal extends Animal {\n} class Reptile extends Animal {\n} public class Dog extends Mammal {\n public static void main(String args[]) {\n Animal a = new Animal();\n Mammal m = new Mammal();\n Dog d = new Dog();\n System.out.println(m instanceof Animal);\n System.out.println(d instanceof Mammal);\n System.out.println(d instanceof Animal);\n }\n}"
},
{
"code": null,
"e": 2175,
"s": 2134,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2190,
"s": 2175,
"text": "true\ntrue\ntrue"
},
{
"code": null,
"e": 2373,
"s": 2190,
"text": "These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs."
},
{
"code": null,
"e": 2403,
"s": 2373,
"text": "Let's look into an example −"
},
{
"code": null,
"e": 2509,
"s": 2403,
"text": "public class Vehicle{ }\npublic class Speed{ }\npublic class Van extends Vehicle {\n private Speed sp; \n}"
},
{
"code": null,
"e": 2743,
"s": 2509,
"text": "This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications."
},
{
"code": null,
"e": 3129,
"s": 2743,
"text": "In an Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action."
}
] |
Unity - Rigidbodies and Physics | The main issue with the collisions in the last chapter was with the code. We will now modify the values of the GameObject’s position directly. We are simply adding a value to the position, if the player is pressing a key. We need a way to make the player move in such a way that it reacts properly to boundaries and other GameObjects.
To do so, we need to understand what rigidbodies are. Rigidbodies are components that allow a GameObject to react to real-time physics. This includes reactions to forces and gravity, mass, drag and momentum.
You can attach a Rigidbody to your GameObject by simply clicking on Add Component and typing in Rigidbody2D in the search field.
Clicking on Rigidbody2D will attach the component to your GameObject. Now that it is attached, you will notice that many new fields have opened up.
With the default settings, the GameObject will fall vertically down due to gravity. To avoid this, set the Gravity Scale to 0.
Now, playing the game will not show any visible difference, because the GameObject does not have anything to do with its physics component yet.
To solve our problem, let us open our code again, and rewrite it.
public class Movement : MonoBehaviour {
public float speed;
public Rigidbody2D body;
// Update is called once per frame
void Update() {
float h = Input.GetAxisRaw(“Horizontal”);
float v = Input.GetAxisRaw(“Vertical”);
body.velocity = new Vector2(h * speed, v * speed);
}
}
We can see that we create a reference to a Rigidbody2D in the declarations, and our update code works on that reference instead of the Object’s transform. This means that the Rigidbody has now been given the responsibility of moving.
You may expect the body reference to throw NullReferenceException, since we have not assigned anything to it. If you compile and run the game as is, you will get the following error on the bottom left of the editor
To fix this, let us consider the component created by the script. Remember that public properties create their own fields in Unity, as we did with the speed variable.
Adjust the speed to a higher value, around 5, and play the game.
Your collisions will now work correctly!
119 Lectures
23.5 hours
Raja Biswas
58 Lectures
10 hours
Three Millennials
16 Lectures
1 hours
Peter Jepson
23 Lectures
2.5 hours
Zenva
21 Lectures
2 hours
Zenva
43 Lectures
9.5 hours
Raja Biswas
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2550,
"s": 2215,
"text": "The main issue with the collisions in the last chapter was with the code. We will now modify the values of the GameObject’s position directly. We are simply adding a value to the position, if the player is pressing a key. We need a way to make the player move in such a way that it reacts properly to boundaries and other GameObjects."
},
{
"code": null,
"e": 2758,
"s": 2550,
"text": "To do so, we need to understand what rigidbodies are. Rigidbodies are components that allow a GameObject to react to real-time physics. This includes reactions to forces and gravity, mass, drag and momentum."
},
{
"code": null,
"e": 2887,
"s": 2758,
"text": "You can attach a Rigidbody to your GameObject by simply clicking on Add Component and typing in Rigidbody2D in the search field."
},
{
"code": null,
"e": 3035,
"s": 2887,
"text": "Clicking on Rigidbody2D will attach the component to your GameObject. Now that it is attached, you will notice that many new fields have opened up."
},
{
"code": null,
"e": 3162,
"s": 3035,
"text": "With the default settings, the GameObject will fall vertically down due to gravity. To avoid this, set the Gravity Scale to 0."
},
{
"code": null,
"e": 3306,
"s": 3162,
"text": "Now, playing the game will not show any visible difference, because the GameObject does not have anything to do with its physics component yet."
},
{
"code": null,
"e": 3372,
"s": 3306,
"text": "To solve our problem, let us open our code again, and rewrite it."
},
{
"code": null,
"e": 3678,
"s": 3372,
"text": "public class Movement : MonoBehaviour {\n public float speed;\n public Rigidbody2D body;\n // Update is called once per frame\n void Update() {\n float h = Input.GetAxisRaw(“Horizontal”);\n float v = Input.GetAxisRaw(“Vertical”);\n body.velocity = new Vector2(h * speed, v * speed);\n }\n}"
},
{
"code": null,
"e": 3912,
"s": 3678,
"text": "We can see that we create a reference to a Rigidbody2D in the declarations, and our update code works on that reference instead of the Object’s transform. This means that the Rigidbody has now been given the responsibility of moving."
},
{
"code": null,
"e": 4127,
"s": 3912,
"text": "You may expect the body reference to throw NullReferenceException, since we have not assigned anything to it. If you compile and run the game as is, you will get the following error on the bottom left of the editor"
},
{
"code": null,
"e": 4294,
"s": 4127,
"text": "To fix this, let us consider the component created by the script. Remember that public properties create their own fields in Unity, as we did with the speed variable."
},
{
"code": null,
"e": 4359,
"s": 4294,
"text": "Adjust the speed to a higher value, around 5, and play the game."
},
{
"code": null,
"e": 4400,
"s": 4359,
"text": "Your collisions will now work correctly!"
},
{
"code": null,
"e": 4437,
"s": 4400,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 4450,
"s": 4437,
"text": " Raja Biswas"
},
{
"code": null,
"e": 4484,
"s": 4450,
"text": "\n 58 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4503,
"s": 4484,
"text": " Three Millennials"
},
{
"code": null,
"e": 4536,
"s": 4503,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4550,
"s": 4536,
"text": " Peter Jepson"
},
{
"code": null,
"e": 4585,
"s": 4550,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4592,
"s": 4585,
"text": " Zenva"
},
{
"code": null,
"e": 4625,
"s": 4592,
"text": "\n 21 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4632,
"s": 4625,
"text": " Zenva"
},
{
"code": null,
"e": 4667,
"s": 4632,
"text": "\n 43 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4680,
"s": 4667,
"text": " Raja Biswas"
},
{
"code": null,
"e": 4687,
"s": 4680,
"text": " Print"
},
{
"code": null,
"e": 4698,
"s": 4687,
"text": " Add Notes"
}
] |
Python Deep Learning - Environment | In this chapter, we will learn about the environment set up for Python Deep Learning. We have to install the following software for making deep learning algorithms.
Python 2.7+
Scipy with Numpy
Matplotlib
Theano
Keras
TensorFlow
It is strongly recommend that Python, NumPy, SciPy, and Matplotlib are installed through the Anaconda distribution. It comes with all of those packages.
We need to ensure that the different types of software are installed properly.
Let us go to our command line program and type in the following command −
$ python
Python 3.6.3 |Anaconda custom (32-bit)| (default, Oct 13 2017, 14:21:34)
[GCC 7.2.0] on linux
Next, we can import the required libraries and print their versions −
import numpy
print numpy.__version__
1.14.2
Before we begin with the installation of the packages − Theano, TensorFlow and Keras, we need to confirm if the pip is installed. The package management system in Anaconda is called the pip.
To confirm the installation of pip, type the following in the command line −
$ pip
Once the installation of pip is confirmed, we can install TensorFlow and Keras by executing the following command −
$pip install theano
$pip install tensorflow
$pip install keras
Confirm the installation of Theano by executing the following line of code −
$python –c “import theano: print (theano.__version__)”
1.0.1
Confirm the installation of Tensorflow by executing the following line of code −
$python –c “import tensorflow: print tensorflow.__version__”
1.7.0
Confirm the installation of Keras by executing the following line of code −
$python –c “import keras: print keras.__version__”
Using TensorFlow backend
2.1.5
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1959,
"s": 1794,
"text": "In this chapter, we will learn about the environment set up for Python Deep Learning. We have to install the following software for making deep learning algorithms."
},
{
"code": null,
"e": 1971,
"s": 1959,
"text": "Python 2.7+"
},
{
"code": null,
"e": 1988,
"s": 1971,
"text": "Scipy with Numpy"
},
{
"code": null,
"e": 1999,
"s": 1988,
"text": "Matplotlib"
},
{
"code": null,
"e": 2006,
"s": 1999,
"text": "Theano"
},
{
"code": null,
"e": 2012,
"s": 2006,
"text": "Keras"
},
{
"code": null,
"e": 2023,
"s": 2012,
"text": "TensorFlow"
},
{
"code": null,
"e": 2176,
"s": 2023,
"text": "It is strongly recommend that Python, NumPy, SciPy, and Matplotlib are installed through the Anaconda distribution. It comes with all of those packages."
},
{
"code": null,
"e": 2255,
"s": 2176,
"text": "We need to ensure that the different types of software are installed properly."
},
{
"code": null,
"e": 2329,
"s": 2255,
"text": "Let us go to our command line program and type in the following command −"
},
{
"code": null,
"e": 2433,
"s": 2329,
"text": "$ python\nPython 3.6.3 |Anaconda custom (32-bit)| (default, Oct 13 2017, 14:21:34)\n[GCC 7.2.0] on linux\n"
},
{
"code": null,
"e": 2503,
"s": 2433,
"text": "Next, we can import the required libraries and print their versions −"
},
{
"code": null,
"e": 2541,
"s": 2503,
"text": "import numpy\nprint numpy.__version__\n"
},
{
"code": null,
"e": 2549,
"s": 2541,
"text": "1.14.2\n"
},
{
"code": null,
"e": 2740,
"s": 2549,
"text": "Before we begin with the installation of the packages − Theano, TensorFlow and Keras, we need to confirm if the pip is installed. The package management system in Anaconda is called the pip."
},
{
"code": null,
"e": 2817,
"s": 2740,
"text": "To confirm the installation of pip, type the following in the command line −"
},
{
"code": null,
"e": 2824,
"s": 2817,
"text": "$ pip\n"
},
{
"code": null,
"e": 2940,
"s": 2824,
"text": "Once the installation of pip is confirmed, we can install TensorFlow and Keras by executing the following command −"
},
{
"code": null,
"e": 3003,
"s": 2940,
"text": "$pip install theano\n$pip install tensorflow\n$pip install keras"
},
{
"code": null,
"e": 3080,
"s": 3003,
"text": "Confirm the installation of Theano by executing the following line of code −"
},
{
"code": null,
"e": 3135,
"s": 3080,
"text": "$python –c “import theano: print (theano.__version__)”"
},
{
"code": null,
"e": 3142,
"s": 3135,
"text": "1.0.1\n"
},
{
"code": null,
"e": 3223,
"s": 3142,
"text": "Confirm the installation of Tensorflow by executing the following line of code −"
},
{
"code": null,
"e": 3285,
"s": 3223,
"text": "$python –c “import tensorflow: print tensorflow.__version__”\n"
},
{
"code": null,
"e": 3292,
"s": 3285,
"text": "1.7.0\n"
},
{
"code": null,
"e": 3368,
"s": 3292,
"text": "Confirm the installation of Keras by executing the following line of code −"
},
{
"code": null,
"e": 3445,
"s": 3368,
"text": "$python –c “import keras: print keras.__version__”\nUsing TensorFlow backend\n"
},
{
"code": null,
"e": 3452,
"s": 3445,
"text": "2.1.5\n"
},
{
"code": null,
"e": 3489,
"s": 3452,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3505,
"s": 3489,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3538,
"s": 3505,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3557,
"s": 3538,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3592,
"s": 3557,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3614,
"s": 3592,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3648,
"s": 3614,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3676,
"s": 3648,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3711,
"s": 3676,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3725,
"s": 3711,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3758,
"s": 3725,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3775,
"s": 3758,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3782,
"s": 3775,
"text": " Print"
},
{
"code": null,
"e": 3793,
"s": 3782,
"text": " Add Notes"
}
] |
New ways to Assign values to Variables in C++ 17 ? | In C++ 17, there are introduced two new ways by which a programmer can assign values to a variable or declared them. In this update, elser then the classical way of assigning values to a variable the following two ways to initialise values.
Initially the assignment operator ‘=’ is used for assignment and declaration of a variable. assignment of a variable using = looks like,
datatype variable_name = value;
Example,
int val = 243;
In uniform initialisation of variables we do not use the ‘=’ operator. the value is enclosed inside a pair of curly braces ' {} '. Value inside the pair of curly braces is passed to the variable.
data_type variable_name{ value};
Live Demo
#include <iostream>
using namespace std;
int main() {
cout<<"Declaring Values using uniform initialization \n";
int val1{ 367 };
cout << "val1 = " <<val1<<endl;
int val2 = { 897 };
cout << "val2 = " << val2<<endl;
return 0;
}
Declaring Values using uniform initialization
val1 = 367
val2 = 897
another method to assign values to a variable. in constructor initialisation of variables, we use a pair of parentheses instead of the = operator. the value of variable is enclosed inside a pair of parentheses ( ).
data_type variable_name(values);
Live Demo
#include <iostream>
using namespace std;
int main() {
cout<<"Declaring Values using constructor initialization \n";
int val1( 367 );
cout << "val1 = " <<val1<<endl;
int val2 = ( 897 );
cout << "val2 = " << val2<<endl;
return 0;
}
Declaring Values using constructor initialization
val1 = 367
val2 = 897 | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "In C++ 17, there are introduced two new ways by which a programmer can assign values to a variable or declared them. In this update, elser then the classical way of assigning values to a variable the following two ways to initialise values."
},
{
"code": null,
"e": 1440,
"s": 1303,
"text": "Initially the assignment operator ‘=’ is used for assignment and declaration of a variable. assignment of a variable using = looks like,"
},
{
"code": null,
"e": 1472,
"s": 1440,
"text": "datatype variable_name = value;"
},
{
"code": null,
"e": 1481,
"s": 1472,
"text": "Example,"
},
{
"code": null,
"e": 1496,
"s": 1481,
"text": "int val = 243;"
},
{
"code": null,
"e": 1692,
"s": 1496,
"text": "In uniform initialisation of variables we do not use the ‘=’ operator. the value is enclosed inside a pair of curly braces ' {} '. Value inside the pair of curly braces is passed to the variable."
},
{
"code": null,
"e": 1725,
"s": 1692,
"text": "data_type variable_name{ value};"
},
{
"code": null,
"e": 1736,
"s": 1725,
"text": " Live Demo"
},
{
"code": null,
"e": 1980,
"s": 1736,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n cout<<\"Declaring Values using uniform initialization \\n\";\n int val1{ 367 };\n cout << \"val1 = \" <<val1<<endl;\n int val2 = { 897 };\n cout << \"val2 = \" << val2<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2048,
"s": 1980,
"text": "Declaring Values using uniform initialization\nval1 = 367\nval2 = 897"
},
{
"code": null,
"e": 2263,
"s": 2048,
"text": "another method to assign values to a variable. in constructor initialisation of variables, we use a pair of parentheses instead of the = operator. the value of variable is enclosed inside a pair of parentheses ( )."
},
{
"code": null,
"e": 2296,
"s": 2263,
"text": "data_type variable_name(values);"
},
{
"code": null,
"e": 2307,
"s": 2296,
"text": " Live Demo"
},
{
"code": null,
"e": 2555,
"s": 2307,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n cout<<\"Declaring Values using constructor initialization \\n\";\n int val1( 367 );\n cout << \"val1 = \" <<val1<<endl;\n int val2 = ( 897 );\n cout << \"val2 = \" << val2<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2627,
"s": 2555,
"text": "Declaring Values using constructor initialization\nval1 = 367\nval2 = 897"
}
] |
How can I split an array of Numbers to individual digits in JavaScript? | We have an array of Number literals, and we are required to write a function, say splitDigit() that
takes in this array and returns an array of Numbers where the numbers greater than 10 are splitted into single digits.
For example −
//if the input is:
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
//then the output should be:
const output = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1,
0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ];
So, let’s write the code for this function, we will use the Array.prototype.reduce() method to split
the numbers.
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
const splitNum = (n, res = []) => {
if(n){
return splitNum(Math.floor(n/10), [n % 10].concat(res));
};
return res;
};
const splitDigit = (arr) => {
return arr.reduce((acc, val) => acc.concat(splitNum(val)), []);
};
console.log(splitDigit(arr));
The output in the console will be −
[
9, 4, 9, 5, 9, 6, 9, 7, 9,
8, 9, 9, 1, 0, 0, 1, 0, 1,
1, 0, 2, 1, 0, 3, 1, 0, 4,
1, 0, 5, 1, 0, 6
] | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "We have an array of Number literals, and we are required to write a function, say splitDigit() that\ntakes in this array and returns an array of Numbers where the numbers greater than 10 are splitted into single digits."
},
{
"code": null,
"e": 1295,
"s": 1281,
"text": "For example −"
},
{
"code": null,
"e": 1535,
"s": 1295,
"text": "//if the input is:\nconst arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]\n//then the output should be:\nconst output = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1,\n0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ];"
},
{
"code": null,
"e": 1649,
"s": 1535,
"text": "So, let’s write the code for this function, we will use the Array.prototype.reduce() method to split\nthe numbers."
},
{
"code": null,
"e": 1986,
"s": 1649,
"text": "const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]\nconst splitNum = (n, res = []) => {\n if(n){\n return splitNum(Math.floor(n/10), [n % 10].concat(res));\n };\n return res;\n};\nconst splitDigit = (arr) => {\n return arr.reduce((acc, val) => acc.concat(splitNum(val)), []);\n};\nconsole.log(splitDigit(arr));"
},
{
"code": null,
"e": 2022,
"s": 1986,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2136,
"s": 2022,
"text": "[\n 9, 4, 9, 5, 9, 6, 9, 7, 9,\n 8, 9, 9, 1, 0, 0, 1, 0, 1,\n 1, 0, 2, 1, 0, 3, 1, 0, 4,\n 1, 0, 5, 1, 0, 6\n]"
}
] |
How to remove all trailing whitespace of string in Python? | We can use the method rstrip() which returns a copy of the string in which all specified chars have been stripped from the end of the string. The default char to be trimmed is whitespace. For example:
>>> ' Hello '.rstrip()
' Hello'
>>> 'Ninja Turtles the movie '.rstrip()
'Ninja Turtles the movie' | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "We can use the method rstrip() which returns a copy of the string in which all specified chars have been stripped from the end of the string. The default char to be trimmed is whitespace. For example:"
},
{
"code": null,
"e": 1371,
"s": 1263,
"text": ">>> ' Hello '.rstrip()\n' Hello'\n>>> 'Ninja Turtles the movie '.rstrip()\n'Ninja Turtles the movie'"
}
] |
Working with hex numbers in MySQL? | In order to work with hex, use the CONV() function to convert between bases. The syntax is as follows −
SET anyVariableName = CONV(yourHexValue,16,10);
To understand the above syntax, let us create a stored procedure. The query to create a stored procedure is as follows −
mysql> DELIMITER //
mysql> CREATE PROCEDURE SP_HEX_TO_DEC( HEXVALUE VARCHAR(10) )
-> BEGIN
-> DECLARE Decimalvalue INTEGER;
-> SET Decimalvalue = CONV(HEXVALUE,16,10);
-> select Decimalvalue;
-> END;
-> //
Query OK, 0 rows affected (0.19 sec)
mysql> DELIMITER ;
The above stored procedure converts the hexadecimal to decimal. As we know the A represents 10 in decimal, we will pass A as the parameter. Call the stored procedure using CALL command.
The syntax is as follows −
CALL yourStoredProcedureName;
Call the above stored procedure using CALL command. The query is as follows −
mysql> call SP_HEX_TO_DEC('A');
The following is the output displaying the decimal value calculated using the stored procedure created above −
+--------------+
| Decimalvalue |
+--------------+
| 10 |
+--------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
Check with select statement directly.
mysql> select conv('AB',16,10) as DecimalResult;
The following is the output −
+---------------+
| DecimalResult |
+---------------+
| 171 |
+---------------+
1 row in set (0.00 sec)
Let us now see the procedure to convert hex to decimal. Remember this rule −
A and B represented as 10 and 11 respectively in hexadecimal.
To convert it into decimal rule is as follows:
N .........+value3 *162 +value2 *161 + value1 * 160
= 10 * 161 + 11 * 160
= 160+11
= 171. | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "In order to work with hex, use the CONV() function to convert between bases. The syntax is as follows −"
},
{
"code": null,
"e": 1214,
"s": 1166,
"text": "SET anyVariableName = CONV(yourHexValue,16,10);"
},
{
"code": null,
"e": 1335,
"s": 1214,
"text": "To understand the above syntax, let us create a stored procedure. The query to create a stored procedure is as follows −"
},
{
"code": null,
"e": 1615,
"s": 1335,
"text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE SP_HEX_TO_DEC( HEXVALUE VARCHAR(10) )\n -> BEGIN\n -> DECLARE Decimalvalue INTEGER;\n -> SET Decimalvalue = CONV(HEXVALUE,16,10);\n -> select Decimalvalue;\n -> END;\n -> //\nQuery OK, 0 rows affected (0.19 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 1801,
"s": 1615,
"text": "The above stored procedure converts the hexadecimal to decimal. As we know the A represents 10 in decimal, we will pass A as the parameter. Call the stored procedure using CALL command."
},
{
"code": null,
"e": 1828,
"s": 1801,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1858,
"s": 1828,
"text": "CALL yourStoredProcedureName;"
},
{
"code": null,
"e": 1936,
"s": 1858,
"text": "Call the above stored procedure using CALL command. The query is as follows −"
},
{
"code": null,
"e": 1968,
"s": 1936,
"text": "mysql> call SP_HEX_TO_DEC('A');"
},
{
"code": null,
"e": 2079,
"s": 1968,
"text": "The following is the output displaying the decimal value calculated using the stored procedure created above −"
},
{
"code": null,
"e": 2225,
"s": 2079,
"text": "+--------------+\n| Decimalvalue |\n+--------------+\n| 10 |\n+--------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.01 sec)"
},
{
"code": null,
"e": 2263,
"s": 2225,
"text": "Check with select statement directly."
},
{
"code": null,
"e": 2312,
"s": 2263,
"text": "mysql> select conv('AB',16,10) as DecimalResult;"
},
{
"code": null,
"e": 2342,
"s": 2312,
"text": "The following is the output −"
},
{
"code": null,
"e": 2456,
"s": 2342,
"text": "+---------------+\n| DecimalResult |\n+---------------+\n| 171 |\n+---------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2533,
"s": 2456,
"text": "Let us now see the procedure to convert hex to decimal. Remember this rule −"
},
{
"code": null,
"e": 2732,
"s": 2533,
"text": "A and B represented as 10 and 11 respectively in hexadecimal.\nTo convert it into decimal rule is as follows:\nN .........+value3 *162 +value2 *161 + value1 * 160\n= 10 * 161 + 11 * 160\n= 160+11\n= 171."
}
] |
The SQL SELECT Statement Questions | 1. Identify the capabilities of SELECT statement.
Projection
Selection
Data Control
Transaction
Projection
Selection
Data Control
Transaction
Answer: A, B. The SELECT statement can be used for selection, projection and joining.
2. Determine the capability of the SELECT statement demonstrated in the given query.
SELECT e.ename, d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno
AND e.sal > 1000;
Selection
Filtering
Joining
Projection
Selection
Filtering
Joining
Projection
Answer: A, C, D. Projection is including only the required columns in query, while Selection is selecting only the required data. Joining means combining two tables together through a connecting column.
3. Which of the following clause is used to suppress duplicates in a SELECT statement?
INTERSECT
DUPLICATE
DISTINCT
UNIQUE
INTERSECT
DUPLICATE
DISTINCT
UNIQUE
Answer: C, D. Duplicate data can be restricted with the use of DISTINCT or UNIQUE in the SELECT statement.
4. Chose the statements which correctly specify a rule to write a SQL statement
SQL statements are case sensitive
Keywords can be abbreviated to build a standard
SQL statements are case in-sensitive
clauses must be placed together
SQL statements are case sensitive
Keywords can be abbreviated to build a standard
SQL statements are case in-sensitive
clauses must be placed together
Answer: C.SQL statements are not case sensitive.
5. Determine the output of the below query -
SELECT '5+7'
FROM dual;
12
5+7
5
7
12
5+7
5
7
Answer: B.Oracle treats the values within double quotes as string expressions.
6. Write a query to display employee details (Name, Department, Salary and Job) from EMP table.
SELECT ename, deptno, sal, job FROM emp;
SELECT * FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal, job FROM emp;
SELECT * FROM emp;
SELECT * FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal FROM emp;
Answer A.Select the required from the tables each separated by a comma.
7. Which of the below queries displays employees' name and new salary after the increment of 1000?
SELECT ename, sal FROM emp;
SELECT ename, sal=sal+1000 FROM emp;
SELECT ename, sal+1000 FROM emp;
SELECT ename, 1000 FROM emp;
SELECT ename, sal FROM emp;
SELECT ename, sal FROM emp;
SELECT ename, sal=sal+1000 FROM emp;
SELECT ename, sal=sal+1000 FROM emp;
SELECT ename, sal+1000 FROM emp;
SELECT ename, sal+1000 FROM emp;
SELECT ename, 1000 FROM emp;
SELECT ename, 1000 FROM emp;
Answer: C. Basic arithmetic calculations can be done using the columns in SELECT statements.
8. Determine the output of the below query
SELECT 36/2-5*10 FROM dual;
130
-32
-120
175
130
-32
-120
175
Answer: B. Multiplication and Division occur before addition and subtraction.
9. Determine the output of the below query
SELECT (100-25)/15*(20-3) FROM dual;
0.294
-85
63.67
85
0.294
-85
63.67
85
Answer: D. Expression within the brackets are executed before the divisions and multiplications in the expression.
10. Chose the statements which correctly define a NULL value.
NULL is a special value with zero bytes
NULL is no value or unknown value
NULL is represented by a blank space
NULL is not same as zero
NULL is a special value with zero bytes
NULL is no value or unknown value
NULL is represented by a blank space
NULL is not same as zero
Answer: B, D.NULL is NO VALUE but neither same as zero nor as blank or space character.
11. Determine the output of the below query
SELECT sal + NULL
FROM emp
WHERE empno = 7369;
sal + NULL
NULL
0
1250
sal + NULL
NULL
0
1250
Answer: B. Any arithmetic operation with NULL results in NULL.
12. Which of the below statements define column alias correctly?
A column alias renames a column heading
A column alias is an alternate column in a table
A column alias can be specified during table definition
A column alias immediately follows the column or expression in the SELECT statement
A column alias renames a column heading
A column alias is an alternate column in a table
A column alias can be specified during table definition
A column alias immediately follows the column or expression in the SELECT statement
Answer: A, D. Column Alias can be used to name an expression in the SELECT statement.
13. Specify the column alias NEWSAL for the expression containing salary in the below SQL query
SELECT ename, job, sal + 100 FROM emp;
(sal + 100) AS NEWSAL
(sal + 100) NEWSAL
(sal + 100) IS NEWSAL
sal + 100 IS NEWSAL
(sal + 100) AS NEWSAL
(sal + 100) NEWSAL
(sal + 100) IS NEWSAL
sal + 100 IS NEWSAL
Answer: A, B.Use 'AS' to signify new alias to a column expression.
14. Specify the column alias "New Salary" for the expression containing salary in the below SQL query
SELECT ename, job, sal + 100 FROM emp;
(sal + 100) AS New Salary
(sal + 100) "New Salary"
(sal + 100) IS New Salary
sal + 100 as "New Salary"
(sal + 100) AS New Salary
(sal + 100) "New Salary"
(sal + 100) IS New Salary
sal + 100 as "New Salary"
Answer: B, D. Column alias with space and special characters must be enquoted within double quotes.
15. Which command is used to display the structure of a table?
LIST
SHOW
DESCRIBE
STRUCTURE
LIST
SHOW
DESCRIBE
STRUCTURE
Answer: C.DESCRIBE is used to show the table structure.
16. Predict the output when below statement is executed in SQL* Plus?
DESC emp
Raises error "SP2-0042: unknown command "desc emp" - rest of line ignored."
Lists the columns of EMP table
Lists the EMP table columns, their data type and nullity
Lists the columns of EMP table along with their data types
Raises error "SP2-0042: unknown command "desc emp" - rest of line ignored."
Lists the columns of EMP table
Lists the EMP table columns, their data type and nullity
Lists the columns of EMP table along with their data types
Answer: C. DESCRIBE is used to show the table structure along with table columns, their data type and nullity
17. Which of the below statements are true about the DESCRIBE command?
It can be used in SQL*Plus only
It can be used in both SQL*Plus as well as SQL Developer
It doesn't works for object tables
It doesn't works for SYS owned tables
It can be used in SQL*Plus only
It can be used in both SQL*Plus as well as SQL Developer
It doesn't works for object tables
It doesn't works for SYS owned tables
Answer: B.
18. Which of the below alphanumeric characters are used to signify concatenation operator in SQL?
+
||
-
::
+
||
-
::
Answer: B.In SQL, concatenation operator is represented by two vertical bars (||).
19. Which of the below statements are correct about the usage of concatenation operator in SQL?
It creates a virtual column in the table
It generates a character expression as the result of concatenation of one or more strings
It creates a link between two character columns
It can be used to concatenate date expressions with other columns
It creates a virtual column in the table
It generates a character expression as the result of concatenation of one or more strings
It creates a link between two character columns
It can be used to concatenate date expressions with other columns
Answer: B, D. Concatenation operator joins two values as an expression.
20. Predict the output of the below query
SELECT ename || NULL
FROM emp
WHERE empno = 7369
SMITH
SMITH NULL
SMITHNULL
ORA-00904: "NULL": invalid identifier
SMITH
SMITH NULL
SMITHNULL
ORA-00904: "NULL": invalid identifier
Answer: A. Concatenation with NULL results into same value.
21. Predict the output of the below query
SELECT 50 || 0001
FROM dual
500001
51
501
5001
500001
51
501
5001
Answer: C. The leading zeroes in the right operand of expression are ignored by Oracle.
22. You execute the below query
SELECT e.ename||' departments's name is:'|| d.dname
FROM emp e, dept d
where e.deptno=d.deptno;
And get the exception - ORA-01756: quoted string not properly terminated. Which of the following solutions can permanently resolve the problem?
Use double quote marks for the literal character string
Use [q] operator to enquote the literal character string and selecting the delimiter of choice
Remove the single quote mark (apostrophe) from the literal character string
Use another delimiter to bypass the single quote apostrophe in the literal string
Use double quote marks for the literal character string
Use [q] operator to enquote the literal character string and selecting the delimiter of choice
Remove the single quote mark (apostrophe) from the literal character string
Use another delimiter to bypass the single quote apostrophe in the literal string
Answer: B. The [q] operator is used to enquote character literals with a quote.
23. Which of the below SELECT statement shows the correct usage of [q] operator?
SELECT e.ename || q'[department's name is]'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q['department's name is']|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q[department's name is]|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q'(department's name is)'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q'[department's name is]'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q'[department's name is]'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q['department's name is']|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q['department's name is']|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q[department's name is]|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q[department's name is]|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q'(department's name is)'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
SELECT e.ename || q'(department's name is)'|| d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno;
Answer: A
24. Which of the below SELECT statement is used to select all columns of EMP table?
SELECT ALL FROM emp
SELECT # FROM emp
SELECT * FROM emp
SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp
SELECT ALL FROM emp
SELECT ALL FROM emp
SELECT # FROM emp
SELECT # FROM emp
SELECT * FROM emp
SELECT * FROM emp
SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp
SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp
Answer: C. The character '*' is used to select all the columns of the table.
25. Which of the below SQL query will display employee names, department, and annual salary?
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
Annual salary cannot be queried since the column doesn't exists in the table
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
Annual salary cannot be queried since the column doesn't exists in the table
Answer: C. Use numeric expressions in SELECT statement to perform basic arithmetic calculations.
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2513,
"s": 2463,
"text": "1. Identify the capabilities of SELECT statement."
},
{
"code": null,
"e": 2561,
"s": 2513,
"text": "\nProjection\nSelection\nData Control\nTransaction\n"
},
{
"code": null,
"e": 2572,
"s": 2561,
"text": "Projection"
},
{
"code": null,
"e": 2582,
"s": 2572,
"text": "Selection"
},
{
"code": null,
"e": 2595,
"s": 2582,
"text": "Data Control"
},
{
"code": null,
"e": 2607,
"s": 2595,
"text": "Transaction"
},
{
"code": null,
"e": 2693,
"s": 2607,
"text": "Answer: A, B. The SELECT statement can be used for selection, projection and joining."
},
{
"code": null,
"e": 2778,
"s": 2693,
"text": "2. Determine the capability of the SELECT statement demonstrated in the given query."
},
{
"code": null,
"e": 2871,
"s": 2778,
"text": "SELECT e.ename, d.dname\nFROM emp e, dept d\nWHERE e.deptno = d.deptno\nAND e.sal > 1000;"
},
{
"code": null,
"e": 2912,
"s": 2871,
"text": "\nSelection\nFiltering\nJoining\nProjection\n"
},
{
"code": null,
"e": 2922,
"s": 2912,
"text": "Selection"
},
{
"code": null,
"e": 2932,
"s": 2922,
"text": "Filtering"
},
{
"code": null,
"e": 2940,
"s": 2932,
"text": "Joining"
},
{
"code": null,
"e": 2951,
"s": 2940,
"text": "Projection"
},
{
"code": null,
"e": 3154,
"s": 2951,
"text": "Answer: A, C, D. Projection is including only the required columns in query, while Selection is selecting only the required data. Joining means combining two tables together through a connecting column."
},
{
"code": null,
"e": 3241,
"s": 3154,
"text": "3. Which of the following clause is used to suppress duplicates in a SELECT statement?"
},
{
"code": null,
"e": 3279,
"s": 3241,
"text": "\nINTERSECT\nDUPLICATE\nDISTINCT\nUNIQUE\n"
},
{
"code": null,
"e": 3289,
"s": 3279,
"text": "INTERSECT"
},
{
"code": null,
"e": 3299,
"s": 3289,
"text": "DUPLICATE"
},
{
"code": null,
"e": 3308,
"s": 3299,
"text": "DISTINCT"
},
{
"code": null,
"e": 3315,
"s": 3308,
"text": "UNIQUE"
},
{
"code": null,
"e": 3422,
"s": 3315,
"text": "Answer: C, D. Duplicate data can be restricted with the use of DISTINCT or UNIQUE in the SELECT statement."
},
{
"code": null,
"e": 3502,
"s": 3422,
"text": "4. Chose the statements which correctly specify a rule to write a SQL statement"
},
{
"code": null,
"e": 3655,
"s": 3502,
"text": "\nSQL statements are case sensitive\nKeywords can be abbreviated to build a standard\nSQL statements are case in-sensitive\nclauses must be placed together\n"
},
{
"code": null,
"e": 3689,
"s": 3655,
"text": "SQL statements are case sensitive"
},
{
"code": null,
"e": 3737,
"s": 3689,
"text": "Keywords can be abbreviated to build a standard"
},
{
"code": null,
"e": 3774,
"s": 3737,
"text": "SQL statements are case in-sensitive"
},
{
"code": null,
"e": 3806,
"s": 3774,
"text": "clauses must be placed together"
},
{
"code": null,
"e": 3855,
"s": 3806,
"text": "Answer: C.SQL statements are not case sensitive."
},
{
"code": null,
"e": 3900,
"s": 3855,
"text": "5. Determine the output of the below query -"
},
{
"code": null,
"e": 3925,
"s": 3900,
"text": "SELECT '5+7' \nFROM dual;"
},
{
"code": null,
"e": 3938,
"s": 3925,
"text": "\n12\n5+7\n5\n7\n"
},
{
"code": null,
"e": 3941,
"s": 3938,
"text": "12"
},
{
"code": null,
"e": 3945,
"s": 3941,
"text": "5+7"
},
{
"code": null,
"e": 3947,
"s": 3945,
"text": "5"
},
{
"code": null,
"e": 3949,
"s": 3947,
"text": "7"
},
{
"code": null,
"e": 4028,
"s": 3949,
"text": "Answer: B.Oracle treats the values within double quotes as string expressions."
},
{
"code": null,
"e": 4124,
"s": 4028,
"text": "6. Write a query to display employee details (Name, Department, Salary and Job) from EMP table."
},
{
"code": null,
"e": 4272,
"s": 4124,
"text": "\nSELECT ename, deptno, sal, job FROM emp;\nSELECT * FROM emp;\nSELECT DISTINCT ename, deptno, sal, job FROM emp;\nSELECT ename, deptno, sal FROM emp;\n"
},
{
"code": null,
"e": 4313,
"s": 4272,
"text": "SELECT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 4354,
"s": 4313,
"text": "SELECT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 4373,
"s": 4354,
"text": "SELECT * FROM emp;"
},
{
"code": null,
"e": 4392,
"s": 4373,
"text": "SELECT * FROM emp;"
},
{
"code": null,
"e": 4442,
"s": 4392,
"text": "SELECT DISTINCT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 4492,
"s": 4442,
"text": "SELECT DISTINCT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 4528,
"s": 4492,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 4564,
"s": 4528,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 4636,
"s": 4564,
"text": "Answer A.Select the required from the tables each separated by a comma."
},
{
"code": null,
"e": 4735,
"s": 4636,
"text": "7. Which of the below queries displays employees' name and new salary after the increment of 1000?"
},
{
"code": null,
"e": 4864,
"s": 4735,
"text": "\nSELECT ename, sal FROM emp;\nSELECT ename, sal=sal+1000 FROM emp;\nSELECT ename, sal+1000 FROM emp;\nSELECT ename, 1000 FROM emp;\n"
},
{
"code": null,
"e": 4892,
"s": 4864,
"text": "SELECT ename, sal FROM emp;"
},
{
"code": null,
"e": 4920,
"s": 4892,
"text": "SELECT ename, sal FROM emp;"
},
{
"code": null,
"e": 4957,
"s": 4920,
"text": "SELECT ename, sal=sal+1000 FROM emp;"
},
{
"code": null,
"e": 4994,
"s": 4957,
"text": "SELECT ename, sal=sal+1000 FROM emp;"
},
{
"code": null,
"e": 5027,
"s": 4994,
"text": "SELECT ename, sal+1000 FROM emp;"
},
{
"code": null,
"e": 5060,
"s": 5027,
"text": "SELECT ename, sal+1000 FROM emp;"
},
{
"code": null,
"e": 5089,
"s": 5060,
"text": "SELECT ename, 1000 FROM emp;"
},
{
"code": null,
"e": 5118,
"s": 5089,
"text": "SELECT ename, 1000 FROM emp;"
},
{
"code": null,
"e": 5211,
"s": 5118,
"text": "Answer: C. Basic arithmetic calculations can be done using the columns in SELECT statements."
},
{
"code": null,
"e": 5254,
"s": 5211,
"text": "8. Determine the output of the below query"
},
{
"code": null,
"e": 5282,
"s": 5254,
"text": "SELECT 36/2-5*10 FROM dual;"
},
{
"code": null,
"e": 5301,
"s": 5282,
"text": "\n130\n-32\n-120\n175\n"
},
{
"code": null,
"e": 5305,
"s": 5301,
"text": "130"
},
{
"code": null,
"e": 5309,
"s": 5305,
"text": "-32"
},
{
"code": null,
"e": 5314,
"s": 5309,
"text": "-120"
},
{
"code": null,
"e": 5318,
"s": 5314,
"text": "175"
},
{
"code": null,
"e": 5396,
"s": 5318,
"text": "Answer: B. Multiplication and Division occur before addition and subtraction."
},
{
"code": null,
"e": 5439,
"s": 5396,
"text": "9. Determine the output of the below query"
},
{
"code": null,
"e": 5476,
"s": 5439,
"text": "SELECT (100-25)/15*(20-3) FROM dual;"
},
{
"code": null,
"e": 5497,
"s": 5476,
"text": "\n0.294\n-85\n63.67\n85\n"
},
{
"code": null,
"e": 5503,
"s": 5497,
"text": "0.294"
},
{
"code": null,
"e": 5507,
"s": 5503,
"text": "-85"
},
{
"code": null,
"e": 5513,
"s": 5507,
"text": "63.67"
},
{
"code": null,
"e": 5516,
"s": 5513,
"text": "85"
},
{
"code": null,
"e": 5631,
"s": 5516,
"text": "Answer: D. Expression within the brackets are executed before the divisions and multiplications in the expression."
},
{
"code": null,
"e": 5693,
"s": 5631,
"text": "10. Chose the statements which correctly define a NULL value."
},
{
"code": null,
"e": 5831,
"s": 5693,
"text": "\nNULL is a special value with zero bytes\nNULL is no value or unknown value\nNULL is represented by a blank space\nNULL is not same as zero\n"
},
{
"code": null,
"e": 5871,
"s": 5831,
"text": "NULL is a special value with zero bytes"
},
{
"code": null,
"e": 5905,
"s": 5871,
"text": "NULL is no value or unknown value"
},
{
"code": null,
"e": 5942,
"s": 5905,
"text": "NULL is represented by a blank space"
},
{
"code": null,
"e": 5967,
"s": 5942,
"text": "NULL is not same as zero"
},
{
"code": null,
"e": 6055,
"s": 5967,
"text": "Answer: B, D.NULL is NO VALUE but neither same as zero nor as blank or space character."
},
{
"code": null,
"e": 6099,
"s": 6055,
"text": "11. Determine the output of the below query"
},
{
"code": null,
"e": 6147,
"s": 6099,
"text": "SELECT sal + NULL \nFROM emp\nWHERE empno = 7369;"
},
{
"code": null,
"e": 6173,
"s": 6147,
"text": "\nsal + NULL \nNULL\n0\n1250\n"
},
{
"code": null,
"e": 6185,
"s": 6173,
"text": "sal + NULL "
},
{
"code": null,
"e": 6190,
"s": 6185,
"text": "NULL"
},
{
"code": null,
"e": 6192,
"s": 6190,
"text": "0"
},
{
"code": null,
"e": 6197,
"s": 6192,
"text": "1250"
},
{
"code": null,
"e": 6260,
"s": 6197,
"text": "Answer: B. Any arithmetic operation with NULL results in NULL."
},
{
"code": null,
"e": 6325,
"s": 6260,
"text": "12. Which of the below statements define column alias correctly?"
},
{
"code": null,
"e": 6556,
"s": 6325,
"text": "\nA column alias renames a column heading\nA column alias is an alternate column in a table\nA column alias can be specified during table definition\nA column alias immediately follows the column or expression in the SELECT statement\n"
},
{
"code": null,
"e": 6596,
"s": 6556,
"text": "A column alias renames a column heading"
},
{
"code": null,
"e": 6645,
"s": 6596,
"text": "A column alias is an alternate column in a table"
},
{
"code": null,
"e": 6701,
"s": 6645,
"text": "A column alias can be specified during table definition"
},
{
"code": null,
"e": 6785,
"s": 6701,
"text": "A column alias immediately follows the column or expression in the SELECT statement"
},
{
"code": null,
"e": 6871,
"s": 6785,
"text": "Answer: A, D. Column Alias can be used to name an expression in the SELECT statement."
},
{
"code": null,
"e": 6967,
"s": 6871,
"text": "13. Specify the column alias NEWSAL for the expression containing salary in the below SQL query"
},
{
"code": null,
"e": 7006,
"s": 6967,
"text": "SELECT ename, job, sal + 100 FROM emp;"
},
{
"code": null,
"e": 7091,
"s": 7006,
"text": "\n(sal + 100) AS NEWSAL\n(sal + 100) NEWSAL\n(sal + 100) IS NEWSAL\nsal + 100 IS NEWSAL\n"
},
{
"code": null,
"e": 7113,
"s": 7091,
"text": "(sal + 100) AS NEWSAL"
},
{
"code": null,
"e": 7132,
"s": 7113,
"text": "(sal + 100) NEWSAL"
},
{
"code": null,
"e": 7154,
"s": 7132,
"text": "(sal + 100) IS NEWSAL"
},
{
"code": null,
"e": 7174,
"s": 7154,
"text": "sal + 100 IS NEWSAL"
},
{
"code": null,
"e": 7243,
"s": 7174,
"text": "Answer: A, B.Use 'AS' to signify new alias to a column expression. "
},
{
"code": null,
"e": 7345,
"s": 7243,
"text": "14. Specify the column alias \"New Salary\" for the expression containing salary in the below SQL query"
},
{
"code": null,
"e": 7384,
"s": 7345,
"text": "SELECT ename, job, sal + 100 FROM emp;"
},
{
"code": null,
"e": 7489,
"s": 7384,
"text": "\n(sal + 100) AS New Salary\n(sal + 100) \"New Salary\"\n(sal + 100) IS New Salary\nsal + 100 as \"New Salary\"\n"
},
{
"code": null,
"e": 7515,
"s": 7489,
"text": "(sal + 100) AS New Salary"
},
{
"code": null,
"e": 7540,
"s": 7515,
"text": "(sal + 100) \"New Salary\""
},
{
"code": null,
"e": 7566,
"s": 7540,
"text": "(sal + 100) IS New Salary"
},
{
"code": null,
"e": 7592,
"s": 7566,
"text": "sal + 100 as \"New Salary\""
},
{
"code": null,
"e": 7693,
"s": 7592,
"text": "Answer: B, D. Column alias with space and special characters must be enquoted within double quotes. "
},
{
"code": null,
"e": 7756,
"s": 7693,
"text": "15. Which command is used to display the structure of a table?"
},
{
"code": null,
"e": 7787,
"s": 7756,
"text": "\nLIST\nSHOW\nDESCRIBE\nSTRUCTURE\n"
},
{
"code": null,
"e": 7792,
"s": 7787,
"text": "LIST"
},
{
"code": null,
"e": 7797,
"s": 7792,
"text": "SHOW"
},
{
"code": null,
"e": 7806,
"s": 7797,
"text": "DESCRIBE"
},
{
"code": null,
"e": 7816,
"s": 7806,
"text": "STRUCTURE"
},
{
"code": null,
"e": 7873,
"s": 7816,
"text": "Answer: C.DESCRIBE is used to show the table structure. "
},
{
"code": null,
"e": 7943,
"s": 7873,
"text": "16. Predict the output when below statement is executed in SQL* Plus?"
},
{
"code": null,
"e": 7952,
"s": 7943,
"text": "DESC emp"
},
{
"code": null,
"e": 8177,
"s": 7952,
"text": "\nRaises error \"SP2-0042: unknown command \"desc emp\" - rest of line ignored.\"\nLists the columns of EMP table\nLists the EMP table columns, their data type and nullity\nLists the columns of EMP table along with their data types\n"
},
{
"code": null,
"e": 8253,
"s": 8177,
"text": "Raises error \"SP2-0042: unknown command \"desc emp\" - rest of line ignored.\""
},
{
"code": null,
"e": 8284,
"s": 8253,
"text": "Lists the columns of EMP table"
},
{
"code": null,
"e": 8341,
"s": 8284,
"text": "Lists the EMP table columns, their data type and nullity"
},
{
"code": null,
"e": 8400,
"s": 8341,
"text": "Lists the columns of EMP table along with their data types"
},
{
"code": null,
"e": 8511,
"s": 8400,
"text": "Answer: C. DESCRIBE is used to show the table structure along with table columns, their data type and nullity "
},
{
"code": null,
"e": 8582,
"s": 8511,
"text": "17. Which of the below statements are true about the DESCRIBE command?"
},
{
"code": null,
"e": 8746,
"s": 8582,
"text": "\nIt can be used in SQL*Plus only\nIt can be used in both SQL*Plus as well as SQL Developer\nIt doesn't works for object tables\nIt doesn't works for SYS owned tables\n"
},
{
"code": null,
"e": 8778,
"s": 8746,
"text": "It can be used in SQL*Plus only"
},
{
"code": null,
"e": 8835,
"s": 8778,
"text": "It can be used in both SQL*Plus as well as SQL Developer"
},
{
"code": null,
"e": 8870,
"s": 8835,
"text": "It doesn't works for object tables"
},
{
"code": null,
"e": 8908,
"s": 8870,
"text": "It doesn't works for SYS owned tables"
},
{
"code": null,
"e": 8919,
"s": 8908,
"text": "Answer: B."
},
{
"code": null,
"e": 9017,
"s": 8919,
"text": "18. Which of the below alphanumeric characters are used to signify concatenation operator in SQL?"
},
{
"code": null,
"e": 9029,
"s": 9017,
"text": "\n+\n||\n-\n::\n"
},
{
"code": null,
"e": 9031,
"s": 9029,
"text": "+"
},
{
"code": null,
"e": 9034,
"s": 9031,
"text": "||"
},
{
"code": null,
"e": 9036,
"s": 9034,
"text": "-"
},
{
"code": null,
"e": 9039,
"s": 9036,
"text": "::"
},
{
"code": null,
"e": 9123,
"s": 9039,
"text": "Answer: B.In SQL, concatenation operator is represented by two vertical bars (||). "
},
{
"code": null,
"e": 9219,
"s": 9123,
"text": "19. Which of the below statements are correct about the usage of concatenation operator in SQL?"
},
{
"code": null,
"e": 9466,
"s": 9219,
"text": "\nIt creates a virtual column in the table\nIt generates a character expression as the result of concatenation of one or more strings\nIt creates a link between two character columns\nIt can be used to concatenate date expressions with other columns\n"
},
{
"code": null,
"e": 9507,
"s": 9466,
"text": "It creates a virtual column in the table"
},
{
"code": null,
"e": 9597,
"s": 9507,
"text": "It generates a character expression as the result of concatenation of one or more strings"
},
{
"code": null,
"e": 9645,
"s": 9597,
"text": "It creates a link between two character columns"
},
{
"code": null,
"e": 9711,
"s": 9645,
"text": "It can be used to concatenate date expressions with other columns"
},
{
"code": null,
"e": 9784,
"s": 9711,
"text": "Answer: B, D. Concatenation operator joins two values as an expression. "
},
{
"code": null,
"e": 9826,
"s": 9784,
"text": "20. Predict the output of the below query"
},
{
"code": null,
"e": 9875,
"s": 9826,
"text": "SELECT ename || NULL\nFROM emp\nWHERE empno = 7369"
},
{
"code": null,
"e": 9942,
"s": 9875,
"text": "\nSMITH\nSMITH NULL\nSMITHNULL\nORA-00904: \"NULL\": invalid identifier\n"
},
{
"code": null,
"e": 9948,
"s": 9942,
"text": "SMITH"
},
{
"code": null,
"e": 9959,
"s": 9948,
"text": "SMITH NULL"
},
{
"code": null,
"e": 9969,
"s": 9959,
"text": "SMITHNULL"
},
{
"code": null,
"e": 10007,
"s": 9969,
"text": "ORA-00904: \"NULL\": invalid identifier"
},
{
"code": null,
"e": 10068,
"s": 10007,
"text": "Answer: A. Concatenation with NULL results into same value. "
},
{
"code": null,
"e": 10110,
"s": 10068,
"text": "21. Predict the output of the below query"
},
{
"code": null,
"e": 10138,
"s": 10110,
"text": "SELECT 50 || 0001\nFROM dual"
},
{
"code": null,
"e": 10159,
"s": 10138,
"text": "\n500001\n51\n501\n5001\n"
},
{
"code": null,
"e": 10166,
"s": 10159,
"text": "500001"
},
{
"code": null,
"e": 10169,
"s": 10166,
"text": "51"
},
{
"code": null,
"e": 10173,
"s": 10169,
"text": "501"
},
{
"code": null,
"e": 10178,
"s": 10173,
"text": "5001"
},
{
"code": null,
"e": 10267,
"s": 10178,
"text": "Answer: C. The leading zeroes in the right operand of expression are ignored by Oracle. "
},
{
"code": null,
"e": 10299,
"s": 10267,
"text": "22. You execute the below query"
},
{
"code": null,
"e": 10395,
"s": 10299,
"text": "SELECT e.ename||' departments's name is:'|| d.dname\nFROM emp e, dept d\nwhere e.deptno=d.deptno;"
},
{
"code": null,
"e": 10539,
"s": 10395,
"text": "And get the exception - ORA-01756: quoted string not properly terminated. Which of the following solutions can permanently resolve the problem?"
},
{
"code": null,
"e": 10850,
"s": 10539,
"text": "\nUse double quote marks for the literal character string\nUse [q] operator to enquote the literal character string and selecting the delimiter of choice\nRemove the single quote mark (apostrophe) from the literal character string\nUse another delimiter to bypass the single quote apostrophe in the literal string\n"
},
{
"code": null,
"e": 10906,
"s": 10850,
"text": "Use double quote marks for the literal character string"
},
{
"code": null,
"e": 11001,
"s": 10906,
"text": "Use [q] operator to enquote the literal character string and selecting the delimiter of choice"
},
{
"code": null,
"e": 11077,
"s": 11001,
"text": "Remove the single quote mark (apostrophe) from the literal character string"
},
{
"code": null,
"e": 11159,
"s": 11077,
"text": "Use another delimiter to bypass the single quote apostrophe in the literal string"
},
{
"code": null,
"e": 11239,
"s": 11159,
"text": "Answer: B. The [q] operator is used to enquote character literals with a quote."
},
{
"code": null,
"e": 11320,
"s": 11239,
"text": "23. Which of the below SELECT statement shows the correct usage of [q] operator?"
},
{
"code": null,
"e": 11744,
"s": 11320,
"text": "\nSELECT e.ename || q'[department's name is]'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;\nSELECT e.ename || q['department's name is']|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;\nSELECT e.ename || q[department's name is]|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;\nSELECT e.ename || q'(department's name is)'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;\n"
},
{
"code": null,
"e": 11850,
"s": 11744,
"text": "SELECT e.ename || q'[department's name is]'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 11956,
"s": 11850,
"text": "SELECT e.ename || q'[department's name is]'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12062,
"s": 11956,
"text": "SELECT e.ename || q['department's name is']|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12168,
"s": 12062,
"text": "SELECT e.ename || q['department's name is']|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12272,
"s": 12168,
"text": "SELECT e.ename || q[department's name is]|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12376,
"s": 12272,
"text": "SELECT e.ename || q[department's name is]|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12482,
"s": 12376,
"text": "SELECT e.ename || q'(department's name is)'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12588,
"s": 12482,
"text": "SELECT e.ename || q'(department's name is)'|| d.dname\n FROM emp e, dept d\n WHERE e.deptno = d.deptno;"
},
{
"code": null,
"e": 12598,
"s": 12588,
"text": "Answer: A"
},
{
"code": null,
"e": 12682,
"s": 12598,
"text": "24. Which of the below SELECT statement is used to select all columns of EMP table?"
},
{
"code": null,
"e": 12796,
"s": 12682,
"text": "\nSELECT ALL FROM emp\nSELECT # FROM emp\nSELECT * FROM emp\nSELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp\n"
},
{
"code": null,
"e": 12816,
"s": 12796,
"text": "SELECT ALL FROM emp"
},
{
"code": null,
"e": 12836,
"s": 12816,
"text": "SELECT ALL FROM emp"
},
{
"code": null,
"e": 12854,
"s": 12836,
"text": "SELECT # FROM emp"
},
{
"code": null,
"e": 12872,
"s": 12854,
"text": "SELECT # FROM emp"
},
{
"code": null,
"e": 12890,
"s": 12872,
"text": "SELECT * FROM emp"
},
{
"code": null,
"e": 12908,
"s": 12890,
"text": "SELECT * FROM emp"
},
{
"code": null,
"e": 12964,
"s": 12908,
"text": "SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp"
},
{
"code": null,
"e": 13020,
"s": 12964,
"text": "SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp"
},
{
"code": null,
"e": 13098,
"s": 13020,
"text": "Answer: C. The character '*' is used to select all the columns of the table. "
},
{
"code": null,
"e": 13191,
"s": 13098,
"text": "25. Which of the below SQL query will display employee names, department, and annual salary?"
},
{
"code": null,
"e": 13403,
"s": 13191,
"text": "\nSELECT ename, deptno, sal FROM emp;\nSELECT ename, deptno, sal + comm FROM emp;\nSELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;\nAnnual salary cannot be queried since the column doesn't exists in the table\n"
},
{
"code": null,
"e": 13439,
"s": 13403,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 13475,
"s": 13439,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 13518,
"s": 13475,
"text": "SELECT ename, deptno, sal + comm FROM emp;"
},
{
"code": null,
"e": 13561,
"s": 13518,
"text": "SELECT ename, deptno, sal + comm FROM emp;"
},
{
"code": null,
"e": 13615,
"s": 13561,
"text": "SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;"
},
{
"code": null,
"e": 13669,
"s": 13615,
"text": "SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;"
},
{
"code": null,
"e": 13746,
"s": 13669,
"text": "Annual salary cannot be queried since the column doesn't exists in the table"
},
{
"code": null,
"e": 13844,
"s": 13746,
"text": "Answer: C. Use numeric expressions in SELECT statement to perform basic arithmetic calculations. "
},
{
"code": null,
"e": 13877,
"s": 13844,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13891,
"s": 13877,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 13924,
"s": 13891,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13938,
"s": 13924,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 13973,
"s": 13938,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13987,
"s": 13973,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14020,
"s": 13987,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 14042,
"s": 14020,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 14077,
"s": 14042,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 14131,
"s": 14077,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 14164,
"s": 14131,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 14192,
"s": 14164,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14199,
"s": 14192,
"text": " Print"
},
{
"code": null,
"e": 14210,
"s": 14199,
"text": " Add Notes"
}
] |
Java Interface methods - GeeksforGeeks | 07 Jun, 2020
There is a rule that every member of interface is only and only public whether you define or not. So when we define the method of the interface in a class implementing the interface, we have to give it public access as child class can’t assign the weaker access to the methods.As defined, every method present inside interface is always public and abstract whether we are declaring or not. Hence inside interface the following methods declarations are equal.
void methodOne();
public Void methodOne();
abstract Void methodOne();
public abstract Void methodOne();
public : To make this method available for every implementation class.abstract : Implementation class is responsible to provide implementation.Also, We can’t use the following modifiers for interface methods.
Private
protected
final
static
synchronized
native
strictfp
// A Simple Java program to demonstrate that// interface methods must be public in // implementing classinterface A{ void fun();} class B implements A{ // If we change public to anything else, // we get compiler error public void fun() { System.out.println("fun()"); }} class C{ public static void main(String[] args) { B b = new B(); b.fun(); }}
Output:
fun()
If we change fun() to anything other than public in class B, we get compiler error “attempting to assign weaker access privileges; was public”
This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
gauravmoney26
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23972,
"s": 23944,
"text": "\n07 Jun, 2020"
},
{
"code": null,
"e": 24431,
"s": 23972,
"text": "There is a rule that every member of interface is only and only public whether you define or not. So when we define the method of the interface in a class implementing the interface, we have to give it public access as child class can’t assign the weaker access to the methods.As defined, every method present inside interface is always public and abstract whether we are declaring or not. Hence inside interface the following methods declarations are equal."
},
{
"code": null,
"e": 24536,
"s": 24431,
"text": "void methodOne();\npublic Void methodOne();\nabstract Void methodOne();\npublic abstract Void methodOne();\n"
},
{
"code": null,
"e": 24745,
"s": 24536,
"text": "public : To make this method available for every implementation class.abstract : Implementation class is responsible to provide implementation.Also, We can’t use the following modifiers for interface methods."
},
{
"code": null,
"e": 24753,
"s": 24745,
"text": "Private"
},
{
"code": null,
"e": 24763,
"s": 24753,
"text": "protected"
},
{
"code": null,
"e": 24769,
"s": 24763,
"text": "final"
},
{
"code": null,
"e": 24776,
"s": 24769,
"text": "static"
},
{
"code": null,
"e": 24789,
"s": 24776,
"text": "synchronized"
},
{
"code": null,
"e": 24796,
"s": 24789,
"text": "native"
},
{
"code": null,
"e": 24805,
"s": 24796,
"text": "strictfp"
},
{
"code": "// A Simple Java program to demonstrate that// interface methods must be public in // implementing classinterface A{ void fun();} class B implements A{ // If we change public to anything else, // we get compiler error public void fun() { System.out.println(\"fun()\"); }} class C{ public static void main(String[] args) { B b = new B(); b.fun(); }}",
"e": 25203,
"s": 24805,
"text": null
},
{
"code": null,
"e": 25211,
"s": 25203,
"text": "Output:"
},
{
"code": null,
"e": 25217,
"s": 25211,
"text": "fun()"
},
{
"code": null,
"e": 25360,
"s": 25217,
"text": "If we change fun() to anything other than public in class B, we get compiler error “attempting to assign weaker access privileges; was public”"
},
{
"code": null,
"e": 25627,
"s": 25360,
"text": "This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 25751,
"s": 25627,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 25765,
"s": 25751,
"text": "gauravmoney26"
},
{
"code": null,
"e": 25770,
"s": 25765,
"text": "Java"
},
{
"code": null,
"e": 25775,
"s": 25770,
"text": "Java"
},
{
"code": null,
"e": 25873,
"s": 25775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25888,
"s": 25873,
"text": "Stream In Java"
},
{
"code": null,
"e": 25934,
"s": 25888,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25955,
"s": 25934,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25974,
"s": 25955,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26004,
"s": 25974,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26021,
"s": 26004,
"text": "Generics in Java"
},
{
"code": null,
"e": 26064,
"s": 26021,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26093,
"s": 26064,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26114,
"s": 26093,
"text": "Introduction to Java"
}
] |
Regression using sklearn on KC Housing Dataset | by Nikhil Kumar Mutyala | Towards Data Science | In order to predict The King County’s home prices, I chose the housing price dataset that was sourced from Kaggle. This dataset contains house sale prices for King County, which includes Seattle. It includes homes sold between May 2014 and May 2015. It has many characteristics of learning, and the dataset can be downloaded from here.
The overall idea of regression is to examine two things: (1) does a set of predictor variables do a good job in predicting an outcome (dependent) variable? (2) Which variables in particular are significant predictors of the outcome variable, and in what way do they–indicated by the magnitude and sign of the beta estimates–impact the outcome variable? These regression estimates are used to explain the relationship between one dependent variable and one or more independent variables.
Simple Linear Regression
‘bedrooms’ vs ‘price’‘grade’ vs ‘price’
‘bedrooms’ vs ‘price’
‘grade’ vs ‘price’
Multiple Regression
‘bedrooms’,’grade’, ‘sqft_living’, ‘sqft_above’‘bedrooms’,’bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘waterfront’, ‘view’, ‘grade’, ‘sqft_above’, ‘sqft_basement’, ‘lat’, ‘sqft_living15’
‘bedrooms’,’grade’, ‘sqft_living’, ‘sqft_above’
‘bedrooms’,’bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘waterfront’, ‘view’, ‘grade’, ‘sqft_above’, ‘sqft_basement’, ‘lat’, ‘sqft_living15’
Polynomial Regression
degree=2degree=3
degree=2
degree=3
In this dataset the sales price of houses in King County, Seattle are present. It includes homes sold between May 2014 and May 2015. Before doing anything we should first know about the dataset what it contains what are its features and what is the structure of data.
By observing the data, we can know that the price is dependent on various features like bedrooms(which is most dependent feature), bathrooms, sqft_living(second most important feature), sqft_lot, floors etc. The price is also dependent on the location of the house where it is present. The other features like waterfront, view are less dependent on the price. Of all the records, there are no missing values, which helps us creating better model.
import required libraries.
#importing numpy and pandas, seabornimport numpy as np #linear algebraimport pandas as pd #datapreprocessing, CSV file I/Oimport seaborn as sns #for plotting graphsimport matplotlib.pyplot as plt
Read the CSV file.
df = pd.read_csv("../input/housesalesprediction/kc_house_data.csv")
Pandas dataframe.info() function is used to get a concise summary of the dataframe. It comes really handy when doing exploratory analysis of the data. To get a quick overview of the dataset we use the dataframe.info() function.
df.info()
Pandas head() method is used to return top n (5 by default) rows of a data frame or series.
df.head()
Pandas shape fucntion isused to return size, shape and dimensions of data frames and series.
#finding no of rows and columnsdf.shape
Calling sum() of the DataFrame returned by isnull() will give a series containing data about count of NaN in each column.
df.isnull().sum()
Finding the count of no of bedrooms.
df['bedrooms'].value_counts()
Finding the count of waterfront.
Finding the count of grade.
df['grade'].value_counts()
Finding the count of condition.
df['condition'].value_counts()
A countplot is plotted for bedrooms.
sns.countplot(df.bedrooms,order=df['bedrooms'].value_counts().index)
A barplot is plotted between sqft living and prices to get an overview of how the price changes with sqft.
A barplot is plotted between the sqft above and prices to see how the price changes with the sqft above.
fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))plt.title("house prices by sqft_above")plt.xlabel('sqft_above')plt.ylabel('house prices')plt.legend()sns.barplot(x='sqft_above',y='price',data=df)
A histogram is plotted for sqft living.
plt.hist('sqft_living',data=df,bins=5)
A distplot is plotted for sqft living to see if the data is skewed or not
fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))sns.distplot(df['sqft_living'],hist=True,kde=True,rug=False,label='sqft_living',norm_hist=True)
A distplot is plotted for sqft above to see if the data is skewed or not
fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))sns.distplot(df['sqft_above'],hist=True,kde=True,rug=False,label='sqft_above',norm_hist=True)
Finding the mean, mode and median of sqft living.
print('Mean',round(df['sqft_living'].mean(),2))print('Median',df['sqft_living'].median())print('Mode',df['sqft_living'].mode()[0])
Through graphs we observe that the sqft living=1300 has more values.
len(df[df['sqft_living']==1300])
Making sure we covered all the relations, we plot a correlation between all the features using a heatmap.
A heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors.
def correlation_heatmap(df1): _,ax=plt.subplots(figsize=(15,10)) colormap=sns.diverging_palette(220,10,as_cmap=True) sns.heatmap(df.corr(),annot=True,cmap=colormap) correlation_heatmap(df)
Now that we have got enough inofrmation about the data, we start linear regression.
For linear Regression, we are using linear_model from sklearn function.
Scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python. The library is built upon the SciPy (Scientific Python) that must be installed before you can use scikit-learn. Extensions or modules for SciPy care conventionally named SciKits. As such, the module provides learning algorithms and is named scikit-learn.
We import train_test_split. This splits the data into required ratio (ex: 80–20), of which a certain ratio is considered for training the data, and the rest for testing the data. The data is trained to predict a line and then the test data is used to see if the line fits perfectly or not.
PolynomialFeatures generates a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree.
The metrics is imported as the metric module implements functions assessing prediction error for specific purposes.
In KNeighborsRegressor the target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set.
from sklearn.model_selection import train_test_splitfrom sklearn import linear_modelfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn import metricsfrom mpl_toolkits.mplot3d import Axes3D%matplotlib inline
Here we splitting the data into 80:20 ratio of which train_size is 80%, test_size is 20%. train_test_split splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state , you will get a different result, this is expected behavior. In order to get the same train ans test subsets we declare a random state. Here the x is ‘sqft_living’ and y is ‘price’. We are reshaping the x_train and y_train and the data is fitted. The x_test and y_test are used to predict the accuracy of the model. Here first we are calculating the squared mean error of y_test. The squared mean error for training and test are found. The intercept and coefficient of the line are found.
train_data,test_data=train_test_split(df,train_size=0.8,random_state=3)reg=linear_model.LinearRegression()x_train=np.array(train_data['sqft_living']).reshape(-1,1)y_train=np.array(train_data['price']).reshape(-1,1)reg.fit(x_train,y_train)x_test=np.array(test_data['sqft_living']).reshape(-1,1)y_test=np.array(test_data['price']).reshape(-1,1)pred=reg.predict(x_test)print('linear model')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('Sqaured mean error', round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(x_train,y_train),3))print('R sqaured testing',round(reg.score(x_test,y_test),3) )print('intercept',reg.intercept_)print('coefficient',reg.coef_)
R-squared testing: 0.496
A scatterplot graph is plotted for x_test, y_test. The data is spread over the graph. Now the line obtained from above is plotted to see how it fits for the data.
_, ax = plt.subplots(figsize= (12, 10))plt.scatter(x_test, y_test, color= 'darkgreen', label = 'data')plt.plot(x_test, reg.predict(x_test), color='red', label= ' Predicted Regression line')plt.xlabel('Living Space (sqft)')plt.ylabel('price')plt.legend()plt.gca().spines['right'].set_visible(False)plt.gca().spines['right'].set_visible(False)
Here we are splitting the data in 80:20 ratio, of which train_size is 80% and test_size is 20%. Here x is ‘grade’ and y is ‘price’. We are reshaping the x_train and y_train and the data is fitted. The x_test and y_test are used to predict the accuracy of the model. Here first we are calculating the squared mean error of y_test. The squared mean error for training and test are found. The intercept and coefficient of the line are found.
train_data,test_data=train_test_split(df,train_size=0.8,random_state=3)reg=linear_model.LinearRegression()x_train=np.array(train_data['grade']).reshape(-1,1)y_train=np.array(train_data['price']).reshape(-1,1)reg.fit(x_train,y_train)x_test=np.array(test_data['grade']).reshape(-1,1)y_test=np.array(test_data['price']).reshape(-1,1)pred=reg.predict(x_test)print('linear model')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('squared mean error',round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(x_train,y_train),3))print('R squared testing',round(reg.score(x_test,y_test),3))print('intercept',reg.intercept_)print('coeeficient',reg.coef_)
R-squared testing: 0.46
The boxplot is plotted for ‘grade’, ‘bedrooms’ and ‘bathrooms’ with respective to ‘price’.
fig,ax=plt.subplots(2,1,figsize=(15,10))sns.boxplot(x=train_data['grade'],y=train_data['price'],ax=ax[0])sns.boxplot(x=train_data['bedrooms'],y=train_data['price'],ax=ax[1])_ , axes = plt.subplots(1, 1, figsize=(15,10))sns.boxplot(x=train_data['bathrooms'],y=train_data['price'])
The features we are considering are ‘bedrooms’, ‘grade’, ‘sqft_living’ and ‘sqft_above’. These are considered are one feature namely features1. Now the data is fitted into the model and test_data of features1 are used for prediction. Mean squared error is calculated for y_test. The mean squared error is rounded of upto 2 decimals. R squared error for both training and test is calculated. The intercept of the line is calculated along with coefficient of individual feature.
features1=['bedrooms','grade','sqft_living','sqft_above']reg=linear_model.LinearRegression()reg.fit(train_data[features1],train_data['price'])pred=reg.predict(test_data[features1])print('complex_model 1')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('mean squared error(MSE)', round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(train_data[features1],train_data['price']),3))print('R squared training', round(reg.score(test_data[features1],test_data['price']),3))print('Intercept: ', reg.intercept_)print('Coefficient:', reg.coef_)
R-squared testing: 0.555
The features we are considering are ‘bedrooms’, ’bathrooms’, ’sqft_living’, ’sqft_lot’, ’floors’, ’waterfront’, ’view’, ’grade’, ’sqft_above’, ’sqft_basement’, ’lat’,’sqft_living15'. These are considered are one feature namely features2. Now the data is fitted into the model and test_data of features2 are used for prediction. Mean squared error is calculated for y_test. The mean squared error is rounded of upto 2 decimals. R squared error for both training and test is calculated. The intercept of the line is calculated along with coefficient of individual feature.
features2 = ['bedrooms','bathrooms','sqft_living','sqft_lot','floors','waterfront','view','grade','sqft_above','sqft_basement','lat','sqft_living15']reg= linear_model.LinearRegression()reg.fit(train_data[features1],train_data['price'])pred = reg.predict(test_data[features1])print('Complex Model_2')mean_squared_error = metrics.mean_squared_error(y_test, pred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(reg.score(train_data[features1], train_data['price']), 3))print('R-squared (testing) ', round(reg.score(test_data[features1], test_data['price']), 3))print('Intercept: ', reg.intercept_)print('Coefficient:', reg.coef_)
R-squared testing: 0.672
Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x).
For degree=2, the linear modelis built. The mean squared error is calculated and r squared is found for training and testing.
polyfeat=PolynomialFeatures(degree=2)xtrain_poly=polyfeat.fit_transform(train_data[features1])xtest_poly=polyfeat.fit_transform(test_data[features1])poly=linear_model.LinearRegression()poly.fit(xtrain_poly,train_data['price'])polypred=poly.predict(xtest_poly)print('Complex Model_3')mean_squared_error = metrics.mean_squared_error(test_data['price'], polypred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(poly.score(xtrain_poly, train_data['price']), 3))print('R-squared (testing) ', round(poly.score(xtest_poly, test_data['price']), 3))
R-squared testing: 0.759
For degree=3, the linear model is built. The mean squared error is calculated and r squared is found for training and testing.
polyfeat=PolynomialFeatures(degree=3)xtrain_poly=polyfeat.fit_transform(train_data[features1])xtest_poly=polyfeat.fit_transform(test_data[features1])poly=linear_model.LinearRegression()poly.fit(xtrain_poly,train_data['price'])polypred=poly.predict(xtest_poly)print('complex model_4')mean_squared_error=metrics.mean_squared_error(test_data['price'],polypred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(poly.score(xtrain_poly, train_data['price']), 3))print('R-squared (testing) ', round(poly.score(xtest_poly, test_data['price']), 3))
R-squared testing: 0.664
Complex Model_3 gives us R-squared (testing) score of 0.759. From above reports, we can conclude that Polynomial regression for degree=2, is best solution.
For notebook, refer here. I would be pleased to receive feedback or questions on any of the above. | [
{
"code": null,
"e": 508,
"s": 172,
"text": "In order to predict The King County’s home prices, I chose the housing price dataset that was sourced from Kaggle. This dataset contains house sale prices for King County, which includes Seattle. It includes homes sold between May 2014 and May 2015. It has many characteristics of learning, and the dataset can be downloaded from here."
},
{
"code": null,
"e": 995,
"s": 508,
"text": "The overall idea of regression is to examine two things: (1) does a set of predictor variables do a good job in predicting an outcome (dependent) variable? (2) Which variables in particular are significant predictors of the outcome variable, and in what way do they–indicated by the magnitude and sign of the beta estimates–impact the outcome variable? These regression estimates are used to explain the relationship between one dependent variable and one or more independent variables."
},
{
"code": null,
"e": 1020,
"s": 995,
"text": "Simple Linear Regression"
},
{
"code": null,
"e": 1060,
"s": 1020,
"text": "‘bedrooms’ vs ‘price’‘grade’ vs ‘price’"
},
{
"code": null,
"e": 1082,
"s": 1060,
"text": "‘bedrooms’ vs ‘price’"
},
{
"code": null,
"e": 1101,
"s": 1082,
"text": "‘grade’ vs ‘price’"
},
{
"code": null,
"e": 1121,
"s": 1101,
"text": "Multiple Regression"
},
{
"code": null,
"e": 1314,
"s": 1121,
"text": "‘bedrooms’,’grade’, ‘sqft_living’, ‘sqft_above’‘bedrooms’,’bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘waterfront’, ‘view’, ‘grade’, ‘sqft_above’, ‘sqft_basement’, ‘lat’, ‘sqft_living15’"
},
{
"code": null,
"e": 1362,
"s": 1314,
"text": "‘bedrooms’,’grade’, ‘sqft_living’, ‘sqft_above’"
},
{
"code": null,
"e": 1508,
"s": 1362,
"text": "‘bedrooms’,’bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘waterfront’, ‘view’, ‘grade’, ‘sqft_above’, ‘sqft_basement’, ‘lat’, ‘sqft_living15’"
},
{
"code": null,
"e": 1530,
"s": 1508,
"text": "Polynomial Regression"
},
{
"code": null,
"e": 1547,
"s": 1530,
"text": "degree=2degree=3"
},
{
"code": null,
"e": 1556,
"s": 1547,
"text": "degree=2"
},
{
"code": null,
"e": 1565,
"s": 1556,
"text": "degree=3"
},
{
"code": null,
"e": 1833,
"s": 1565,
"text": "In this dataset the sales price of houses in King County, Seattle are present. It includes homes sold between May 2014 and May 2015. Before doing anything we should first know about the dataset what it contains what are its features and what is the structure of data."
},
{
"code": null,
"e": 2280,
"s": 1833,
"text": "By observing the data, we can know that the price is dependent on various features like bedrooms(which is most dependent feature), bathrooms, sqft_living(second most important feature), sqft_lot, floors etc. The price is also dependent on the location of the house where it is present. The other features like waterfront, view are less dependent on the price. Of all the records, there are no missing values, which helps us creating better model."
},
{
"code": null,
"e": 2307,
"s": 2280,
"text": "import required libraries."
},
{
"code": null,
"e": 2503,
"s": 2307,
"text": "#importing numpy and pandas, seabornimport numpy as np #linear algebraimport pandas as pd #datapreprocessing, CSV file I/Oimport seaborn as sns #for plotting graphsimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 2522,
"s": 2503,
"text": "Read the CSV file."
},
{
"code": null,
"e": 2590,
"s": 2522,
"text": "df = pd.read_csv(\"../input/housesalesprediction/kc_house_data.csv\")"
},
{
"code": null,
"e": 2818,
"s": 2590,
"text": "Pandas dataframe.info() function is used to get a concise summary of the dataframe. It comes really handy when doing exploratory analysis of the data. To get a quick overview of the dataset we use the dataframe.info() function."
},
{
"code": null,
"e": 2828,
"s": 2818,
"text": "df.info()"
},
{
"code": null,
"e": 2920,
"s": 2828,
"text": "Pandas head() method is used to return top n (5 by default) rows of a data frame or series."
},
{
"code": null,
"e": 2930,
"s": 2920,
"text": "df.head()"
},
{
"code": null,
"e": 3023,
"s": 2930,
"text": "Pandas shape fucntion isused to return size, shape and dimensions of data frames and series."
},
{
"code": null,
"e": 3063,
"s": 3023,
"text": "#finding no of rows and columnsdf.shape"
},
{
"code": null,
"e": 3185,
"s": 3063,
"text": "Calling sum() of the DataFrame returned by isnull() will give a series containing data about count of NaN in each column."
},
{
"code": null,
"e": 3203,
"s": 3185,
"text": "df.isnull().sum()"
},
{
"code": null,
"e": 3240,
"s": 3203,
"text": "Finding the count of no of bedrooms."
},
{
"code": null,
"e": 3270,
"s": 3240,
"text": "df['bedrooms'].value_counts()"
},
{
"code": null,
"e": 3303,
"s": 3270,
"text": "Finding the count of waterfront."
},
{
"code": null,
"e": 3331,
"s": 3303,
"text": "Finding the count of grade."
},
{
"code": null,
"e": 3358,
"s": 3331,
"text": "df['grade'].value_counts()"
},
{
"code": null,
"e": 3390,
"s": 3358,
"text": "Finding the count of condition."
},
{
"code": null,
"e": 3421,
"s": 3390,
"text": "df['condition'].value_counts()"
},
{
"code": null,
"e": 3458,
"s": 3421,
"text": "A countplot is plotted for bedrooms."
},
{
"code": null,
"e": 3527,
"s": 3458,
"text": "sns.countplot(df.bedrooms,order=df['bedrooms'].value_counts().index)"
},
{
"code": null,
"e": 3634,
"s": 3527,
"text": "A barplot is plotted between sqft living and prices to get an overview of how the price changes with sqft."
},
{
"code": null,
"e": 3739,
"s": 3634,
"text": "A barplot is plotted between the sqft above and prices to see how the price changes with the sqft above."
},
{
"code": null,
"e": 3940,
"s": 3739,
"text": "fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))plt.title(\"house prices by sqft_above\")plt.xlabel('sqft_above')plt.ylabel('house prices')plt.legend()sns.barplot(x='sqft_above',y='price',data=df)"
},
{
"code": null,
"e": 3980,
"s": 3940,
"text": "A histogram is plotted for sqft living."
},
{
"code": null,
"e": 4019,
"s": 3980,
"text": "plt.hist('sqft_living',data=df,bins=5)"
},
{
"code": null,
"e": 4093,
"s": 4019,
"text": "A distplot is plotted for sqft living to see if the data is skewed or not"
},
{
"code": null,
"e": 4243,
"s": 4093,
"text": "fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))sns.distplot(df['sqft_living'],hist=True,kde=True,rug=False,label='sqft_living',norm_hist=True)"
},
{
"code": null,
"e": 4316,
"s": 4243,
"text": "A distplot is plotted for sqft above to see if the data is skewed or not"
},
{
"code": null,
"e": 4464,
"s": 4316,
"text": "fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))sns.distplot(df['sqft_above'],hist=True,kde=True,rug=False,label='sqft_above',norm_hist=True)"
},
{
"code": null,
"e": 4514,
"s": 4464,
"text": "Finding the mean, mode and median of sqft living."
},
{
"code": null,
"e": 4645,
"s": 4514,
"text": "print('Mean',round(df['sqft_living'].mean(),2))print('Median',df['sqft_living'].median())print('Mode',df['sqft_living'].mode()[0])"
},
{
"code": null,
"e": 4714,
"s": 4645,
"text": "Through graphs we observe that the sqft living=1300 has more values."
},
{
"code": null,
"e": 4747,
"s": 4714,
"text": "len(df[df['sqft_living']==1300])"
},
{
"code": null,
"e": 4853,
"s": 4747,
"text": "Making sure we covered all the relations, we plot a correlation between all the features using a heatmap."
},
{
"code": null,
"e": 5003,
"s": 4853,
"text": "A heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors."
},
{
"code": null,
"e": 5204,
"s": 5003,
"text": "def correlation_heatmap(df1): _,ax=plt.subplots(figsize=(15,10)) colormap=sns.diverging_palette(220,10,as_cmap=True) sns.heatmap(df.corr(),annot=True,cmap=colormap) correlation_heatmap(df)"
},
{
"code": null,
"e": 5288,
"s": 5204,
"text": "Now that we have got enough inofrmation about the data, we start linear regression."
},
{
"code": null,
"e": 5360,
"s": 5288,
"text": "For linear Regression, we are using linear_model from sklearn function."
},
{
"code": null,
"e": 5734,
"s": 5360,
"text": "Scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python. The library is built upon the SciPy (Scientific Python) that must be installed before you can use scikit-learn. Extensions or modules for SciPy care conventionally named SciKits. As such, the module provides learning algorithms and is named scikit-learn."
},
{
"code": null,
"e": 6024,
"s": 5734,
"text": "We import train_test_split. This splits the data into required ratio (ex: 80–20), of which a certain ratio is considered for training the data, and the rest for testing the data. The data is trained to predict a line and then the test data is used to see if the line fits perfectly or not."
},
{
"code": null,
"e": 6188,
"s": 6024,
"text": "PolynomialFeatures generates a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree."
},
{
"code": null,
"e": 6304,
"s": 6188,
"text": "The metrics is imported as the metric module implements functions assessing prediction error for specific purposes."
},
{
"code": null,
"e": 6446,
"s": 6304,
"text": "In KNeighborsRegressor the target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set."
},
{
"code": null,
"e": 6716,
"s": 6446,
"text": "from sklearn.model_selection import train_test_splitfrom sklearn import linear_modelfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn import metricsfrom mpl_toolkits.mplot3d import Axes3D%matplotlib inline"
},
{
"code": null,
"e": 7444,
"s": 6716,
"text": "Here we splitting the data into 80:20 ratio of which train_size is 80%, test_size is 20%. train_test_split splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state , you will get a different result, this is expected behavior. In order to get the same train ans test subsets we declare a random state. Here the x is ‘sqft_living’ and y is ‘price’. We are reshaping the x_train and y_train and the data is fitted. The x_test and y_test are used to predict the accuracy of the model. Here first we are calculating the squared mean error of y_test. The squared mean error for training and test are found. The intercept and coefficient of the line are found."
},
{
"code": null,
"e": 8142,
"s": 7444,
"text": "train_data,test_data=train_test_split(df,train_size=0.8,random_state=3)reg=linear_model.LinearRegression()x_train=np.array(train_data['sqft_living']).reshape(-1,1)y_train=np.array(train_data['price']).reshape(-1,1)reg.fit(x_train,y_train)x_test=np.array(test_data['sqft_living']).reshape(-1,1)y_test=np.array(test_data['price']).reshape(-1,1)pred=reg.predict(x_test)print('linear model')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('Sqaured mean error', round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(x_train,y_train),3))print('R sqaured testing',round(reg.score(x_test,y_test),3) )print('intercept',reg.intercept_)print('coefficient',reg.coef_)"
},
{
"code": null,
"e": 8167,
"s": 8142,
"text": "R-squared testing: 0.496"
},
{
"code": null,
"e": 8330,
"s": 8167,
"text": "A scatterplot graph is plotted for x_test, y_test. The data is spread over the graph. Now the line obtained from above is plotted to see how it fits for the data."
},
{
"code": null,
"e": 8672,
"s": 8330,
"text": "_, ax = plt.subplots(figsize= (12, 10))plt.scatter(x_test, y_test, color= 'darkgreen', label = 'data')plt.plot(x_test, reg.predict(x_test), color='red', label= ' Predicted Regression line')plt.xlabel('Living Space (sqft)')plt.ylabel('price')plt.legend()plt.gca().spines['right'].set_visible(False)plt.gca().spines['right'].set_visible(False)"
},
{
"code": null,
"e": 9111,
"s": 8672,
"text": "Here we are splitting the data in 80:20 ratio, of which train_size is 80% and test_size is 20%. Here x is ‘grade’ and y is ‘price’. We are reshaping the x_train and y_train and the data is fitted. The x_test and y_test are used to predict the accuracy of the model. Here first we are calculating the squared mean error of y_test. The squared mean error for training and test are found. The intercept and coefficient of the line are found."
},
{
"code": null,
"e": 9795,
"s": 9111,
"text": "train_data,test_data=train_test_split(df,train_size=0.8,random_state=3)reg=linear_model.LinearRegression()x_train=np.array(train_data['grade']).reshape(-1,1)y_train=np.array(train_data['price']).reshape(-1,1)reg.fit(x_train,y_train)x_test=np.array(test_data['grade']).reshape(-1,1)y_test=np.array(test_data['price']).reshape(-1,1)pred=reg.predict(x_test)print('linear model')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('squared mean error',round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(x_train,y_train),3))print('R squared testing',round(reg.score(x_test,y_test),3))print('intercept',reg.intercept_)print('coeeficient',reg.coef_)"
},
{
"code": null,
"e": 9819,
"s": 9795,
"text": "R-squared testing: 0.46"
},
{
"code": null,
"e": 9910,
"s": 9819,
"text": "The boxplot is plotted for ‘grade’, ‘bedrooms’ and ‘bathrooms’ with respective to ‘price’."
},
{
"code": null,
"e": 10190,
"s": 9910,
"text": "fig,ax=plt.subplots(2,1,figsize=(15,10))sns.boxplot(x=train_data['grade'],y=train_data['price'],ax=ax[0])sns.boxplot(x=train_data['bedrooms'],y=train_data['price'],ax=ax[1])_ , axes = plt.subplots(1, 1, figsize=(15,10))sns.boxplot(x=train_data['bathrooms'],y=train_data['price'])"
},
{
"code": null,
"e": 10667,
"s": 10190,
"text": "The features we are considering are ‘bedrooms’, ‘grade’, ‘sqft_living’ and ‘sqft_above’. These are considered are one feature namely features1. Now the data is fitted into the model and test_data of features1 are used for prediction. Mean squared error is calculated for y_test. The mean squared error is rounded of upto 2 decimals. R squared error for both training and test is calculated. The intercept of the line is calculated along with coefficient of individual feature."
},
{
"code": null,
"e": 11245,
"s": 10667,
"text": "features1=['bedrooms','grade','sqft_living','sqft_above']reg=linear_model.LinearRegression()reg.fit(train_data[features1],train_data['price'])pred=reg.predict(test_data[features1])print('complex_model 1')mean_squared_error=metrics.mean_squared_error(y_test,pred)print('mean squared error(MSE)', round(np.sqrt(mean_squared_error),2))print('R squared training',round(reg.score(train_data[features1],train_data['price']),3))print('R squared training', round(reg.score(test_data[features1],test_data['price']),3))print('Intercept: ', reg.intercept_)print('Coefficient:', reg.coef_)"
},
{
"code": null,
"e": 11270,
"s": 11245,
"text": "R-squared testing: 0.555"
},
{
"code": null,
"e": 11841,
"s": 11270,
"text": "The features we are considering are ‘bedrooms’, ’bathrooms’, ’sqft_living’, ’sqft_lot’, ’floors’, ’waterfront’, ’view’, ’grade’, ’sqft_above’, ’sqft_basement’, ’lat’,’sqft_living15'. These are considered are one feature namely features2. Now the data is fitted into the model and test_data of features2 are used for prediction. Mean squared error is calculated for y_test. The mean squared error is rounded of upto 2 decimals. R squared error for both training and test is calculated. The intercept of the line is calculated along with coefficient of individual feature."
},
{
"code": null,
"e": 12530,
"s": 11841,
"text": "features2 = ['bedrooms','bathrooms','sqft_living','sqft_lot','floors','waterfront','view','grade','sqft_above','sqft_basement','lat','sqft_living15']reg= linear_model.LinearRegression()reg.fit(train_data[features1],train_data['price'])pred = reg.predict(test_data[features1])print('Complex Model_2')mean_squared_error = metrics.mean_squared_error(y_test, pred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(reg.score(train_data[features1], train_data['price']), 3))print('R-squared (testing) ', round(reg.score(test_data[features1], test_data['price']), 3))print('Intercept: ', reg.intercept_)print('Coefficient:', reg.coef_)"
},
{
"code": null,
"e": 12555,
"s": 12530,
"text": "R-squared testing: 0.672"
},
{
"code": null,
"e": 12871,
"s": 12555,
"text": "Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x)."
},
{
"code": null,
"e": 12997,
"s": 12871,
"text": "For degree=2, the linear modelis built. The mean squared error is calculated and r squared is found for training and testing."
},
{
"code": null,
"e": 13600,
"s": 12997,
"text": "polyfeat=PolynomialFeatures(degree=2)xtrain_poly=polyfeat.fit_transform(train_data[features1])xtest_poly=polyfeat.fit_transform(test_data[features1])poly=linear_model.LinearRegression()poly.fit(xtrain_poly,train_data['price'])polypred=poly.predict(xtest_poly)print('Complex Model_3')mean_squared_error = metrics.mean_squared_error(test_data['price'], polypred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(poly.score(xtrain_poly, train_data['price']), 3))print('R-squared (testing) ', round(poly.score(xtest_poly, test_data['price']), 3))"
},
{
"code": null,
"e": 13625,
"s": 13600,
"text": "R-squared testing: 0.759"
},
{
"code": null,
"e": 13752,
"s": 13625,
"text": "For degree=3, the linear model is built. The mean squared error is calculated and r squared is found for training and testing."
},
{
"code": null,
"e": 14352,
"s": 13752,
"text": "polyfeat=PolynomialFeatures(degree=3)xtrain_poly=polyfeat.fit_transform(train_data[features1])xtest_poly=polyfeat.fit_transform(test_data[features1])poly=linear_model.LinearRegression()poly.fit(xtrain_poly,train_data['price'])polypred=poly.predict(xtest_poly)print('complex model_4')mean_squared_error=metrics.mean_squared_error(test_data['price'],polypred)print('Mean Squared Error (MSE) ', round(np.sqrt(mean_squared_error), 2))print('R-squared (training) ', round(poly.score(xtrain_poly, train_data['price']), 3))print('R-squared (testing) ', round(poly.score(xtest_poly, test_data['price']), 3))"
},
{
"code": null,
"e": 14377,
"s": 14352,
"text": "R-squared testing: 0.664"
},
{
"code": null,
"e": 14533,
"s": 14377,
"text": "Complex Model_3 gives us R-squared (testing) score of 0.759. From above reports, we can conclude that Polynomial regression for degree=2, is best solution."
}
] |
Check If the Rune is a Decimal Digit or not in Golang - GeeksforGeeks | 27 Sep, 2019
Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a decimal digit or not with the help of IsDigit() function. This function returns true if the given rune is a decimal digit, or return false if the given rune is a non-decimal digit. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program.
Syntax:
func IsDigit(r rune) bool
The return type of this function is boolean. Let us discuss this concept with the help of given examples:
Example 1:
// Go program to illustrate how to// check the given rune is a// decimal digit or notpackage main import ( "fmt" "unicode") // Main functionfunc main() { // Creating rune rune_1 := 'g' rune_2 := 'e' rune_3 := '1' rune_4 := '4' rune_5 := 'S' // Checking the given rune is // a decimal digit or not // Using IsDigit() function res_1 := unicode.IsDigit(rune_1) res_2 := unicode.IsDigit(rune_2) res_3 := unicode.IsDigit(rune_3) res_4 := unicode.IsDigit(rune_4) res_5 := unicode.IsDigit(rune_5) // Displaying results fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4) fmt.Println(res_5) }
Output:
false
false
true
true
false
Example 2:
// Go program to illustrate how to check// the given rune is a decimal digit or notpackage main import ( "fmt" "unicode") // Main functionfunc main() { // Creating a slice of rune val := []rune{'g', 'E', '3', 'K', '1'} // Checking each element of the given // slice of the rune is a decimal // digit or not // Using IsDigit() function for i := 0; i < len(val); i++ { if unicode.IsDigit(val[i]) == true { fmt.Println("It is a decimal digit") } else { fmt.Println("It is not a decimal digit") } }}
Output:
It is not a decimal digit
It is not a decimal digit
It is a decimal digit
It is not a decimal digit
It is a decimal digit
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Loops in Go Language
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Class and Object in Golang | [
{
"code": null,
"e": 24460,
"s": 24432,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 25156,
"s": 24460,
"text": "Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a decimal digit or not with the help of IsDigit() function. This function returns true if the given rune is a decimal digit, or return false if the given rune is a non-decimal digit. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program."
},
{
"code": null,
"e": 25164,
"s": 25156,
"text": "Syntax:"
},
{
"code": null,
"e": 25190,
"s": 25164,
"text": "func IsDigit(r rune) bool"
},
{
"code": null,
"e": 25296,
"s": 25190,
"text": "The return type of this function is boolean. Let us discuss this concept with the help of given examples:"
},
{
"code": null,
"e": 25307,
"s": 25296,
"text": "Example 1:"
},
{
"code": "// Go program to illustrate how to// check the given rune is a// decimal digit or notpackage main import ( \"fmt\" \"unicode\") // Main functionfunc main() { // Creating rune rune_1 := 'g' rune_2 := 'e' rune_3 := '1' rune_4 := '4' rune_5 := 'S' // Checking the given rune is // a decimal digit or not // Using IsDigit() function res_1 := unicode.IsDigit(rune_1) res_2 := unicode.IsDigit(rune_2) res_3 := unicode.IsDigit(rune_3) res_4 := unicode.IsDigit(rune_4) res_5 := unicode.IsDigit(rune_5) // Displaying results fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4) fmt.Println(res_5) }",
"e": 25992,
"s": 25307,
"text": null
},
{
"code": null,
"e": 26000,
"s": 25992,
"text": "Output:"
},
{
"code": null,
"e": 26029,
"s": 26000,
"text": "false\nfalse\ntrue\ntrue\nfalse\n"
},
{
"code": null,
"e": 26040,
"s": 26029,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate how to check// the given rune is a decimal digit or notpackage main import ( \"fmt\" \"unicode\") // Main functionfunc main() { // Creating a slice of rune val := []rune{'g', 'E', '3', 'K', '1'} // Checking each element of the given // slice of the rune is a decimal // digit or not // Using IsDigit() function for i := 0; i < len(val); i++ { if unicode.IsDigit(val[i]) == true { fmt.Println(\"It is a decimal digit\") } else { fmt.Println(\"It is not a decimal digit\") } }}",
"e": 26644,
"s": 26040,
"text": null
},
{
"code": null,
"e": 26652,
"s": 26644,
"text": "Output:"
},
{
"code": null,
"e": 26775,
"s": 26652,
"text": "It is not a decimal digit\nIt is not a decimal digit\nIt is a decimal digit\nIt is not a decimal digit\nIt is a decimal digit\n"
},
{
"code": null,
"e": 26782,
"s": 26775,
"text": "Golang"
},
{
"code": null,
"e": 26794,
"s": 26782,
"text": "Go Language"
},
{
"code": null,
"e": 26892,
"s": 26794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26901,
"s": 26892,
"text": "Comments"
},
{
"code": null,
"e": 26914,
"s": 26901,
"text": "Old Comments"
},
{
"code": null,
"e": 26943,
"s": 26914,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26967,
"s": 26943,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 26988,
"s": 26967,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27034,
"s": 26988,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 27068,
"s": 27034,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 27093,
"s": 27068,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27114,
"s": 27093,
"text": "Structures in Golang"
},
{
"code": null,
"e": 27132,
"s": 27114,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27187,
"s": 27132,
"text": "How to iterate over an Array using for loop in Golang?"
}
] |
C++ Basic Syntax | When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
The line int main() is the main function where program execution begins.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
Let's look at how to save the file, compile and run the program. Please follow the steps given below −
Open a text editor and add the code as above.
Open a text editor and add the code as above.
Save the file as: hello.cpp
Save the file as: hello.cpp
Open a command prompt and go to the directory where you saved the file.
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
Now, type 'a.out' to run your program.
Now, type 'a.out' to run your program.
You will be able to see ' Hello World ' printed on the window.
You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'.
In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives.
Following are most frequently used trigraph sequences −
All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.
A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins.
int age;
In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them.
fruit = apples + oranges; // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2535,
"s": 2318,
"text": "When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean."
},
{
"code": null,
"e": 2713,
"s": 2535,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class. "
},
{
"code": null,
"e": 2891,
"s": 2713,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class. "
},
{
"code": null,
"e": 3015,
"s": 2891,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support."
},
{
"code": null,
"e": 3139,
"s": 3015,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support."
},
{
"code": null,
"e": 3318,
"s": 3139,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3497,
"s": 3318,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3653,
"s": 3497,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 3809,
"s": 3653,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 3878,
"s": 3809,
"text": "Let us look at a simple code that would print the words Hello World."
},
{
"code": null,
"e": 4041,
"s": 3878,
"text": "#include <iostream>\nusing namespace std;\n\n// main() is where program execution begins.\nint main() {\n cout << \"Hello World\"; // prints Hello World\n return 0;\n}"
},
{
"code": null,
"e": 4097,
"s": 4041,
"text": "Let us look at the various parts of the above program −"
},
{
"code": null,
"e": 4268,
"s": 4097,
"text": "The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed."
},
{
"code": null,
"e": 4439,
"s": 4268,
"text": "The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed."
},
{
"code": null,
"e": 4566,
"s": 4439,
"text": "The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++."
},
{
"code": null,
"e": 4693,
"s": 4566,
"text": "The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++."
},
{
"code": null,
"e": 4865,
"s": 4693,
"text": "The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line."
},
{
"code": null,
"e": 5037,
"s": 4865,
"text": "The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line."
},
{
"code": null,
"e": 5110,
"s": 5037,
"text": "The line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 5183,
"s": 5110,
"text": "The line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 5284,
"s": 5183,
"text": "The next line cout << \"Hello World\"; causes the message \"Hello World\" to be displayed on the screen."
},
{
"code": null,
"e": 5385,
"s": 5284,
"text": "The next line cout << \"Hello World\"; causes the message \"Hello World\" to be displayed on the screen."
},
{
"code": null,
"e": 5496,
"s": 5385,
"text": "The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process."
},
{
"code": null,
"e": 5607,
"s": 5496,
"text": "The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process."
},
{
"code": null,
"e": 5710,
"s": 5607,
"text": "Let's look at how to save the file, compile and run the program. Please follow the steps given below −"
},
{
"code": null,
"e": 5756,
"s": 5710,
"text": "Open a text editor and add the code as above."
},
{
"code": null,
"e": 5802,
"s": 5756,
"text": "Open a text editor and add the code as above."
},
{
"code": null,
"e": 5830,
"s": 5802,
"text": "Save the file as: hello.cpp"
},
{
"code": null,
"e": 5858,
"s": 5830,
"text": "Save the file as: hello.cpp"
},
{
"code": null,
"e": 5930,
"s": 5858,
"text": "Open a command prompt and go to the directory where you saved the file."
},
{
"code": null,
"e": 6002,
"s": 5930,
"text": "Open a command prompt and go to the directory where you saved the file."
},
{
"code": null,
"e": 6189,
"s": 6002,
"text": "Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file."
},
{
"code": null,
"e": 6376,
"s": 6189,
"text": "Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file."
},
{
"code": null,
"e": 6415,
"s": 6376,
"text": "Now, type 'a.out' to run your program."
},
{
"code": null,
"e": 6454,
"s": 6415,
"text": "Now, type 'a.out' to run your program."
},
{
"code": null,
"e": 6517,
"s": 6454,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 6580,
"s": 6517,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 6619,
"s": 6580,
"text": "$ g++ hello.cpp\n$ ./a.out\nHello World\n"
},
{
"code": null,
"e": 6726,
"s": 6619,
"text": "Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp."
},
{
"code": null,
"e": 6830,
"s": 6726,
"text": "You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'."
},
{
"code": null,
"e": 6990,
"s": 6830,
"text": "In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity."
},
{
"code": null,
"e": 7046,
"s": 6990,
"text": "For example, following are three different statements −"
},
{
"code": null,
"e": 7076,
"s": 7046,
"text": "x = y;\ny = y + 1;\nadd(x, y);\n"
},
{
"code": null,
"e": 7192,
"s": 7076,
"text": "A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −"
},
{
"code": null,
"e": 7258,
"s": 7192,
"text": "{\n cout << \"Hello World\"; // prints Hello World\n return 0;\n}\n"
},
{
"code": null,
"e": 7405,
"s": 7258,
"text": "C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −"
},
{
"code": null,
"e": 7435,
"s": 7405,
"text": "x = y;\ny = y + 1;\nadd(x, y);\n"
},
{
"code": null,
"e": 7450,
"s": 7435,
"text": "is the same as"
},
{
"code": null,
"e": 7480,
"s": 7450,
"text": "x = y; y = y + 1; add(x, y);\n"
},
{
"code": null,
"e": 7734,
"s": 7480,
"text": "A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9)."
},
{
"code": null,
"e": 7929,
"s": 7734,
"text": "C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C++."
},
{
"code": null,
"e": 7980,
"s": 7929,
"text": "Here are some examples of acceptable identifiers −"
},
{
"code": null,
"e": 8066,
"s": 7980,
"text": "mohd zara abc move_name a_123\nmyname50 _temp j a23b9 retVal\n"
},
{
"code": null,
"e": 8210,
"s": 8066,
"text": "The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names."
},
{
"code": null,
"e": 8423,
"s": 8210,
"text": "A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks."
},
{
"code": null,
"e": 8570,
"s": 8423,
"text": "Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives."
},
{
"code": null,
"e": 8626,
"s": 8570,
"text": "Following are most frequently used trigraph sequences −"
},
{
"code": null,
"e": 8740,
"s": 8626,
"text": "All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature."
},
{
"code": null,
"e": 8863,
"s": 8740,
"text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it."
},
{
"code": null,
"e": 9133,
"s": 8863,
"text": "Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins."
},
{
"code": null,
"e": 9143,
"s": 9133,
"text": "int age;\n"
},
{
"code": null,
"e": 9301,
"s": 9143,
"text": "In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them."
},
{
"code": null,
"e": 9353,
"s": 9301,
"text": "fruit = apples + oranges; // Get the total fruit\n"
},
{
"code": null,
"e": 9539,
"s": 9353,
"text": "In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose."
},
{
"code": null,
"e": 9576,
"s": 9539,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 9595,
"s": 9576,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9627,
"s": 9595,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 9650,
"s": 9627,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9686,
"s": 9650,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 9703,
"s": 9686,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9738,
"s": 9703,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9755,
"s": 9738,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9790,
"s": 9755,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9807,
"s": 9790,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9842,
"s": 9807,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9859,
"s": 9842,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9866,
"s": 9859,
"text": " Print"
},
{
"code": null,
"e": 9877,
"s": 9866,
"text": " Add Notes"
}
] |
Subsets and Splits