title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python Tuple len() Method
|
Python tuple method len() returns the number of elements in the tuple.
Following is the syntax for len() method −
len(tuple)
tuple − This is a tuple for which number of elements to be counted.
tuple − This is a tuple for which number of elements to be counted.
This method returns the number of elements in the tuple.
The following example shows the usage of len() method.
#!/usr/bin/python
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)
When we run above program, it produces following result −
First tuple length : 3
Second tuple length : 2
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": 2315,
"s": 2244,
"text": "Python tuple method len() returns the number of elements in the tuple."
},
{
"code": null,
"e": 2358,
"s": 2315,
"text": "Following is the syntax for len() method −"
},
{
"code": null,
"e": 2369,
"s": 2358,
"text": "len(tuple)"
},
{
"code": null,
"e": 2437,
"s": 2369,
"text": "tuple − This is a tuple for which number of elements to be counted."
},
{
"code": null,
"e": 2505,
"s": 2437,
"text": "tuple − This is a tuple for which number of elements to be counted."
},
{
"code": null,
"e": 2562,
"s": 2505,
"text": "This method returns the number of elements in the tuple."
},
{
"code": null,
"e": 2617,
"s": 2562,
"text": "The following example shows the usage of len() method."
},
{
"code": null,
"e": 2775,
"s": 2617,
"text": "#!/usr/bin/python\n\ntuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')\nprint \"First tuple length : \", len(tuple1)\nprint \"Second tuple length : \", len(tuple2)"
},
{
"code": null,
"e": 2833,
"s": 2775,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2883,
"s": 2833,
"text": "First tuple length : 3\nSecond tuple length : 2\n"
},
{
"code": null,
"e": 2920,
"s": 2883,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2936,
"s": 2920,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2969,
"s": 2936,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2988,
"s": 2969,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3023,
"s": 2988,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3045,
"s": 3023,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3079,
"s": 3045,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3107,
"s": 3079,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3142,
"s": 3107,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3156,
"s": 3142,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3189,
"s": 3156,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3206,
"s": 3189,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3213,
"s": 3206,
"text": " Print"
},
{
"code": null,
"e": 3224,
"s": 3213,
"text": " Add Notes"
}
] |
time.Ticker.Stop() Function in Golang With Examples - GeeksforGeeks
|
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The NewTicker() function in Go language is used to disable a ticker. So, after calling Stop() method no further ticks will be transmitted. And it doesn’t close the channel, in order to avoid a concurrent go-routine reading from the channel from viewing an inaccurate “tick”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t *Ticker) Stop()
Here, “t” is a pointer to the Ticker. Where Ticker is used to hold a channel that supplies `ticks’ of a clock at intervals.
Return Value: It returns the output of the stated operation before calling the Stop() method because after calling it ticker is turned off.
Example:
// Golang program to illustrate the usage of// time.Ticker.Stop() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling NewTicker method Ticker := time.NewTicker(2 * time.Second) // Creating channel using make // keyword mychannel := make(chan bool) // Go function go func() { // Using for loop for { // Select statement select { // Case statement case <-mychannel: return // Case to print current time case tm := <-Ticker.C: fmt.Println("The Current time is: ", tm) } } }() // Calling Sleep() method time.Sleep(7 * time.Second) // Calling Stop() method Ticker.Stop() // Setting the value of channel mychannel <- true // Printed when the ticker is turned off fmt.Println("Ticker is turned off!")}
Output:
The Current time is: 2020-04-09 07:26:05.374436607 +0000 UTC m=+2.000213251
The Current time is: 2020-04-09 07:26:07.374442201 +0000 UTC m=+4.000218858
The Current time is: 2020-04-09 07:26:09.374511648 +0000 UTC m=+6.000288424
Ticker is turned off!
Here, at first a Ticker is created then a channel is created that transmits time. After that for loop is used in order to print the current time then Ticker.Stop() method is called and the ticker is turned off.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Interfaces in Golang
|
[
{
"code": null,
"e": 23955,
"s": 23927,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24460,
"s": 23955,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The NewTicker() function in Go language is used to disable a ticker. So, after calling Stop() method no further ticks will be transmitted. And it doesn’t close the channel, in order to avoid a concurrent go-routine reading from the channel from viewing an inaccurate “tick”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 24468,
"s": 24460,
"text": "Syntax:"
},
{
"code": null,
"e": 24493,
"s": 24468,
"text": "func (t *Ticker) Stop()\n"
},
{
"code": null,
"e": 24617,
"s": 24493,
"text": "Here, “t” is a pointer to the Ticker. Where Ticker is used to hold a channel that supplies `ticks’ of a clock at intervals."
},
{
"code": null,
"e": 24757,
"s": 24617,
"text": "Return Value: It returns the output of the stated operation before calling the Stop() method because after calling it ticker is turned off."
},
{
"code": null,
"e": 24766,
"s": 24757,
"text": "Example:"
},
{
"code": "// Golang program to illustrate the usage of// time.Ticker.Stop() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling NewTicker method Ticker := time.NewTicker(2 * time.Second) // Creating channel using make // keyword mychannel := make(chan bool) // Go function go func() { // Using for loop for { // Select statement select { // Case statement case <-mychannel: return // Case to print current time case tm := <-Ticker.C: fmt.Println(\"The Current time is: \", tm) } } }() // Calling Sleep() method time.Sleep(7 * time.Second) // Calling Stop() method Ticker.Stop() // Setting the value of channel mychannel <- true // Printed when the ticker is turned off fmt.Println(\"Ticker is turned off!\")}",
"e": 25748,
"s": 24766,
"text": null
},
{
"code": null,
"e": 25756,
"s": 25748,
"text": "Output:"
},
{
"code": null,
"e": 26010,
"s": 25756,
"text": "The Current time is: 2020-04-09 07:26:05.374436607 +0000 UTC m=+2.000213251\nThe Current time is: 2020-04-09 07:26:07.374442201 +0000 UTC m=+4.000218858\nThe Current time is: 2020-04-09 07:26:09.374511648 +0000 UTC m=+6.000288424\nTicker is turned off!\n"
},
{
"code": null,
"e": 26221,
"s": 26010,
"text": "Here, at first a Ticker is created then a channel is created that transmits time. After that for loop is used in order to print the current time then Ticker.Stop() method is called and the ticker is turned off."
},
{
"code": null,
"e": 26233,
"s": 26221,
"text": "GoLang-time"
},
{
"code": null,
"e": 26245,
"s": 26233,
"text": "Go Language"
},
{
"code": null,
"e": 26343,
"s": 26245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26352,
"s": 26343,
"text": "Comments"
},
{
"code": null,
"e": 26365,
"s": 26352,
"text": "Old Comments"
},
{
"code": null,
"e": 26416,
"s": 26365,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 26429,
"s": 26416,
"text": "Arrays in Go"
},
{
"code": null,
"e": 26462,
"s": 26429,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 26479,
"s": 26462,
"text": "Slices in Golang"
},
{
"code": null,
"e": 26491,
"s": 26479,
"text": "Golang Maps"
},
{
"code": null,
"e": 26540,
"s": 26491,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 26594,
"s": 26540,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 26616,
"s": 26594,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 26648,
"s": 26616,
"text": "How to compare times in Golang?"
}
] |
SAP ABAP - Encapsulation
|
Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
ABAP supports the properties of encapsulation and data hiding through the creation of user-defined types called classes. As discussed earlier, a class can contain private, protected and public members. By default, all items defined in a class are private.
Encapsulation actually means one attribute and method could be modified in different classes. Hence data and method can have different form and logic that can be hidden to separate class.
Let's consider encapsulation by interface. Interface is used when we need to create one method with different functionality in different classes. Here the name of the method need not be changed. The same method will have to be implemented in different class implementations.
The following program contains an Interface inter_1. We have declared attribute and a method method1. We have also defined two classes like Class1 and Class2. So we have to implement the method ‘method1’ in both of the class implementations. We have implemented the method ‘method1’ differently in different classes. In the start-ofselection, we create two objects Object1 and Object2 for two classes. Then, we call the method by different objects to get the function declared in separate classes.
Report ZEncap1.
Interface inter_1.
Data text1 Type char35.
Methods method1.
EndInterface.
CLASS Class1 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class2 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class1 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 1 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
CLASS Class2 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 2 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Object1 Type Ref To Class1,
Object2 Type Ref To Class2.
Create Object: Object1, Object2.
CALL Method: Object1→inter_1~method1,
Object2→inter_1~method1.
The above code produces the following output −
Class 1 Interface method
Class 2 Interface method
Encapsulated classes do not have a lot of dependencies on the outside world. Moreover, the interactions that they do have with external clients are controlled through a stabilized public interface. That is, an encapsulated class and its clients are loosely coupled. For the most part, classes with well-defined interfaces can be plugged into another context. When designed correctly, encapsulated classes become reusable software assets.
Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members and it also applies equally to all members.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3355,
"s": 2898,
"text": "Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user."
},
{
"code": null,
"e": 3611,
"s": 3355,
"text": "ABAP supports the properties of encapsulation and data hiding through the creation of user-defined types called classes. As discussed earlier, a class can contain private, protected and public members. By default, all items defined in a class are private."
},
{
"code": null,
"e": 3799,
"s": 3611,
"text": "Encapsulation actually means one attribute and method could be modified in different classes. Hence data and method can have different form and logic that can be hidden to separate class."
},
{
"code": null,
"e": 4074,
"s": 3799,
"text": "Let's consider encapsulation by interface. Interface is used when we need to create one method with different functionality in different classes. Here the name of the method need not be changed. The same method will have to be implemented in different class implementations."
},
{
"code": null,
"e": 4572,
"s": 4074,
"text": "The following program contains an Interface inter_1. We have declared attribute and a method method1. We have also defined two classes like Class1 and Class2. So we have to implement the method ‘method1’ in both of the class implementations. We have implemented the method ‘method1’ differently in different classes. In the start-ofselection, we create two objects Object1 and Object2 for two classes. Then, we call the method by different objects to get the function declared in separate classes."
},
{
"code": null,
"e": 5371,
"s": 4572,
"text": "Report ZEncap1. \nInterface inter_1.\n Data text1 Type char35.\n Methods method1.\nEndInterface.\n\nCLASS Class1 Definition.\n PUBLIC Section.\n Interfaces inter_1.\nENDCLASS. \n\nCLASS Class2 Definition.\n PUBLIC Section.\n Interfaces inter_1. \nENDCLASS.\n\nCLASS Class1 Implementation.\n Method inter_1~method1.\n inter_1~text1 = 'Class 1 Interface method'.\n Write / inter_1~text1.\n EndMethod. \nENDCLASS.\n \nCLASS Class2 Implementation.\n Method inter_1~method1.\n inter_1~text1 = 'Class 2 Interface method'.\n Write / inter_1~text1.\n EndMethod. \nENDCLASS.\n \nStart-Of-Selection.\n Data: Object1 Type Ref To Class1,\n Object2 Type Ref To Class2.\n\t\t\n Create Object: Object1, Object2.\n CALL Method: Object1→inter_1~method1,\n Object2→inter_1~method1. "
},
{
"code": null,
"e": 5418,
"s": 5371,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5470,
"s": 5418,
"text": "Class 1 Interface method \nClass 2 Interface method\n"
},
{
"code": null,
"e": 5908,
"s": 5470,
"text": "Encapsulated classes do not have a lot of dependencies on the outside world. Moreover, the interactions that they do have with external clients are controlled through a stabilized public interface. That is, an encapsulated class and its clients are loosely coupled. For the most part, classes with well-defined interfaces can be plugged into another context. When designed correctly, encapsulated classes become reusable software assets."
},
{
"code": null,
"e": 6169,
"s": 5908,
"text": "Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members and it also applies equally to all members."
},
{
"code": null,
"e": 6202,
"s": 6169,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6216,
"s": 6202,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 6249,
"s": 6216,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6261,
"s": 6249,
"text": " Neha Gupta"
},
{
"code": null,
"e": 6296,
"s": 6261,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6311,
"s": 6296,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6344,
"s": 6311,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6359,
"s": 6344,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6394,
"s": 6359,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6406,
"s": 6394,
"text": " Neha Malik"
},
{
"code": null,
"e": 6441,
"s": 6406,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6453,
"s": 6441,
"text": " Neha Malik"
},
{
"code": null,
"e": 6460,
"s": 6453,
"text": " Print"
},
{
"code": null,
"e": 6471,
"s": 6460,
"text": " Add Notes"
}
] |
Program to check if a body is in equilibrium or not - GeeksforGeeks
|
27 Apr, 2021
Given a 2D array a[][] where each row consists of N vector coordinates of the form (xi, yi, zi) of an applied body. If the body is in equilibrium, print “YES“. Otherwise, print “NO“.
Examples:
Input: a[][] = {{4, 1, 7}, {-2, 4, -1}, {1, -5, -3}}Output: NO
Input: a[][] = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}Output: YES
Approach: Follow the steps below to solve the problem:
Apply vector addition on all the vector coordinates.
If the result of the vector addition is (0, 0, 0), the body is in equilibrium. Therefore, print “YES“.
Otherwise, print “NO“.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <iostream>using namespace std; // Function to calculate vector additionvoid vectorAddition(int a[][3], int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium cout << "YES"; } else { // Body is not in // equilibrium cout << "NO"; }} // Driver Codeint main(){ int N = 3; int a[N][3] = { { 3, -1, 7 }, { -5, 2, -4 }, { 2, -1, -3 } }; vectorAddition(a, N); return 0;}
// Java Program to implement// the above approachimport java.util.*;class GFG{ // Function to calculate// vector additionstatic void vectorAddition(int a[][], int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium System.out.print("YES"); } else { // Body is not in // equilibrium System.out.print("NO"); }} // Driver Codepublic static void main(String[] args){ int N = 3; int a[][] = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}; vectorAddition(a, N);}} // This code is contributed by shikhasingrajput
# Python3 program to implement# the above approach # Function to calculate vector additiondef vectorAddition(a, N): # Sum1 to store sum of xi # Sum2 to store sum of yi # Sum3 to store sum of zi sum1 = 0 sum2 = 0 sum3 = 0 for i in range(N): sum1 += a[i][0] sum2 += a[i][1] sum3 += a[i][2] # If the sum1, sum2 and sum3 # are all equal to zero if (sum1 == 0 and sum2 == 0 and sum3 == 0): # Body is in # equilibrium print("YES") else: # Body is not in # equilibrium print("NO") # Driver Codeif __name__ == '__main__': N = 3 a = [ [ 3, -1, 7 ], [ -5, 2, -4 ], [ 2, -1, -3 ] ] vectorAddition(a, N) # This code is contributed by mohit kumar 29
// C# Program to implement// the above approachusing System;class GFG{ // Function to calculate// vector additionstatic void vectorAddition(int[,]a, int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i, 0]; sum2 += a[i, 1]; sum3 += a[i, 2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium Console.Write("YES"); } else { // Body is not in // equilibrium Console.Write("NO"); }} // Driver Codepublic static void Main(String[] args){ int N = 3; int[,]a = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}; vectorAddition(a, N);}} // This code is contributed by shikhasingrajput
<script> // Javascript program for the above approach // Function to calculate// vector additionfunction vectorAddition(a, N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi let sum1 = 0, sum2 = 0, sum3 = 0; for (let i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium document.write("YES"); } else { // Body is not in // equilibrium document.write("NO"); }} // Driver Code let N = 3; let a = [[3, -1, 7], [-5, 2, -4], [2, -1, -3]]; vectorAddition(a, N); </script> </script>
YES
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
shikhasingrajput
chinmoy1997pal
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
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": 25020,
"s": 24992,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 25203,
"s": 25020,
"text": "Given a 2D array a[][] where each row consists of N vector coordinates of the form (xi, yi, zi) of an applied body. If the body is in equilibrium, print “YES“. Otherwise, print “NO“."
},
{
"code": null,
"e": 25213,
"s": 25203,
"text": "Examples:"
},
{
"code": null,
"e": 25276,
"s": 25213,
"text": "Input: a[][] = {{4, 1, 7}, {-2, 4, -1}, {1, -5, -3}}Output: NO"
},
{
"code": null,
"e": 25341,
"s": 25276,
"text": "Input: a[][] = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}Output: YES"
},
{
"code": null,
"e": 25396,
"s": 25341,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25449,
"s": 25396,
"text": "Apply vector addition on all the vector coordinates."
},
{
"code": null,
"e": 25552,
"s": 25449,
"text": "If the result of the vector addition is (0, 0, 0), the body is in equilibrium. Therefore, print “YES“."
},
{
"code": null,
"e": 25575,
"s": 25552,
"text": "Otherwise, print “NO“."
},
{
"code": null,
"e": 25626,
"s": 25575,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25630,
"s": 25626,
"text": "C++"
},
{
"code": null,
"e": 25635,
"s": 25630,
"text": "Java"
},
{
"code": null,
"e": 25643,
"s": 25635,
"text": "Python3"
},
{
"code": null,
"e": 25646,
"s": 25643,
"text": "C#"
},
{
"code": null,
"e": 25657,
"s": 25646,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <iostream>using namespace std; // Function to calculate vector additionvoid vectorAddition(int a[][3], int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium cout << \"YES\"; } else { // Body is not in // equilibrium cout << \"NO\"; }} // Driver Codeint main(){ int N = 3; int a[N][3] = { { 3, -1, 7 }, { -5, 2, -4 }, { 2, -1, -3 } }; vectorAddition(a, N); return 0;}",
"e": 26511,
"s": 25657,
"text": null
},
{
"code": "// Java Program to implement// the above approachimport java.util.*;class GFG{ // Function to calculate// vector additionstatic void vectorAddition(int a[][], int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium System.out.print(\"YES\"); } else { // Body is not in // equilibrium System.out.print(\"NO\"); }} // Driver Codepublic static void main(String[] args){ int N = 3; int a[][] = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}; vectorAddition(a, N);}} // This code is contributed by shikhasingrajput",
"e": 27392,
"s": 26511,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to calculate vector additiondef vectorAddition(a, N): # Sum1 to store sum of xi # Sum2 to store sum of yi # Sum3 to store sum of zi sum1 = 0 sum2 = 0 sum3 = 0 for i in range(N): sum1 += a[i][0] sum2 += a[i][1] sum3 += a[i][2] # If the sum1, sum2 and sum3 # are all equal to zero if (sum1 == 0 and sum2 == 0 and sum3 == 0): # Body is in # equilibrium print(\"YES\") else: # Body is not in # equilibrium print(\"NO\") # Driver Codeif __name__ == '__main__': N = 3 a = [ [ 3, -1, 7 ], [ -5, 2, -4 ], [ 2, -1, -3 ] ] vectorAddition(a, N) # This code is contributed by mohit kumar 29",
"e": 28175,
"s": 27392,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;class GFG{ // Function to calculate// vector additionstatic void vectorAddition(int[,]a, int N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 0; i < N; i++) { sum1 += a[i, 0]; sum2 += a[i, 1]; sum3 += a[i, 2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium Console.Write(\"YES\"); } else { // Body is not in // equilibrium Console.Write(\"NO\"); }} // Driver Codepublic static void Main(String[] args){ int N = 3; int[,]a = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}; vectorAddition(a, N);}} // This code is contributed by shikhasingrajput",
"e": 29034,
"s": 28175,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to calculate// vector additionfunction vectorAddition(a, N){ // Sum1 to store sum of xi // Sum2 to store sum of yi // Sum3 to store sum of zi let sum1 = 0, sum2 = 0, sum3 = 0; for (let i = 0; i < N; i++) { sum1 += a[i][0]; sum2 += a[i][1]; sum3 += a[i][2]; } // If the sum1, sum2 and sum3 // are all equal to zero if (sum1 == 0 && sum2 == 0 && sum3 == 0) { // Body is in // equilibrium document.write(\"YES\"); } else { // Body is not in // equilibrium document.write(\"NO\"); }} // Driver Code let N = 3; let a = [[3, -1, 7], [-5, 2, -4], [2, -1, -3]]; vectorAddition(a, N); </script> </script>",
"e": 29776,
"s": 29034,
"text": null
},
{
"code": null,
"e": 29780,
"s": 29776,
"text": "YES"
},
{
"code": null,
"e": 29823,
"s": 29780,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29838,
"s": 29823,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29855,
"s": 29838,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 29870,
"s": 29855,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 29883,
"s": 29870,
"text": "Mathematical"
},
{
"code": null,
"e": 29902,
"s": 29883,
"text": "School Programming"
},
{
"code": null,
"e": 29915,
"s": 29902,
"text": "Mathematical"
},
{
"code": null,
"e": 30013,
"s": 29915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30055,
"s": 30013,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 30098,
"s": 30055,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30122,
"s": 30098,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30136,
"s": 30122,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30185,
"s": 30136,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30203,
"s": 30185,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30219,
"s": 30203,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30238,
"s": 30219,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30263,
"s": 30238,
"text": "Reverse a string in Java"
}
] |
How to create a div using jQuery with style tag ? - GeeksforGeeks
|
28 Apr, 2021
Creating an <div> element with a style tag using jQuery can be done in the following steps.
Steps:
Create a new <div> element.
Create an object with all the styles that we want to apply.
Choose a parent element, where to put this newly created element.
Put the created div element into the parent element.
Example 1: This example will create an <div> element and use the append() method to append the element at the end of the parent element.
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-git.js"> </script> <style> .divClass { height: 40px; width: 200px; border: 1px solid blue; color: white } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h2> <div id="parent"> This is parent div </div> <div style="height:10px;"></div> <!-- JavaScript function addText() is called to add to parent div--> <input type="button" value="Add <div> Text" onclick="addText()" /> <script> <!-- Function to add text in a div element with above styles--> function addText() { $(document).ready(function() { var object = { id: "divID", class: "divClass", css: { "color": "Red" } }; var addition = $("<div>", object); addition.html("Added text GFG"); $("#parent").append(addition); }); } </script></body> </html>
Output:
append
Example 2: This example will create an <div> element and uses the prependTo() method to append the element at the start of the parent element.
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-git.js"> </script> <style> .divClass { height: 40px; width: 200px; border: 1px solid blue; color: white } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h2> <div style="height:10px;"></div> <div id='parent'> This is parent div </div> <div style="height:10px;"></div> <input type="button" value="Prepend text div " onclick="prependDiv()" /> <script> function prependDiv() { $(document).ready(function() { var object = { id: "divID", class: "divClass", css: { "color": "Red" } }; <!--Prepend object is created before the parent div--> var prependObject = $("<div>", object); prependObject.html("Prepend text is GFG"); $(prependObject).prependTo($('#parent')); }); } </script></body> </html>
Output:
Prepend text
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
QR Code Generator using HTML, CSS and jQuery
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25456,
"s": 25364,
"text": "Creating an <div> element with a style tag using jQuery can be done in the following steps."
},
{
"code": null,
"e": 25463,
"s": 25456,
"text": "Steps:"
},
{
"code": null,
"e": 25491,
"s": 25463,
"text": "Create a new <div> element."
},
{
"code": null,
"e": 25551,
"s": 25491,
"text": "Create an object with all the styles that we want to apply."
},
{
"code": null,
"e": 25617,
"s": 25551,
"text": "Choose a parent element, where to put this newly created element."
},
{
"code": null,
"e": 25670,
"s": 25617,
"text": "Put the created div element into the parent element."
},
{
"code": null,
"e": 25807,
"s": 25670,
"text": "Example 1: This example will create an <div> element and use the append() method to append the element at the end of the parent element."
},
{
"code": null,
"e": 25812,
"s": 25807,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <style> .divClass { height: 40px; width: 200px; border: 1px solid blue; color: white } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <div id=\"parent\"> This is parent div </div> <div style=\"height:10px;\"></div> <!-- JavaScript function addText() is called to add to parent div--> <input type=\"button\" value=\"Add <div> Text\" onclick=\"addText()\" /> <script> <!-- Function to add text in a div element with above styles--> function addText() { $(document).ready(function() { var object = { id: \"divID\", class: \"divClass\", css: { \"color\": \"Red\" } }; var addition = $(\"<div>\", object); addition.html(\"Added text GFG\"); $(\"#parent\").append(addition); }); } </script></body> </html>",
"e": 26924,
"s": 25812,
"text": null
},
{
"code": null,
"e": 26932,
"s": 26924,
"text": "Output:"
},
{
"code": null,
"e": 26939,
"s": 26932,
"text": "append"
},
{
"code": null,
"e": 27082,
"s": 26939,
"text": "Example 2: This example will create an <div> element and uses the prependTo() method to append the element at the start of the parent element."
},
{
"code": null,
"e": 27087,
"s": 27082,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <style> .divClass { height: 40px; width: 200px; border: 1px solid blue; color: white } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <div style=\"height:10px;\"></div> <div id='parent'> This is parent div </div> <div style=\"height:10px;\"></div> <input type=\"button\" value=\"Prepend text div \" onclick=\"prependDiv()\" /> <script> function prependDiv() { $(document).ready(function() { var object = { id: \"divID\", class: \"divClass\", css: { \"color\": \"Red\" } }; <!--Prepend object is created before the parent div--> var prependObject = $(\"<div>\", object); prependObject.html(\"Prepend text is GFG\"); $(prependObject).prependTo($('#parent')); }); } </script></body> </html>",
"e": 28210,
"s": 27087,
"text": null
},
{
"code": null,
"e": 28218,
"s": 28210,
"text": "Output:"
},
{
"code": null,
"e": 28231,
"s": 28218,
"text": "Prepend text"
},
{
"code": null,
"e": 28246,
"s": 28231,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 28263,
"s": 28246,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 28270,
"s": 28263,
"text": "Picked"
},
{
"code": null,
"e": 28277,
"s": 28270,
"text": "JQuery"
},
{
"code": null,
"e": 28294,
"s": 28277,
"text": "Web Technologies"
},
{
"code": null,
"e": 28392,
"s": 28294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28401,
"s": 28392,
"text": "Comments"
},
{
"code": null,
"e": 28414,
"s": 28401,
"text": "Old Comments"
},
{
"code": null,
"e": 28487,
"s": 28414,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 28510,
"s": 28487,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 28551,
"s": 28510,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 28608,
"s": 28551,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 28653,
"s": 28608,
"text": "QR Code Generator using HTML, CSS and jQuery"
},
{
"code": null,
"e": 28709,
"s": 28653,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28742,
"s": 28709,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28804,
"s": 28742,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28847,
"s": 28804,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Convert a number m to n using minimum number of given operations - GeeksforGeeks
|
10 Mar, 2022
Convert a number m to n with minimum operations. The operations allowed are :
Multiply by 2, i.e., do m = 2 * mSubtract 1, i.e., do m = m – 1
Multiply by 2, i.e., do m = 2 * m
Subtract 1, i.e., do m = m – 1
Print -1 if it is not possible to convert.Examples :
Input : m = 3, n = 11
Output : 3
1st operation: *2 = 3*2 = 6
2nd operation: *2 = 6*2 = 12
3rd operation: -1 = 12-1 = 11
Input : m = 15, n = 20
Output : 6
1st operation: -1 '5' times = 15 + (-1*5) = 10
2nd operation: *2 = 10*2 = 20
Input : m = 0, n = 8
Output : -1
Using the given set of operations 'm'
cannot be converted to 'n'
Input : m = 12, n = 8
Output : 4
The idea is based on below facts. 1) If m is less than 0 and n is greater than 0, then not possible. 2) If m is greater than n, then we can reach n using subtractions only. 3) Else (m is less than n), we must do m*2 operations. Following two cases arise. ......a) If n is odd, we must do a -1 operation to reach it. ......b) If n is even, we must do a *2 operation to reach it.Algorithm:
int convert(m,n)
if (m == n)
return 0;
// not possible
if (m <= 0 && n > 0)
return -1;
// m is greater than n
if (m > n)
return m-n;
// n is odd
if (n % 2 == 1)
// perform '-1'
return 1 + convert(m, n+1);
// n is even
else
// perform '*2'
return 1 + convert(m, n/2);
Note: The list of operations so generated should be applied in reverse order. For example:
m = 3, n = 11
convert(3,11)
| --> n is odd: operation '-1'
convert(3,12)
| --> n is even: operation '*2'
convert(3,6)
| --> n is even: operation '*2'
convert(3,3)
| --> m == n
return
Therefore, the sequence of operations is '*2', '*2', '-1'.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to convert// a number m to n using minimum// number of given operations#include <bits/stdc++.h>using namespace std; // Function to find minimum// number of given operations// to convert m to nint convert(int m, int n){ if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n/2 on n) return 1 + convert(m, n / 2);} // Driver codeint main(){ int m = 3, n = 11; cout << "Minimum number of operations : " << convert(m, n); return 0;}
// Java implementation to convert// a number m to n using minimum// number of given operations class ConvertNum{ // function to find minimum // number of given operations // to convert m to n static int convert(int m, int n) { if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2); } // Driver Code public static void main (String[] args) { int m = 3, n = 11; System.out.println("Minimum number of " + "operations : " + convert(m, n)); }}
# Python implementation to convert# a number m to n using minimum# number of given operations # Function to find minimum# number of given operations# to convert m to ndef convert(m, n): if(m == n): return 0 # only way is to do # -1(m - n): times if(m > n): return m - n # not possible if(m <= 0 and n > 0): return -1 # n is greater and n is odd if(n % 2 == 1): # perform '-1' on m #(or +1 on n): return 1 + convert(m, n + 1) # n is even else: # perform '*2' on m #(or n/2 on n): return 1 + convert(m, n / 2) # Driver codem = 3n = 11print("Minimum number of operations :", convert(m, n)) # This code is contributed by# Sanjit_Prasad
// C# implementation to convert// a number m to n using minimum// number of given operationsusing System; class GFG{ // function to find minimum // number of given operations // to convert m to n static int convert(int m, int n) { if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2); } // Driver code public static void Main () { int m = 3, n = 11; Console.Write("Minimum number of " + "operations : " + convert(m, n)); }} // This code is contributed by nitin mittal
<?php// PHP implementation to convert// a number m to n using minimum// number of given operations // Function to find minimum// number of given operations// to convert m to nfunction convert($m, $n){ if ($m == $n) return 0; // only way is to do // -1 (m - n) times if ($m > $n) return $m - $n; // not possible if ($m <= 0 && $n > 0) return -1; // n is greater and n is odd if ($n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert($m, $n + 1); // n is even else // perform '*2' on m // (or n/2 on n) return 1 + convert($m, $n / 2);} // Driver code{ $m = 3; $n = 11; echo "Minimum number of ". "operations : ", convert($m, $n); return 0;} // This code is contributed// by nitin mittal.?>
<script>// javascript implementation to convert// a number m to n using minimum// number of given operations // function to find minimum// number of given operations// to convert m to nfunction convert(m , n){ if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2);} // Driver Codevar m = 3, n = 11;document.write("Minimum number of " + "operations : " + convert(m, n)); // This code is contributed by Princi Singh</script>
Output :
Minimum number of operations : 3
References : http://tech.queryhome.com/112705/convert-number-with-minimum-operations-operations-allowedThis article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
aeros15
Sanjit_Prasad
princi singh
sumitgumber28
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 25390,
"s": 25362,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 25470,
"s": 25390,
"text": "Convert a number m to n with minimum operations. The operations allowed are : "
},
{
"code": null,
"e": 25534,
"s": 25470,
"text": "Multiply by 2, i.e., do m = 2 * mSubtract 1, i.e., do m = m – 1"
},
{
"code": null,
"e": 25568,
"s": 25534,
"text": "Multiply by 2, i.e., do m = 2 * m"
},
{
"code": null,
"e": 25599,
"s": 25568,
"text": "Subtract 1, i.e., do m = m – 1"
},
{
"code": null,
"e": 25654,
"s": 25599,
"text": "Print -1 if it is not possible to convert.Examples : "
},
{
"code": null,
"e": 26020,
"s": 25654,
"text": "Input : m = 3, n = 11\nOutput : 3\n1st operation: *2 = 3*2 = 6\n2nd operation: *2 = 6*2 = 12\n3rd operation: -1 = 12-1 = 11\n\nInput : m = 15, n = 20\nOutput : 6\n1st operation: -1 '5' times = 15 + (-1*5) = 10\n2nd operation: *2 = 10*2 = 20\n\nInput : m = 0, n = 8\nOutput : -1\nUsing the given set of operations 'm' \ncannot be converted to 'n'\n\nInput : m = 12, n = 8\nOutput : 4"
},
{
"code": null,
"e": 26412,
"s": 26022,
"text": "The idea is based on below facts. 1) If m is less than 0 and n is greater than 0, then not possible. 2) If m is greater than n, then we can reach n using subtractions only. 3) Else (m is less than n), we must do m*2 operations. Following two cases arise. ......a) If n is odd, we must do a -1 operation to reach it. ......b) If n is even, we must do a *2 operation to reach it.Algorithm: "
},
{
"code": null,
"e": 26771,
"s": 26412,
"text": "int convert(m,n)\n if (m == n) \n return 0;\n \n // not possible\n if (m <= 0 && n > 0) \n return -1;\n\n // m is greater than n\n if (m > n) \n return m-n;\n\n // n is odd\n if (n % 2 == 1) \n // perform '-1' \n return 1 + convert(m, n+1);\n \n // n is even\n else \n // perform '*2' \n return 1 + convert(m, n/2);"
},
{
"code": null,
"e": 26864,
"s": 26771,
"text": "Note: The list of operations so generated should be applied in reverse order. For example: "
},
{
"code": null,
"e": 27306,
"s": 26864,
"text": "m = 3, n = 11\n convert(3,11)\n | --> n is odd: operation '-1'\n convert(3,12) \n | --> n is even: operation '*2' \n convert(3,6)\n | --> n is even: operation '*2' \n convert(3,3) \n | --> m == n\n return \nTherefore, the sequence of operations is '*2', '*2', '-1'."
},
{
"code": null,
"e": 27312,
"s": 27308,
"text": "C++"
},
{
"code": null,
"e": 27317,
"s": 27312,
"text": "Java"
},
{
"code": null,
"e": 27325,
"s": 27317,
"text": "Python3"
},
{
"code": null,
"e": 27328,
"s": 27325,
"text": "C#"
},
{
"code": null,
"e": 27332,
"s": 27328,
"text": "PHP"
},
{
"code": null,
"e": 27343,
"s": 27332,
"text": "Javascript"
},
{
"code": "// C++ implementation to convert// a number m to n using minimum// number of given operations#include <bits/stdc++.h>using namespace std; // Function to find minimum// number of given operations// to convert m to nint convert(int m, int n){ if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n/2 on n) return 1 + convert(m, n / 2);} // Driver codeint main(){ int m = 3, n = 11; cout << \"Minimum number of operations : \" << convert(m, n); return 0;}",
"e": 28150,
"s": 27343,
"text": null
},
{
"code": "// Java implementation to convert// a number m to n using minimum// number of given operations class ConvertNum{ // function to find minimum // number of given operations // to convert m to n static int convert(int m, int n) { if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2); } // Driver Code public static void main (String[] args) { int m = 3, n = 11; System.out.println(\"Minimum number of \" + \"operations : \" + convert(m, n)); }}",
"e": 29177,
"s": 28150,
"text": null
},
{
"code": "# Python implementation to convert# a number m to n using minimum# number of given operations # Function to find minimum# number of given operations# to convert m to ndef convert(m, n): if(m == n): return 0 # only way is to do # -1(m - n): times if(m > n): return m - n # not possible if(m <= 0 and n > 0): return -1 # n is greater and n is odd if(n % 2 == 1): # perform '-1' on m #(or +1 on n): return 1 + convert(m, n + 1) # n is even else: # perform '*2' on m #(or n/2 on n): return 1 + convert(m, n / 2) # Driver codem = 3n = 11print(\"Minimum number of operations :\", convert(m, n)) # This code is contributed by# Sanjit_Prasad",
"e": 29942,
"s": 29177,
"text": null
},
{
"code": "// C# implementation to convert// a number m to n using minimum// number of given operationsusing System; class GFG{ // function to find minimum // number of given operations // to convert m to n static int convert(int m, int n) { if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2); } // Driver code public static void Main () { int m = 3, n = 11; Console.Write(\"Minimum number of \" + \"operations : \" + convert(m, n)); }} // This code is contributed by nitin mittal",
"e": 30989,
"s": 29942,
"text": null
},
{
"code": "<?php// PHP implementation to convert// a number m to n using minimum// number of given operations // Function to find minimum// number of given operations// to convert m to nfunction convert($m, $n){ if ($m == $n) return 0; // only way is to do // -1 (m - n) times if ($m > $n) return $m - $n; // not possible if ($m <= 0 && $n > 0) return -1; // n is greater and n is odd if ($n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert($m, $n + 1); // n is even else // perform '*2' on m // (or n/2 on n) return 1 + convert($m, $n / 2);} // Driver code{ $m = 3; $n = 11; echo \"Minimum number of \". \"operations : \", convert($m, $n); return 0;} // This code is contributed// by nitin mittal.?>",
"e": 31829,
"s": 30989,
"text": null
},
{
"code": "<script>// javascript implementation to convert// a number m to n using minimum// number of given operations // function to find minimum// number of given operations// to convert m to nfunction convert(m , n){ if (m == n) return 0; // only way is to do // -1 (m - n) times if (m > n) return m - n; // not possible if (m <= 0 && n > 0) return -1; // n is greater and n is odd if (n % 2 == 1) // perform '-1' on m // (or +1 on n) return 1 + convert(m, n + 1); // n is even else // perform '*2' on m // (or n / 2 on n) return 1 + convert(m, n / 2);} // Driver Codevar m = 3, n = 11;document.write(\"Minimum number of \" + \"operations : \" + convert(m, n)); // This code is contributed by Princi Singh</script>",
"e": 32679,
"s": 31829,
"text": null
},
{
"code": null,
"e": 32690,
"s": 32679,
"text": "Output : "
},
{
"code": null,
"e": 32723,
"s": 32690,
"text": "Minimum number of operations : 3"
},
{
"code": null,
"e": 33248,
"s": 32723,
"text": "References : http://tech.queryhome.com/112705/convert-number-with-minimum-operations-operations-allowedThis article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33261,
"s": 33248,
"text": "nitin mittal"
},
{
"code": null,
"e": 33269,
"s": 33261,
"text": "aeros15"
},
{
"code": null,
"e": 33283,
"s": 33269,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 33296,
"s": 33283,
"text": "princi singh"
},
{
"code": null,
"e": 33310,
"s": 33296,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33323,
"s": 33310,
"text": "Mathematical"
},
{
"code": null,
"e": 33336,
"s": 33323,
"text": "Mathematical"
},
{
"code": null,
"e": 33434,
"s": 33336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33458,
"s": 33434,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33500,
"s": 33458,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33543,
"s": 33500,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33557,
"s": 33543,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33606,
"s": 33557,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33628,
"s": 33606,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 33669,
"s": 33628,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 33703,
"s": 33669,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33724,
"s": 33703,
"text": "Operators in C / C++"
}
] |
Write a program in Python to merge two dataframes based on matching data in a column
|
Assume, you have two dataframe,
first dataframe is
id country
0 1 India
1 2 UK
2 3 US
3 4 China
second dataframe is
id City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu
And the result for merging based on same column is,
Merging data based on same column - id
id country City
0 1 India Chennai
1 4 China Chengdu
To solve this, we will follow the steps given below −
Define a two dataframes
Define a two dataframes
Merge two dataframes based on the same column id is defined below,
Merge two dataframes based on the same column id is defined below,
pd.merge(first_df,second_df,how='inner',on='id')
Let us see the following implementation to get a better understanding −
import pandas as pd
import numpy as np
first_df = pd.DataFrame({'id':[1,2,3,4], 'country':['India','UK','US','China']
})
print("first dataframe is\n", first_df)
second_df = pd.DataFrame({'id':[1,11,22,4], 'City' : ['Chennai','Cambridge','Chicago','Chengdu']
})
print("second dataframe is\n", second_df)
print("Merging data based on same column - id")
print(pd.merge(first_df,second_df,how='inner',on='id'))
first dataframe is
id country
0 1 India
1 2 UK
2 3 US
3 4 China
second dataframe is
id City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu
Merging data based on same column - id
id country City
0 1 India Chennai
1 4 China Chengdu
|
[
{
"code": null,
"e": 1094,
"s": 1062,
"text": "Assume, you have two dataframe,"
},
{
"code": null,
"e": 1242,
"s": 1094,
"text": "first dataframe is\n id country\n0 1 India\n1 2 UK\n2 3 US\n3 4 China\n\nsecond dataframe is\n\n id City\n0 1 Chennai\n1 11 Cambridge\n2 22 Chicago\n3 4 Chengdu"
},
{
"code": null,
"e": 1294,
"s": 1242,
"text": "And the result for merging based on same column is,"
},
{
"code": null,
"e": 1404,
"s": 1294,
"text": "Merging data based on same column - id\n id country City\n0 1 India Chennai\n1 4 China Chengdu"
},
{
"code": null,
"e": 1458,
"s": 1404,
"text": "To solve this, we will follow the steps given below −"
},
{
"code": null,
"e": 1482,
"s": 1458,
"text": "Define a two dataframes"
},
{
"code": null,
"e": 1506,
"s": 1482,
"text": "Define a two dataframes"
},
{
"code": null,
"e": 1573,
"s": 1506,
"text": "Merge two dataframes based on the same column id is defined below,"
},
{
"code": null,
"e": 1640,
"s": 1573,
"text": "Merge two dataframes based on the same column id is defined below,"
},
{
"code": null,
"e": 1689,
"s": 1640,
"text": "pd.merge(first_df,second_df,how='inner',on='id')"
},
{
"code": null,
"e": 1761,
"s": 1689,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2216,
"s": 1761,
"text": "import pandas as pd\nimport numpy as np\nfirst_df = pd.DataFrame({'id':[1,2,3,4], 'country':['India','UK','US','China']\n })\nprint(\"first dataframe is\\n\", first_df)\nsecond_df = pd.DataFrame({'id':[1,11,22,4], 'City' : ['Chennai','Cambridge','Chicago','Chengdu']\n })\nprint(\"second dataframe is\\n\", second_df)\nprint(\"Merging data based on same column - id\")\nprint(pd.merge(first_df,second_df,how='inner',on='id'))"
},
{
"code": null,
"e": 2458,
"s": 2216,
"text": "first dataframe is\n id country\n0 1 India\n1 2 UK\n2 3 US\n3 4 China\n\nsecond dataframe is\n id City\n0 1 Chennai\n1 11 Cambridge\n2 22 Chicago\n3 4 Chengdu\n\nMerging data based on same column - id\n id country City\n0 1 India Chennai\n1 4 China Chengdu"
}
] |
Implicit Join vs Explicit Join in SQL - GeeksforGeeks
|
28 Oct, 2021
JOIN clause is used to combine rows from two or more tables, based on a relation between them. There are two different syntax forms to perform JOIN operation:
Explicit join
Implicit join
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Step 3: Creating the Tables
Use the below SQL statement to create a table called student:
CREATE TABLE student(
ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(25),
AGE INT);
Use the below SQL statement to create a table called course:
CREATE TABLE course(
COURSE_ID INT,
ROLL_NO INT);
Step 4: Adding Data to the Tables
Use the below SQL statement to add the data to the student table:
INSERT INTO student
VALUES
(1, 'Anjali', 20),
(2, 'Rachna', 18),
(3, 'Shubham', 21),
(4, 'Harsh', 25),
(5, 'Shivam', 18),
(6, 'Harshit', 20);
Use the below SQL statement to add the data to the course table:
INSERT INTO course
VALUES
(1, 1),
(2, 2),
(2, 3),
(5, 4),
(3, 5);
Step 5: Student Table
Use the below SQL statement to view the content of the student table:
SELECT * FROM student;
Course Table:
Use the below SQL statement to view the content of the course table:
SELECT * FROM course;
Step 6: Explicit Join
This notation uses the ON keyword to specify the predicates for Join and the JOIN keyword to specify the tables to join. Join can be of any type i.e. INNER JOIN, LEFT JOIN, RIGHT JOIN, or FULL JOIN. It is easier to understand and less prone to errors.
Syntax:
SELECT column_names
FROM table1
JOIN table2
ON table1.column_name = table2.column_name
The following query will show the course id, names, and age of students enrolled in different courses by using explicit join notation.
Query:
SELECT COURSE_ID, NAME, AGE
FROM student
JOIN course
ON student.ROLL_NO = course.ROLL_NO;
Output:
Step 7: Implicit Join
This notation simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them and WHERE clause to apply to join predicates. It performs a CROSS JOIN. It is difficult to understand and more prone to errors.
Syntax:
SELECT column_names
FROM table1, table2
WHERE table1.column_name = table2.column_name
The following query will show the course id, names, and age of students enrolled in different courses by using implicit join notation.
Query:
SELECT COURSE_ID, NAME, AGE
FROM student, course
WHERE student.ROLL_NO = course.ROLL_NO;
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
|
[
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 24036,
"s": 23877,
"text": "JOIN clause is used to combine rows from two or more tables, based on a relation between them. There are two different syntax forms to perform JOIN operation:"
},
{
"code": null,
"e": 24050,
"s": 24036,
"text": "Explicit join"
},
{
"code": null,
"e": 24064,
"s": 24050,
"text": "Implicit join"
},
{
"code": null,
"e": 24094,
"s": 24064,
"text": "Step 1: Creating the Database"
},
{
"code": null,
"e": 24157,
"s": 24094,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 24180,
"s": 24157,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 24207,
"s": 24180,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 24276,
"s": 24207,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 24287,
"s": 24276,
"text": "USE geeks;"
},
{
"code": null,
"e": 24315,
"s": 24287,
"text": "Step 3: Creating the Tables"
},
{
"code": null,
"e": 24377,
"s": 24315,
"text": "Use the below SQL statement to create a table called student:"
},
{
"code": null,
"e": 24458,
"s": 24377,
"text": "CREATE TABLE student(\n ROLL_NO INT PRIMARY KEY,\n NAME VARCHAR(25),\n AGE INT);"
},
{
"code": null,
"e": 24519,
"s": 24458,
"text": "Use the below SQL statement to create a table called course:"
},
{
"code": null,
"e": 24573,
"s": 24519,
"text": "CREATE TABLE course(\n COURSE_ID INT,\n ROLL_NO INT);"
},
{
"code": null,
"e": 24607,
"s": 24573,
"text": "Step 4: Adding Data to the Tables"
},
{
"code": null,
"e": 24673,
"s": 24607,
"text": "Use the below SQL statement to add the data to the student table:"
},
{
"code": null,
"e": 24822,
"s": 24673,
"text": "INSERT INTO student \nVALUES \n(1, 'Anjali', 20), \n(2, 'Rachna', 18), \n(3, 'Shubham', 21), \n(4, 'Harsh', 25), \n(5, 'Shivam', 18), \n(6, 'Harshit', 20);"
},
{
"code": null,
"e": 24887,
"s": 24822,
"text": "Use the below SQL statement to add the data to the course table:"
},
{
"code": null,
"e": 24955,
"s": 24887,
"text": "INSERT INTO course \nVALUES \n(1, 1),\n(2, 2),\n(2, 3),\n(5, 4),\n(3, 5);"
},
{
"code": null,
"e": 24977,
"s": 24955,
"text": "Step 5: Student Table"
},
{
"code": null,
"e": 25047,
"s": 24977,
"text": "Use the below SQL statement to view the content of the student table:"
},
{
"code": null,
"e": 25070,
"s": 25047,
"text": "SELECT * FROM student;"
},
{
"code": null,
"e": 25084,
"s": 25070,
"text": "Course Table:"
},
{
"code": null,
"e": 25153,
"s": 25084,
"text": "Use the below SQL statement to view the content of the course table:"
},
{
"code": null,
"e": 25175,
"s": 25153,
"text": "SELECT * FROM course;"
},
{
"code": null,
"e": 25198,
"s": 25175,
"text": "Step 6: Explicit Join "
},
{
"code": null,
"e": 25450,
"s": 25198,
"text": "This notation uses the ON keyword to specify the predicates for Join and the JOIN keyword to specify the tables to join. Join can be of any type i.e. INNER JOIN, LEFT JOIN, RIGHT JOIN, or FULL JOIN. It is easier to understand and less prone to errors."
},
{
"code": null,
"e": 25458,
"s": 25450,
"text": "Syntax:"
},
{
"code": null,
"e": 25545,
"s": 25458,
"text": "SELECT column_names\nFROM table1\nJOIN table2\nON table1.column_name = table2.column_name"
},
{
"code": null,
"e": 25680,
"s": 25545,
"text": "The following query will show the course id, names, and age of students enrolled in different courses by using explicit join notation."
},
{
"code": null,
"e": 25687,
"s": 25680,
"text": "Query:"
},
{
"code": null,
"e": 25778,
"s": 25687,
"text": "SELECT COURSE_ID, NAME, AGE \nFROM student\nJOIN course\nON student.ROLL_NO = course.ROLL_NO;"
},
{
"code": null,
"e": 25786,
"s": 25778,
"text": "Output:"
},
{
"code": null,
"e": 25809,
"s": 25786,
"text": "Step 7: Implicit Join "
},
{
"code": null,
"e": 26063,
"s": 25809,
"text": "This notation simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them and WHERE clause to apply to join predicates. It performs a CROSS JOIN. It is difficult to understand and more prone to errors."
},
{
"code": null,
"e": 26071,
"s": 26063,
"text": "Syntax:"
},
{
"code": null,
"e": 26157,
"s": 26071,
"text": "SELECT column_names\nFROM table1, table2\nWHERE table1.column_name = table2.column_name"
},
{
"code": null,
"e": 26292,
"s": 26157,
"text": "The following query will show the course id, names, and age of students enrolled in different courses by using implicit join notation."
},
{
"code": null,
"e": 26299,
"s": 26292,
"text": "Query:"
},
{
"code": null,
"e": 26389,
"s": 26299,
"text": "SELECT COURSE_ID, NAME, AGE \nFROM student, course\nWHERE student.ROLL_NO = course.ROLL_NO;"
},
{
"code": null,
"e": 26397,
"s": 26389,
"text": "Output:"
},
{
"code": null,
"e": 26404,
"s": 26397,
"text": "Picked"
},
{
"code": null,
"e": 26415,
"s": 26404,
"text": "SQL-Server"
},
{
"code": null,
"e": 26419,
"s": 26415,
"text": "SQL"
},
{
"code": null,
"e": 26423,
"s": 26419,
"text": "SQL"
},
{
"code": null,
"e": 26521,
"s": 26423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26530,
"s": 26521,
"text": "Comments"
},
{
"code": null,
"e": 26543,
"s": 26530,
"text": "Old Comments"
},
{
"code": null,
"e": 26609,
"s": 26543,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26641,
"s": 26609,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26719,
"s": 26641,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26736,
"s": 26719,
"text": "SQL using Python"
},
{
"code": null,
"e": 26751,
"s": 26736,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26817,
"s": 26751,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26853,
"s": 26817,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26888,
"s": 26853,
"text": "SQL Query to Delete Duplicate Rows"
},
{
"code": null,
"e": 26919,
"s": 26888,
"text": "SQL Query to Compare Two Dates"
}
] |
What happens when we try to add a duplicate key into a HashMap object in java?
|
The HashMap is a class that implements the Map interface. It is based on the Hash table. It allows null values and null keys.
You can store key-value pairs in the HashMap object. Once you do so you can retrieve the values of the respective keys but, the values we use for keys should be unique
The put command associates the value with the specified key. i.e. if we add a key-value pair where the key exists already, this method replaces the existing value of the key with the new value,
Live Demo
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DuplicatesInHashMap {
public static void main(String args[]) {
HashMap<String, Long> map = new HashMap<String, Long>();
map.put("Krishna", 9000123456L);
map.put("Rama", 9000234567L);
map.put("Sita", 9000345678L);
map.put("Bhima", 9000456789L);
map.put("Yousuf ", 9000456789L);
System.out.println("Values Stored . . . . . .");
//Retrieving the values of a Hash map
Iterator it1 = map.entrySet().iterator();
System.out.println("Contents of the hashMap are: ");
while(it1.hasNext()){
Map.Entry <String, Long> ele = (Map.Entry) it1.next();
System.out.print(ele.getKey()+" : ");
System.out.print(ele.getValue());
System.out.println();
}
map.put("Bhima", 0000000000L);
map.put("Rama", 0000000000L);
//Retrieving the values of a Hash map
Iterator it2 = map.entrySet().iterator();
System.out.println("Contents of the hashMap after inserting new key-value pair: ");
while(it2.hasNext()){
Map.Entry <String, Long> ele = (Map.Entry) it2.next();
System.out.print(ele.getKey()+" : ");
System.out.print(ele.getValue());
System.out.println();
}
}
}
Values Stored . . . . . .
Contents of the hashMap are:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 9000234567
Bhima : 9000456789
Contents of the hashMap after inserting new key-value pair:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 0
Bhima : 0
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "The HashMap is a class that implements the Map interface. It is based on the Hash table. It allows null values and null keys."
},
{
"code": null,
"e": 1356,
"s": 1188,
"text": "You can store key-value pairs in the HashMap object. Once you do so you can retrieve the values of the respective keys but, the values we use for keys should be unique"
},
{
"code": null,
"e": 1550,
"s": 1356,
"text": "The put command associates the value with the specified key. i.e. if we add a key-value pair where the key exists already, this method replaces the existing value of the key with the new value,"
},
{
"code": null,
"e": 1561,
"s": 1550,
"text": " Live Demo"
},
{
"code": null,
"e": 2875,
"s": 1561,
"text": "import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\npublic class DuplicatesInHashMap {\n public static void main(String args[]) {\n HashMap<String, Long> map = new HashMap<String, Long>();\n map.put(\"Krishna\", 9000123456L);\n map.put(\"Rama\", 9000234567L);\n map.put(\"Sita\", 9000345678L);\n map.put(\"Bhima\", 9000456789L);\n map.put(\"Yousuf \", 9000456789L);\n System.out.println(\"Values Stored . . . . . .\");\n //Retrieving the values of a Hash map\n Iterator it1 = map.entrySet().iterator();\n System.out.println(\"Contents of the hashMap are: \");\n while(it1.hasNext()){\n Map.Entry <String, Long> ele = (Map.Entry) it1.next();\n System.out.print(ele.getKey()+\" : \");\n System.out.print(ele.getValue());\n System.out.println();\n }\n map.put(\"Bhima\", 0000000000L);\n map.put(\"Rama\", 0000000000L);\n //Retrieving the values of a Hash map\n Iterator it2 = map.entrySet().iterator();\n System.out.println(\"Contents of the hashMap after inserting new key-value pair: \");\n while(it2.hasNext()){\n Map.Entry <String, Long> ele = (Map.Entry) it2.next();\n System.out.print(ele.getKey()+\" : \");\n System.out.print(ele.getValue());\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 3164,
"s": 2875,
"text": "Values Stored . . . . . .\nContents of the hashMap are:\nYousuf : 9000456789\nKrishna : 9000123456\nSita : 9000345678\nRama : 9000234567\nBhima : 9000456789\nContents of the hashMap after inserting new key-value pair:\nYousuf : 9000456789\nKrishna : 9000123456\nSita : 9000345678\nRama : 0\nBhima : 0"
}
] |
How to Copy NTFS permissions using PowerShell?
|
To change, add or remove security permissions on the files or folder using PowerShell you can use the Set-Acl command. The best way to set the permission is to copy the permissions from another file or folder if you need the same permissions on the destination path.
For example, I want the same folder permissions of the source C:\Shared\ to the destination folder path c:\shared1 path. You can use any destination path, it could be the remote shared UNC path.
See the difference in the above security permissions, the Shared named folder has one additional permission assigned (LABDOMAIN\Delta). We will copy the permission from one folder to another using Get-ACL of the source and Set-ACL to the destination path using the pipeline.
Get-ACL C:\Shared | Set-Acl C:\Shared1
Once the above operation is done, you can check the permission on the destination path.
You can see the delta user permission is added and other permissions are also copied. If the user already exists at the source and destination location then destination user permissions will be overwritten with the source user permission.
You can also store the Get-ACL output of the source object to the variable and assign it to the Set-ACL of the destination object. Set-ACL uses -AclObject parameter to take input of the permissions.
$perm = Get-Acl C:\Shared Set-Acl C:\Shared1 -AclObject $perm
If you need to apply permission on the multiple folders or the files or the subfolders then you can use Get-ChildItem to retrieve files and folders and use the Set-ACL command as shown above.
For example, we have reference folder C:\shared permission to apply on the destination objects. First, we will copy permissions using Get-Acl command.
$perm = Get-Acl C:\Shared
Second, we will retrieve the files/folders using Get-ChildItem, and then we will use the Set-ACL command after the pipeline.
Get-ChildItem C:\Temp -Recurse | Set-Acl -AclObject $perm
Before you set permissions on the multiple files and folders, it is always recommended that you use the -WhatIf parameter to know on which file or folder permissions are being applied.
PS C:\> Get-ChildItem C:\Temp -Recurse | Set-Acl -AclObject $perm -WhatIf
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\Scripts".
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\vcredist_x64.exe".
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\W2K12-KB3191565-x64.msu".
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\WindowsSensor.exe".
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\WindowsSensor_7E3A9735FA064249A7005E9BE8CDD
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\Scripts\MyModules".
What if: Performing the operation "Set-Acl" on target "Microsoft.PowerShell.Core\FileSystem::C:\Temp\Scripts\MyModules\MyModules.psm1".
|
[
{
"code": null,
"e": 1329,
"s": 1062,
"text": "To change, add or remove security permissions on the files or folder using PowerShell you can use the Set-Acl command. The best way to set the permission is to copy the permissions from another file or folder if you need the same permissions on the destination path."
},
{
"code": null,
"e": 1524,
"s": 1329,
"text": "For example, I want the same folder permissions of the source C:\\Shared\\ to the destination folder path c:\\shared1 path. You can use any destination path, it could be the remote shared UNC path."
},
{
"code": null,
"e": 1799,
"s": 1524,
"text": "See the difference in the above security permissions, the Shared named folder has one additional permission assigned (LABDOMAIN\\Delta). We will copy the permission from one folder to another using Get-ACL of the source and Set-ACL to the destination path using the pipeline."
},
{
"code": null,
"e": 1838,
"s": 1799,
"text": "Get-ACL C:\\Shared | Set-Acl C:\\Shared1"
},
{
"code": null,
"e": 1926,
"s": 1838,
"text": "Once the above operation is done, you can check the permission on the destination path."
},
{
"code": null,
"e": 2165,
"s": 1926,
"text": "You can see the delta user permission is added and other permissions are also copied. If the user already exists at the source and destination location then destination user permissions will be overwritten with the source user permission."
},
{
"code": null,
"e": 2364,
"s": 2165,
"text": "You can also store the Get-ACL output of the source object to the variable and assign it to the Set-ACL of the destination object. Set-ACL uses -AclObject parameter to take input of the permissions."
},
{
"code": null,
"e": 2426,
"s": 2364,
"text": "$perm = Get-Acl C:\\Shared Set-Acl C:\\Shared1 -AclObject $perm"
},
{
"code": null,
"e": 2618,
"s": 2426,
"text": "If you need to apply permission on the multiple folders or the files or the subfolders then you can use Get-ChildItem to retrieve files and folders and use the Set-ACL command as shown above."
},
{
"code": null,
"e": 2769,
"s": 2618,
"text": "For example, we have reference folder C:\\shared permission to apply on the destination objects. First, we will copy permissions using Get-Acl command."
},
{
"code": null,
"e": 2795,
"s": 2769,
"text": "$perm = Get-Acl C:\\Shared"
},
{
"code": null,
"e": 2920,
"s": 2795,
"text": "Second, we will retrieve the files/folders using Get-ChildItem, and then we will use the Set-ACL command after the pipeline."
},
{
"code": null,
"e": 2978,
"s": 2920,
"text": "Get-ChildItem C:\\Temp -Recurse | Set-Acl -AclObject $perm"
},
{
"code": null,
"e": 3163,
"s": 2978,
"text": "Before you set permissions on the multiple files and folders, it is always recommended that you use the -WhatIf parameter to know on which file or folder permissions are being applied."
},
{
"code": null,
"e": 4118,
"s": 3163,
"text": "PS C:\\> Get-ChildItem C:\\Temp -Recurse | Set-Acl -AclObject $perm -WhatIf\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\Scripts\".\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\vcredist_x64.exe\".\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\W2K12-KB3191565-x64.msu\".\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\WindowsSensor.exe\".\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\WindowsSensor_7E3A9735FA064249A7005E9BE8CDD\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\Scripts\\MyModules\".\nWhat if: Performing the operation \"Set-Acl\" on target \"Microsoft.PowerShell.Core\\FileSystem::C:\\Temp\\Scripts\\MyModules\\MyModules.psm1\"."
}
] |
K-Means Clustering. An overview | by Carter Bouley | Towards Data Science
|
Most applications of machine learning today are based on supervised learning. However the large majority of data is unlabelled: We have inputs X, but no label Y. Computer scientist Yann LeCunn famously said
‘If intelligence was a cake, unsupervised learning would be the cake, supervised learning would be the icing, and reinforcement learning would be the cherry on top’.
In other words, there is a huge potential in unsupervised learning.
One form or unsupervised learning is grouping similar instances together in clusters. Clustering is a great tool for data analysis, customer segmentation, recommendation systems, search engines, semi-supervised learning, dimensionality reduction and more.
If you wander around a park on your one lockdown walk a day, you may stumble upon a tree you have never seen before. If you look around and notice a few more, which are not identical but are similar enough looking that you know they belong to the same genus. You may need an arborist to tell you which species it is, but you don’t need the expert to just group your trees into similar looking groups. This is the essence of clustering: the task of identifying similar instances, and assigning them into clusters, or groups of similar instances.
One of the most commonly used clustering techniques is K-means. The K-means algorithm was proposed by Stuart Lloyd and Bell Labs in 1957 as a technique for pulse-code modulation, but only published outside the company in 1982. Edward Forgy published virtually the same algorithm in 1965 so it is referred to as Lloyd-Forgy. The following generates our data which we will cluster:
from sklearn.datasets import make_blobsblob_centers = np.array([[ 0.2, 2.3],[-1.5 , 2.3],[-2.8, 1.8],[-2.8, 2.8],[-2.8, 1.3]])blob_std = np.array([0.4, 0.3, 0.1, 0.1, 0.1])X, y = make_blobs(n_samples=2000, centers=blob_centers,cluster_std=blob_std, random_state=7)plt.figure(figsize=(8, 4))plot_clusters(X)save_fig("blobs_plot")plt.show()
K-Means is very efficient at clustering data like the set above, often in very few iterations. It will try to find the centre of each cluster, and assign each instance to the closes cluster. Let’s train a K-Means clutterer:
from sklearn.cluster import KMeansk = 5kmeans = KMeans(n_clusters = k)y_pred = kmeans.fit_predict(X)
Each instance is assigned to one of the five clusters. It receives a label as the index of the cluster it gets assigned to.
We can see these labels:
y_predarray([4, 0, 1, ..., 2, 1, 0], dtype=int32)y_pred is kmeans.labels_True
We can also see the five centroids (cluster centres) that the algorithm found:
kmeans.cluster_centers_array([[ 0.20876306, 2.25551336], [-2.80580621, 1.80056812], [-1.46046922, 2.30278886], [-2.79290307, 2.79641063], [-1.99213367, 1.3131094 ]])
We can easily do this for new data too, by seeing which centroid any new data point is closest to. We can also visualise the decision boundaries, and each centroid is represented by X.
Initially, centroids are placed randomly, instances labelled, and the centroids are updated. This process iterates until the centroids stop moving, and the clusters have been defined.
Accelerated K-Means is the default for Sklearn. it considerably accelerates this algorithm by keeping track of the lower and upper bounds for the distances between instances and centroids. You can force Sklearn to use the original algorithm, although its unlikely to be needed.
Instead of using the full dataset at each iteration, the algorithm is capable of using mini-batches, moving the centroid slightly at each iteration. This increases the speed of the algorithm by a factor of 3–4 typically. Especially important, it makes it possible to cluster huge datasets that do not fit in memory. One limitation is that its inertia is usually slightly worse, especially as clusters increase, however with many clusters the speed is much faster using mini-batch.
In this dataset we can see that there are clearly 5 clusters we want to segment from each other. However that is not always the case, and often our data isn’t as obviously segmented as this. Our result can be quite poor if we don’t take precautions to figure out the optimal number of clusters:
The first thought is to choose the k which minimises inertia, however we cannot do that as inertia will always decrease with a higher k. Indeed, the more clusters there are, the closer each instance will be to its closest centroid, and therefore the lower the inertia will be. As we can see with a k=8, we are splitting clusters for no good reason.
Inertia drops very quickly up to 5, but then it decreases very slowly afterwards. Any k lower than 5and the gain would be dramatic, and any higher and we are not gaining much more information. This is a rather rough, subjective way of assigning k, however it generally works pretty well. When doing this it allows us to take context of a specific needs of a business problem too.
However, in this case we could see that there were 5 clusters we wanted to segment. 4 clusters may be adequate but we should investigate the difference between k=4 and k=5
Another, more precise approach is to use silhouette score for each instance and plot them for different numbers of clusters, however it is more computationally intensive, it will give us a more clear optimal k:
from sklearn.metrics import silhouette_scoresilhouette_score(X, kmeans.labels_)silhouette_scores = [silhouette_score(X, model.labels_) for model in kmeans_per_k[1:]]
As we can see, using silhouette score for each level of k, it is far more obvious which k is optimal.
Even more informative is plotting every instances silhouette coefficient, sorted by the cluster they are in and by the value of the coefficient. This is a silhouette diagram. The shapes height indicates number of instances the cluster contains, and its width represents the sorted silhouette coefficients of the instances in the cluster (the wider the better). The dashed line indicates the mean silhouette coefficient.
The vertical dashed lines represent the silhouette score for each number of clusters. If many instances stop short (left) of the dashed line, then the cluster is rather bad because it means the instances are much too close to each other. at k=3, and k=6 we get bad clusters, but at k=4 and k=5 they are pretty good. Most instances extend beyond the dashed line. When k=4 though, the orange cluster is rather big, and at k=5 they are all similar sizes, so it seems like 5 should be used to get clusters of similar sizes.
Performing this process shows a clear limitation of the elbow method, and doing it regularly can reinforce the robustness of your choices of k.
To be a good data scientist, it’s important to know the assumptions behind methods you use so that you have an idea about the strength and weakness of them. This will help you decide when to use each method and under what circumstances:
Often we can end up with suboptimal solutions and a local minima (due to the random initialisation of centroids), so it’s important to run the algorithm several times to avoid this.
As well as this, we need to specify k, which can be subjective and quite a hassle sometimes, depending on the dataset.
And the largest problem is that K-Means does not perform particularly well when clusters are different sizes, densities or non-spherical shapes. Depending on the data, another clustering algorithm may work better. (Often, scaling input features before performing K-Means can help with this, however it does not guarantee all clusters will be nice and spherical)
K-Means also gives more weight to bigger clusters than smaller ones. In other words, data points in smaller clusters may be left away from the centroid in order to focus more on the larger cluster. This can lead to poorly assigned smaller clusters simply because of unbalanced data.
And finally, because K-Means assigns each instance into a non-overlapping cluster, there is no measure of uncertainty for points that lie near boundary lines
In this article, I discussed one of the most famous clustering algorithms — K-Means. We looked at the challenges which we might face while working with K-Means.
We implemented k-means and looked at the elbow curve which helps to find the optimum number of clusters in the K-Means algorithm, and showed its limitations too.
If you have any doubts or feedback, feel free to share them in the comments section below
References
Aurelien Geron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems Book , 2 edn., : O’Reilly.
All code for visualisations can be found at my GitHub here
|
[
{
"code": null,
"e": 379,
"s": 172,
"text": "Most applications of machine learning today are based on supervised learning. However the large majority of data is unlabelled: We have inputs X, but no label Y. Computer scientist Yann LeCunn famously said"
},
{
"code": null,
"e": 545,
"s": 379,
"text": "‘If intelligence was a cake, unsupervised learning would be the cake, supervised learning would be the icing, and reinforcement learning would be the cherry on top’."
},
{
"code": null,
"e": 613,
"s": 545,
"text": "In other words, there is a huge potential in unsupervised learning."
},
{
"code": null,
"e": 869,
"s": 613,
"text": "One form or unsupervised learning is grouping similar instances together in clusters. Clustering is a great tool for data analysis, customer segmentation, recommendation systems, search engines, semi-supervised learning, dimensionality reduction and more."
},
{
"code": null,
"e": 1414,
"s": 869,
"text": "If you wander around a park on your one lockdown walk a day, you may stumble upon a tree you have never seen before. If you look around and notice a few more, which are not identical but are similar enough looking that you know they belong to the same genus. You may need an arborist to tell you which species it is, but you don’t need the expert to just group your trees into similar looking groups. This is the essence of clustering: the task of identifying similar instances, and assigning them into clusters, or groups of similar instances."
},
{
"code": null,
"e": 1794,
"s": 1414,
"text": "One of the most commonly used clustering techniques is K-means. The K-means algorithm was proposed by Stuart Lloyd and Bell Labs in 1957 as a technique for pulse-code modulation, but only published outside the company in 1982. Edward Forgy published virtually the same algorithm in 1965 so it is referred to as Lloyd-Forgy. The following generates our data which we will cluster:"
},
{
"code": null,
"e": 2138,
"s": 1794,
"text": "from sklearn.datasets import make_blobsblob_centers = np.array([[ 0.2, 2.3],[-1.5 , 2.3],[-2.8, 1.8],[-2.8, 2.8],[-2.8, 1.3]])blob_std = np.array([0.4, 0.3, 0.1, 0.1, 0.1])X, y = make_blobs(n_samples=2000, centers=blob_centers,cluster_std=blob_std, random_state=7)plt.figure(figsize=(8, 4))plot_clusters(X)save_fig(\"blobs_plot\")plt.show()"
},
{
"code": null,
"e": 2362,
"s": 2138,
"text": "K-Means is very efficient at clustering data like the set above, often in very few iterations. It will try to find the centre of each cluster, and assign each instance to the closes cluster. Let’s train a K-Means clutterer:"
},
{
"code": null,
"e": 2463,
"s": 2362,
"text": "from sklearn.cluster import KMeansk = 5kmeans = KMeans(n_clusters = k)y_pred = kmeans.fit_predict(X)"
},
{
"code": null,
"e": 2587,
"s": 2463,
"text": "Each instance is assigned to one of the five clusters. It receives a label as the index of the cluster it gets assigned to."
},
{
"code": null,
"e": 2612,
"s": 2587,
"text": "We can see these labels:"
},
{
"code": null,
"e": 2690,
"s": 2612,
"text": "y_predarray([4, 0, 1, ..., 2, 1, 0], dtype=int32)y_pred is kmeans.labels_True"
},
{
"code": null,
"e": 2769,
"s": 2690,
"text": "We can also see the five centroids (cluster centres) that the algorithm found:"
},
{
"code": null,
"e": 2964,
"s": 2769,
"text": "kmeans.cluster_centers_array([[ 0.20876306, 2.25551336], [-2.80580621, 1.80056812], [-1.46046922, 2.30278886], [-2.79290307, 2.79641063], [-1.99213367, 1.3131094 ]])"
},
{
"code": null,
"e": 3149,
"s": 2964,
"text": "We can easily do this for new data too, by seeing which centroid any new data point is closest to. We can also visualise the decision boundaries, and each centroid is represented by X."
},
{
"code": null,
"e": 3333,
"s": 3149,
"text": "Initially, centroids are placed randomly, instances labelled, and the centroids are updated. This process iterates until the centroids stop moving, and the clusters have been defined."
},
{
"code": null,
"e": 3611,
"s": 3333,
"text": "Accelerated K-Means is the default for Sklearn. it considerably accelerates this algorithm by keeping track of the lower and upper bounds for the distances between instances and centroids. You can force Sklearn to use the original algorithm, although its unlikely to be needed."
},
{
"code": null,
"e": 4092,
"s": 3611,
"text": "Instead of using the full dataset at each iteration, the algorithm is capable of using mini-batches, moving the centroid slightly at each iteration. This increases the speed of the algorithm by a factor of 3–4 typically. Especially important, it makes it possible to cluster huge datasets that do not fit in memory. One limitation is that its inertia is usually slightly worse, especially as clusters increase, however with many clusters the speed is much faster using mini-batch."
},
{
"code": null,
"e": 4387,
"s": 4092,
"text": "In this dataset we can see that there are clearly 5 clusters we want to segment from each other. However that is not always the case, and often our data isn’t as obviously segmented as this. Our result can be quite poor if we don’t take precautions to figure out the optimal number of clusters:"
},
{
"code": null,
"e": 4736,
"s": 4387,
"text": "The first thought is to choose the k which minimises inertia, however we cannot do that as inertia will always decrease with a higher k. Indeed, the more clusters there are, the closer each instance will be to its closest centroid, and therefore the lower the inertia will be. As we can see with a k=8, we are splitting clusters for no good reason."
},
{
"code": null,
"e": 5116,
"s": 4736,
"text": "Inertia drops very quickly up to 5, but then it decreases very slowly afterwards. Any k lower than 5and the gain would be dramatic, and any higher and we are not gaining much more information. This is a rather rough, subjective way of assigning k, however it generally works pretty well. When doing this it allows us to take context of a specific needs of a business problem too."
},
{
"code": null,
"e": 5288,
"s": 5116,
"text": "However, in this case we could see that there were 5 clusters we wanted to segment. 4 clusters may be adequate but we should investigate the difference between k=4 and k=5"
},
{
"code": null,
"e": 5499,
"s": 5288,
"text": "Another, more precise approach is to use silhouette score for each instance and plot them for different numbers of clusters, however it is more computationally intensive, it will give us a more clear optimal k:"
},
{
"code": null,
"e": 5665,
"s": 5499,
"text": "from sklearn.metrics import silhouette_scoresilhouette_score(X, kmeans.labels_)silhouette_scores = [silhouette_score(X, model.labels_) for model in kmeans_per_k[1:]]"
},
{
"code": null,
"e": 5767,
"s": 5665,
"text": "As we can see, using silhouette score for each level of k, it is far more obvious which k is optimal."
},
{
"code": null,
"e": 6187,
"s": 5767,
"text": "Even more informative is plotting every instances silhouette coefficient, sorted by the cluster they are in and by the value of the coefficient. This is a silhouette diagram. The shapes height indicates number of instances the cluster contains, and its width represents the sorted silhouette coefficients of the instances in the cluster (the wider the better). The dashed line indicates the mean silhouette coefficient."
},
{
"code": null,
"e": 6707,
"s": 6187,
"text": "The vertical dashed lines represent the silhouette score for each number of clusters. If many instances stop short (left) of the dashed line, then the cluster is rather bad because it means the instances are much too close to each other. at k=3, and k=6 we get bad clusters, but at k=4 and k=5 they are pretty good. Most instances extend beyond the dashed line. When k=4 though, the orange cluster is rather big, and at k=5 they are all similar sizes, so it seems like 5 should be used to get clusters of similar sizes."
},
{
"code": null,
"e": 6851,
"s": 6707,
"text": "Performing this process shows a clear limitation of the elbow method, and doing it regularly can reinforce the robustness of your choices of k."
},
{
"code": null,
"e": 7088,
"s": 6851,
"text": "To be a good data scientist, it’s important to know the assumptions behind methods you use so that you have an idea about the strength and weakness of them. This will help you decide when to use each method and under what circumstances:"
},
{
"code": null,
"e": 7270,
"s": 7088,
"text": "Often we can end up with suboptimal solutions and a local minima (due to the random initialisation of centroids), so it’s important to run the algorithm several times to avoid this."
},
{
"code": null,
"e": 7389,
"s": 7270,
"text": "As well as this, we need to specify k, which can be subjective and quite a hassle sometimes, depending on the dataset."
},
{
"code": null,
"e": 7751,
"s": 7389,
"text": "And the largest problem is that K-Means does not perform particularly well when clusters are different sizes, densities or non-spherical shapes. Depending on the data, another clustering algorithm may work better. (Often, scaling input features before performing K-Means can help with this, however it does not guarantee all clusters will be nice and spherical)"
},
{
"code": null,
"e": 8034,
"s": 7751,
"text": "K-Means also gives more weight to bigger clusters than smaller ones. In other words, data points in smaller clusters may be left away from the centroid in order to focus more on the larger cluster. This can lead to poorly assigned smaller clusters simply because of unbalanced data."
},
{
"code": null,
"e": 8192,
"s": 8034,
"text": "And finally, because K-Means assigns each instance into a non-overlapping cluster, there is no measure of uncertainty for points that lie near boundary lines"
},
{
"code": null,
"e": 8353,
"s": 8192,
"text": "In this article, I discussed one of the most famous clustering algorithms — K-Means. We looked at the challenges which we might face while working with K-Means."
},
{
"code": null,
"e": 8515,
"s": 8353,
"text": "We implemented k-means and looked at the elbow curve which helps to find the optimum number of clusters in the K-Means algorithm, and showed its limitations too."
},
{
"code": null,
"e": 8605,
"s": 8515,
"text": "If you have any doubts or feedback, feel free to share them in the comments section below"
},
{
"code": null,
"e": 8616,
"s": 8605,
"text": "References"
},
{
"code": null,
"e": 8794,
"s": 8616,
"text": "Aurelien Geron (2019) Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems Book , 2 edn., : O’Reilly."
}
] |
Find the area of a circle in C programming.
|
A circle is a closed figure. All the points of the circle are equidistant from a point that lies inside in circle. The point at the center is known as the center of the circle. The distance of points from the center is known as the radius.
The area is the quantitative representation of the span of the dimensions of a closed figure.
The area of circle is the area enclosed inside the dimensions of a circle.
The formula for calculating the area of a circle,
Area = π*r*r
To calculate the area we are given the radius of the circle as input and we will use the formula to calculate the area,
STEP 1: Take radius as input from the user using std input.
STEP 2: Calculate the area of circle using,
area = (3.14)*r*r
STEP 3: Print the area to the screen using the std output.
int r , the radius of the circle
float area, the area of circle calculated using the formula.
Live Demo
#include <stdio.h>
int main(){
int r = 8;
float area = (3.14)*r*r;
printf("The area of the circle is %f",area);
return 0;
}
The area of the circle is 200.96
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "A circle is a closed figure. All the points of the circle are equidistant from a point that lies inside in circle. The point at the center is known as the center of the circle. The distance of points from the center is known as the radius."
},
{
"code": null,
"e": 1396,
"s": 1302,
"text": "The area is the quantitative representation of the span of the dimensions of a closed figure."
},
{
"code": null,
"e": 1471,
"s": 1396,
"text": "The area of circle is the area enclosed inside the dimensions of a circle."
},
{
"code": null,
"e": 1521,
"s": 1471,
"text": "The formula for calculating the area of a circle,"
},
{
"code": null,
"e": 1534,
"s": 1521,
"text": "Area = π*r*r"
},
{
"code": null,
"e": 1654,
"s": 1534,
"text": "To calculate the area we are given the radius of the circle as input and we will use the formula to calculate the area,"
},
{
"code": null,
"e": 1838,
"s": 1654,
"text": "STEP 1: Take radius as input from the user using std input.\nSTEP 2: Calculate the area of circle using,\n area = (3.14)*r*r\nSTEP 3: Print the area to the screen using the std output."
},
{
"code": null,
"e": 1871,
"s": 1838,
"text": "int r , the radius of the circle"
},
{
"code": null,
"e": 1932,
"s": 1871,
"text": "float area, the area of circle calculated using the formula."
},
{
"code": null,
"e": 1943,
"s": 1932,
"text": " Live Demo"
},
{
"code": null,
"e": 2079,
"s": 1943,
"text": "#include <stdio.h>\nint main(){\n int r = 8;\n float area = (3.14)*r*r;\n printf(\"The area of the circle is %f\",area);\n return 0;\n}"
},
{
"code": null,
"e": 2112,
"s": 2079,
"text": "The area of the circle is 200.96"
}
] |
Can we create an enum with custom values in java?
|
Enumeration (enum) in Java is a datatype which stores a set of constant values (Strings in general). You can use enumerations to store fixed values such as days in a week, months in a year etc.
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Instead of declaring just string constants in an enum, you can also have values to these constants as −
enum Vehicles {
ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
}
Whenever, you need to assign custom values to the constants of an enum −
To hold the value of each constant you need to have an instance variable (generally, private).
You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s).
The initialization should be done only once. Therefore, the constructor must be declared private or default.
To returns the values of the constants using an instance method(getter).
In the following Java example, we are defining an enum with name Vehicles and declaring five constants representing the vehicle names with their prices as values.
Live Demo
enum Vehicles {
//Constants with values
ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
//Instance variable
private int price;
//Constructor to initialize the instance variable
Vehicles(int price) {
this.price = price;
}
public int getPrice() {
return this.price;
}
}
public class EnumTest{
public static void main(String args[]) {
Vehicles vehicles[] = Vehicles.values();
for(Vehicles veh: vehicles) {
System.out.println("Price of "+veh+" is: "+veh.getPrice());
}
}
}
Price of ACTIVA125 is: 80000
Price of ACTIVA5G is: 70000
Price of ACCESS125 is: 75000
Price of VESPA is: 90000
Price of TVSJUPITER is: 75000
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Enumeration (enum) in Java is a datatype which stores a set of constant values (Strings in general). You can use enumerations to store fixed values such as days in a week, months in a year etc."
},
{
"code": null,
"e": 1336,
"s": 1256,
"text": "enum Days {\n SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY\n}"
},
{
"code": null,
"e": 1440,
"s": 1336,
"text": "Instead of declaring just string constants in an enum, you can also have values to these constants as −"
},
{
"code": null,
"e": 1547,
"s": 1440,
"text": "enum Vehicles {\n ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);\n}"
},
{
"code": null,
"e": 1620,
"s": 1547,
"text": "Whenever, you need to assign custom values to the constants of an enum −"
},
{
"code": null,
"e": 1715,
"s": 1620,
"text": "To hold the value of each constant you need to have an instance variable (generally, private)."
},
{
"code": null,
"e": 1841,
"s": 1715,
"text": "You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s)."
},
{
"code": null,
"e": 1950,
"s": 1841,
"text": "The initialization should be done only once. Therefore, the constructor must be declared private or default."
},
{
"code": null,
"e": 2023,
"s": 1950,
"text": "To returns the values of the constants using an instance method(getter)."
},
{
"code": null,
"e": 2186,
"s": 2023,
"text": "In the following Java example, we are defining an enum with name Vehicles and declaring five constants representing the vehicle names with their prices as values."
},
{
"code": null,
"e": 2197,
"s": 2186,
"text": " Live Demo"
},
{
"code": null,
"e": 2776,
"s": 2197,
"text": "enum Vehicles {\n //Constants with values\n ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);\n //Instance variable\n private int price;\n //Constructor to initialize the instance variable\n Vehicles(int price) {\n this.price = price;\n }\n public int getPrice() {\n return this.price;\n }\n}\npublic class EnumTest{\n public static void main(String args[]) {\n Vehicles vehicles[] = Vehicles.values();\n for(Vehicles veh: vehicles) {\n System.out.println(\"Price of \"+veh+\" is: \"+veh.getPrice());\n }\n }\n}"
},
{
"code": null,
"e": 2917,
"s": 2776,
"text": "Price of ACTIVA125 is: 80000\nPrice of ACTIVA5G is: 70000\nPrice of ACCESS125 is: 75000\nPrice of VESPA is: 90000\nPrice of TVSJUPITER is: 75000"
}
] |
Vim surround tutorial | Towards Data Science
|
I recently started learning Vim and it was difficult, especially during the first few days — my productivity took a real hit. I could barely write any code in Visual Studio Code without feeling a pain in my head. To learn more about my 15-day journey, check out this post:
towardsdatascience.com
Now, two weeks later, I feel quite comfortable using Vim and have fallen in love with it, thanks to lots of regular deliberate practice and Tim Pope’s surround.vim plugin. In fact, this post was written in Markdown with Vim and I’ve started using a very powerful note-taking app (and strategies) that allows me to use Vim.
medium.com
This post assumes you already know Vim basics. I’ll introduce surround.vim, provide examples to explain how it works, and show you how to practice effectively. If you’re new to Vim, check out some articles written for beginners first (e.g., here and here). Also, check out my posts that show you how to be a more productive coder or programmer.
medium.com
medium.com
towardsdatascience.com
The surround.vim plugin lets you deal with pairs of things surrounding things, like brackets, HTML tags, and quotation marks (documentation here). Whether you’re coding or writing, this plugin can make your life much easier.
To install, run the four lines of code below in terminal.
mkdir -p ~/.vim/pack/tpope/startcd ~/.vim/pack/tpope/startgit clone https://tpope.io/vim/surround.gitvim -u NONE -c "helptags surround/doc" -c q
First, understand how the plugin works — learn how to surround (ys), delete (ds), and change (cs). Then, work through guided examples, like the ones below. Once you understand the basics, immediately start using the plugin in your everyday writing/coding.
To improve rapidly, use deliberate practice: Every day, identify your weak areas (e.g., adding quotes multiple words), work through relevant guided examples (see Surround Multiple Words section below), generate more examples yourself, and test yourself repeatedly until you can execute the correct motions/keystrokes without having to think too much.
If you engage in this kind of deliberate practice for a few days — even if it’s just a few minutes each day — you’ll become good at using surround.vim very quickly.
I am happy.I am "happy".
Solution: ysiw" (ys: add surroundings; iw: entire word, no matter where the cursor is as long as it's at the word you want to surround; ": character to surround text with)
I am happy; she is sad.(I am happy; she is sad.)
Solution: yss) (ys: add surroundings; s: entire line; ) character to surround line with)
Note: If you use yss( instead of yss), spaces will be added around your text: ( I am happy; she is sad. )
Hello World! How are you?<p>Hello World! How are you?</p>
Solution: yss<p> (yss: add surroundings to entire line; <p> tag to surround line with)
Note: The closing tag </p> will be auto-completed. Very convenient!
I am very very happy.I am *very very* happy.
Solution: ys2aw* (ys: add surroundings; 2: number of words to surround, starting with the word under the cursor; aw: around words; *: character to surround text with)
Hello World! How are you?<em>Hello World</em>! How are you?
Solution: ys2aw<em> (add surroundings around 2 words; remember to place your cursor under Hello first!)
The solution is x + y = z. You responded wrongly.The solution is `x + y = z`. You responded wrongly.
Solution: Place cursor under x, then veeeeS` (v: enter visual mode to select text; eeee: press however many times you need to select the number of words you want to select; S` surrounds the selected text with `)
"Hello World!"Hello World
Solution: ds" (ds: delete surrounding; ": character to delete; place cursor anywhere inside the text area)
<em><p>Hello World!</p></em>Hello World!
Solution: dstdst (dst; delete surrounding tag); if you install repeat.vim, you can use . to repeat, so dst. will be the same as dstdst
"Hello World!"*Hello World!*
Solution: cs"* (cs: change surrounding; ": existing surrounding; *: new surrounding)
<p>Hello World!</p><em>Hello World!</em>
Solution: cst<em> (cst: change surrounding tag; <em>: new surrounding)
Find the mean of a set of numbers
3 + 2 + 5 + 7 / 4 # wrong because brackets are missing# solution3 + 2 + 5 + 7 / 4 # place cursor under 3, then veeeeS)(3 + 2 + 5 + 7) / 4# surround text with functions/methods when coding(3 + 2 + 5 + 7) / 4 # yss)iprintprint((3 + 2 + 5 + 7) / 4)
Emphasize text, with and without repeat.vim
Hello World.Hello *World*. Hello **World**.
Solution 1 (without repeat.vim): ysiw*lysiw after moving cursor to under W (ysiw*: surround word with *; l: move cursor to W again; ysiw*: surround word with *)
Solution 2 (with repeat.vim): ysiw*l. (. repeats ysiw*)
To help with deliberate practice, I’ve consolidated all the examples above so you can easily use them to test yourself regularly. For each example, the first row is the original/starting text and the second row is the goal or end state. Have fun and also check out the documentation!
# surround.vim practice# SurroundI am happy. # startI am "happy". # goalI am happy; she is sad.(I am happy; she is sad.)Hello World! How are you?<p>Hello World! How are you?</p>I am very very happy.I am *very very* happy.Hello World! How are you?<em>Hello World</em>! How are you?The solution is x + y = z. You responded wrongly.The solution is `x + y = z`. You responded wrongly.# Delete"Hello World!"Hello World<em><p>Hello World!</p></em>Hello World!# Change"Hello World!"*Hello World!*<p>Hello World!</p><em>Hello World!</em># Examples3 + 2 + 5 + 7 / 4print((3 + 2 + 5 + 7) / 4)Hello World.Hello **World**.
For more posts, subscribe to my mailing list.
|
[
{
"code": null,
"e": 445,
"s": 172,
"text": "I recently started learning Vim and it was difficult, especially during the first few days — my productivity took a real hit. I could barely write any code in Visual Studio Code without feeling a pain in my head. To learn more about my 15-day journey, check out this post:"
},
{
"code": null,
"e": 468,
"s": 445,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 791,
"s": 468,
"text": "Now, two weeks later, I feel quite comfortable using Vim and have fallen in love with it, thanks to lots of regular deliberate practice and Tim Pope’s surround.vim plugin. In fact, this post was written in Markdown with Vim and I’ve started using a very powerful note-taking app (and strategies) that allows me to use Vim."
},
{
"code": null,
"e": 802,
"s": 791,
"text": "medium.com"
},
{
"code": null,
"e": 1147,
"s": 802,
"text": "This post assumes you already know Vim basics. I’ll introduce surround.vim, provide examples to explain how it works, and show you how to practice effectively. If you’re new to Vim, check out some articles written for beginners first (e.g., here and here). Also, check out my posts that show you how to be a more productive coder or programmer."
},
{
"code": null,
"e": 1158,
"s": 1147,
"text": "medium.com"
},
{
"code": null,
"e": 1169,
"s": 1158,
"text": "medium.com"
},
{
"code": null,
"e": 1192,
"s": 1169,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1417,
"s": 1192,
"text": "The surround.vim plugin lets you deal with pairs of things surrounding things, like brackets, HTML tags, and quotation marks (documentation here). Whether you’re coding or writing, this plugin can make your life much easier."
},
{
"code": null,
"e": 1475,
"s": 1417,
"text": "To install, run the four lines of code below in terminal."
},
{
"code": null,
"e": 1620,
"s": 1475,
"text": "mkdir -p ~/.vim/pack/tpope/startcd ~/.vim/pack/tpope/startgit clone https://tpope.io/vim/surround.gitvim -u NONE -c \"helptags surround/doc\" -c q"
},
{
"code": null,
"e": 1876,
"s": 1620,
"text": "First, understand how the plugin works — learn how to surround (ys), delete (ds), and change (cs). Then, work through guided examples, like the ones below. Once you understand the basics, immediately start using the plugin in your everyday writing/coding."
},
{
"code": null,
"e": 2227,
"s": 1876,
"text": "To improve rapidly, use deliberate practice: Every day, identify your weak areas (e.g., adding quotes multiple words), work through relevant guided examples (see Surround Multiple Words section below), generate more examples yourself, and test yourself repeatedly until you can execute the correct motions/keystrokes without having to think too much."
},
{
"code": null,
"e": 2392,
"s": 2227,
"text": "If you engage in this kind of deliberate practice for a few days — even if it’s just a few minutes each day — you’ll become good at using surround.vim very quickly."
},
{
"code": null,
"e": 2417,
"s": 2392,
"text": "I am happy.I am \"happy\"."
},
{
"code": null,
"e": 2589,
"s": 2417,
"text": "Solution: ysiw\" (ys: add surroundings; iw: entire word, no matter where the cursor is as long as it's at the word you want to surround; \": character to surround text with)"
},
{
"code": null,
"e": 2638,
"s": 2589,
"text": "I am happy; she is sad.(I am happy; she is sad.)"
},
{
"code": null,
"e": 2727,
"s": 2638,
"text": "Solution: yss) (ys: add surroundings; s: entire line; ) character to surround line with)"
},
{
"code": null,
"e": 2833,
"s": 2727,
"text": "Note: If you use yss( instead of yss), spaces will be added around your text: ( I am happy; she is sad. )"
},
{
"code": null,
"e": 2891,
"s": 2833,
"text": "Hello World! How are you?<p>Hello World! How are you?</p>"
},
{
"code": null,
"e": 2978,
"s": 2891,
"text": "Solution: yss<p> (yss: add surroundings to entire line; <p> tag to surround line with)"
},
{
"code": null,
"e": 3046,
"s": 2978,
"text": "Note: The closing tag </p> will be auto-completed. Very convenient!"
},
{
"code": null,
"e": 3091,
"s": 3046,
"text": "I am very very happy.I am *very very* happy."
},
{
"code": null,
"e": 3258,
"s": 3091,
"text": "Solution: ys2aw* (ys: add surroundings; 2: number of words to surround, starting with the word under the cursor; aw: around words; *: character to surround text with)"
},
{
"code": null,
"e": 3318,
"s": 3258,
"text": "Hello World! How are you?<em>Hello World</em>! How are you?"
},
{
"code": null,
"e": 3422,
"s": 3318,
"text": "Solution: ys2aw<em> (add surroundings around 2 words; remember to place your cursor under Hello first!)"
},
{
"code": null,
"e": 3523,
"s": 3422,
"text": "The solution is x + y = z. You responded wrongly.The solution is `x + y = z`. You responded wrongly."
},
{
"code": null,
"e": 3735,
"s": 3523,
"text": "Solution: Place cursor under x, then veeeeS` (v: enter visual mode to select text; eeee: press however many times you need to select the number of words you want to select; S` surrounds the selected text with `)"
},
{
"code": null,
"e": 3761,
"s": 3735,
"text": "\"Hello World!\"Hello World"
},
{
"code": null,
"e": 3868,
"s": 3761,
"text": "Solution: ds\" (ds: delete surrounding; \": character to delete; place cursor anywhere inside the text area)"
},
{
"code": null,
"e": 3909,
"s": 3868,
"text": "<em><p>Hello World!</p></em>Hello World!"
},
{
"code": null,
"e": 4044,
"s": 3909,
"text": "Solution: dstdst (dst; delete surrounding tag); if you install repeat.vim, you can use . to repeat, so dst. will be the same as dstdst"
},
{
"code": null,
"e": 4073,
"s": 4044,
"text": "\"Hello World!\"*Hello World!*"
},
{
"code": null,
"e": 4158,
"s": 4073,
"text": "Solution: cs\"* (cs: change surrounding; \": existing surrounding; *: new surrounding)"
},
{
"code": null,
"e": 4199,
"s": 4158,
"text": "<p>Hello World!</p><em>Hello World!</em>"
},
{
"code": null,
"e": 4270,
"s": 4199,
"text": "Solution: cst<em> (cst: change surrounding tag; <em>: new surrounding)"
},
{
"code": null,
"e": 4304,
"s": 4270,
"text": "Find the mean of a set of numbers"
},
{
"code": null,
"e": 4553,
"s": 4304,
"text": "3 + 2 + 5 + 7 / 4 # wrong because brackets are missing# solution3 + 2 + 5 + 7 / 4 # place cursor under 3, then veeeeS)(3 + 2 + 5 + 7) / 4# surround text with functions/methods when coding(3 + 2 + 5 + 7) / 4 # yss)iprintprint((3 + 2 + 5 + 7) / 4)"
},
{
"code": null,
"e": 4597,
"s": 4553,
"text": "Emphasize text, with and without repeat.vim"
},
{
"code": null,
"e": 4641,
"s": 4597,
"text": "Hello World.Hello *World*. Hello **World**."
},
{
"code": null,
"e": 4802,
"s": 4641,
"text": "Solution 1 (without repeat.vim): ysiw*lysiw after moving cursor to under W (ysiw*: surround word with *; l: move cursor to W again; ysiw*: surround word with *)"
},
{
"code": null,
"e": 4858,
"s": 4802,
"text": "Solution 2 (with repeat.vim): ysiw*l. (. repeats ysiw*)"
},
{
"code": null,
"e": 5142,
"s": 4858,
"text": "To help with deliberate practice, I’ve consolidated all the examples above so you can easily use them to test yourself regularly. For each example, the first row is the original/starting text and the second row is the goal or end state. Have fun and also check out the documentation!"
},
{
"code": null,
"e": 5761,
"s": 5142,
"text": "# surround.vim practice# SurroundI am happy. # startI am \"happy\". # goalI am happy; she is sad.(I am happy; she is sad.)Hello World! How are you?<p>Hello World! How are you?</p>I am very very happy.I am *very very* happy.Hello World! How are you?<em>Hello World</em>! How are you?The solution is x + y = z. You responded wrongly.The solution is `x + y = z`. You responded wrongly.# Delete\"Hello World!\"Hello World<em><p>Hello World!</p></em>Hello World!# Change\"Hello World!\"*Hello World!*<p>Hello World!</p><em>Hello World!</em># Examples3 + 2 + 5 + 7 / 4print((3 + 2 + 5 + 7) / 4)Hello World.Hello **World**."
}
] |
Get Bit Coin price in real time using Python - GeeksforGeeks
|
13 Jan, 2022
In this article we will see how we can get the current price of the bit coin.
Bitcoin is a cryptocurrency. It is a decentralized digital currency without a central bank or single administrator that can be sent from user to user on the peer-to-peer bitcoin network without the need for intermediaries.
Modules required and Installation:
Requests :Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs.
pip install requests
Beautiful Soup:Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree.
pip install beautifulsoup4
Explanation –We have the google search URL of the bit coin price from that we have scrape the price of the bitcoin in Indian rupees and stored it in a variable, which we further print it.
Python3
# importing librariesfrom bs4 import BeautifulSoup as BSimport requests # method to get the price of bit coindef get_price(url): # getting the request from url data = requests.get(url) # converting the text soup = BS(data.text, 'html.parser') # finding metha info for the current price ans = soup.find("div", class_ ="BNeawe iBp4i AP7Wnd").text # returning the price return ans # url of the bit coin priceurl = "https://www.google.com / search?q = bitcoin + price" # calling the get_price methodans = get_price(url) # printing the ansprint(ans)
Output :
520, 106.95 Indian Rupee
varshagumber28
as5853535
Python web-scraping-exercises
Python-BS3
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
|
[
{
"code": null,
"e": 23823,
"s": 23795,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 23901,
"s": 23823,
"text": "In this article we will see how we can get the current price of the bit coin."
},
{
"code": null,
"e": 24124,
"s": 23901,
"text": "Bitcoin is a cryptocurrency. It is a decentralized digital currency without a central bank or single administrator that can be sent from user to user on the peer-to-peer bitcoin network without the need for intermediaries."
},
{
"code": null,
"e": 24159,
"s": 24124,
"text": "Modules required and Installation:"
},
{
"code": null,
"e": 24293,
"s": 24159,
"text": "Requests :Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs."
},
{
"code": null,
"e": 24314,
"s": 24293,
"text": "pip install requests"
},
{
"code": null,
"e": 24532,
"s": 24314,
"text": "Beautiful Soup:Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree."
},
{
"code": null,
"e": 24559,
"s": 24532,
"text": "pip install beautifulsoup4"
},
{
"code": null,
"e": 24747,
"s": 24559,
"text": "Explanation –We have the google search URL of the bit coin price from that we have scrape the price of the bitcoin in Indian rupees and stored it in a variable, which we further print it."
},
{
"code": null,
"e": 24755,
"s": 24747,
"text": "Python3"
},
{
"code": "# importing librariesfrom bs4 import BeautifulSoup as BSimport requests # method to get the price of bit coindef get_price(url): # getting the request from url data = requests.get(url) # converting the text soup = BS(data.text, 'html.parser') # finding metha info for the current price ans = soup.find(\"div\", class_ =\"BNeawe iBp4i AP7Wnd\").text # returning the price return ans # url of the bit coin priceurl = \"https://www.google.com / search?q = bitcoin + price\" # calling the get_price methodans = get_price(url) # printing the ansprint(ans)",
"e": 25349,
"s": 24755,
"text": null
},
{
"code": null,
"e": 25358,
"s": 25349,
"text": "Output :"
},
{
"code": null,
"e": 25383,
"s": 25358,
"text": "520, 106.95 Indian Rupee"
},
{
"code": null,
"e": 25398,
"s": 25383,
"text": "varshagumber28"
},
{
"code": null,
"e": 25408,
"s": 25398,
"text": "as5853535"
},
{
"code": null,
"e": 25438,
"s": 25408,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 25449,
"s": 25438,
"text": "Python-BS3"
},
{
"code": null,
"e": 25462,
"s": 25449,
"text": "Web-scraping"
},
{
"code": null,
"e": 25469,
"s": 25462,
"text": "Python"
},
{
"code": null,
"e": 25567,
"s": 25469,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25576,
"s": 25567,
"text": "Comments"
},
{
"code": null,
"e": 25589,
"s": 25576,
"text": "Old Comments"
},
{
"code": null,
"e": 25607,
"s": 25589,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25629,
"s": 25607,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25664,
"s": 25629,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25686,
"s": 25664,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25728,
"s": 25686,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25753,
"s": 25728,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25783,
"s": 25753,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25799,
"s": 25783,
"text": "Deque in Python"
},
{
"code": null,
"e": 25831,
"s": 25799,
"text": "How to Install PIP on Windows ?"
}
] |
MySQL Tryit Editor v1.0
|
SELECT TRUNCATE(345.156, 0);
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 29,
"s": 0,
"text": "SELECT TRUNCATE(345.156, 0);"
},
{
"code": null,
"e": 31,
"s": 29,
"text": ""
},
{
"code": null,
"e": 103,
"s": 40,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 163,
"s": 103,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 231,
"s": 163,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 269,
"s": 231,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 354,
"s": 269,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 528,
"s": 354,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 579,
"s": 528,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 647,
"s": 579,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 818,
"s": 647,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 918,
"s": 818,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 968,
"s": 918,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
std::istream_iterator and std::ostream_iterator in C++ STL - GeeksforGeeks
|
06 Jan, 2022
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components :
Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, dequeue, list, forward list, set, multiset, map and multimap.Algorithms: The STL library also provides us functions to process the data stored in containers. These functions are provided in the algorithm header fileIterators: Iterators are the link between the Containers and the Algorithms. They are the common interface to these classes. An Iterator is an object which can be used to iterator over the elements in a container. Thus iterators are used by Algorithms to modify the containers.
Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, dequeue, list, forward list, set, multiset, map and multimap.
Algorithms: The STL library also provides us functions to process the data stored in containers. These functions are provided in the algorithm header file
Iterators: Iterators are the link between the Containers and the Algorithms. They are the common interface to these classes. An Iterator is an object which can be used to iterator over the elements in a container. Thus iterators are used by Algorithms to modify the containers.
All three components are so designed that they confirm to the principles of data abstraction. Thus any object which holds data and behaves like a container, is a container. Similarly, any iterator which sweeps through the elements in a container is an iterator.If an iterator can be used to access elements of a data container, then what about streams? In keeping with the design, Streams too are data containers and so C++ provides us with iterators to iterate over the elements present in any stream. These iterators are called Stream Iterators. To use these iterators the iterator header file must be included. Stream iterators are either input stream iterator or output stream iterator. The classes for these iterators are istream_iterator and ostream_iterator. These iterators behave like input iterators and output iterators respectively .
istream_iterator
Class Definition for istream_iterator
namespace std {
template < typename T, typename charT=char,
typename traits=char_traits <charT> >
class istream_iterator;
}
Syntax :
istream_iterator<T>(stream)
T: Template parameter for specifying type of data
stream: The object representing the stream
ostream_iterator<T>(stream, delim).
stream: The object representing the stream.
T: Template Parameter for data type in the stream
delim: An optional char sequence that is used to
separate the data items while displaying them.
Note :
Using an iterator we can only access elements of one type only.
istream_iterator has a special state end of stream iterator which is acquired when the end of the stream is reached or when an input operation fails. The end of stream iterator is returned by the default constructor.
ostream_iterator
Class Definition for ostream_iterator
namespace std {
template < typename T, typename charT=char,
typename traits=char_traits <charT> >
class ostream_iterator;
}
Syntax :
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
first: Input Iterator to the first element
in source from where elements need to be copied.
last: Input Iterator to the last element
in source till where elements need to be copied.
result: Output iterator to the first element
in the destination container to where elements will copied.
Return Value: Iterator pointing to the last element that was copied to the destination.
The second and third template arguments have a default values assigned to them. We only need to specify the first template parameter which specifies the type of data present in the stream i.e whether the stream contains integers, floats or strings. Examples :
istream_iterator cin_it(cin) is an iterator for the stream cin.
ostream_iterator cout_it(cout, " ") is an iterator for the stream cout.
ostream_iterator cout_it(cout) is an iterator for stream cout, with no delimiter.
Importance of Stream IteratorsThe advantage of stream iterators is that they provide a common interface to access elements in I/O stream, file streams and also other stream to external physical devices.
Once an iterator to the respective stream has been obtained the code that follows is nearly same form all types of streams.
Thus tasks like reading from an input stream and reading from another external stream become similar.
Stream Iterators allow us access to all the powerful STL algorithms like for_each, replace_if which take an input range to operate on. A particularly useful function is the copy() function. This function is used to copy the elements from one container to another.
Using the copy() function, we can easily transfer data from a stream to a container and vice-versa. Here are a few example programs to demonstrate working with stream iterators
Example 1
CPP
// Cpp program to illustrate// Read a bunch of integers from the input stream// and print them to output stream #include <algorithm>#include <iostream>#include <iterator> using namespace std;int main(){ // Get input stream and end of stream iterators istream_iterator<int> cin_it(cin); istream_iterator<int> eos; // Get output stream iterators ostream_iterator<int> cout_it(cout, " "); // We have both input and output iterators, now we can treat them // as containers. Using copy function we transfer data from one // container to another. // Copy elements from input to output using copy function copy(cin_it, eos, cout_it); return 0;}
Input: 1 2 3 4 5
Output: 1 2 3 4 5
Example 2
CPP
// Cpp program to illustrate// Read a bunch of strings from a file// sort them lexicographically and print them to output stream #include <algorithm>#include <fstream>#include <iostream>#include <iterator>#include <string>#include <vector> using namespace std;int main(){ // Define a vector to store the strings received from input vector<string> strings_v; // Define the filestream object used to read data from file ifstream fin("input_file.txt"); // Get input stream and end of stream iterators istream_iterator<string> fin_it(fin); istream_iterator<string> eos; // Get output stream iterators ostream_iterator<string> cout_it(cout, " "); // Copy elements from input to vector using copy function copy(fin_it, eos, back_inserter(strings_v)); // Sort the vector sort(strings_v.begin(), strings_v.end()); // Copy elements from vector to output copy(strings_v.begin(), strings_v.end(), cout_it); return 0;}
Contents of File "input_file.txt": quick brown fox jumps over the lazy dog
Output: brown dog fox jumps lazy over quick the
Example 3:
CPP
// Cpp program to illustrate // Read a bunch of integers from the stream// print the sorted order of even integers only #include <algorithm>#include <iostream>#include <iterator>#include <vector> using namespace std;int main(){ // Define a vector to store the even integers received from input vector<int> vi; // Get input stream and end of stream iterators istream_iterator<int> cin_it(cin); istream_iterator<int> eos; // Get output stream iterators ostream_iterator<int> cout_it(cout, " "); // Copy even integer elements from input to vector using for_each function for_each(cin_it, eos, [&](int a) { if (a % 2 == 0) { // if a is even push it to vector vi.push_back(a); } }); // Sort the vector sort(vi.begin(), vi.end()); // Copy elements from vector to output copy(vi.begin(), vi.end(), cout_it); return 0;}
Input: 1 4 3 2 6 8 31 52
Output: 2 4 6 8 52
References: istream_iterator ostream_iterator
nidhi_biet
ManasChhabra2
akshaysingh98088
adnanirshad158
cpp-iterator
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
Polymorphism in C++
C++ Data Types
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 24948,
"s": 24796,
"text": "The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : "
},
{
"code": null,
"e": 25639,
"s": 24948,
"text": "Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, dequeue, list, forward list, set, multiset, map and multimap.Algorithms: The STL library also provides us functions to process the data stored in containers. These functions are provided in the algorithm header fileIterators: Iterators are the link between the Containers and the Algorithms. They are the common interface to these classes. An Iterator is an object which can be used to iterator over the elements in a container. Thus iterators are used by Algorithms to modify the containers. "
},
{
"code": null,
"e": 25897,
"s": 25639,
"text": "Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, dequeue, list, forward list, set, multiset, map and multimap."
},
{
"code": null,
"e": 26052,
"s": 25897,
"text": "Algorithms: The STL library also provides us functions to process the data stored in containers. These functions are provided in the algorithm header file"
},
{
"code": null,
"e": 26332,
"s": 26052,
"text": "Iterators: Iterators are the link between the Containers and the Algorithms. They are the common interface to these classes. An Iterator is an object which can be used to iterator over the elements in a container. Thus iterators are used by Algorithms to modify the containers. "
},
{
"code": null,
"e": 27180,
"s": 26332,
"text": "All three components are so designed that they confirm to the principles of data abstraction. Thus any object which holds data and behaves like a container, is a container. Similarly, any iterator which sweeps through the elements in a container is an iterator.If an iterator can be used to access elements of a data container, then what about streams? In keeping with the design, Streams too are data containers and so C++ provides us with iterators to iterate over the elements present in any stream. These iterators are called Stream Iterators. To use these iterators the iterator header file must be included. Stream iterators are either input stream iterator or output stream iterator. The classes for these iterators are istream_iterator and ostream_iterator. These iterators behave like input iterators and output iterators respectively . "
},
{
"code": null,
"e": 27197,
"s": 27180,
"text": "istream_iterator"
},
{
"code": null,
"e": 27236,
"s": 27197,
"text": "Class Definition for istream_iterator "
},
{
"code": null,
"e": 27384,
"s": 27236,
"text": "namespace std {\n template < typename T, typename charT=char, \n typename traits=char_traits <charT> >\n class istream_iterator;\n}"
},
{
"code": null,
"e": 27394,
"s": 27384,
"text": "Syntax : "
},
{
"code": null,
"e": 27520,
"s": 27394,
"text": "istream_iterator<T>(stream)\nT: Template parameter for specifying type of data\nstream: The object representing the stream"
},
{
"code": null,
"e": 27761,
"s": 27520,
"text": "ostream_iterator<T>(stream, delim).\nstream: The object representing the stream.\nT: Template Parameter for data type in the stream\ndelim: An optional char sequence that is used to \n separate the data items while displaying them."
},
{
"code": null,
"e": 27770,
"s": 27761,
"text": "Note : "
},
{
"code": null,
"e": 27834,
"s": 27770,
"text": "Using an iterator we can only access elements of one type only."
},
{
"code": null,
"e": 28051,
"s": 27834,
"text": "istream_iterator has a special state end of stream iterator which is acquired when the end of the stream is reached or when an input operation fails. The end of stream iterator is returned by the default constructor."
},
{
"code": null,
"e": 28068,
"s": 28051,
"text": "ostream_iterator"
},
{
"code": null,
"e": 28108,
"s": 28068,
"text": "Class Definition for ostream_iterator "
},
{
"code": null,
"e": 28256,
"s": 28108,
"text": "namespace std {\n template < typename T, typename charT=char, \n typename traits=char_traits <charT> >\n class ostream_iterator;\n}"
},
{
"code": null,
"e": 28267,
"s": 28256,
"text": "Syntax : "
},
{
"code": null,
"e": 28734,
"s": 28267,
"text": "OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);\n\nfirst: Input Iterator to the first element \nin source from where elements need to be copied.\nlast: Input Iterator to the last element \nin source till where elements need to be copied.\nresult: Output iterator to the first element \nin the destination container to where elements will copied.\n\nReturn Value: Iterator pointing to the last element that was copied to the destination."
},
{
"code": null,
"e": 28996,
"s": 28734,
"text": "The second and third template arguments have a default values assigned to them. We only need to specify the first template parameter which specifies the type of data present in the stream i.e whether the stream contains integers, floats or strings. Examples : "
},
{
"code": null,
"e": 29214,
"s": 28996,
"text": "istream_iterator cin_it(cin) is an iterator for the stream cin.\nostream_iterator cout_it(cout, \" \") is an iterator for the stream cout.\nostream_iterator cout_it(cout) is an iterator for stream cout, with no delimiter."
},
{
"code": null,
"e": 29419,
"s": 29214,
"text": " Importance of Stream IteratorsThe advantage of stream iterators is that they provide a common interface to access elements in I/O stream, file streams and also other stream to external physical devices. "
},
{
"code": null,
"e": 29543,
"s": 29419,
"text": "Once an iterator to the respective stream has been obtained the code that follows is nearly same form all types of streams."
},
{
"code": null,
"e": 29645,
"s": 29543,
"text": "Thus tasks like reading from an input stream and reading from another external stream become similar."
},
{
"code": null,
"e": 29909,
"s": 29645,
"text": "Stream Iterators allow us access to all the powerful STL algorithms like for_each, replace_if which take an input range to operate on. A particularly useful function is the copy() function. This function is used to copy the elements from one container to another."
},
{
"code": null,
"e": 30086,
"s": 29909,
"text": "Using the copy() function, we can easily transfer data from a stream to a container and vice-versa. Here are a few example programs to demonstrate working with stream iterators"
},
{
"code": null,
"e": 30097,
"s": 30086,
"text": "Example 1 "
},
{
"code": null,
"e": 30101,
"s": 30097,
"text": "CPP"
},
{
"code": "// Cpp program to illustrate// Read a bunch of integers from the input stream// and print them to output stream #include <algorithm>#include <iostream>#include <iterator> using namespace std;int main(){ // Get input stream and end of stream iterators istream_iterator<int> cin_it(cin); istream_iterator<int> eos; // Get output stream iterators ostream_iterator<int> cout_it(cout, \" \"); // We have both input and output iterators, now we can treat them // as containers. Using copy function we transfer data from one // container to another. // Copy elements from input to output using copy function copy(cin_it, eos, cout_it); return 0;}",
"e": 30776,
"s": 30101,
"text": null
},
{
"code": null,
"e": 30812,
"s": 30776,
"text": "Input: 1 2 3 4 5 \nOutput: 1 2 3 4 5"
},
{
"code": null,
"e": 30823,
"s": 30812,
"text": "Example 2 "
},
{
"code": null,
"e": 30827,
"s": 30823,
"text": "CPP"
},
{
"code": "// Cpp program to illustrate// Read a bunch of strings from a file// sort them lexicographically and print them to output stream #include <algorithm>#include <fstream>#include <iostream>#include <iterator>#include <string>#include <vector> using namespace std;int main(){ // Define a vector to store the strings received from input vector<string> strings_v; // Define the filestream object used to read data from file ifstream fin(\"input_file.txt\"); // Get input stream and end of stream iterators istream_iterator<string> fin_it(fin); istream_iterator<string> eos; // Get output stream iterators ostream_iterator<string> cout_it(cout, \" \"); // Copy elements from input to vector using copy function copy(fin_it, eos, back_inserter(strings_v)); // Sort the vector sort(strings_v.begin(), strings_v.end()); // Copy elements from vector to output copy(strings_v.begin(), strings_v.end(), cout_it); return 0;}",
"e": 31790,
"s": 30827,
"text": null
},
{
"code": null,
"e": 31914,
"s": 31790,
"text": "Contents of File \"input_file.txt\": quick brown fox jumps over the lazy dog\nOutput: brown dog fox jumps lazy over quick the "
},
{
"code": null,
"e": 31926,
"s": 31914,
"text": "Example 3: "
},
{
"code": null,
"e": 31930,
"s": 31926,
"text": "CPP"
},
{
"code": "// Cpp program to illustrate // Read a bunch of integers from the stream// print the sorted order of even integers only #include <algorithm>#include <iostream>#include <iterator>#include <vector> using namespace std;int main(){ // Define a vector to store the even integers received from input vector<int> vi; // Get input stream and end of stream iterators istream_iterator<int> cin_it(cin); istream_iterator<int> eos; // Get output stream iterators ostream_iterator<int> cout_it(cout, \" \"); // Copy even integer elements from input to vector using for_each function for_each(cin_it, eos, [&](int a) { if (a % 2 == 0) { // if a is even push it to vector vi.push_back(a); } }); // Sort the vector sort(vi.begin(), vi.end()); // Copy elements from vector to output copy(vi.begin(), vi.end(), cout_it); return 0;}",
"e": 32830,
"s": 31930,
"text": null
},
{
"code": null,
"e": 32876,
"s": 32830,
"text": "Input: 1 4 3 2 6 8 31 52 \nOutput: 2 4 6 8 52 "
},
{
"code": null,
"e": 32922,
"s": 32876,
"text": "References: istream_iterator ostream_iterator"
},
{
"code": null,
"e": 32933,
"s": 32922,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32947,
"s": 32933,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 32964,
"s": 32947,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 32979,
"s": 32964,
"text": "adnanirshad158"
},
{
"code": null,
"e": 32992,
"s": 32979,
"text": "cpp-iterator"
},
{
"code": null,
"e": 33004,
"s": 32992,
"text": "CPP-Library"
},
{
"code": null,
"e": 33008,
"s": 33004,
"text": "STL"
},
{
"code": null,
"e": 33012,
"s": 33008,
"text": "C++"
},
{
"code": null,
"e": 33016,
"s": 33012,
"text": "STL"
},
{
"code": null,
"e": 33020,
"s": 33016,
"text": "CPP"
},
{
"code": null,
"e": 33118,
"s": 33020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33142,
"s": 33118,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 33170,
"s": 33142,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 33190,
"s": 33170,
"text": "Constructors in C++"
},
{
"code": null,
"e": 33218,
"s": 33190,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 33242,
"s": 33218,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 33277,
"s": 33242,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 33308,
"s": 33277,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 33332,
"s": 33308,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 33352,
"s": 33332,
"text": "Polymorphism in C++"
}
] |
Impala - Select Statement
|
Impala SELECT statement is used to fetch the data from one or more tables in a database. This query returns data in the form of tables.
Following is the syntax of the Impala select statement.
SELECT column1, column2, columnN from table_name;
Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −
SELECT * FROM table_name;
Assume we have a table named customers in Impala, with the following data −
ID NAME AGE ADDRESS SALARY
--- ------- --- ---------- -------
1 Ramesh 32 Ahmedabad 20000
2 Khilan 25 Delhi 15000
3 Hardik 27 Bhopal 40000
4 Chaitali 25 Mumbai 35000
5 kaushik 23 Kota 30000
6 Komal 22 Mp 32000
You can fetch the id, name, and age of all the records of the customers table using select statement as shown below −
[quickstart.cloudera:21000] > select id, name, age from customers;
On executing the above query, Impala fetches id, name, age of all the records from the specified table and displays them as shown below.
Query: select id,name,age from customers
+----+----------+-----+
| id | name | age |
| 1 | Ramesh | 32 |
| 2 | Khilan | 25 |
| 3 | Hardik | 27 |
| 4 | Chaitali | 25 |
| 5 | kaushik | 23 |
| 6 | Komal | 22 |
+----+----------+-----+
Fetched 6 row(s) in 0.66s
You can also fetch all the records from the customers table using the select query as shown below.
[quickstart.cloudera:21000] > select name, age from customers;
Query: select * from customers
On executing the above query, Impala fetches and displays all the records from the specified table as shown below.
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 3 | Hardik | 27 | Bhopal | 40000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 5 | kaushik | 23 | Kota | 30000 |
| 6 | Komal | 22 | MP | 32000 |
+----+----------+-----+-----------+--------+
Fetched 6 row(s) in 0.66s
Open Impala Query editor and type the select Statement in it. And click on the execute button as shown in the following screenshot.
After executing the query, if you scroll down and select the Results tab, you can see the list of the records of the specified table as shown below.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2421,
"s": 2285,
"text": "Impala SELECT statement is used to fetch the data from one or more tables in a database. This query returns data in the form of tables."
},
{
"code": null,
"e": 2477,
"s": 2421,
"text": "Following is the syntax of the Impala select statement."
},
{
"code": null,
"e": 2528,
"s": 2477,
"text": "SELECT column1, column2, columnN from table_name;\n"
},
{
"code": null,
"e": 2711,
"s": 2528,
"text": "Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −"
},
{
"code": null,
"e": 2738,
"s": 2711,
"text": "SELECT * FROM table_name;\n"
},
{
"code": null,
"e": 2814,
"s": 2738,
"text": "Assume we have a table named customers in Impala, with the following data −"
},
{
"code": null,
"e": 3162,
"s": 2814,
"text": "ID NAME AGE ADDRESS SALARY\n--- ------- --- ---------- -------\n1 Ramesh 32 Ahmedabad 20000\n2 Khilan 25 Delhi 15000\n3 Hardik 27 Bhopal 40000\n4 Chaitali 25 Mumbai 35000\n5 kaushik 23 Kota 30000\n6 Komal 22 Mp 32000\n"
},
{
"code": null,
"e": 3280,
"s": 3162,
"text": "You can fetch the id, name, and age of all the records of the customers table using select statement as shown below −"
},
{
"code": null,
"e": 3348,
"s": 3280,
"text": "[quickstart.cloudera:21000] > select id, name, age from customers;\n"
},
{
"code": null,
"e": 3485,
"s": 3348,
"text": "On executing the above query, Impala fetches id, name, age of all the records from the specified table and displays them as shown below."
},
{
"code": null,
"e": 3771,
"s": 3485,
"text": "Query: select id,name,age from customers\n\n+----+----------+-----+\n| id | name | age |\n| 1 | Ramesh | 32 |\n| 2 | Khilan | 25 |\n| 3 | Hardik | 27 |\n| 4 | Chaitali | 25 |\n| 5 | kaushik | 23 |\n| 6 | Komal | 22 |\n+----+----------+-----+\n\nFetched 6 row(s) in 0.66s\n"
},
{
"code": null,
"e": 3870,
"s": 3771,
"text": "You can also fetch all the records from the customers table using the select query as shown below."
},
{
"code": null,
"e": 3966,
"s": 3870,
"text": "[quickstart.cloudera:21000] > select name, age from customers; \nQuery: select * from customers\n"
},
{
"code": null,
"e": 4081,
"s": 3966,
"text": "On executing the above query, Impala fetches and displays all the records from the specified table as shown below."
},
{
"code": null,
"e": 4559,
"s": 4081,
"text": "+----+----------+-----+-----------+--------+\n| id | name | age | address | salary |\n+----+----------+-----+-----------+--------+\n| 1 | Ramesh | 32 | Ahmedabad | 20000 |\n| 2 | Khilan | 25 | Delhi | 15000 |\n| 3 | Hardik | 27 | Bhopal | 40000 |\n| 4 | Chaitali | 25 | Mumbai | 35000 |\n| 5 | kaushik | 23 | Kota | 30000 |\n| 6 | Komal | 22 | MP | 32000 |\n+----+----------+-----+-----------+--------+\n\nFetched 6 row(s) in 0.66s\n"
},
{
"code": null,
"e": 4691,
"s": 4559,
"text": "Open Impala Query editor and type the select Statement in it. And click on the execute button as shown in the following screenshot."
},
{
"code": null,
"e": 4840,
"s": 4691,
"text": "After executing the query, if you scroll down and select the Results tab, you can see the list of the records of the specified table as shown below."
},
{
"code": null,
"e": 4847,
"s": 4840,
"text": " Print"
},
{
"code": null,
"e": 4858,
"s": 4847,
"text": " Add Notes"
}
] |
Collectors toList() method in Java 8
|
The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.
The syntax is as follows −
static <T> Collector<T,?,List<T>> toList()
Here, parameter T is the type of input elements.
To work with Collectors class in Java, import the following package −
import java.util.stream.Collectors;
The following is an example to implement Collectors toList() method in Java −
Live Demo
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("25", "40", "90", "150", "180", "220", "350");
List<String> list = stream.collect(Collectors.toList());
System.out.println("List = "+list);
}
}
List = [25, 40, 90, 150, 180, 220, 350]
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List."
},
{
"code": null,
"e": 1206,
"s": 1179,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1249,
"s": 1206,
"text": "static <T> Collector<T,?,List<T>> toList()"
},
{
"code": null,
"e": 1298,
"s": 1249,
"text": "Here, parameter T is the type of input elements."
},
{
"code": null,
"e": 1368,
"s": 1298,
"text": "To work with Collectors class in Java, import the following package −"
},
{
"code": null,
"e": 1404,
"s": 1368,
"text": "import java.util.stream.Collectors;"
},
{
"code": null,
"e": 1482,
"s": 1404,
"text": "The following is an example to implement Collectors toList() method in Java −"
},
{
"code": null,
"e": 1493,
"s": 1482,
"text": " Live Demo"
},
{
"code": null,
"e": 1848,
"s": 1493,
"text": "import java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class Demo {\n public static void main(String[] args) {\n Stream<String> stream = Stream.of(\"25\", \"40\", \"90\", \"150\", \"180\", \"220\", \"350\");\n List<String> list = stream.collect(Collectors.toList());\n System.out.println(\"List = \"+list);\n }\n}"
},
{
"code": null,
"e": 1888,
"s": 1848,
"text": "List = [25, 40, 90, 150, 180, 220, 350]"
}
] |
C# Program to Convert a Binary String to an Integer - GeeksforGeeks
|
02 Jul, 2020
Given an binary string as input, we need to write a program to convert the binary string into equivalent integer. To convert an binary string to integer, we have to use Convert.ToInt32(String, Base/Int32) function to convert the values. The base of the binary is 2.
Syntax:
Convert.ToInt32(String, Base/Int32);
Examples:
Input : 1010101010101010
Output : 43690
Input : 1100011000
111100001111
11001100110011001100
Output : 792
3855
838860
Program 1:
csharp
// C# program to convert array// of binary string to an integerusing System;using System.Text; class GFG { static void Main(string[] args) { // binary number as string string bin_strng = "1010101010101010"; int number = 0; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine("Number value of binary \"{0}\" is = {1}", bin_strng, number); }}
Output:
Number value of binary "1010101010101010" is = 43690
Program 2:
C#
// C# program to convert array// of binary string to an integerusing System;using System.Text; namespace geeks {class GFG { static void Main(string[] args) { // binary number as string string bin_strng = "1100011000"; int number = 0; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine("Number value of binary \"{0}\" is = {1}", bin_strng, number); bin_strng = "111100001111"; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine("Number value of binary \"{0}\" is = {1}", bin_strng, number); bin_strng = "11001100110011001100"; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine("Number value of binary \"{0}\" is = {1}", bin_strng, number); // hit ENTER to exit Console.ReadLine(); }}}
Output:
Number value of binary "1100011000" is = 792
Number value of binary "111100001111" is = 3855
Number value of binary "11001100110011001100" is = 838860
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Convert String to Character Array in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to Print a New Line in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 23781,
"s": 23753,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 24048,
"s": 23781,
"text": "Given an binary string as input, we need to write a program to convert the binary string into equivalent integer. To convert an binary string to integer, we have to use Convert.ToInt32(String, Base/Int32) function to convert the values. The base of the binary is 2. "
},
{
"code": null,
"e": 24057,
"s": 24048,
"text": "Syntax: "
},
{
"code": null,
"e": 24096,
"s": 24057,
"text": " Convert.ToInt32(String, Base/Int32);\n"
},
{
"code": null,
"e": 24106,
"s": 24096,
"text": "Examples:"
},
{
"code": null,
"e": 24262,
"s": 24106,
"text": "Input : 1010101010101010\nOutput : 43690\n\nInput : 1100011000\n 111100001111\n 11001100110011001100\n\nOutput : 792\n 3855\n 838860\n"
},
{
"code": null,
"e": 24275,
"s": 24262,
"text": "Program 1: "
},
{
"code": null,
"e": 24282,
"s": 24275,
"text": "csharp"
},
{
"code": "// C# program to convert array// of binary string to an integerusing System;using System.Text; class GFG { static void Main(string[] args) { // binary number as string string bin_strng = \"1010101010101010\"; int number = 0; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine(\"Number value of binary \\\"{0}\\\" is = {1}\", bin_strng, number); }}",
"e": 24779,
"s": 24282,
"text": null
},
{
"code": null,
"e": 24787,
"s": 24779,
"text": "Output:"
},
{
"code": null,
"e": 24841,
"s": 24787,
"text": "Number value of binary \"1010101010101010\" is = 43690\n"
},
{
"code": null,
"e": 24854,
"s": 24841,
"text": "Program 2: "
},
{
"code": null,
"e": 24857,
"s": 24854,
"text": "C#"
},
{
"code": "// C# program to convert array// of binary string to an integerusing System;using System.Text; namespace geeks {class GFG { static void Main(string[] args) { // binary number as string string bin_strng = \"1100011000\"; int number = 0; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine(\"Number value of binary \\\"{0}\\\" is = {1}\", bin_strng, number); bin_strng = \"111100001111\"; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine(\"Number value of binary \\\"{0}\\\" is = {1}\", bin_strng, number); bin_strng = \"11001100110011001100\"; // converting to integer number = Convert.ToInt32(bin_strng, 2); // to print the value Console.WriteLine(\"Number value of binary \\\"{0}\\\" is = {1}\", bin_strng, number); // hit ENTER to exit Console.ReadLine(); }}}",
"e": 25964,
"s": 24857,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25964,
"text": "Output: "
},
{
"code": null,
"e": 26125,
"s": 25973,
"text": "Number value of binary \"1100011000\" is = 792\nNumber value of binary \"111100001111\" is = 3855\nNumber value of binary \"11001100110011001100\" is = 838860\n"
},
{
"code": null,
"e": 26128,
"s": 26125,
"text": "C#"
},
{
"code": null,
"e": 26140,
"s": 26128,
"text": "C# Programs"
},
{
"code": null,
"e": 26238,
"s": 26140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26247,
"s": 26238,
"text": "Comments"
},
{
"code": null,
"e": 26260,
"s": 26247,
"text": "Old Comments"
},
{
"code": null,
"e": 26283,
"s": 26260,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26311,
"s": 26283,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26357,
"s": 26311,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26372,
"s": 26357,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26412,
"s": 26372,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26452,
"s": 26412,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26498,
"s": 26452,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 26523,
"s": 26498,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 26557,
"s": 26523,
"text": "Program to Print a New Line in C#"
}
] |
HBase - Update Data
|
You can update an existing cell value using the put command. To do so, just follow the same syntax and mention your new value as shown below.
put ‘table name’,’row ’,'Column family:column name',’new value’
The newly given value replaces the existing value, updating the row.
Suppose there is a table in HBase called emp with the following data.
hbase(main):003:0> scan 'emp'
ROW COLUMN + CELL
row1 column = personal:name, timestamp = 1418051555, value = raju
row1 column = personal:city, timestamp = 1418275907, value = Hyderabad
row1 column = professional:designation, timestamp = 14180555,value = manager
row1 column = professional:salary, timestamp = 1418035791555,value = 50000
1 row(s) in 0.0100 seconds
The following command will update the city value of the employee named ‘Raju’ to Delhi.
hbase(main):002:0> put 'emp','row1','personal:city','Delhi'
0 row(s) in 0.0400 seconds
The updated table looks as follows where you can observe the city of Raju has been changed to ‘Delhi’.
hbase(main):003:0> scan 'emp'
ROW COLUMN + CELL
row1 column = personal:name, timestamp = 1418035791555, value = raju
row1 column = personal:city, timestamp = 1418274645907, value = Delhi
row1 column = professional:designation, timestamp = 141857555,value = manager
row1 column = professional:salary, timestamp = 1418039555, value = 50000
1 row(s) in 0.0100 seconds
You can update the data in a particular cell using the put() method. Follow the steps given below to update an existing cell value of a table.
Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below.
Configuration conf = HbaseConfiguration.create();
You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below.
HTable hTable = new HTable(conf, tableName);
To insert data into HBase Table, the add() method and its variants are used. This method belongs to Put, therefore instantiate the put class. This class requires the row name you want to insert the data into, in string format. You can instantiate the Put class as shown below.
Put p = new Put(Bytes.toBytes("row1"));
The add() method of Put class is used to insert data. It requires 3 byte arrays representing column family, column qualifier (column name), and the value to be inserted, respectively. Insert data into HBase table using the add() method as shown below.
p.add(Bytes.toBytes("coloumn family "), Bytes.toBytes("column
name"),Bytes.toBytes("value"));
p.add(Bytes.toBytes("personal"),
Bytes.toBytes("city"),Bytes.toBytes("Delih"));
After inserting the required rows, save the changes by adding the put instance
to the put() method of the HTable class as shown below.
hTable.put(p);
After creating data in HBase Table, close the HTable instance using the close() method as shown below.
hTable.close();
Given below is the complete program to update data in a particular table.
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
public class UpdateData{
public static void main(String[] args) throws IOException {
// Instantiating Configuration class
Configuration config = HBaseConfiguration.create();
// Instantiating HTable class
HTable hTable = new HTable(config, "emp");
// Instantiating Put class
//accepts a row name
Put p = new Put(Bytes.toBytes("row1"));
// Updating a cell value
p.add(Bytes.toBytes("personal"),
Bytes.toBytes("city"),Bytes.toBytes("Delih"));
// Saving the put Instance to the HTable.
hTable.put(p);
System.out.println("data Updated");
// closing HTable
hTable.close();
}
}
Compile and execute the above program as shown below.
$javac UpdateData.java
$java UpdateData
The following should be the output:
data Updated
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2179,
"s": 2037,
"text": "You can update an existing cell value using the put command. To do so, just follow the same syntax and mention your new value as shown below."
},
{
"code": null,
"e": 2244,
"s": 2179,
"text": "put ‘table name’,’row ’,'Column family:column name',’new value’\n"
},
{
"code": null,
"e": 2313,
"s": 2244,
"text": "The newly given value replaces the existing value, updating the row."
},
{
"code": null,
"e": 2383,
"s": 2313,
"text": "Suppose there is a table in HBase called emp with the following data."
},
{
"code": null,
"e": 2762,
"s": 2383,
"text": "hbase(main):003:0> scan 'emp'\n ROW COLUMN + CELL\nrow1 column = personal:name, timestamp = 1418051555, value = raju\nrow1 column = personal:city, timestamp = 1418275907, value = Hyderabad\nrow1 column = professional:designation, timestamp = 14180555,value = manager\nrow1 column = professional:salary, timestamp = 1418035791555,value = 50000\n1 row(s) in 0.0100 seconds\n"
},
{
"code": null,
"e": 2850,
"s": 2762,
"text": "The following command will update the city value of the employee named ‘Raju’ to Delhi."
},
{
"code": null,
"e": 2938,
"s": 2850,
"text": "hbase(main):002:0> put 'emp','row1','personal:city','Delhi'\n0 row(s) in 0.0400 seconds\n"
},
{
"code": null,
"e": 3041,
"s": 2938,
"text": "The updated table looks as follows where you can observe the city of Raju has been changed to ‘Delhi’."
},
{
"code": null,
"e": 3418,
"s": 3041,
"text": "hbase(main):003:0> scan 'emp'\n ROW COLUMN + CELL\nrow1 column = personal:name, timestamp = 1418035791555, value = raju\nrow1 column = personal:city, timestamp = 1418274645907, value = Delhi\nrow1 column = professional:designation, timestamp = 141857555,value = manager\nrow1 column = professional:salary, timestamp = 1418039555, value = 50000\n1 row(s) in 0.0100 seconds\n"
},
{
"code": null,
"e": 3561,
"s": 3418,
"text": "You can update the data in a particular cell using the put() method. Follow the steps given below to update an existing cell value of a table."
},
{
"code": null,
"e": 3739,
"s": 3561,
"text": "Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below."
},
{
"code": null,
"e": 3790,
"s": 3739,
"text": "Configuration conf = HbaseConfiguration.create();\n"
},
{
"code": null,
"e": 4075,
"s": 3790,
"text": "You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below."
},
{
"code": null,
"e": 4121,
"s": 4075,
"text": "HTable hTable = new HTable(conf, tableName);\n"
},
{
"code": null,
"e": 4398,
"s": 4121,
"text": "To insert data into HBase Table, the add() method and its variants are used. This method belongs to Put, therefore instantiate the put class. This class requires the row name you want to insert the data into, in string format. You can instantiate the Put class as shown below."
},
{
"code": null,
"e": 4439,
"s": 4398,
"text": "Put p = new Put(Bytes.toBytes(\"row1\"));\n"
},
{
"code": null,
"e": 4691,
"s": 4439,
"text": "The add() method of Put class is used to insert data. It requires 3 byte arrays representing column family, column qualifier (column name), and the value to be inserted, respectively. Insert data into HBase table using the add() method as shown below."
},
{
"code": null,
"e": 4866,
"s": 4691,
"text": "p.add(Bytes.toBytes(\"coloumn family \"), Bytes.toBytes(\"column\nname\"),Bytes.toBytes(\"value\"));\np.add(Bytes.toBytes(\"personal\"),\nBytes.toBytes(\"city\"),Bytes.toBytes(\"Delih\"));\n"
},
{
"code": null,
"e": 5001,
"s": 4866,
"text": "After inserting the required rows, save the changes by adding the put instance\nto the put() method of the HTable class as shown below."
},
{
"code": null,
"e": 5018,
"s": 5001,
"text": "hTable.put(p); \n"
},
{
"code": null,
"e": 5121,
"s": 5018,
"text": "After creating data in HBase Table, close the HTable instance using the close() method as shown below."
},
{
"code": null,
"e": 5138,
"s": 5121,
"text": "hTable.close();\n"
},
{
"code": null,
"e": 5212,
"s": 5138,
"text": "Given below is the complete program to update data in a particular table."
},
{
"code": null,
"e": 6145,
"s": 5212,
"text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.client.HTable;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.util.Bytes;\n\npublic class UpdateData{\n\n public static void main(String[] args) throws IOException {\n\n // Instantiating Configuration class\n Configuration config = HBaseConfiguration.create();\n\n // Instantiating HTable class\n HTable hTable = new HTable(config, \"emp\");\n\n // Instantiating Put class\n //accepts a row name\n Put p = new Put(Bytes.toBytes(\"row1\"));\n\n // Updating a cell value\n p.add(Bytes.toBytes(\"personal\"),\n Bytes.toBytes(\"city\"),Bytes.toBytes(\"Delih\"));\n\n // Saving the put Instance to the HTable.\n hTable.put(p);\n System.out.println(\"data Updated\");\n\n // closing HTable\n hTable.close();\n }\n}"
},
{
"code": null,
"e": 6199,
"s": 6145,
"text": "Compile and execute the above program as shown below."
},
{
"code": null,
"e": 6240,
"s": 6199,
"text": "$javac UpdateData.java\n$java UpdateData\n"
},
{
"code": null,
"e": 6276,
"s": 6240,
"text": "The following should be the output:"
},
{
"code": null,
"e": 6290,
"s": 6276,
"text": "data Updated\n"
},
{
"code": null,
"e": 6297,
"s": 6290,
"text": " Print"
},
{
"code": null,
"e": 6308,
"s": 6297,
"text": " Add Notes"
}
] |
Tokenizing a string in C++ - GeeksforGeeks
|
14 Dec, 2021
Tokenizing a string denotes splitting a string with respect to some delimiter(s). There are many ways to tokenize a string. In this article four of them are explained:
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream.
Below is the C++ implementation :
C++
// Tokenizing a string using stringstream#include <bits/stdc++.h> using namespace std; int main(){ string line = "GeeksForGeeks is a must try"; // Vector of string to save tokens vector <string> tokens; // stringstream class check1 stringstream check1(line); string intermediate; // Tokenizing w.r.t. space ' ' while(getline(check1, intermediate, ' ')) { tokens.push_back(intermediate); } // Printing the token vector for(int i = 0; i < tokens.size(); i++) cout << tokens[i] << '\n';}
GeeksForGeeks
is
a
must
try
// Splits str[] according to given delimiters.
// and returns next token. It needs to be called
// in a loop to get all tokens. It returns NULL
// when there are no more tokens.
char * strtok(char str[], const char *delims);
Below is the C++ implementation :
C++
// C/C++ program for splitting a string// using strtok()#include <stdio.h>#include <string.h> int main(){ char str[] = "Geeks-for-Geeks"; // Returns first token char *token = strtok(str, "-"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf("%s\n", token); token = strtok(NULL, "-"); } return 0;}
Geeks
for
Geeks
C
// C code to demonstrate working of// strtok#include <string.h>#include <stdio.h> // Driver functionint main(){ // Declaration of string char gfg[100] = " Geeks - for - geeks - Contribute"; // Declaration of delimiter const char s[4] = "-"; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf(" %s\n", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}
Geeks
for
geeks
Contribute
Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok().
There are two ways we can call strtok_r()
// The third argument saveptr is a pointer to a char *
// variable that is used internally by strtok_r() in
// order to maintain context between successive calls
// that parse the same string.
char *strtok_r(char *str, const char *delim, char **saveptr);
Below is a simple C++ program to show the use of strtok_r() :
C++
// C/C++ program to demonstrate working of strtok_r()// by splitting string based on space character.#include<stdio.h>#include<string.h> int main(){ char str[] = "Geeks for Geeks"; char *token; char *rest = str; while ((token = strtok_r(rest, " ", &rest))) printf("%s\n", token); return(0);}
Geeks
for
Geeks
In this method the tokenization is done on the basis of regex matches. Better for use cases when multiple delimiters are needed.
Below is a simple C++ program to show the use of std::sregex_token_iterator:
C++
// CPP program for above approach#include <iostream>#include <regex>#include <string>#include <vector> /** * @brief Tokenize the given vector according to the regex * and remove the empty tokens. * * @param str * @param re * @return std::vector<std::string> */std::vector<std::string> tokenize( const std::string str, const std::regex re){ std::sregex_token_iterator it{ str.begin(), str.end(), re, -1 }; std::vector<std::string> tokenized{ it, {} }; // Additional check to remove empty strings tokenized.erase( std::remove_if(tokenized.begin(), tokenized.end(), [](std::string const& s) { return s.size() == 0; }), tokenized.end()); return tokenized;} // Driver Codeint main(){ const std::string str = "Break string a,spaces,and,commas"; const std::regex re(R"([\s|,]+)"); // Function Call const std::vector<std::string> tokenized = tokenize(str, re); for (std::string token : tokenized) std::cout << token << std::endl; return 0;}
Break
string
a
spaces
and
commas
mani00manu
akshaysingh98088
cpp-string
cpp-stringstream
C Language
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
|
[
{
"code": null,
"e": 26571,
"s": 26543,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 26739,
"s": 26571,
"text": "Tokenizing a string denotes splitting a string with respect to some delimiter(s). There are many ways to tokenize a string. In this article four of them are explained:"
},
{
"code": null,
"e": 26856,
"s": 26739,
"text": "A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream."
},
{
"code": null,
"e": 26891,
"s": 26856,
"text": "Below is the C++ implementation : "
},
{
"code": null,
"e": 26895,
"s": 26891,
"text": "C++"
},
{
"code": "// Tokenizing a string using stringstream#include <bits/stdc++.h> using namespace std; int main(){ string line = \"GeeksForGeeks is a must try\"; // Vector of string to save tokens vector <string> tokens; // stringstream class check1 stringstream check1(line); string intermediate; // Tokenizing w.r.t. space ' ' while(getline(check1, intermediate, ' ')) { tokens.push_back(intermediate); } // Printing the token vector for(int i = 0; i < tokens.size(); i++) cout << tokens[i] << '\\n';}",
"e": 27460,
"s": 26895,
"text": null
},
{
"code": null,
"e": 27488,
"s": 27460,
"text": "GeeksForGeeks\nis\na\nmust\ntry"
},
{
"code": null,
"e": 27713,
"s": 27488,
"text": "// Splits str[] according to given delimiters.\n// and returns next token. It needs to be called\n// in a loop to get all tokens. It returns NULL\n// when there are no more tokens.\nchar * strtok(char str[], const char *delims);"
},
{
"code": null,
"e": 27748,
"s": 27713,
"text": "Below is the C++ implementation : "
},
{
"code": null,
"e": 27752,
"s": 27748,
"text": "C++"
},
{
"code": "// C/C++ program for splitting a string// using strtok()#include <stdio.h>#include <string.h> int main(){ char str[] = \"Geeks-for-Geeks\"; // Returns first token char *token = strtok(str, \"-\"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf(\"%s\\n\", token); token = strtok(NULL, \"-\"); } return 0;}",
"e": 28149,
"s": 27752,
"text": null
},
{
"code": null,
"e": 28165,
"s": 28149,
"text": "Geeks\nfor\nGeeks"
},
{
"code": null,
"e": 28169,
"s": 28167,
"text": "C"
},
{
"code": "// C code to demonstrate working of// strtok#include <string.h>#include <stdio.h> // Driver functionint main(){ // Declaration of string char gfg[100] = \" Geeks - for - geeks - Contribute\"; // Declaration of delimiter const char s[4] = \"-\"; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf(\" %s\\n\", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}",
"e": 28689,
"s": 28169,
"text": null
},
{
"code": null,
"e": 28727,
"s": 28689,
"text": " Geeks \n for \n geeks \n Contribute"
},
{
"code": null,
"e": 28885,
"s": 28727,
"text": "Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok()."
},
{
"code": null,
"e": 28928,
"s": 28885,
"text": "There are two ways we can call strtok_r() "
},
{
"code": null,
"e": 29185,
"s": 28928,
"text": "// The third argument saveptr is a pointer to a char * \n// variable that is used internally by strtok_r() in \n// order to maintain context between successive calls\n// that parse the same string.\nchar *strtok_r(char *str, const char *delim, char **saveptr);"
},
{
"code": null,
"e": 29248,
"s": 29185,
"text": "Below is a simple C++ program to show the use of strtok_r() : "
},
{
"code": null,
"e": 29252,
"s": 29248,
"text": "C++"
},
{
"code": "// C/C++ program to demonstrate working of strtok_r()// by splitting string based on space character.#include<stdio.h>#include<string.h> int main(){ char str[] = \"Geeks for Geeks\"; char *token; char *rest = str; while ((token = strtok_r(rest, \" \", &rest))) printf(\"%s\\n\", token); return(0);}",
"e": 29568,
"s": 29252,
"text": null
},
{
"code": null,
"e": 29584,
"s": 29568,
"text": "Geeks\nfor\nGeeks"
},
{
"code": null,
"e": 29713,
"s": 29584,
"text": "In this method the tokenization is done on the basis of regex matches. Better for use cases when multiple delimiters are needed."
},
{
"code": null,
"e": 29790,
"s": 29713,
"text": "Below is a simple C++ program to show the use of std::sregex_token_iterator:"
},
{
"code": null,
"e": 29794,
"s": 29790,
"text": "C++"
},
{
"code": "// CPP program for above approach#include <iostream>#include <regex>#include <string>#include <vector> /** * @brief Tokenize the given vector according to the regex * and remove the empty tokens. * * @param str * @param re * @return std::vector<std::string> */std::vector<std::string> tokenize( const std::string str, const std::regex re){ std::sregex_token_iterator it{ str.begin(), str.end(), re, -1 }; std::vector<std::string> tokenized{ it, {} }; // Additional check to remove empty strings tokenized.erase( std::remove_if(tokenized.begin(), tokenized.end(), [](std::string const& s) { return s.size() == 0; }), tokenized.end()); return tokenized;} // Driver Codeint main(){ const std::string str = \"Break string a,spaces,and,commas\"; const std::regex re(R\"([\\s|,]+)\"); // Function Call const std::vector<std::string> tokenized = tokenize(str, re); for (std::string token : tokenized) std::cout << token << std::endl; return 0;}",
"e": 31005,
"s": 29794,
"text": null
},
{
"code": null,
"e": 31038,
"s": 31005,
"text": "Break\nstring\na\nspaces\nand\ncommas"
},
{
"code": null,
"e": 31049,
"s": 31038,
"text": "mani00manu"
},
{
"code": null,
"e": 31066,
"s": 31049,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 31077,
"s": 31066,
"text": "cpp-string"
},
{
"code": null,
"e": 31094,
"s": 31077,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 31105,
"s": 31094,
"text": "C Language"
},
{
"code": null,
"e": 31109,
"s": 31105,
"text": "C++"
},
{
"code": null,
"e": 31117,
"s": 31109,
"text": "Strings"
},
{
"code": null,
"e": 31125,
"s": 31117,
"text": "Strings"
},
{
"code": null,
"e": 31129,
"s": 31125,
"text": "CPP"
},
{
"code": null,
"e": 31227,
"s": 31129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31236,
"s": 31227,
"text": "Comments"
},
{
"code": null,
"e": 31249,
"s": 31236,
"text": "Old Comments"
},
{
"code": null,
"e": 31327,
"s": 31249,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 31350,
"s": 31327,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 31377,
"s": 31350,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 31405,
"s": 31377,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 31451,
"s": 31405,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 31469,
"s": 31451,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 31515,
"s": 31469,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 31538,
"s": 31515,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 31565,
"s": 31538,
"text": "Bitwise Operators in C/C++"
}
] |
How To Change The MySQL Data Directory to Another Location on Ubuntu 16.04
|
In this article, we will learn how to change the MySQL Data Directory or relocate the MySQL Database data to the new location, this situation may be used when the database is growing very fast, or for some security reasons we want to move the data directory to the new location.
An Ubuntu machine with a non-root user with Sudo permission.
MySQL installed and working.
A new volume or location where we want to move the database data location, the new location will be /mnt/data_vol/MySQL as the data_vol is the new volume attached to the machine or server.
Before we proceed further, we will first find the current location of the data directory
$ mysql –u root –p
Output:
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 472
Server version: 5.6.30-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
When prompted for the root password of the MySQL, please enter the password. Run the below command to know the current working data directory for MySQL.
Mysql> select @@datadir;
Output:
+-----------------+
| @@datadir |
+-----------------+
| /var/lib/mysql/ |
+-----------------+
1 row in set (0.00 sec)
As the output will show that the MySQL database uses the /var/lib/MySQL as the default folder as the data directory. Before we modify anything first, we will check the integrity of the data, we will stop the MySQL and check the status
$ sudo systemctl stop mysql
As systemctl will not display anything for the services command
$ sudo systemctl status mysql
Output:
mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Mon 2016-09-12 13:57:43 IST; 1s ago
Process: 17669 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCCESS)
Process: 17668 ExecStart=/usr/sbin/mysqld (code=exited, status=0/SUCCESS)
Process: 17664 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
Main PID: 17668 (code=exited, status=0/SUCCESS)
Sep 12 13:55:14 ubuntu-16 systemd[1]: Starting MySQL Community Server...
Sep 12 13:55:15 ubuntu-16 systemd[1]: Started MySQL Community Server.
Sep 12 13:57:40 ubuntu-16 systemd[1]: Stopping MySQL Community Server...
Sep 12 13:57:43 ubuntu-16 systemd[1]: Stopped MySQL Community Server.
Once, we confirm that the MySQL is stopped, we will move the data to the new location. To move the data, we will use Rsync with –a option which preserves the permission of the data files and –v which show the verbose output.
Below is the full command to move the data to the new location –
$ rsync –av /var/lib/mysql /mnt/data_vol/
OutPut:
sending incremental file list
mysql/
mysql/auto.cnf
mysql/debian-5.7.flag
mysql/ib_buffer_pool
mysql/ib_logfile0
mysql/ib_logfile1
mysql/ibdata1
mysql/mysql/
mysql/mysql/columns_priv.MYD
mysql/mysql/columns_priv.MYI
mysql/mysql/columns_priv.frm
mysql/mysql/db.MYD
mysql/mysql/db.MYI
mysql/mysql/db.frm
mysql/mysql/db.opt
....
mysql/sys/x@0024user_summary.frmmysql/sys/x@0024user_summary_by_file_io.frm
mysql/sys/x@0024user_summary_by_file_io_type.frm
mysql/sys/x@0024user_summary_by_stages.frm
mysql/sys/x@0024user_summary_by_statement_latency.frm
mysql/sys/x@0024user_summary_by_statement_type.frm
mysql/sys/x@0024wait_classes_global_by_avg_latency.frm
mysql/sys/x@0024wait_classes_global_by_latency.frm
mysql/sys/x@0024waits_by_host_by_latency.frm
mysqlsys//x@0024waits_by_user_by_latency.frm
mysql/sys/x@0024waits_global_by_latency.frm
sent 199,384,083 bytes received 6,858 bytes 132,927,294.00 bytes/sec
total size is 199,307,568 speedup is 1.00
After the rsync, successfully move the data folder to the new location. For security reasons we will keep the data folder till confirms that the data is at the new location, we will rename the present data directory from /var/lib/mysql to /var/lib/mysql_backup. below is the command to change the current data directory.
Below is the command to change the current data directory –
$ sudo mv /var/lib/mysql /var/lib/mysql_backup
Now, we will change the default data directory, for changing we have a lot of ways, but we will edit the mysqld.cnf file which is located in the /etc/mysql/mysql.conf.d/mysqld.cnf.
To edit the mysqld.cnf, below is the command
$ sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
Output:
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /mnt/data_vol/mysql/
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
Also, we needed to edit the /etc/apparmor.d/tunables/alias
At the bottom of the file, we needed to add the following lines in the alias rules.
$ sudo vi /etc/apparmor.d/tunables/alias
Output:
# ------------------------------------------------------------------
#
# Copyright (C) 2010 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ------------------------------------------------------------------
# Alias rules can be used to rewrite paths and are done after variable
# resolution. For example, if '/usr' is on removable media:
# alias /usr/ -> /mnt/usr/,
#
# Or if mysql databases are stored in /home:
# alias /var/lib/mysql/ -> /home/mysql/,
alias /var/lib/mysql/ -> /mnt/data_vol/mysql
Once the file is edited, we need to restart the apparmor.
Below is the command to restart the apparmor.
As we have changed the default data directory, we needed to run the below command which will create the minimal directory folder structure to pass the script environments.
$ sudo mkdir /var/lib/mysql/mysql –p
Now we will restart the mysql services.
$ sudo systemctl start mysql
Now we will check the status of the MySQL services with the below command
$ sudo systemctl status mysql
Output:
mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2016-09-12 14:17:27 IST; 23s ago
Process: 18481 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCC
Process: 18477 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCES
Main PID: 18480 (mysqld)
Tasks: 28 (limit: 512)
Memory: 137.3M
CPU: 329ms
CGroup: /system.slice/mysql.service
└─18480 /usr/sbin/mysqld
Sep 12 14:17:26 ubuntu-16 systemd[1]: Starting MySQL Community Server...
Sep 12 14:17:27 ubuntu-16 systemd[1]: Started MySQL Community Server.
To make sure that the new data directory is changed, we will run the below command
$ mysql -uroot -p
Output:
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.13-0ubuntu0.16.04.2 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select @@datadir
+----------------------+
| @@datadir |
+----------------------+
| /mnt/data_vol/mysql/ |
+-----------------+
1 row in set (0.00 sec)
mysql>
Once we confirm that the data directory is changed, we will remove the default data directory which at /var/lib/mysql_backup, below is the command to remove the old database directory.
$ sudo rm –rf /var/lib/mysql_backup
In the above configuration and steps, we have learned to relocate the MySQL data directory to the new location which will help us to secure or to store more data to a different location.
|
[
{
"code": null,
"e": 1341,
"s": 1062,
"text": "In this article, we will learn how to change the MySQL Data Directory or relocate the MySQL Database data to the new location, this situation may be used when the database is growing very fast, or for some security reasons we want to move the data directory to the new location."
},
{
"code": null,
"e": 1402,
"s": 1341,
"text": "An Ubuntu machine with a non-root user with Sudo permission."
},
{
"code": null,
"e": 1431,
"s": 1402,
"text": "MySQL installed and working."
},
{
"code": null,
"e": 1620,
"s": 1431,
"text": "A new volume or location where we want to move the database data location, the new location will be /mnt/data_vol/MySQL as the data_vol is the new volume attached to the machine or server."
},
{
"code": null,
"e": 1709,
"s": 1620,
"text": "Before we proceed further, we will first find the current location of the data directory"
},
{
"code": null,
"e": 2189,
"s": 1709,
"text": "$ mysql –u root –p\nOutput:\nEnter password:\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 472\nServer version: 5.6.30-0ubuntu0.14.04.1 (Ubuntu)\nCopyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective owners.\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\nmysql>"
},
{
"code": null,
"e": 2342,
"s": 2189,
"text": "When prompted for the root password of the MySQL, please enter the password. Run the below command to know the current working data directory for MySQL."
},
{
"code": null,
"e": 2499,
"s": 2342,
"text": "Mysql> select @@datadir;\nOutput:\n+-----------------+\n| @@datadir |\n+-----------------+\n| /var/lib/mysql/ |\n+-----------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2734,
"s": 2499,
"text": "As the output will show that the MySQL database uses the /var/lib/MySQL as the default folder as the data directory. Before we modify anything first, we will check the integrity of the data, we will stop the MySQL and check the status"
},
{
"code": null,
"e": 2762,
"s": 2734,
"text": "$ sudo systemctl stop mysql"
},
{
"code": null,
"e": 2826,
"s": 2762,
"text": "As systemctl will not display anything for the services command"
},
{
"code": null,
"e": 3683,
"s": 2826,
"text": "$ sudo systemctl status mysql\nOutput:\nmysql.service - MySQL Community Server\n Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)\n Active: inactive (dead) since Mon 2016-09-12 13:57:43 IST; 1s ago\n Process: 17669 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCCESS)\n Process: 17668 ExecStart=/usr/sbin/mysqld (code=exited, status=0/SUCCESS)\n Process: 17664 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)\n Main PID: 17668 (code=exited, status=0/SUCCESS)\nSep 12 13:55:14 ubuntu-16 systemd[1]: Starting MySQL Community Server...\nSep 12 13:55:15 ubuntu-16 systemd[1]: Started MySQL Community Server.\nSep 12 13:57:40 ubuntu-16 systemd[1]: Stopping MySQL Community Server...\nSep 12 13:57:43 ubuntu-16 systemd[1]: Stopped MySQL Community Server."
},
{
"code": null,
"e": 3908,
"s": 3683,
"text": "Once, we confirm that the MySQL is stopped, we will move the data to the new location. To move the data, we will use Rsync with –a option which preserves the permission of the data files and –v which show the verbose output."
},
{
"code": null,
"e": 3973,
"s": 3908,
"text": "Below is the full command to move the data to the new location –"
},
{
"code": null,
"e": 4973,
"s": 3973,
"text": "$ rsync –av /var/lib/mysql /mnt/data_vol/\nOutPut:\nsending incremental file list\nmysql/\nmysql/auto.cnf\nmysql/debian-5.7.flag\nmysql/ib_buffer_pool\nmysql/ib_logfile0\nmysql/ib_logfile1\nmysql/ibdata1\nmysql/mysql/\nmysql/mysql/columns_priv.MYD\nmysql/mysql/columns_priv.MYI\nmysql/mysql/columns_priv.frm\nmysql/mysql/db.MYD\nmysql/mysql/db.MYI\nmysql/mysql/db.frm\nmysql/mysql/db.opt\n....\nmysql/sys/x@0024user_summary.frmmysql/sys/x@0024user_summary_by_file_io.frm\nmysql/sys/x@0024user_summary_by_file_io_type.frm\nmysql/sys/x@0024user_summary_by_stages.frm\nmysql/sys/x@0024user_summary_by_statement_latency.frm\nmysql/sys/x@0024user_summary_by_statement_type.frm\nmysql/sys/x@0024wait_classes_global_by_avg_latency.frm\nmysql/sys/x@0024wait_classes_global_by_latency.frm\nmysql/sys/x@0024waits_by_host_by_latency.frm\nmysqlsys//x@0024waits_by_user_by_latency.frm\nmysql/sys/x@0024waits_global_by_latency.frm\nsent 199,384,083 bytes received 6,858 bytes 132,927,294.00 bytes/sec\ntotal size is 199,307,568 speedup is 1.00"
},
{
"code": null,
"e": 5294,
"s": 4973,
"text": "After the rsync, successfully move the data folder to the new location. For security reasons we will keep the data folder till confirms that the data is at the new location, we will rename the present data directory from /var/lib/mysql to /var/lib/mysql_backup. below is the command to change the current data directory."
},
{
"code": null,
"e": 5354,
"s": 5294,
"text": "Below is the command to change the current data directory –"
},
{
"code": null,
"e": 5401,
"s": 5354,
"text": "$ sudo mv /var/lib/mysql /var/lib/mysql_backup"
},
{
"code": null,
"e": 5582,
"s": 5401,
"text": "Now, we will change the default data directory, for changing we have a lot of ways, but we will edit the mysqld.cnf file which is located in the /etc/mysql/mysql.conf.d/mysqld.cnf."
},
{
"code": null,
"e": 5627,
"s": 5582,
"text": "To edit the mysqld.cnf, below is the command"
},
{
"code": null,
"e": 6067,
"s": 5627,
"text": "$ sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf\nOutput:\n[mysqld_safe]\nsocket = /var/run/mysqld/mysqld.sock\nnice = 0\n[mysqld]\n#\n# * Basic Settings\n#\nuser = mysql\npid-file = /var/run/mysqld/mysqld.pid\nsocket = /var/run/mysqld/mysqld.sock\nport = 3306\nbasedir = /usr\ndatadir = /mnt/data_vol/mysql/\ntmpdir = /tmp\nlc-messages-dir = /usr/share/mysql\nskip-external-locking"
},
{
"code": null,
"e": 6126,
"s": 6067,
"text": "Also, we needed to edit the /etc/apparmor.d/tunables/alias"
},
{
"code": null,
"e": 6210,
"s": 6126,
"text": "At the bottom of the file, we needed to add the following lines in the alias rules."
},
{
"code": null,
"e": 6915,
"s": 6210,
"text": "$ sudo vi /etc/apparmor.d/tunables/alias\nOutput:\n# ------------------------------------------------------------------\n#\n# Copyright (C) 2010 Canonical Ltd.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of version 2 of the GNU General Public\n# License published by the Free Software Foundation.\n#\n# ------------------------------------------------------------------\n# Alias rules can be used to rewrite paths and are done after variable\n# resolution. For example, if '/usr' is on removable media:\n# alias /usr/ -> /mnt/usr/,\n#\n# Or if mysql databases are stored in /home:\n# alias /var/lib/mysql/ -> /home/mysql/,\nalias /var/lib/mysql/ -> /mnt/data_vol/mysql"
},
{
"code": null,
"e": 6973,
"s": 6915,
"text": "Once the file is edited, we need to restart the apparmor."
},
{
"code": null,
"e": 7019,
"s": 6973,
"text": "Below is the command to restart the apparmor."
},
{
"code": null,
"e": 7191,
"s": 7019,
"text": "As we have changed the default data directory, we needed to run the below command which will create the minimal directory folder structure to pass the script environments."
},
{
"code": null,
"e": 7228,
"s": 7191,
"text": "$ sudo mkdir /var/lib/mysql/mysql –p"
},
{
"code": null,
"e": 7268,
"s": 7228,
"text": "Now we will restart the mysql services."
},
{
"code": null,
"e": 7297,
"s": 7268,
"text": "$ sudo systemctl start mysql"
},
{
"code": null,
"e": 7371,
"s": 7297,
"text": "Now we will check the status of the MySQL services with the below command"
},
{
"code": null,
"e": 8112,
"s": 7371,
"text": "$ sudo systemctl status mysql\nOutput:\nmysql.service - MySQL Community Server\n Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)\n Active: active (running) since Mon 2016-09-12 14:17:27 IST; 23s ago\n Process: 18481 ExecStartPost=/usr/share/mysql/mysql-systemd-start post (code=exited, status=0/SUCC\n Process: 18477 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCES\n Main PID: 18480 (mysqld)\n Tasks: 28 (limit: 512)\n Memory: 137.3M\n CPU: 329ms\nCGroup: /system.slice/mysql.service\n └─18480 /usr/sbin/mysqld\nSep 12 14:17:26 ubuntu-16 systemd[1]: Starting MySQL Community Server...\nSep 12 14:17:27 ubuntu-16 systemd[1]: Started MySQL Community Server."
},
{
"code": null,
"e": 8195,
"s": 8112,
"text": "To make sure that the new data directory is changed, we will run the below command"
},
{
"code": null,
"e": 8840,
"s": 8195,
"text": "$ mysql -uroot -p\nOutput:\nEnter password:\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 3\nServer version: 5.7.13-0ubuntu0.16.04.2 (Ubuntu)\nCopyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective owners.\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\nmysql> select @@datadir\n+----------------------+\n| @@datadir |\n+----------------------+\n| /mnt/data_vol/mysql/ |\n+-----------------+\n1 row in set (0.00 sec)\nmysql>"
},
{
"code": null,
"e": 9025,
"s": 8840,
"text": "Once we confirm that the data directory is changed, we will remove the default data directory which at /var/lib/mysql_backup, below is the command to remove the old database directory."
},
{
"code": null,
"e": 9061,
"s": 9025,
"text": "$ sudo rm –rf /var/lib/mysql_backup"
},
{
"code": null,
"e": 9248,
"s": 9061,
"text": "In the above configuration and steps, we have learned to relocate the MySQL data directory to the new location which will help us to secure or to store more data to a different location."
}
] |
Features of Structured Query Language (SQL) - GeeksforGeeks
|
30 Nov, 2021
Structured Query Language (SQL) is the standard language used for writing queries in a databases. It was approved by ISO (International Standard Organization) and ANSI(American National Standards Institute).
SQL contains of some important features and they are:
Data Definition language (DDL): It contains of commands which defines the data. The commands are:
Data Definition language (DDL): It contains of commands which defines the data. The commands are:
create: It is used to create a table. Syntax:
create table
tablename(attribute1 datatype......attributen datatype);
drop: It is used to delete the table including all the attributes. Syntax:
drop table tablename;
alter: alter is a reserve word which modifies the structure of the table. Syntax:
alter table
tablename add(new column1 datatype......new columnx datatype);
rename: A table name can be changed using the reserver ‘rename’ Syntax:
rename old table name to new table name;
2. Data Manipulation Language (DML): Data Manipulation Language contains commands used to manipulate the data. The commands are:
insert: This command is generally used after the create command to insert a set of values into the table. Syntax:
insert into tablename values(attribute1 datatype);
:
:
:
insert into tablename values (attributen datatype);
delete: A command used to delete particular tuples or rows or cardinality from the table. Syntax:
delete from tablename where condition;
update: It updates the tuples in a table. Syntax:
update tablename set tuplename='attributename';
Triggers: Triggers are actions performed when certain conditions are met on the data. A trigger contains of three parts. (i). event – The change in the database that activates the trigger is event. (ii). condition – A query or test that is run when the trigger is activated. (iii). action – A procedure that is executed when trigger is activated and the condition met is true.
A trigger contains of three parts.
(i). event – The change in the database that activates the trigger is event.
(ii). condition – A query or test that is run when the trigger is activated.
(iii). action – A procedure that is executed when trigger is activated and the condition met is true.
2. Client server execution and remote database access: Client server technology maintains a many to one relationship of clients(many) and server(one). We have commands in SQL that control how a client application can access the database over a network.
3. Security and authentication: SQL provides a mechanism to control the database meaning it makes sure that only the particular details of the database is to be shown the user and the original database is secured by DBMS.
4. Embedded SQL: SQL provides the feature of embedding host languages such as C, COBOL, Java for query from their language at runtime.
5. Transaction Control Language: Transactions are an important element of DBMS and to control the transactions, TCL is used which has commands like commit, rollback and savepoint.
commit: It saves the database at any point whenever database is consistent. Syntax:
commit;
rollback: It rollbacks/undo to the previous point of the transaction. Syntax:
rollback;
savepoint: It goes back to the previous transaction without going back to the entire transaction. Syntax:
savepoint;
6. Advanced SQL: The current features include OOP ones like recursive queries, decision supporting queries and also query supporting areas like data mining, spatial data and XML(Xtensible Markup Language).
simmytarika5
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of ER Model
Introduction of DBMS (Database Management System) | Set 1
SQL Interview Questions
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
|
[
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24249,
"s": 24040,
"text": "Structured Query Language (SQL) is the standard language used for writing queries in a databases. It was approved by ISO (International Standard Organization) and ANSI(American National Standards Institute). "
},
{
"code": null,
"e": 24304,
"s": 24249,
"text": "SQL contains of some important features and they are: "
},
{
"code": null,
"e": 24403,
"s": 24304,
"text": "Data Definition language (DDL): It contains of commands which defines the data. The commands are: "
},
{
"code": null,
"e": 24502,
"s": 24403,
"text": "Data Definition language (DDL): It contains of commands which defines the data. The commands are: "
},
{
"code": null,
"e": 24549,
"s": 24502,
"text": "create: It is used to create a table. Syntax: "
},
{
"code": null,
"e": 24621,
"s": 24549,
"text": "create table \ntablename(attribute1 datatype......attributen datatype); "
},
{
"code": null,
"e": 24697,
"s": 24621,
"text": "drop: It is used to delete the table including all the attributes. Syntax: "
},
{
"code": null,
"e": 24720,
"s": 24697,
"text": "drop table tablename; "
},
{
"code": null,
"e": 24803,
"s": 24720,
"text": "alter: alter is a reserve word which modifies the structure of the table. Syntax: "
},
{
"code": null,
"e": 24880,
"s": 24803,
"text": "alter table \ntablename add(new column1 datatype......new columnx datatype); "
},
{
"code": null,
"e": 24953,
"s": 24880,
"text": "rename: A table name can be changed using the reserver ‘rename’ Syntax: "
},
{
"code": null,
"e": 24995,
"s": 24953,
"text": "rename old table name to new table name; "
},
{
"code": null,
"e": 25157,
"s": 24995,
"text": " 2. Data Manipulation Language (DML): Data Manipulation Language contains commands used to manipulate the data. The commands are: "
},
{
"code": null,
"e": 25272,
"s": 25157,
"text": "insert: This command is generally used after the create command to insert a set of values into the table. Syntax: "
},
{
"code": null,
"e": 25382,
"s": 25272,
"text": "insert into tablename values(attribute1 datatype);\n:\n:\n:\ninsert into tablename values (attributen datatype); "
},
{
"code": null,
"e": 25481,
"s": 25382,
"text": "delete: A command used to delete particular tuples or rows or cardinality from the table. Syntax: "
},
{
"code": null,
"e": 25521,
"s": 25481,
"text": "delete from tablename where condition; "
},
{
"code": null,
"e": 25572,
"s": 25521,
"text": "update: It updates the tuples in a table. Syntax: "
},
{
"code": null,
"e": 25621,
"s": 25572,
"text": "update tablename set tuplename='attributename'; "
},
{
"code": null,
"e": 26002,
"s": 25621,
"text": "Triggers: Triggers are actions performed when certain conditions are met on the data. A trigger contains of three parts. (i). event – The change in the database that activates the trigger is event. (ii). condition – A query or test that is run when the trigger is activated. (iii). action – A procedure that is executed when trigger is activated and the condition met is true. "
},
{
"code": null,
"e": 26038,
"s": 26002,
"text": "A trigger contains of three parts. "
},
{
"code": null,
"e": 26117,
"s": 26038,
"text": "(i). event – The change in the database that activates the trigger is event. "
},
{
"code": null,
"e": 26196,
"s": 26117,
"text": "(ii). condition – A query or test that is run when the trigger is activated. "
},
{
"code": null,
"e": 26300,
"s": 26196,
"text": "(iii). action – A procedure that is executed when trigger is activated and the condition met is true. "
},
{
"code": null,
"e": 26601,
"s": 26300,
"text": " 2. Client server execution and remote database access: Client server technology maintains a many to one relationship of clients(many) and server(one). We have commands in SQL that control how a client application can access the database over a network. "
},
{
"code": null,
"e": 26864,
"s": 26601,
"text": " 3. Security and authentication: SQL provides a mechanism to control the database meaning it makes sure that only the particular details of the database is to be shown the user and the original database is secured by DBMS. "
},
{
"code": null,
"e": 27026,
"s": 26864,
"text": " 4. Embedded SQL: SQL provides the feature of embedding host languages such as C, COBOL, Java for query from their language at runtime. "
},
{
"code": null,
"e": 27233,
"s": 27026,
"text": " 5. Transaction Control Language: Transactions are an important element of DBMS and to control the transactions, TCL is used which has commands like commit, rollback and savepoint. "
},
{
"code": null,
"e": 27318,
"s": 27233,
"text": "commit: It saves the database at any point whenever database is consistent. Syntax: "
},
{
"code": null,
"e": 27327,
"s": 27318,
"text": "commit; "
},
{
"code": null,
"e": 27406,
"s": 27327,
"text": "rollback: It rollbacks/undo to the previous point of the transaction. Syntax: "
},
{
"code": null,
"e": 27417,
"s": 27406,
"text": "rollback; "
},
{
"code": null,
"e": 27524,
"s": 27417,
"text": "savepoint: It goes back to the previous transaction without going back to the entire transaction. Syntax: "
},
{
"code": null,
"e": 27536,
"s": 27524,
"text": "savepoint; "
},
{
"code": null,
"e": 27775,
"s": 27536,
"text": " 6. Advanced SQL: The current features include OOP ones like recursive queries, decision supporting queries and also query supporting areas like data mining, spatial data and XML(Xtensible Markup Language). "
},
{
"code": null,
"e": 27788,
"s": 27775,
"text": "simmytarika5"
},
{
"code": null,
"e": 27793,
"s": 27788,
"text": "DBMS"
},
{
"code": null,
"e": 27797,
"s": 27793,
"text": "SQL"
},
{
"code": null,
"e": 27802,
"s": 27797,
"text": "DBMS"
},
{
"code": null,
"e": 27806,
"s": 27802,
"text": "SQL"
},
{
"code": null,
"e": 27904,
"s": 27806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27927,
"s": 27904,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27980,
"s": 27927,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28005,
"s": 27980,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 28063,
"s": 28005,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 28087,
"s": 28063,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 28129,
"s": 28087,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 28173,
"s": 28129,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 28194,
"s": 28173,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 28260,
"s": 28194,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Contour plots - GeeksforGeeks
|
22 Jan, 2021
A contour plot is a graphical method to visualize the 3-D surface by plotting constant Z slices called contours in a 2-D format. The contour plot is an alternative to a 3-D surface plot
The contour plot is formed by:
Vertical axis: Independent variable 2
Horizontal axis: Independent variable 1
Lines: iso-response values, can be calculated with the help (x,y).
The independent variable usually restricted to a regular grid. The actual techniques for determining the correct iso-response values are rather complex and almost always computer-generated.
The contour plot is used to depict the change in Z values as compared to X and Y values. If the data (or function) do not form a regular grid, you typically need to perform a 2-D interpolation to form a regular grid.
For one variable data, a run sequence/ histogram is considered necessary. For two-variable data, a scatter plot is considered necessary. The contour plots can also polar co-ordinates (r,theta) instead of traditional rectangular (x, y, z) coordinates.
Rectangular Contour plot: A projection of 2D-plot in 2D-rectangular canvas. It is the most common form of the contour plot.
Polar contour plot: Polar contour plot is plotted by using the polar coordinates r and theta. The response variable here is the collection of values generated while passing r and theta into the given function, where r is the distance from origin and theta is the angle from the positive x axis.
Ternary contour plot: Ternary contour plot is used to represent the relationship between 3 explanatory variables and the response variable in the form of a filled triangle.
Contour plot can be plotted in different programming languages:
Python/ Matplotlib: Contour plot can be plotted using plt.contour or plt.contourf functions, where plt is matplotlib.pyplot. The difference between these two that plot.contour generates hollow contour plot, the plt.contourf generated filled.
Matlab: functions such as contourf (2d-plot) and contour3 (3D-contour) can be used for contour plotting
R: can create a contour plot with filled.contour functions in R.
Rectangular Contour Plot: Below is the sample code for plotting rectangular contour plots in Python and matplotlib.
Python3
# importsimport numpy as npimport matplotlib.pyplot as plt## define a functiondef func(x, y): return np.sin(x) ** 2 + np.cos(y) **2# generate 50 values b/w 0 a5x = np.linspace(0, 5, 50)y = np.linspace(0, 5, 50) # Generate combination of gridsX, Y = np.meshgrid(x, y)Z = func(X, Y) # Draw rectangular contour plotplt.contour(X, Y, Z, cmap='gist_rainbow_r');
Polar Contour plot: For plotting polar contour plot we need to define first r and theta. Below is the sample code for plotting polar contour plots using matplotlib subplots.
Python3
# generate r and theta arraysrad_arr = np.radians(np.linspace(0, 360, 20))r_arr = np.arange(0, 1, .1)# define functiondef func(r, theta): return r * np.sin(theta) r, theta = np.meshgrid(r_arr, rad_arr)# get the values of response variablesvalues = func(r,theta) # plot the polar coordinatesfig, ax = plt.subplots(subplot_kw=dict(projection='polar'))ax.contourf(theta, r, values, cmap='Spectral_r') plt.show()
Polar contour plot
Ternary Contour Plot: Matplotlib does not provide a definitive API for plotting Ternary Contour plot, however, there are many other package which does that. IN this example, we will be using Plotly library.
Python3
# install & import plotly! pip install plotlyimport plotly.figure_factory as ff # Define variablesa = np.array([0. , 0. , 0., 0., 1./3, 1./3, 1./3, 2./3, 2./3, 1.])b = np.array([0., 1./3, 2./3, 1., 0., 1./3, 2./3, 0., 1./3, 0.])c = 1 - a - b# Define function that generates response variablefunc = (a - 0.02) * b * (a - 0.5) * (b - 0.4) * (c - 1)**2 # plot ternary contourfig = ff.create_ternary_contour(np.array([a, b, c]), func, pole_labels=['a', 'b', 'c'], interp_mode='cartesian', colorscale='Viridis',)fig.show()
Ternary Contour plot
NIST Handbook
Plotly Library
Data Visualization
ML-EDA
ML-plots
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Search Algorithms in AI
Python | Decision tree implementation
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24270,
"s": 24242,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 24456,
"s": 24270,
"text": "A contour plot is a graphical method to visualize the 3-D surface by plotting constant Z slices called contours in a 2-D format. The contour plot is an alternative to a 3-D surface plot"
},
{
"code": null,
"e": 24487,
"s": 24456,
"text": "The contour plot is formed by:"
},
{
"code": null,
"e": 24525,
"s": 24487,
"text": "Vertical axis: Independent variable 2"
},
{
"code": null,
"e": 24565,
"s": 24525,
"text": "Horizontal axis: Independent variable 1"
},
{
"code": null,
"e": 24632,
"s": 24565,
"text": "Lines: iso-response values, can be calculated with the help (x,y)."
},
{
"code": null,
"e": 24822,
"s": 24632,
"text": "The independent variable usually restricted to a regular grid. The actual techniques for determining the correct iso-response values are rather complex and almost always computer-generated."
},
{
"code": null,
"e": 25039,
"s": 24822,
"text": "The contour plot is used to depict the change in Z values as compared to X and Y values. If the data (or function) do not form a regular grid, you typically need to perform a 2-D interpolation to form a regular grid."
},
{
"code": null,
"e": 25291,
"s": 25039,
"text": "For one variable data, a run sequence/ histogram is considered necessary. For two-variable data, a scatter plot is considered necessary. The contour plots can also polar co-ordinates (r,theta) instead of traditional rectangular (x, y, z) coordinates. "
},
{
"code": null,
"e": 25415,
"s": 25291,
"text": "Rectangular Contour plot: A projection of 2D-plot in 2D-rectangular canvas. It is the most common form of the contour plot."
},
{
"code": null,
"e": 25710,
"s": 25415,
"text": "Polar contour plot: Polar contour plot is plotted by using the polar coordinates r and theta. The response variable here is the collection of values generated while passing r and theta into the given function, where r is the distance from origin and theta is the angle from the positive x axis."
},
{
"code": null,
"e": 25883,
"s": 25710,
"text": "Ternary contour plot: Ternary contour plot is used to represent the relationship between 3 explanatory variables and the response variable in the form of a filled triangle."
},
{
"code": null,
"e": 25947,
"s": 25883,
"text": "Contour plot can be plotted in different programming languages:"
},
{
"code": null,
"e": 26189,
"s": 25947,
"text": "Python/ Matplotlib: Contour plot can be plotted using plt.contour or plt.contourf functions, where plt is matplotlib.pyplot. The difference between these two that plot.contour generates hollow contour plot, the plt.contourf generated filled."
},
{
"code": null,
"e": 26293,
"s": 26189,
"text": "Matlab: functions such as contourf (2d-plot) and contour3 (3D-contour) can be used for contour plotting"
},
{
"code": null,
"e": 26358,
"s": 26293,
"text": "R: can create a contour plot with filled.contour functions in R."
},
{
"code": null,
"e": 26474,
"s": 26358,
"text": "Rectangular Contour Plot: Below is the sample code for plotting rectangular contour plots in Python and matplotlib."
},
{
"code": null,
"e": 26482,
"s": 26474,
"text": "Python3"
},
{
"code": "# importsimport numpy as npimport matplotlib.pyplot as plt## define a functiondef func(x, y): return np.sin(x) ** 2 + np.cos(y) **2# generate 50 values b/w 0 a5x = np.linspace(0, 5, 50)y = np.linspace(0, 5, 50) # Generate combination of gridsX, Y = np.meshgrid(x, y)Z = func(X, Y) # Draw rectangular contour plotplt.contour(X, Y, Z, cmap='gist_rainbow_r');",
"e": 26846,
"s": 26482,
"text": null
},
{
"code": null,
"e": 27020,
"s": 26846,
"text": "Polar Contour plot: For plotting polar contour plot we need to define first r and theta. Below is the sample code for plotting polar contour plots using matplotlib subplots."
},
{
"code": null,
"e": 27028,
"s": 27020,
"text": "Python3"
},
{
"code": "# generate r and theta arraysrad_arr = np.radians(np.linspace(0, 360, 20))r_arr = np.arange(0, 1, .1)# define functiondef func(r, theta): return r * np.sin(theta) r, theta = np.meshgrid(r_arr, rad_arr)# get the values of response variablesvalues = func(r,theta) # plot the polar coordinatesfig, ax = plt.subplots(subplot_kw=dict(projection='polar'))ax.contourf(theta, r, values, cmap='Spectral_r') plt.show()",
"e": 27442,
"s": 27028,
"text": null
},
{
"code": null,
"e": 27461,
"s": 27442,
"text": "Polar contour plot"
},
{
"code": null,
"e": 27668,
"s": 27461,
"text": "Ternary Contour Plot: Matplotlib does not provide a definitive API for plotting Ternary Contour plot, however, there are many other package which does that. IN this example, we will be using Plotly library."
},
{
"code": null,
"e": 27676,
"s": 27668,
"text": "Python3"
},
{
"code": "# install & import plotly! pip install plotlyimport plotly.figure_factory as ff # Define variablesa = np.array([0. , 0. , 0., 0., 1./3, 1./3, 1./3, 2./3, 2./3, 1.])b = np.array([0., 1./3, 2./3, 1., 0., 1./3, 2./3, 0., 1./3, 0.])c = 1 - a - b# Define function that generates response variablefunc = (a - 0.02) * b * (a - 0.5) * (b - 0.4) * (c - 1)**2 # plot ternary contourfig = ff.create_ternary_contour(np.array([a, b, c]), func, pole_labels=['a', 'b', 'c'], interp_mode='cartesian', colorscale='Viridis',)fig.show()",
"e": 28289,
"s": 27676,
"text": null
},
{
"code": null,
"e": 28310,
"s": 28289,
"text": "Ternary Contour plot"
},
{
"code": null,
"e": 28324,
"s": 28310,
"text": "NIST Handbook"
},
{
"code": null,
"e": 28339,
"s": 28324,
"text": "Plotly Library"
},
{
"code": null,
"e": 28358,
"s": 28339,
"text": "Data Visualization"
},
{
"code": null,
"e": 28365,
"s": 28358,
"text": "ML-EDA"
},
{
"code": null,
"e": 28374,
"s": 28365,
"text": "ML-plots"
},
{
"code": null,
"e": 28391,
"s": 28374,
"text": "Machine Learning"
},
{
"code": null,
"e": 28398,
"s": 28391,
"text": "Python"
},
{
"code": null,
"e": 28415,
"s": 28398,
"text": "Machine Learning"
},
{
"code": null,
"e": 28513,
"s": 28415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28536,
"s": 28513,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28550,
"s": 28536,
"text": "Decision Tree"
},
{
"code": null,
"e": 28574,
"s": 28550,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 28612,
"s": 28574,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28652,
"s": 28612,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28680,
"s": 28652,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28730,
"s": 28680,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28752,
"s": 28730,
"text": "Python map() function"
}
] |
How to Create a Simple Object Detection System with Python and ImageAI | by Ruben Winastwan | Towards Data Science
|
We all can agree that object detection is one of the most popular topics in Computer Vision. The problem is, creating an object detection system from scratch requires deep technical knowledge in Deep Learning and a huge amount of resources on your hardware.
If you look at the common object detection models like ResNet, YOLO, NASNet, or RCNN, they all have a deep stack of layers. It requires technical knowledge and also a huge amount of time to make them work. All of these factors would be a challenge for people who just want to implement object detection algorithms to solve their problems.
Fortunately, nowadays we can implement object detection algorithms in an easy way, even with just few lines of code. With ImageAI library, we can create our image or video object detection system in a quick and easy way. I’ll show you how in this article.
Below are the steps on what we’re going to do in this article:
Introduction
Creating image object detection
Creating video object detection
So, let’s get started right away.
As previously mentioned, we’re going to create an image and a video object detection system with the help of ImageAI. ImageAI is a Python library to enable ML practitioners to build an object detection system with only a few lines of code.
Before we start, we need to install some of the dependencies that we will need to run ImageAI properly. These dependencies are:
Numpy
pip install numpy==1.16.1
TensorFlow
pip install tensorflow==1.14.0
TensorFlow GPU
pip install tensorflow-gpu==1.14.0
Keras
pip install keras==2.2.4
OpenCV
pip install opencv-python
After installing all of those libraries, then we can start to install ImageAI library by typing the following command in your prompt:
pip install imageai --upgrade
Next, we are ready to build our object detection system for image and for video.
To start creating an image object detection system, first let’s import the libraries that we’re going to use and also set our current working directory.
from imageai.Detection import ObjectDetectionimport oscurrent_directory = os.getcwd()
As we want to implement an object detection in an easy and quick way, we will use a pretrained model specific for object detection that has been trained on COCO dataset.
There are three different pretrained models that you can choose with ImageAI: RetinaNet, YOLOv3, and tinyYOLOv3. You can download the model of your choice here.
After you’ve downloaded the model, place the h5 file in the same directory as your Python script. Your working directory should now has the following structure.
root_folder/ python_script.py pretrain_model.h5
Back to our Python script, we now can instantiate the ObjectDetection class that we have imported before. Depending on the model that you have downloaded before, we need to call a proper method from ObjectDetection class. Below is the code implementation for that.
detector = ObjectDetection()# if you use RetinaNet model, call the following methoddetector.setModelTypeAsRetinaNet()# if you use YOLOv3 model, call the following methoddetector.setModelTypeAsYOLOv3()# if you use tinyYOLOv3 model, call the following methoddetector.setModelTypeAsTinyYOLOv3()
Next, we can start to load the model by first specifying the path to our model. Since our model is in the same directory as our Python script, here I show you how to load the RetinaNet model. If you use YOLOv3 or tinyYOLOv3, you need to change the file name of your h5 file accordingly.
detector.setModelPath(os.path.join(current_directory , "resnet50_coco_best_v2.0.1.h5"))detector.loadModel()
Finally, we can start to create an image object detection system. To do this, we need to specify two things: First, the directory and the filename of our input image and second, the directory and the filename of the output image.
In the following code implementation, the input image will be an image called ‘traffic.jpg’ that is located in the same directory as the Python script. Meanwhile, the detection result will be saved in a file called ‘traffic_detected.jpg’ in the same directory.
detections = detector.detectObjectsFromImage(input_image = os.path.join(current_directory, "traffic.jpg"), output_image_path = os.path.join(current_directory , "traffic_detected.jpg"))for eachObject in detections: print( eachObject["name"] , " : ", eachObject["percentage_probability"], " : ", eachObject["box_points"] ) print("--------------------------------")
And that’s the code that we need to instantiate our image object detection system. Below is the full code implementation of the steps that we have covered above:
If you run the complete code above, you’ll get more or less similar result on the image of your choice.
If you use the default value that we have seen in the implementation above, you might think that somehow the result of the object detection is overcrowded, with several bounding boxes overlapping one another.
In order to reduce the clutter in the prediction result, you can tune the object detector such that it only shows the object that really matters for you.
Let’s use the image above as an example. Let’s say I want the object detector to predict only the people and the bicycle. To do this, we need to instantiate CustomObjects method. Then, we pass the name of the objects that we want the system to detect as the argument.
custom = detector.CustomObjects(person=True, bicycle=True)
Next, we can start to build the object detection system with detectCustomObjectsFromImage method. We pass our custom variable, the path and name of our input image, as well as the path and name of our output image.
detections = detector.detectCustomObjectsFromImage(custom_objects = custom,input_image = os.path.join(current_directory, "traffic.jpg"), output_image_path = os.path.join(current_directory , "traffic_detected.jpg"))
Moreover, we can also further remove the clutter by ignoring the predictions that have probability values below a certain threshold value. Let’s say that you want to ignore the predictions with probability value below 70%. You can do that by adding the minimum_percentage_probability argument in the detectCustomObjectsFromImage method.
detections = detector.detectCustomObjectsFromImage(custom_objects = custom,input_image = os.path.join(current_directory, "traffic.jpg"), output_image_path = os.path.join(current_directory , "traffic_detected.jpg"),minimum_percentage_probability = 70)
Below is the complete code implementation when we want to detect only people and bicycle from our image, and we also only want to show the detection where the probability value is above 70%.
If you run the code above, you’ll get more or less the result like this:
And that’s it! With just a few lines of code now you can implement an object detection system for your own image. However, what if you want to detect objects in a video or even from your webcam instead of an image? Let’s find out how to create a similar object detection for video with ImageAI in the next section.
Believe it or not, the code to create a video object detection system with ImageAI is pretty much similar with the image object detection system we’ve built before. All we need to do is changing 3 lines of code.
The first one is the library that we should import. So instead of ObjectDetection , we need to import VideoObjectDetection .
from imageai.Detection import VideoObjectDetection
The second change that we should apply is the step where we instantiate object detection class. Instead of using ObjectDetection() , we should use VideoObjectDetection() .
detector = VideoObjectDetection()
Next, the third or the final change that we should apply is when we create the object detection system. In our previous code, we use detectObjectsFromImage method. If we want to detect objects from a video, we need to use detectObjectsFromVideo instead.
detections = detector.detectObjectsFromVideo( input_file_path=os.path.join(current_directory, "footage.mp4"), output_file_path=os.path.join(current_directory,"footage_detected"))
As you can see, the argument that we need to pass into this method is still the same as before. First, we need to specify the path to our video directory and the filename of our video. Second, we also need to specify the path and the filename of the output video.
Below is the entire code implementation to create a video object detection system.
Now if you run the code implementation above, you’ll get more or less similar result as below.
Note: if you somehow don’t get the same color format in your output video, i.e you get the output video that is in BGR format instead of RGB format, you can use the code below to convert the output video back to RGB format.
All you need to do is specifying the path and the filename of the video that you want to convert as well as the converted video.
Same as our image object detection system, we can also fine tune our video object detection system a little bit. We have the option to pick which objects that we want to detect and to select the threshold for the probability value that should be displayed.
Let’s say we want to only detect people and bicycle for our video object detection system. Also, we only want to show the detections that have the probability value above 70%. We can do so by first instantiating a variable to store the objects that we want to observe.
custom = detector.CustomObjects(person=True, bicycle=True)
Next, we can create our video object detection system with our custom objects. To do so, we call the detectCustomObjectsFromVideo method. For the arguments of this method, we pass our custom variable, path and filename of our input and output video, frames per second, as well as the minimum threshold for probability value.
detections = detector.detectCustomObjectsFromVideo( custom_objects = custom, input_file_path=os.path.join(execution_path, "footage.mp4"), output_file_path=os.path.join(execution_path, "footage_detected"), frames_per_second=20, log_progress=True, minimum_percentage_probability = 70)
Below is the complete code implementation if you want to only detect people and bicycle which has a probability value above 70%.
Now what if you want to create an object detection system with your camera feeds as your input? Creating this system with ImageAI is also very straightforward. The code itself is very much similar with our video object detection system. You only need to add one line of code and also change one line of code to do this.
First, we need to create a variable to instantiate the OpenCV library to capture the frame directly from our webcam.
camera = cv2.VideoCapture(0)
Finally, we need to change the argument in detectObjectsFromVideo method. Instead of specifying the input file path, we need to specify our camera input, which is the camera variable that we’ve created above.
detections = detector.detectObjectsFromVideo( camera_input = camera, output_file_path = os.path.join(current_directory,"camera_detected_video"), frames_per_second=20, log_progress=True)
Below is the complete code implementation to create an object detection system directly from your webcam.
Again, if you somehow get the a different color format in your output video, you can use the aforementioned code to convert the output from BGR to RGB format.
Now you already know how to create a quick and easy object detection system with ImageAI. As you have seen, ImageAI library enables us to build an object detection system without having to deal with the complexity behind object detection model like ResNet or YOLO.
Note that with the pretrained model supported by ImageAI, the object detector can detect 80 different objects. These objects are:
person, bicycle, car, motorcycle, airplane, bus, train, truck, boat, traffic light, fire hydrant, stop_sign, parking meter, bench, bird, cat, dog, horse, sheep, cow, elephant, bear,zebra, giraffe, backpack, umbrella, handbag, tie, suitcase, frisbee, skis, snowboard, sports ball, kite, baseball bat, baseball glove, skateboard, surfboard, tennis racket, bottle, wine glass, cup, fork, knife, spoon, bowl, banana, apple, sandwich, orange, broccoli, carrot, hot dog, pizza, donot, cake, chair, couch, potted plant, bed, dining table, toilet, tv, laptop, mouse, remote, keyboard, cell phone, microwave, oven, toaster, sink, refrigerator, book, clock, vase, scissors, teddy bear, hair dryer, toothbrush.
Now the question is, what if you want to create a custom object detection system with your own label that is not included in the list above?
You can create your own custom object detection with ImageAI as well. I will show you how to do so in another post.
That’s all for now and I hope that this article is somehow useful for you.
|
[
{
"code": null,
"e": 429,
"s": 171,
"text": "We all can agree that object detection is one of the most popular topics in Computer Vision. The problem is, creating an object detection system from scratch requires deep technical knowledge in Deep Learning and a huge amount of resources on your hardware."
},
{
"code": null,
"e": 768,
"s": 429,
"text": "If you look at the common object detection models like ResNet, YOLO, NASNet, or RCNN, they all have a deep stack of layers. It requires technical knowledge and also a huge amount of time to make them work. All of these factors would be a challenge for people who just want to implement object detection algorithms to solve their problems."
},
{
"code": null,
"e": 1024,
"s": 768,
"text": "Fortunately, nowadays we can implement object detection algorithms in an easy way, even with just few lines of code. With ImageAI library, we can create our image or video object detection system in a quick and easy way. I’ll show you how in this article."
},
{
"code": null,
"e": 1087,
"s": 1024,
"text": "Below are the steps on what we’re going to do in this article:"
},
{
"code": null,
"e": 1100,
"s": 1087,
"text": "Introduction"
},
{
"code": null,
"e": 1132,
"s": 1100,
"text": "Creating image object detection"
},
{
"code": null,
"e": 1164,
"s": 1132,
"text": "Creating video object detection"
},
{
"code": null,
"e": 1198,
"s": 1164,
"text": "So, let’s get started right away."
},
{
"code": null,
"e": 1438,
"s": 1198,
"text": "As previously mentioned, we’re going to create an image and a video object detection system with the help of ImageAI. ImageAI is a Python library to enable ML practitioners to build an object detection system with only a few lines of code."
},
{
"code": null,
"e": 1566,
"s": 1438,
"text": "Before we start, we need to install some of the dependencies that we will need to run ImageAI properly. These dependencies are:"
},
{
"code": null,
"e": 1572,
"s": 1566,
"text": "Numpy"
},
{
"code": null,
"e": 1598,
"s": 1572,
"text": "pip install numpy==1.16.1"
},
{
"code": null,
"e": 1609,
"s": 1598,
"text": "TensorFlow"
},
{
"code": null,
"e": 1640,
"s": 1609,
"text": "pip install tensorflow==1.14.0"
},
{
"code": null,
"e": 1655,
"s": 1640,
"text": "TensorFlow GPU"
},
{
"code": null,
"e": 1690,
"s": 1655,
"text": "pip install tensorflow-gpu==1.14.0"
},
{
"code": null,
"e": 1696,
"s": 1690,
"text": "Keras"
},
{
"code": null,
"e": 1721,
"s": 1696,
"text": "pip install keras==2.2.4"
},
{
"code": null,
"e": 1728,
"s": 1721,
"text": "OpenCV"
},
{
"code": null,
"e": 1754,
"s": 1728,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 1888,
"s": 1754,
"text": "After installing all of those libraries, then we can start to install ImageAI library by typing the following command in your prompt:"
},
{
"code": null,
"e": 1918,
"s": 1888,
"text": "pip install imageai --upgrade"
},
{
"code": null,
"e": 1999,
"s": 1918,
"text": "Next, we are ready to build our object detection system for image and for video."
},
{
"code": null,
"e": 2152,
"s": 1999,
"text": "To start creating an image object detection system, first let’s import the libraries that we’re going to use and also set our current working directory."
},
{
"code": null,
"e": 2238,
"s": 2152,
"text": "from imageai.Detection import ObjectDetectionimport oscurrent_directory = os.getcwd()"
},
{
"code": null,
"e": 2408,
"s": 2238,
"text": "As we want to implement an object detection in an easy and quick way, we will use a pretrained model specific for object detection that has been trained on COCO dataset."
},
{
"code": null,
"e": 2569,
"s": 2408,
"text": "There are three different pretrained models that you can choose with ImageAI: RetinaNet, YOLOv3, and tinyYOLOv3. You can download the model of your choice here."
},
{
"code": null,
"e": 2730,
"s": 2569,
"text": "After you’ve downloaded the model, place the h5 file in the same directory as your Python script. Your working directory should now has the following structure."
},
{
"code": null,
"e": 2782,
"s": 2730,
"text": "root_folder/ python_script.py pretrain_model.h5"
},
{
"code": null,
"e": 3047,
"s": 2782,
"text": "Back to our Python script, we now can instantiate the ObjectDetection class that we have imported before. Depending on the model that you have downloaded before, we need to call a proper method from ObjectDetection class. Below is the code implementation for that."
},
{
"code": null,
"e": 3339,
"s": 3047,
"text": "detector = ObjectDetection()# if you use RetinaNet model, call the following methoddetector.setModelTypeAsRetinaNet()# if you use YOLOv3 model, call the following methoddetector.setModelTypeAsYOLOv3()# if you use tinyYOLOv3 model, call the following methoddetector.setModelTypeAsTinyYOLOv3()"
},
{
"code": null,
"e": 3626,
"s": 3339,
"text": "Next, we can start to load the model by first specifying the path to our model. Since our model is in the same directory as our Python script, here I show you how to load the RetinaNet model. If you use YOLOv3 or tinyYOLOv3, you need to change the file name of your h5 file accordingly."
},
{
"code": null,
"e": 3734,
"s": 3626,
"text": "detector.setModelPath(os.path.join(current_directory , \"resnet50_coco_best_v2.0.1.h5\"))detector.loadModel()"
},
{
"code": null,
"e": 3964,
"s": 3734,
"text": "Finally, we can start to create an image object detection system. To do this, we need to specify two things: First, the directory and the filename of our input image and second, the directory and the filename of the output image."
},
{
"code": null,
"e": 4225,
"s": 3964,
"text": "In the following code implementation, the input image will be an image called ‘traffic.jpg’ that is located in the same directory as the Python script. Meanwhile, the detection result will be saved in a file called ‘traffic_detected.jpg’ in the same directory."
},
{
"code": null,
"e": 4618,
"s": 4225,
"text": "detections = detector.detectObjectsFromImage(input_image = os.path.join(current_directory, \"traffic.jpg\"), output_image_path = os.path.join(current_directory , \"traffic_detected.jpg\"))for eachObject in detections: print( eachObject[\"name\"] , \" : \", eachObject[\"percentage_probability\"], \" : \", eachObject[\"box_points\"] ) print(\"--------------------------------\")"
},
{
"code": null,
"e": 4780,
"s": 4618,
"text": "And that’s the code that we need to instantiate our image object detection system. Below is the full code implementation of the steps that we have covered above:"
},
{
"code": null,
"e": 4884,
"s": 4780,
"text": "If you run the complete code above, you’ll get more or less similar result on the image of your choice."
},
{
"code": null,
"e": 5093,
"s": 4884,
"text": "If you use the default value that we have seen in the implementation above, you might think that somehow the result of the object detection is overcrowded, with several bounding boxes overlapping one another."
},
{
"code": null,
"e": 5247,
"s": 5093,
"text": "In order to reduce the clutter in the prediction result, you can tune the object detector such that it only shows the object that really matters for you."
},
{
"code": null,
"e": 5515,
"s": 5247,
"text": "Let’s use the image above as an example. Let’s say I want the object detector to predict only the people and the bicycle. To do this, we need to instantiate CustomObjects method. Then, we pass the name of the objects that we want the system to detect as the argument."
},
{
"code": null,
"e": 5574,
"s": 5515,
"text": "custom = detector.CustomObjects(person=True, bicycle=True)"
},
{
"code": null,
"e": 5789,
"s": 5574,
"text": "Next, we can start to build the object detection system with detectCustomObjectsFromImage method. We pass our custom variable, the path and name of our input image, as well as the path and name of our output image."
},
{
"code": null,
"e": 6004,
"s": 5789,
"text": "detections = detector.detectCustomObjectsFromImage(custom_objects = custom,input_image = os.path.join(current_directory, \"traffic.jpg\"), output_image_path = os.path.join(current_directory , \"traffic_detected.jpg\"))"
},
{
"code": null,
"e": 6341,
"s": 6004,
"text": "Moreover, we can also further remove the clutter by ignoring the predictions that have probability values below a certain threshold value. Let’s say that you want to ignore the predictions with probability value below 70%. You can do that by adding the minimum_percentage_probability argument in the detectCustomObjectsFromImage method."
},
{
"code": null,
"e": 6592,
"s": 6341,
"text": "detections = detector.detectCustomObjectsFromImage(custom_objects = custom,input_image = os.path.join(current_directory, \"traffic.jpg\"), output_image_path = os.path.join(current_directory , \"traffic_detected.jpg\"),minimum_percentage_probability = 70)"
},
{
"code": null,
"e": 6783,
"s": 6592,
"text": "Below is the complete code implementation when we want to detect only people and bicycle from our image, and we also only want to show the detection where the probability value is above 70%."
},
{
"code": null,
"e": 6856,
"s": 6783,
"text": "If you run the code above, you’ll get more or less the result like this:"
},
{
"code": null,
"e": 7171,
"s": 6856,
"text": "And that’s it! With just a few lines of code now you can implement an object detection system for your own image. However, what if you want to detect objects in a video or even from your webcam instead of an image? Let’s find out how to create a similar object detection for video with ImageAI in the next section."
},
{
"code": null,
"e": 7383,
"s": 7171,
"text": "Believe it or not, the code to create a video object detection system with ImageAI is pretty much similar with the image object detection system we’ve built before. All we need to do is changing 3 lines of code."
},
{
"code": null,
"e": 7508,
"s": 7383,
"text": "The first one is the library that we should import. So instead of ObjectDetection , we need to import VideoObjectDetection ."
},
{
"code": null,
"e": 7559,
"s": 7508,
"text": "from imageai.Detection import VideoObjectDetection"
},
{
"code": null,
"e": 7731,
"s": 7559,
"text": "The second change that we should apply is the step where we instantiate object detection class. Instead of using ObjectDetection() , we should use VideoObjectDetection() ."
},
{
"code": null,
"e": 7765,
"s": 7731,
"text": "detector = VideoObjectDetection()"
},
{
"code": null,
"e": 8019,
"s": 7765,
"text": "Next, the third or the final change that we should apply is when we create the object detection system. In our previous code, we use detectObjectsFromImage method. If we want to detect objects from a video, we need to use detectObjectsFromVideo instead."
},
{
"code": null,
"e": 8198,
"s": 8019,
"text": "detections = detector.detectObjectsFromVideo( input_file_path=os.path.join(current_directory, \"footage.mp4\"), output_file_path=os.path.join(current_directory,\"footage_detected\"))"
},
{
"code": null,
"e": 8462,
"s": 8198,
"text": "As you can see, the argument that we need to pass into this method is still the same as before. First, we need to specify the path to our video directory and the filename of our video. Second, we also need to specify the path and the filename of the output video."
},
{
"code": null,
"e": 8545,
"s": 8462,
"text": "Below is the entire code implementation to create a video object detection system."
},
{
"code": null,
"e": 8640,
"s": 8545,
"text": "Now if you run the code implementation above, you’ll get more or less similar result as below."
},
{
"code": null,
"e": 8864,
"s": 8640,
"text": "Note: if you somehow don’t get the same color format in your output video, i.e you get the output video that is in BGR format instead of RGB format, you can use the code below to convert the output video back to RGB format."
},
{
"code": null,
"e": 8993,
"s": 8864,
"text": "All you need to do is specifying the path and the filename of the video that you want to convert as well as the converted video."
},
{
"code": null,
"e": 9250,
"s": 8993,
"text": "Same as our image object detection system, we can also fine tune our video object detection system a little bit. We have the option to pick which objects that we want to detect and to select the threshold for the probability value that should be displayed."
},
{
"code": null,
"e": 9519,
"s": 9250,
"text": "Let’s say we want to only detect people and bicycle for our video object detection system. Also, we only want to show the detections that have the probability value above 70%. We can do so by first instantiating a variable to store the objects that we want to observe."
},
{
"code": null,
"e": 9578,
"s": 9519,
"text": "custom = detector.CustomObjects(person=True, bicycle=True)"
},
{
"code": null,
"e": 9903,
"s": 9578,
"text": "Next, we can create our video object detection system with our custom objects. To do so, we call the detectCustomObjectsFromVideo method. For the arguments of this method, we pass our custom variable, path and filename of our input and output video, frames per second, as well as the minimum threshold for probability value."
},
{
"code": null,
"e": 10187,
"s": 9903,
"text": "detections = detector.detectCustomObjectsFromVideo( custom_objects = custom, input_file_path=os.path.join(execution_path, \"footage.mp4\"), output_file_path=os.path.join(execution_path, \"footage_detected\"), frames_per_second=20, log_progress=True, minimum_percentage_probability = 70)"
},
{
"code": null,
"e": 10316,
"s": 10187,
"text": "Below is the complete code implementation if you want to only detect people and bicycle which has a probability value above 70%."
},
{
"code": null,
"e": 10636,
"s": 10316,
"text": "Now what if you want to create an object detection system with your camera feeds as your input? Creating this system with ImageAI is also very straightforward. The code itself is very much similar with our video object detection system. You only need to add one line of code and also change one line of code to do this."
},
{
"code": null,
"e": 10753,
"s": 10636,
"text": "First, we need to create a variable to instantiate the OpenCV library to capture the frame directly from our webcam."
},
{
"code": null,
"e": 10782,
"s": 10753,
"text": "camera = cv2.VideoCapture(0)"
},
{
"code": null,
"e": 10991,
"s": 10782,
"text": "Finally, we need to change the argument in detectObjectsFromVideo method. Instead of specifying the input file path, we need to specify our camera input, which is the camera variable that we’ve created above."
},
{
"code": null,
"e": 11220,
"s": 10991,
"text": "detections = detector.detectObjectsFromVideo( camera_input = camera, output_file_path = os.path.join(current_directory,\"camera_detected_video\"), frames_per_second=20, log_progress=True)"
},
{
"code": null,
"e": 11326,
"s": 11220,
"text": "Below is the complete code implementation to create an object detection system directly from your webcam."
},
{
"code": null,
"e": 11485,
"s": 11326,
"text": "Again, if you somehow get the a different color format in your output video, you can use the aforementioned code to convert the output from BGR to RGB format."
},
{
"code": null,
"e": 11750,
"s": 11485,
"text": "Now you already know how to create a quick and easy object detection system with ImageAI. As you have seen, ImageAI library enables us to build an object detection system without having to deal with the complexity behind object detection model like ResNet or YOLO."
},
{
"code": null,
"e": 11880,
"s": 11750,
"text": "Note that with the pretrained model supported by ImageAI, the object detector can detect 80 different objects. These objects are:"
},
{
"code": null,
"e": 12598,
"s": 11880,
"text": "person, bicycle, car, motorcycle, airplane, bus, train, truck, boat, traffic light, fire hydrant, stop_sign, parking meter, bench, bird, cat, dog, horse, sheep, cow, elephant, bear,zebra, giraffe, backpack, umbrella, handbag, tie, suitcase, frisbee, skis, snowboard, sports ball, kite, baseball bat, baseball glove, skateboard, surfboard, tennis racket, bottle, wine glass, cup, fork, knife, spoon, bowl, banana, apple, sandwich, orange, broccoli, carrot, hot dog, pizza, donot, cake, chair, couch, potted plant, bed, dining table, toilet, tv, laptop, mouse, remote, keyboard, cell phone, microwave, oven, toaster, sink, refrigerator, book, clock, vase, scissors, teddy bear, hair dryer, toothbrush."
},
{
"code": null,
"e": 12739,
"s": 12598,
"text": "Now the question is, what if you want to create a custom object detection system with your own label that is not included in the list above?"
},
{
"code": null,
"e": 12855,
"s": 12739,
"text": "You can create your own custom object detection with ImageAI as well. I will show you how to do so in another post."
}
] |
C# - Operators Precedence
|
Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators are evaluated first.
using System;
namespace OperatorsAppl {
class Program {
static void Main(string[] args) {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
Console.WriteLine("Value of (a + b) * c / d is : {0}", e);
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Console.WriteLine("Value of ((a + b) * c) / d is : {0}", e);
e = (a + b) * (c / d); // (30) * (15/5) {0}", e);
e = a + (b * c) / d; // 20 + (150/5) {0}", e);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2528,
"s": 2270,
"text": "Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator."
},
{
"code": null,
"e": 2708,
"s": 2528,
"text": "For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it."
},
{
"code": null,
"e": 2899,
"s": 2708,
"text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators are evaluated first."
},
{
"code": null,
"e": 3509,
"s": 2899,
"text": "using System;\nnamespace OperatorsAppl {\n class Program {\n static void Main(string[] args) {\n int a = 20;\n int b = 10;\n int c = 15;\n int d = 5;\n int e;\n e = (a + b) * c / d; // ( 30 * 15 ) / 5\n Console.WriteLine(\"Value of (a + b) * c / d is : {0}\", e);\n\n e = ((a + b) * c) / d; // (30 * 15 ) / 5\n Console.WriteLine(\"Value of ((a + b) * c) / d is : {0}\", e);\n\n e = (a + b) * (c / d); // (30) * (15/5) {0}\", e);\n\n e = a + (b * c) / d; // 20 + (150/5) {0}\", e);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3590,
"s": 3509,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3660,
"s": 3590,
"text": "Value of (a + b) * c / d is : 90\nValue of ((a + b) * c) / d is : 90\n"
},
{
"code": null,
"e": 3697,
"s": 3660,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3710,
"s": 3697,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3744,
"s": 3710,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3762,
"s": 3744,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3795,
"s": 3762,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3809,
"s": 3795,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3846,
"s": 3809,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3861,
"s": 3846,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3896,
"s": 3861,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3911,
"s": 3896,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3946,
"s": 3911,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3958,
"s": 3946,
"text": " Eric Frick"
},
{
"code": null,
"e": 3965,
"s": 3958,
"text": " Print"
},
{
"code": null,
"e": 3976,
"s": 3965,
"text": " Add Notes"
}
] |
Convert an image into grayscale image using HTML/CSS - GeeksforGeeks
|
07 Dec, 2018
Given a colored image and the task is to convert the image into grayscale image using CSS property. In CSS, filter property is used to convert an image into grayscale image. Filter property is mainly used to set the visual effect of an image.
Syntax:
filter: grayscale()
Example 1: In this example, use filter: grayscale(100%) to convert an image into grayscale.
<!DOCTYPE html><html> <head> <title>Convert into grayscale image</title> <style> img { -webkit-filter: grayscale(100%); filter: grayscale(100%); } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Grayscale Image</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png" width="500px" height="250px" alt="filter applied" /> </center> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>Convert into grayscale image</title> <style> img { -webkit-filter: grayscale(1); filter: grayscale(1); } img:hover { -webkit-filter: grayscale(0); filter: none; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Grayscale Image</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png" width="500px" height="250px" alt="filter applied" /> </center> </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 23918,
"s": 23890,
"text": "\n07 Dec, 2018"
},
{
"code": null,
"e": 24161,
"s": 23918,
"text": "Given a colored image and the task is to convert the image into grayscale image using CSS property. In CSS, filter property is used to convert an image into grayscale image. Filter property is mainly used to set the visual effect of an image."
},
{
"code": null,
"e": 24169,
"s": 24161,
"text": "Syntax:"
},
{
"code": null,
"e": 24189,
"s": 24169,
"text": "filter: grayscale()"
},
{
"code": null,
"e": 24281,
"s": 24189,
"text": "Example 1: In this example, use filter: grayscale(100%) to convert an image into grayscale."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Convert into grayscale image</title> <style> img { -webkit-filter: grayscale(100%); filter: grayscale(100%); } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Grayscale Image</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png\" width=\"500px\" height=\"250px\" alt=\"filter applied\" /> </center> </body></html>",
"e": 24864,
"s": 24281,
"text": null
},
{
"code": null,
"e": 24872,
"s": 24864,
"text": "Output:"
},
{
"code": null,
"e": 24883,
"s": 24872,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Convert into grayscale image</title> <style> img { -webkit-filter: grayscale(1); filter: grayscale(1); } img:hover { -webkit-filter: grayscale(0); filter: none; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Grayscale Image</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png\" width=\"500px\" height=\"250px\" alt=\"filter applied\" /> </center> </body></html>",
"e": 25566,
"s": 24883,
"text": null
},
{
"code": null,
"e": 25574,
"s": 25566,
"text": "Output:"
},
{
"code": null,
"e": 25711,
"s": 25574,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25718,
"s": 25711,
"text": "Picked"
},
{
"code": null,
"e": 25722,
"s": 25718,
"text": "CSS"
},
{
"code": null,
"e": 25727,
"s": 25722,
"text": "HTML"
},
{
"code": null,
"e": 25744,
"s": 25727,
"text": "Web Technologies"
},
{
"code": null,
"e": 25771,
"s": 25744,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25776,
"s": 25771,
"text": "HTML"
},
{
"code": null,
"e": 25874,
"s": 25776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25883,
"s": 25874,
"text": "Comments"
},
{
"code": null,
"e": 25896,
"s": 25883,
"text": "Old Comments"
},
{
"code": null,
"e": 25958,
"s": 25896,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26008,
"s": 25958,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26056,
"s": 26008,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26114,
"s": 26056,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26164,
"s": 26114,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26226,
"s": 26164,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26276,
"s": 26226,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26324,
"s": 26276,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26384,
"s": 26324,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
ES6 - Operators
|
An expression is a special kind of statement that evaluates to a value. Every expression is composed of −
Operands − Represents the data.
Operands − Represents the data.
Operator − Defines how the operands will be processed to produce a value.
Operator − Defines how the operands will be processed to produce a value.
Consider the following expression- 2 + 3. Here in the expression, 2 and 3 are operands and the symbol + (plus) is the operator. JavaScript supports the following types of operators −
Arithmetic operators
Logical operators
Relational operators
Bitwise operators
Assignment operators
Ternary/conditional operators
String operators
Type operators
The void operator
Assume the values in variables a and b are 10 and 5 respectively.
Show Examples
Returns the sum of the operands.
Returns the difference of the values.
Returns the product of the values.
Performs a division operation and returns the quotient.
Performs a division and returns the remainder.
Increments the value of the variable by one.
Decrements the value of the variable by one.
Relational operators test or define the kind of relationship between two entities. Relational operators return a boolean value, i.e. true/false.
Assume the value of A is 10 and B is 20.
Show Examples
Logical operators are used to combine two or more conditions. Logical operators, too, return a Boolean value. Assume the value of variable A is 10 and B is 20.
Show Examples.
The operator returns true only if all the expressions specified return true.
The operator returns true if at least one of the expressions specified return true.
The operator returns the inverse of the expression’s result. For E.g.: !(7>5) returns false.
JavaScript supports the following bitwise operators. The following table summarizes JavaScript's bitwise operators.
Show Examples.
The following table summarizes Assignment operators.
Show Examples.
= (Simple Assignment)
Assigns values from the right side operand to the left side operand.
Example − C = A + B will assign the value of A + B into C
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Example − C += A is equivalent to C = C + A
-= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left operand.
Example C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left operand.
Example C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left operand.
Note − The same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |= and ^=.
Following are some of the miscellaneous operators.
Changes the sign of a value. The following program is an example of the same.
var x = 4
var y = -x;
console.log("value of x: ",x); //outputs 4
console.log("value of y: ",y); //outputs -4
The following output is displayed on successful execution of the above program.
value of x: 4
value of y: -4
The + operator when applied to strings appends the second string to the first. The following program helps to understand this concept.
var msg = "hello"+"world"
console.log(msg)
The following output is displayed on successful execution of the above program.
helloworld
The concatenation operation doesn’t add a space between the strings. Multiple strings can be concatenated in a single statement.
This operator is used to represent a conditional expression. The conditional operator is also sometimes referred to as the ternary operator. Following is the syntax.
Test ? expr1 : expr2
Where,
Test − Refers to the conditional expression
expr1 − Value returned if the condition is true
expr2 − Value returned if the condition is false
Example
var num = -2
var result = num > 0 ?"positive":"non-positive"
console.log(result)
Line 2 checks whether the value in the variable num is greater than zero. If num is set to a value greater than zero, it returns the string “positive” else a “non-positive” string is returned.
The following output is displayed on successful execution of the above program.
non-positive
It is a unary operator. This operator returns the data type of the operand. The following table lists the data types and the values returned by the typeof operator in JavaScript.
The following example code displays the number as the output.
var num = 12
console.log(typeof num); //output: number
The following output is displayed on successful execution of the above code.
number
ES6 provides a new operator called the spread operator. The spread operator is represented by three dots “...” . The spread operator converts an array into individual array elements.
The following example illustrates the use of spread operators in a function
<script>
function addThreeNumbers(a,b,c){
return a+b+c;
}
const arr = [10,20,30]
console.log('sum is :',addThreeNumbers(...arr))
console.log('sum is ',addThreeNumbers(...[1,2,3]))
</script>
The output of the above code will be as seen below −
sum is : 60
sum is 6
The spread operator can be used to copy one array into another. It can also be used to concatenate two or more arrays. This is shown in the example below −
<script>
//copy array using spread operator
let source_arr = [10,20,30]
let dest_arr = [...source_arr]
console.log(dest_arr)
//concatenate two arrays
let arr1 = [10,20,30]
let arr2 =[40,50,60]
let arr3 = [...arr1,...arr2]
console.log(arr3)
</script>
The output of the above code will be as stated below −
[10, 20, 30]
[10, 20, 30, 40, 50, 60]
The spread operator can be used to copy one object into another. It can also be used to concatenate two or more objects. This is shown in the example below −
<script>
//copy object
let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}
let student2 ={...student1}
console.log(student2)
//concatenate objects
let student3 = {lastName:'Mohammad'}
let student4 = {...student1,...student3}
console.log(student4)
</script>
The output of the above code will be as given below −
{firstName: "Mohtashim", company: "TutorialsPoint"}
{firstName: "Mohtashim", company: "TutorialsPoint", lastName: "Mohammad"}
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2383,
"s": 2277,
"text": "An expression is a special kind of statement that evaluates to a value. Every expression is composed of −"
},
{
"code": null,
"e": 2415,
"s": 2383,
"text": "Operands − Represents the data."
},
{
"code": null,
"e": 2447,
"s": 2415,
"text": "Operands − Represents the data."
},
{
"code": null,
"e": 2521,
"s": 2447,
"text": "Operator − Defines how the operands will be processed to produce a value."
},
{
"code": null,
"e": 2595,
"s": 2521,
"text": "Operator − Defines how the operands will be processed to produce a value."
},
{
"code": null,
"e": 2778,
"s": 2595,
"text": "Consider the following expression- 2 + 3. Here in the expression, 2 and 3 are operands and the symbol + (plus) is the operator. JavaScript supports the following types of operators −"
},
{
"code": null,
"e": 2799,
"s": 2778,
"text": "Arithmetic operators"
},
{
"code": null,
"e": 2817,
"s": 2799,
"text": "Logical operators"
},
{
"code": null,
"e": 2838,
"s": 2817,
"text": "Relational operators"
},
{
"code": null,
"e": 2856,
"s": 2838,
"text": "Bitwise operators"
},
{
"code": null,
"e": 2877,
"s": 2856,
"text": "Assignment operators"
},
{
"code": null,
"e": 2907,
"s": 2877,
"text": "Ternary/conditional operators"
},
{
"code": null,
"e": 2924,
"s": 2907,
"text": "String operators"
},
{
"code": null,
"e": 2939,
"s": 2924,
"text": "Type operators"
},
{
"code": null,
"e": 2957,
"s": 2939,
"text": "The void operator"
},
{
"code": null,
"e": 3023,
"s": 2957,
"text": "Assume the values in variables a and b are 10 and 5 respectively."
},
{
"code": null,
"e": 3037,
"s": 3023,
"text": "Show Examples"
},
{
"code": null,
"e": 3070,
"s": 3037,
"text": "Returns the sum of the operands."
},
{
"code": null,
"e": 3108,
"s": 3070,
"text": "Returns the difference of the values."
},
{
"code": null,
"e": 3143,
"s": 3108,
"text": "Returns the product of the values."
},
{
"code": null,
"e": 3199,
"s": 3143,
"text": "Performs a division operation and returns the quotient."
},
{
"code": null,
"e": 3246,
"s": 3199,
"text": "Performs a division and returns the remainder."
},
{
"code": null,
"e": 3291,
"s": 3246,
"text": "Increments the value of the variable by one."
},
{
"code": null,
"e": 3336,
"s": 3291,
"text": "Decrements the value of the variable by one."
},
{
"code": null,
"e": 3481,
"s": 3336,
"text": "Relational operators test or define the kind of relationship between two entities. Relational operators return a boolean value, i.e. true/false."
},
{
"code": null,
"e": 3522,
"s": 3481,
"text": "Assume the value of A is 10 and B is 20."
},
{
"code": null,
"e": 3536,
"s": 3522,
"text": "Show Examples"
},
{
"code": null,
"e": 3696,
"s": 3536,
"text": "Logical operators are used to combine two or more conditions. Logical operators, too, return a Boolean value. Assume the value of variable A is 10 and B is 20."
},
{
"code": null,
"e": 3711,
"s": 3696,
"text": "Show Examples."
},
{
"code": null,
"e": 3788,
"s": 3711,
"text": "The operator returns true only if all the expressions specified return true."
},
{
"code": null,
"e": 3872,
"s": 3788,
"text": "The operator returns true if at least one of the expressions specified return true."
},
{
"code": null,
"e": 3965,
"s": 3872,
"text": "The operator returns the inverse of the expression’s result. For E.g.: !(7>5) returns false."
},
{
"code": null,
"e": 4081,
"s": 3965,
"text": "JavaScript supports the following bitwise operators. The following table summarizes JavaScript's bitwise operators."
},
{
"code": null,
"e": 4096,
"s": 4081,
"text": "Show Examples."
},
{
"code": null,
"e": 4149,
"s": 4096,
"text": "The following table summarizes Assignment operators."
},
{
"code": null,
"e": 4164,
"s": 4149,
"text": "Show Examples."
},
{
"code": null,
"e": 4186,
"s": 4164,
"text": "= (Simple Assignment)"
},
{
"code": null,
"e": 4255,
"s": 4186,
"text": "Assigns values from the right side operand to the left side operand."
},
{
"code": null,
"e": 4314,
"s": 4255,
"text": "Example − C = A + B will assign the value of A + B into C"
},
{
"code": null,
"e": 4338,
"s": 4314,
"text": "+= (Add and Assignment)"
},
{
"code": null,
"e": 4428,
"s": 4338,
"text": "It adds the right operand to the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 4472,
"s": 4428,
"text": "Example − C += A is equivalent to C = C + A"
},
{
"code": null,
"e": 4501,
"s": 4472,
"text": "-= (Subtract and Assignment)"
},
{
"code": null,
"e": 4598,
"s": 4501,
"text": "It subtracts the right operand from the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 4640,
"s": 4598,
"text": "Example C -= A is equivalent to C = C - A"
},
{
"code": null,
"e": 4669,
"s": 4640,
"text": "*= (Multiply and Assignment)"
},
{
"code": null,
"e": 4767,
"s": 4669,
"text": "It multiplies the right operand with the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 4809,
"s": 4767,
"text": "Example C *= A is equivalent to C = C * A"
},
{
"code": null,
"e": 4836,
"s": 4809,
"text": "/= (Divide and Assignment)"
},
{
"code": null,
"e": 4931,
"s": 4836,
"text": "It divides the left operand with the right operand and assigns the result to the left operand."
},
{
"code": null,
"e": 5033,
"s": 4931,
"text": "Note − The same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |= and ^=."
},
{
"code": null,
"e": 5084,
"s": 5033,
"text": "Following are some of the miscellaneous operators."
},
{
"code": null,
"e": 5162,
"s": 5084,
"text": "Changes the sign of a value. The following program is an example of the same."
},
{
"code": null,
"e": 5274,
"s": 5162,
"text": "var x = 4 \nvar y = -x; \nconsole.log(\"value of x: \",x); //outputs 4 \nconsole.log(\"value of y: \",y); //outputs -4"
},
{
"code": null,
"e": 5354,
"s": 5274,
"text": "The following output is displayed on successful execution of the above program."
},
{
"code": null,
"e": 5386,
"s": 5354,
"text": "value of x: 4 \nvalue of y: -4 \n"
},
{
"code": null,
"e": 5521,
"s": 5386,
"text": "The + operator when applied to strings appends the second string to the first. The following program helps to understand this concept."
},
{
"code": null,
"e": 5566,
"s": 5521,
"text": "var msg = \"hello\"+\"world\" \nconsole.log(msg) "
},
{
"code": null,
"e": 5646,
"s": 5566,
"text": "The following output is displayed on successful execution of the above program."
},
{
"code": null,
"e": 5658,
"s": 5646,
"text": "helloworld\n"
},
{
"code": null,
"e": 5787,
"s": 5658,
"text": "The concatenation operation doesn’t add a space between the strings. Multiple strings can be concatenated in a single statement."
},
{
"code": null,
"e": 5953,
"s": 5787,
"text": "This operator is used to represent a conditional expression. The conditional operator is also sometimes referred to as the ternary operator. Following is the syntax."
},
{
"code": null,
"e": 5975,
"s": 5953,
"text": "Test ? expr1 : expr2\n"
},
{
"code": null,
"e": 5982,
"s": 5975,
"text": "Where,"
},
{
"code": null,
"e": 6026,
"s": 5982,
"text": "Test − Refers to the conditional expression"
},
{
"code": null,
"e": 6075,
"s": 6026,
"text": "expr1 − Value returned if the condition is true"
},
{
"code": null,
"e": 6124,
"s": 6075,
"text": "expr2 − Value returned if the condition is false"
},
{
"code": null,
"e": 6132,
"s": 6124,
"text": "Example"
},
{
"code": null,
"e": 6215,
"s": 6132,
"text": "var num = -2 \nvar result = num > 0 ?\"positive\":\"non-positive\" \nconsole.log(result)"
},
{
"code": null,
"e": 6408,
"s": 6215,
"text": "Line 2 checks whether the value in the variable num is greater than zero. If num is set to a value greater than zero, it returns the string “positive” else a “non-positive” string is returned."
},
{
"code": null,
"e": 6488,
"s": 6408,
"text": "The following output is displayed on successful execution of the above program."
},
{
"code": null,
"e": 6503,
"s": 6488,
"text": "non-positive \n"
},
{
"code": null,
"e": 6682,
"s": 6503,
"text": "It is a unary operator. This operator returns the data type of the operand. The following table lists the data types and the values returned by the typeof operator in JavaScript."
},
{
"code": null,
"e": 6744,
"s": 6682,
"text": "The following example code displays the number as the output."
},
{
"code": null,
"e": 6800,
"s": 6744,
"text": "var num = 12 \nconsole.log(typeof num); //output: number"
},
{
"code": null,
"e": 6877,
"s": 6800,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 6885,
"s": 6877,
"text": "number\n"
},
{
"code": null,
"e": 7068,
"s": 6885,
"text": "ES6 provides a new operator called the spread operator. The spread operator is represented by three dots “...” . The spread operator converts an array into individual array elements."
},
{
"code": null,
"e": 7144,
"s": 7068,
"text": "The following example illustrates the use of spread operators in a function"
},
{
"code": null,
"e": 7355,
"s": 7144,
"text": "<script>\n function addThreeNumbers(a,b,c){\n return a+b+c;\n }\n const arr = [10,20,30]\n console.log('sum is :',addThreeNumbers(...arr))\n console.log('sum is ',addThreeNumbers(...[1,2,3]))\n</script>"
},
{
"code": null,
"e": 7408,
"s": 7355,
"text": "The output of the above code will be as seen below −"
},
{
"code": null,
"e": 7430,
"s": 7408,
"text": "sum is : 60\nsum is 6\n"
},
{
"code": null,
"e": 7586,
"s": 7430,
"text": "The spread operator can be used to copy one array into another. It can also be used to concatenate two or more arrays. This is shown in the example below −"
},
{
"code": null,
"e": 7865,
"s": 7586,
"text": "<script>\n //copy array using spread operator\n let source_arr = [10,20,30]\n let dest_arr = [...source_arr]\n console.log(dest_arr)\n\t\n //concatenate two arrays\n let arr1 = [10,20,30]\n let arr2 =[40,50,60]\n let arr3 = [...arr1,...arr2]\n console.log(arr3)\n</script>"
},
{
"code": null,
"e": 7921,
"s": 7865,
"text": "The output of the above code will be as stated below −"
},
{
"code": null,
"e": 7960,
"s": 7921,
"text": "[10, 20, 30]\n[10, 20, 30, 40, 50, 60]\n"
},
{
"code": null,
"e": 8118,
"s": 7960,
"text": "The spread operator can be used to copy one object into another. It can also be used to concatenate two or more objects. This is shown in the example below −"
},
{
"code": null,
"e": 8410,
"s": 8118,
"text": "<script>\n //copy object\n let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}\n let student2 ={...student1}\n console.log(student2)\n //concatenate objects\n let student3 = {lastName:'Mohammad'}\n let student4 = {...student1,...student3}\n console.log(student4)\n</script>"
},
{
"code": null,
"e": 8464,
"s": 8410,
"text": "The output of the above code will be as given below −"
},
{
"code": null,
"e": 8591,
"s": 8464,
"text": "{firstName: \"Mohtashim\", company: \"TutorialsPoint\"}\n{firstName: \"Mohtashim\", company: \"TutorialsPoint\", lastName: \"Mohammad\"}\n"
},
{
"code": null,
"e": 8626,
"s": 8591,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8640,
"s": 8626,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 8673,
"s": 8640,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8691,
"s": 8673,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 8724,
"s": 8691,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8738,
"s": 8724,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8773,
"s": 8738,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 8790,
"s": 8773,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 8823,
"s": 8790,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8839,
"s": 8823,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 8874,
"s": 8839,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8882,
"s": 8874,
"text": " Shweta"
},
{
"code": null,
"e": 8889,
"s": 8882,
"text": " Print"
},
{
"code": null,
"e": 8900,
"s": 8889,
"text": " Add Notes"
}
] |
Python - turtle.delay() method - GeeksforGeeks
|
01 Aug, 2020
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to return or set the drawing delay in milliseconds. It requires only one optional argument as a positive integer for delay.
Syntax : turtle.delay(delay)Parameter :
delay : a positive integer, denoted the delay time in milliseconds, is optional
Returns : The delayed value
Below is the implementation of above method with some examples :Example 1 :
# import packageimport turtle # turtle movement with# normal speedturtle.forward(100) # slow the speed by # turtle delayturtle.delay(50) # turtle movementturtle.forward(80)
Output :
Example 2 :
# import packageimport turtle # loop for patternfor i in range(10): # set turtle delay turtle.delay(10 * i) # motion for pattern turtle.forward(50 + 10 * i) turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24489,
"s": 24292,
"text": "Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967."
},
{
"code": null,
"e": 24706,
"s": 24489,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 24850,
"s": 24706,
"text": "This method is used to return or set the drawing delay in milliseconds. It requires only one optional argument as a positive integer for delay."
},
{
"code": null,
"e": 24890,
"s": 24850,
"text": "Syntax : turtle.delay(delay)Parameter :"
},
{
"code": null,
"e": 24970,
"s": 24890,
"text": "delay : a positive integer, denoted the delay time in milliseconds, is optional"
},
{
"code": null,
"e": 24998,
"s": 24970,
"text": "Returns : The delayed value"
},
{
"code": null,
"e": 25074,
"s": 24998,
"text": "Below is the implementation of above method with some examples :Example 1 :"
},
{
"code": "# import packageimport turtle # turtle movement with# normal speedturtle.forward(100) # slow the speed by # turtle delayturtle.delay(50) # turtle movementturtle.forward(80)",
"e": 25250,
"s": 25074,
"text": null
},
{
"code": null,
"e": 25259,
"s": 25250,
"text": "Output :"
},
{
"code": null,
"e": 25271,
"s": 25259,
"text": "Example 2 :"
},
{
"code": "# import packageimport turtle # loop for patternfor i in range(10): # set turtle delay turtle.delay(10 * i) # motion for pattern turtle.forward(50 + 10 * i) turtle.right(90)",
"e": 25466,
"s": 25271,
"text": null
},
{
"code": null,
"e": 25475,
"s": 25466,
"text": "Output :"
},
{
"code": null,
"e": 25489,
"s": 25475,
"text": "Python-turtle"
},
{
"code": null,
"e": 25496,
"s": 25489,
"text": "Python"
},
{
"code": null,
"e": 25594,
"s": 25496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25603,
"s": 25594,
"text": "Comments"
},
{
"code": null,
"e": 25616,
"s": 25603,
"text": "Old Comments"
},
{
"code": null,
"e": 25648,
"s": 25616,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25704,
"s": 25648,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25759,
"s": 25704,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25801,
"s": 25759,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25843,
"s": 25801,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25874,
"s": 25843,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25913,
"s": 25874,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25935,
"s": 25913,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25964,
"s": 25935,
"text": "Create a directory in Python"
}
] |
Essential Math for Data Science: Eigenvectors and application to PCA | by Hadrien Jean | Towards Data Science
|
Matrix decomposition, also called matrix factorization is the process of splitting a matrix into multiple pieces. In the context of data science, you can for instance use it to select parts of the data, aimed at reducing dimensionality without losing much information (as for instance in Principal Component Analysis, as you’ll later in this post). Some operations are also more easily computed on the matrices resulting from the decomposition.
In this article, you’ll learn about the eigendecomposition of a matrix. One way to understand it is to consider it as a special change of basis (more details about change of basis in my last post). You’ll first learn about eigenvectors and eigenvalues and then you’ll see how they can be applied to Principal Component Analysis (PCA). The main idea is to consider the eigendecomposition of a matrix A as a change of basis where the new basis vectors are the eigenvectors.
As you can see in Chapter 7 of Essential Math for Data Science you can consider matrices as linear transformations. This means that if you take any vector u and apply the matrix A to it, you obtain a transformed vector v.
Take the example of:
and
If you apply A to the vector u (with the matrix-vector product), you get a new vector:
Let’s draw the initial and transformed vectors:
Note that, as you can expect, the transformed vector v doesn’t run in the same direction as the initial vector u. This change of direction characterizes most of the vectors you can transform by A.
However, take the following vector:
You can see in Figure 2 that the vector x has a special relationship with the matrix A: it is rescaled (with a negative value), but both the initial vector x and the transformed vector y are on the same line.
The vector x is an eigenvector of A. It is only scaled by a value, which is called an eigenvalue of the matrix A. An eigenvector of the matrix A is a vector that is contracted or elongated when transformed by the matrix. The eigenvalue is the scaling factor by which the vector is contracted or elongated.
Mathematically, the vector x is an eigenvector of A if:
with λ (pronounced “lambda”) being the eigenvalue corresponding to the eigenvector x.
Eigenvectors
Eigenvectors of a matrix are nonzero vectors that are only rescaled when the matrix is applied to them. If the scaling factor is positive, the directions of the initial and the transformed vectors are the same, if it is negative, their directions are reversed.
Number of eigenvectors
An n-by- n matrix has, at most, n linearly independent eigenvectors. However, each eigenvector multiplied by a nonzero scalar is also an eigenvector. If you have:
Then:
with c any nonzero value.
This excludes the zero vector as eigenvector, since you would have
In this case, every scalar would be an eigenvalue and thus would be undefined.
Principal Component Analysis, or PCA, is an algorithm that you can use to reduce the dimensionality of a dataset. It is useful, for instance, to reduce computation time, compress data, or avoid what is called the curse of dimensionality. It is also useful for visualization purposes: high dimensional data is hard to visualize and it can be useful to decrease the number of dimensions to plot your data.
In this hands-on project, you’ll use various concepts that you can learn in the book Essential Math for Data Science, as change of basis (Sections 7.5 and 9.2, some samples here), eigendecomposition (Chapter 9), or covariance matrices (Section 2.1.3) to understand how PCA is working.
In the first part, you’ll learn about the relationship between projections, explained variance and error minimization, first with a bit of theory, and then by coding a PCA on the beer dataset (consumption of beer as a function of temperature). In the second part, you’ll use Sklearn to use PCA on audio data to visualize audio samples according to their category, and then to compress these audio samples.
The goal of PCA is to project data onto a lower dimensional space while keeping as much of the information contained in the data as possible. The problem can be seen as a perpendicular least squares problem also called orthogonal regression.
You’ll see here that the error of the orthogonal projections is minimized when the projection line corresponds to the direction where the variance of the data is maximal.
It is first important to understand that, when the features of your dataset are not completely uncorrelated, some directions are associated with a larger variance than others.
Projecting data to a lower-dimensional space means that you might lose some information. In Figure 3, if you project two-dimensional data onto a line, the variance of the projected data tells you how much information you lose. For instance, if the variance of the projected data is near zero, it means that the data points will be projected to very close positions: you lose a lot of information.
For this reason, the goal of the PCA is to change the basis of the data matrix such that the direction with the maximum variance (u in Figure 3) becomes the first principal component. The second component is the direction with the maximum variance which is orthogonal to the first one, and so on.
When you have found the components of the PCA, you change the basis of your data such that the components are the new basis vectors. This transformed dataset has new features, which are the components and which are linear combinations of the initial features. Reducing the dimensionality is done by selecting some of the components only.
As an illustration, Figure 4 shows the data after a change of basis: the maximum variance is now associated with the x-axis. You can for instance keep only this first dimension.
In other words, expressing the PCA in terms of change of basis, its goal is to find a new basis (which is a linear combination of the initial basis) in which the variance of the data is maximized along the first dimensions.
Finding the directions that maximize the variance is similar as minimizing the error between the data and its projection.
You can see in Figure 5 that lower errors are shown in the left figure. Since projections are orthogonal, the variance associated with the direction of the line on which you project doesn’t impact the error.
After changing the basis of the dataset, you should have a covariance between features close to zero (as for instance in Figure 4). In other terms, you want that the transformed dataset has a diagonal covariance matrix: the covariance between each pair of principal components is equal to zero.
You can see in Chapter 9 of Essential Math for Data Science, that you can use eigendecomposition to diagonalize a matrix (make the matrix diagonal). Thus, you can calculate the eigenvectors of the covariance matrix of the dataset. They will give you the directions of the new basis in which the covariance matrix is diagonal.
To summarize, the principal components are calculated as the eigenvectors of the covariance matrix of the dataset. In addition, the eigenvalues give you the explained variance of the corresponding eigenvector. Thus, by sorting the eigenvectors in the decreasing order according to their eigenvalues, you can sort the principal components by importance order, and eventually remove the ones associated with a small variance.
Dataset
Let’s illustrate how PCA is working with the beer dataset showing the beer consumption and the temperature in São Paulo, Brazil for the year 2015.
Let’s load the data and plot the consumption as a function of the temperature:
Now, let’s create the data matrix X with the two variables: temperatures and consumption.
(365, 2)
The matrix X has 365 rows and two columns (the two variables).
As you saw, the first step is to compute the covariance matrix of the dataset:
array([[18.63964745, 12.20609082], [12.20609082, 19.35245652]])
Remember that you can read it as follows: the diagonal values are respectively the variances of the first and the second variable. The covariance between the two variables is around 12.2.
Now, you will calculate the eigenvectors and eigenvalues of this covariance matrix:
(array([ 6.78475896, 31.20734501]), array([[-0.71735154, -0.69671139], [ 0.69671139, -0.71735154]]))
You can store the eigenvectors as two vectors u and v.
Let’s plot the eigenvectors with the data (note that you should use centered data because it is the data used to calculate the covariance matrix).
You can scale the eigenvectors by their corresponding eigenvalues, which is the explained variance. For visualization purpose, let’s use a vector length of three standard deviations (equal to three times the square root of the explained variance):
You can see in Figure 7 that the eigenvectors of the covariance matrix give you the important directions of the data. The vector v in red is associated with the largest eigenvalue and thus corresponds to the direction with the largest variance. The vector u in gray is orthogonal to v and is the second principal component.
Then, you just need to change the basis of the data using the eigenvectors as the new basis vectors. But first, you can sort the eigenvectors with respect to the eigenvalues in decreasing order:
array([[-0.69671139, -0.71735154], [-0.71735154, 0.69671139]])
Now that your eigenvectors are sorted, let’s change the basis of the data:
You can plot the transformed data to check that the principal components are now uncorrelated:
Figure 8 shows the data samples in the new basis. You can see that the first dimension (the x-axis) corresponds to the direction with the largest variance.
You can keep only the first component of the data in this new basis without losing too much information.
Covariance matrix or Singular Value Decomposition?
One caveat of using the covariance matrix to calculate the PCA is that it can be hard to compute when there are many features (as with audio data, like in the second part of this hands-on). For this reason, it is usually preferred to use the Singular Value Decomposition (SVD) to calculate the PCA.
This post is a sample of my book Essential Math for Data Science!
Get the book here: https://bit.ly/2WVf4CR!
|
[
{
"code": null,
"e": 492,
"s": 47,
"text": "Matrix decomposition, also called matrix factorization is the process of splitting a matrix into multiple pieces. In the context of data science, you can for instance use it to select parts of the data, aimed at reducing dimensionality without losing much information (as for instance in Principal Component Analysis, as you’ll later in this post). Some operations are also more easily computed on the matrices resulting from the decomposition."
},
{
"code": null,
"e": 964,
"s": 492,
"text": "In this article, you’ll learn about the eigendecomposition of a matrix. One way to understand it is to consider it as a special change of basis (more details about change of basis in my last post). You’ll first learn about eigenvectors and eigenvalues and then you’ll see how they can be applied to Principal Component Analysis (PCA). The main idea is to consider the eigendecomposition of a matrix A as a change of basis where the new basis vectors are the eigenvectors."
},
{
"code": null,
"e": 1186,
"s": 964,
"text": "As you can see in Chapter 7 of Essential Math for Data Science you can consider matrices as linear transformations. This means that if you take any vector u and apply the matrix A to it, you obtain a transformed vector v."
},
{
"code": null,
"e": 1207,
"s": 1186,
"text": "Take the example of:"
},
{
"code": null,
"e": 1211,
"s": 1207,
"text": "and"
},
{
"code": null,
"e": 1298,
"s": 1211,
"text": "If you apply A to the vector u (with the matrix-vector product), you get a new vector:"
},
{
"code": null,
"e": 1346,
"s": 1298,
"text": "Let’s draw the initial and transformed vectors:"
},
{
"code": null,
"e": 1543,
"s": 1346,
"text": "Note that, as you can expect, the transformed vector v doesn’t run in the same direction as the initial vector u. This change of direction characterizes most of the vectors you can transform by A."
},
{
"code": null,
"e": 1579,
"s": 1543,
"text": "However, take the following vector:"
},
{
"code": null,
"e": 1788,
"s": 1579,
"text": "You can see in Figure 2 that the vector x has a special relationship with the matrix A: it is rescaled (with a negative value), but both the initial vector x and the transformed vector y are on the same line."
},
{
"code": null,
"e": 2094,
"s": 1788,
"text": "The vector x is an eigenvector of A. It is only scaled by a value, which is called an eigenvalue of the matrix A. An eigenvector of the matrix A is a vector that is contracted or elongated when transformed by the matrix. The eigenvalue is the scaling factor by which the vector is contracted or elongated."
},
{
"code": null,
"e": 2150,
"s": 2094,
"text": "Mathematically, the vector x is an eigenvector of A if:"
},
{
"code": null,
"e": 2236,
"s": 2150,
"text": "with λ (pronounced “lambda”) being the eigenvalue corresponding to the eigenvector x."
},
{
"code": null,
"e": 2249,
"s": 2236,
"text": "Eigenvectors"
},
{
"code": null,
"e": 2510,
"s": 2249,
"text": "Eigenvectors of a matrix are nonzero vectors that are only rescaled when the matrix is applied to them. If the scaling factor is positive, the directions of the initial and the transformed vectors are the same, if it is negative, their directions are reversed."
},
{
"code": null,
"e": 2533,
"s": 2510,
"text": "Number of eigenvectors"
},
{
"code": null,
"e": 2696,
"s": 2533,
"text": "An n-by- n matrix has, at most, n linearly independent eigenvectors. However, each eigenvector multiplied by a nonzero scalar is also an eigenvector. If you have:"
},
{
"code": null,
"e": 2702,
"s": 2696,
"text": "Then:"
},
{
"code": null,
"e": 2728,
"s": 2702,
"text": "with c any nonzero value."
},
{
"code": null,
"e": 2795,
"s": 2728,
"text": "This excludes the zero vector as eigenvector, since you would have"
},
{
"code": null,
"e": 2874,
"s": 2795,
"text": "In this case, every scalar would be an eigenvalue and thus would be undefined."
},
{
"code": null,
"e": 3278,
"s": 2874,
"text": "Principal Component Analysis, or PCA, is an algorithm that you can use to reduce the dimensionality of a dataset. It is useful, for instance, to reduce computation time, compress data, or avoid what is called the curse of dimensionality. It is also useful for visualization purposes: high dimensional data is hard to visualize and it can be useful to decrease the number of dimensions to plot your data."
},
{
"code": null,
"e": 3563,
"s": 3278,
"text": "In this hands-on project, you’ll use various concepts that you can learn in the book Essential Math for Data Science, as change of basis (Sections 7.5 and 9.2, some samples here), eigendecomposition (Chapter 9), or covariance matrices (Section 2.1.3) to understand how PCA is working."
},
{
"code": null,
"e": 3969,
"s": 3563,
"text": "In the first part, you’ll learn about the relationship between projections, explained variance and error minimization, first with a bit of theory, and then by coding a PCA on the beer dataset (consumption of beer as a function of temperature). In the second part, you’ll use Sklearn to use PCA on audio data to visualize audio samples according to their category, and then to compress these audio samples."
},
{
"code": null,
"e": 4211,
"s": 3969,
"text": "The goal of PCA is to project data onto a lower dimensional space while keeping as much of the information contained in the data as possible. The problem can be seen as a perpendicular least squares problem also called orthogonal regression."
},
{
"code": null,
"e": 4382,
"s": 4211,
"text": "You’ll see here that the error of the orthogonal projections is minimized when the projection line corresponds to the direction where the variance of the data is maximal."
},
{
"code": null,
"e": 4558,
"s": 4382,
"text": "It is first important to understand that, when the features of your dataset are not completely uncorrelated, some directions are associated with a larger variance than others."
},
{
"code": null,
"e": 4955,
"s": 4558,
"text": "Projecting data to a lower-dimensional space means that you might lose some information. In Figure 3, if you project two-dimensional data onto a line, the variance of the projected data tells you how much information you lose. For instance, if the variance of the projected data is near zero, it means that the data points will be projected to very close positions: you lose a lot of information."
},
{
"code": null,
"e": 5252,
"s": 4955,
"text": "For this reason, the goal of the PCA is to change the basis of the data matrix such that the direction with the maximum variance (u in Figure 3) becomes the first principal component. The second component is the direction with the maximum variance which is orthogonal to the first one, and so on."
},
{
"code": null,
"e": 5590,
"s": 5252,
"text": "When you have found the components of the PCA, you change the basis of your data such that the components are the new basis vectors. This transformed dataset has new features, which are the components and which are linear combinations of the initial features. Reducing the dimensionality is done by selecting some of the components only."
},
{
"code": null,
"e": 5768,
"s": 5590,
"text": "As an illustration, Figure 4 shows the data after a change of basis: the maximum variance is now associated with the x-axis. You can for instance keep only this first dimension."
},
{
"code": null,
"e": 5992,
"s": 5768,
"text": "In other words, expressing the PCA in terms of change of basis, its goal is to find a new basis (which is a linear combination of the initial basis) in which the variance of the data is maximized along the first dimensions."
},
{
"code": null,
"e": 6114,
"s": 5992,
"text": "Finding the directions that maximize the variance is similar as minimizing the error between the data and its projection."
},
{
"code": null,
"e": 6322,
"s": 6114,
"text": "You can see in Figure 5 that lower errors are shown in the left figure. Since projections are orthogonal, the variance associated with the direction of the line on which you project doesn’t impact the error."
},
{
"code": null,
"e": 6617,
"s": 6322,
"text": "After changing the basis of the dataset, you should have a covariance between features close to zero (as for instance in Figure 4). In other terms, you want that the transformed dataset has a diagonal covariance matrix: the covariance between each pair of principal components is equal to zero."
},
{
"code": null,
"e": 6943,
"s": 6617,
"text": "You can see in Chapter 9 of Essential Math for Data Science, that you can use eigendecomposition to diagonalize a matrix (make the matrix diagonal). Thus, you can calculate the eigenvectors of the covariance matrix of the dataset. They will give you the directions of the new basis in which the covariance matrix is diagonal."
},
{
"code": null,
"e": 7367,
"s": 6943,
"text": "To summarize, the principal components are calculated as the eigenvectors of the covariance matrix of the dataset. In addition, the eigenvalues give you the explained variance of the corresponding eigenvector. Thus, by sorting the eigenvectors in the decreasing order according to their eigenvalues, you can sort the principal components by importance order, and eventually remove the ones associated with a small variance."
},
{
"code": null,
"e": 7375,
"s": 7367,
"text": "Dataset"
},
{
"code": null,
"e": 7523,
"s": 7375,
"text": "Let’s illustrate how PCA is working with the beer dataset showing the beer consumption and the temperature in São Paulo, Brazil for the year 2015."
},
{
"code": null,
"e": 7602,
"s": 7523,
"text": "Let’s load the data and plot the consumption as a function of the temperature:"
},
{
"code": null,
"e": 7692,
"s": 7602,
"text": "Now, let’s create the data matrix X with the two variables: temperatures and consumption."
},
{
"code": null,
"e": 7701,
"s": 7692,
"text": "(365, 2)"
},
{
"code": null,
"e": 7764,
"s": 7701,
"text": "The matrix X has 365 rows and two columns (the two variables)."
},
{
"code": null,
"e": 7843,
"s": 7764,
"text": "As you saw, the first step is to compute the covariance matrix of the dataset:"
},
{
"code": null,
"e": 7907,
"s": 7843,
"text": "array([[18.63964745, 12.20609082], [12.20609082, 19.35245652]])"
},
{
"code": null,
"e": 8095,
"s": 7907,
"text": "Remember that you can read it as follows: the diagonal values are respectively the variances of the first and the second variable. The covariance between the two variables is around 12.2."
},
{
"code": null,
"e": 8179,
"s": 8095,
"text": "Now, you will calculate the eigenvectors and eigenvalues of this covariance matrix:"
},
{
"code": null,
"e": 8280,
"s": 8179,
"text": "(array([ 6.78475896, 31.20734501]), array([[-0.71735154, -0.69671139], [ 0.69671139, -0.71735154]]))"
},
{
"code": null,
"e": 8335,
"s": 8280,
"text": "You can store the eigenvectors as two vectors u and v."
},
{
"code": null,
"e": 8482,
"s": 8335,
"text": "Let’s plot the eigenvectors with the data (note that you should use centered data because it is the data used to calculate the covariance matrix)."
},
{
"code": null,
"e": 8730,
"s": 8482,
"text": "You can scale the eigenvectors by their corresponding eigenvalues, which is the explained variance. For visualization purpose, let’s use a vector length of three standard deviations (equal to three times the square root of the explained variance):"
},
{
"code": null,
"e": 9054,
"s": 8730,
"text": "You can see in Figure 7 that the eigenvectors of the covariance matrix give you the important directions of the data. The vector v in red is associated with the largest eigenvalue and thus corresponds to the direction with the largest variance. The vector u in gray is orthogonal to v and is the second principal component."
},
{
"code": null,
"e": 9249,
"s": 9054,
"text": "Then, you just need to change the basis of the data using the eigenvectors as the new basis vectors. But first, you can sort the eigenvectors with respect to the eigenvalues in decreasing order:"
},
{
"code": null,
"e": 9312,
"s": 9249,
"text": "array([[-0.69671139, -0.71735154], [-0.71735154, 0.69671139]])"
},
{
"code": null,
"e": 9387,
"s": 9312,
"text": "Now that your eigenvectors are sorted, let’s change the basis of the data:"
},
{
"code": null,
"e": 9482,
"s": 9387,
"text": "You can plot the transformed data to check that the principal components are now uncorrelated:"
},
{
"code": null,
"e": 9638,
"s": 9482,
"text": "Figure 8 shows the data samples in the new basis. You can see that the first dimension (the x-axis) corresponds to the direction with the largest variance."
},
{
"code": null,
"e": 9743,
"s": 9638,
"text": "You can keep only the first component of the data in this new basis without losing too much information."
},
{
"code": null,
"e": 9794,
"s": 9743,
"text": "Covariance matrix or Singular Value Decomposition?"
},
{
"code": null,
"e": 10093,
"s": 9794,
"text": "One caveat of using the covariance matrix to calculate the PCA is that it can be hard to compute when there are many features (as with audio data, like in the second part of this hands-on). For this reason, it is usually preferred to use the Singular Value Decomposition (SVD) to calculate the PCA."
},
{
"code": null,
"e": 10159,
"s": 10093,
"text": "This post is a sample of my book Essential Math for Data Science!"
}
] |
C++ Vector Library - emplace() Function
|
The C++ function std::vector::emplace() extends container by inserting new element at position. Reallocation happens if there is need of more space.
This method increases container size by one.
Following is the declaration for std::vector::emplace() function form std::vector header.
template <class... Args>
iterator emplace (const_iterator position, Args&&... args);
position − Index in the container where the new element is to be inserted.
position − Index in the container where the new element is to be inserted.
args − Arguments forwarded to construct the new element.
args − Arguments forwarded to construct the new element.
Returns a random access iterator which points to the newly emplaced element.
If reallocation fails bad_alloc exception is thrown.
Linear i.e. O(n)
The following example shows the usage of std::vector::emplace() function.
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v = {1, 2, 5};
/* insert element at index 3 */
auto it = v.emplace(v.begin() + 2, 4);
/* insert element at index 2 */
v.emplace(it, 3);
for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2752,
"s": 2603,
"text": "The C++ function std::vector::emplace() extends container by inserting new element at position. Reallocation happens if there is need of more space."
},
{
"code": null,
"e": 2797,
"s": 2752,
"text": "This method increases container size by one."
},
{
"code": null,
"e": 2887,
"s": 2797,
"text": "Following is the declaration for std::vector::emplace() function form std::vector header."
},
{
"code": null,
"e": 2973,
"s": 2887,
"text": "template <class... Args>\niterator emplace (const_iterator position, Args&&... args);\n"
},
{
"code": null,
"e": 3048,
"s": 2973,
"text": "position − Index in the container where the new element is to be inserted."
},
{
"code": null,
"e": 3123,
"s": 3048,
"text": "position − Index in the container where the new element is to be inserted."
},
{
"code": null,
"e": 3180,
"s": 3123,
"text": "args − Arguments forwarded to construct the new element."
},
{
"code": null,
"e": 3237,
"s": 3180,
"text": "args − Arguments forwarded to construct the new element."
},
{
"code": null,
"e": 3314,
"s": 3237,
"text": "Returns a random access iterator which points to the newly emplaced element."
},
{
"code": null,
"e": 3367,
"s": 3314,
"text": "If reallocation fails bad_alloc exception is thrown."
},
{
"code": null,
"e": 3384,
"s": 3367,
"text": "Linear i.e. O(n)"
},
{
"code": null,
"e": 3458,
"s": 3384,
"text": "The following example shows the usage of std::vector::emplace() function."
},
{
"code": null,
"e": 3795,
"s": 3458,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 2, 5};\n\n /* insert element at index 3 */\n auto it = v.emplace(v.begin() + 2, 4);\n\n /* insert element at index 2 */\n v.emplace(it, 3);\n\n for (auto it = v.begin(); it != v.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3878,
"s": 3795,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3889,
"s": 3878,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3896,
"s": 3889,
"text": " Print"
},
{
"code": null,
"e": 3907,
"s": 3896,
"text": " Add Notes"
}
] |
getpixel() function in C - GeeksforGeeks
|
23 Jan, 2018
The header file graphics.h contains getpixel() function which returns the color of pixel present at location (x, y).
Syntax :
int getpixel(int x, int y);
Note : By default the screen is BLACK, therefore color of pixel at (0,0) is BLACK.
Below is the implementation of getpixel() function.
// C Implementation for getpixel()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm, color; char arr[50]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // getpixel function color = getpixel(0, 0); // sprintf stands for “String print”. // Instead of printing on console, // it store output on char buffer // which are specified in sprintf sprintf(arr, "color of pixel at (0,0) = %d", color); // outtext function displays text // at current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
Explanation : As nothing is drawn anything on screen and by default screen is BLACK, therefore color of pixel at (0, 0) is BLACK as 0 indicates BLACK color.
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Multiple Inheritance in C++
Ways to copy a vector in C++
Basics of File Handling in C
|
[
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n23 Jan, 2018"
},
{
"code": null,
"e": 25704,
"s": 25587,
"text": "The header file graphics.h contains getpixel() function which returns the color of pixel present at location (x, y)."
},
{
"code": null,
"e": 25713,
"s": 25704,
"text": "Syntax :"
},
{
"code": null,
"e": 25742,
"s": 25713,
"text": "int getpixel(int x, int y);\n"
},
{
"code": null,
"e": 25825,
"s": 25742,
"text": "Note : By default the screen is BLACK, therefore color of pixel at (0,0) is BLACK."
},
{
"code": null,
"e": 25877,
"s": 25825,
"text": "Below is the implementation of getpixel() function."
},
{
"code": "// C Implementation for getpixel()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm, color; char arr[50]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // getpixel function color = getpixel(0, 0); // sprintf stands for “String print”. // Instead of printing on console, // it store output on char buffer // which are specified in sprintf sprintf(arr, \"color of pixel at (0,0) = %d\", color); // outtext function displays text // at current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 26888,
"s": 25877,
"text": null
},
{
"code": null,
"e": 26897,
"s": 26888,
"text": "Output :"
},
{
"code": null,
"e": 27056,
"s": 26899,
"text": "Explanation : As nothing is drawn anything on screen and by default screen is BLACK, therefore color of pixel at (0, 0) is BLACK as 0 indicates BLACK color."
},
{
"code": null,
"e": 27067,
"s": 27056,
"text": "c-graphics"
},
{
"code": null,
"e": 27085,
"s": 27067,
"text": "computer-graphics"
},
{
"code": null,
"e": 27096,
"s": 27085,
"text": "C Language"
},
{
"code": null,
"e": 27194,
"s": 27096,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27232,
"s": 27194,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27258,
"s": 27232,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27280,
"s": 27258,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27300,
"s": 27280,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27341,
"s": 27300,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27383,
"s": 27341,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 27419,
"s": 27383,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 27447,
"s": 27419,
"text": "Multiple Inheritance in C++"
},
{
"code": null,
"e": 27476,
"s": 27447,
"text": "Ways to copy a vector in C++"
}
] |
Whois tutorialspoint.com
|
Register a Domain
Get your domain name now
Domain Suggestions
Get help picking a domain name
Domain Prices
Compare prices across TLDs
Special Offers
Take advantage of our unbeatable promotions
Domain Services
Transfer your Domain
Consolidate your domains quickly & easily
Free with Every Domain
Get over $100 worth of free services
Register a Domain
Get your domain name now
Domain Suggestions
Get help picking a domain name
Domain Prices
Compare prices across TLDs
Special Offers
Take advantage of our unbeatable promotions
Transfer your Domain
Consolidate your domains quickly & easily
Free with Every Domain
Get over $100 worth of free services
Website
DIY Website Builder
Create a stunning website in minutes using our intuitive builder tool
Starts at just | $1.58/mo
DIY Website Builder
Create a stunning website in minutes using our intuitive builder tool
Starts at just | $1.58/mo
Cloud
Cloud Hosting
Next-level performance and reliability with simplified cPanel management
Starts at just | $6.88/mo
Cloud Hosting
Next-level performance and reliability with simplified cPanel management
Starts at just | $6.88/mo
Hosting
Shared Hosting
Linux Shared Hosting
Fully featured Linux plans with cPanel, Perl, PHP and more
Starts at just | $1.68/mo
Windows Shared Hosting
Complete Windows Hosting with Plesk, IIS and more
Starts at just | $1.68/mo
Reseller Hosting
Linux Reseller Hosting
Use the power of WHM to start your Hosting business today
Starts at just | $14.88/mo
Windows Reseller Hosting
Plesk-enabled plans to kickoff your Hosting business
Starts at just | $25.88/mo
Specialized Hosting
WordPress Hosting
The easiest way to start your blog/website Trusted by over 30% of the world's websites
Starts at just | $3.78/mo
Linux Shared Hosting
Fully featured Linux plans with cPanel, Perl, PHP and more
Starts at just | $1.68/mo
Windows Shared Hosting
Complete Windows Hosting with Plesk, IIS and more
Starts at just | $1.68/mo
Linux Reseller Hosting
Use the power of WHM to start your Hosting business today
Starts at just | $14.88/mo
Windows Reseller Hosting
Plesk-enabled plans to kickoff your Hosting business
Starts at just | $25.88/mo
WordPress Hosting
The easiest way to start your blog/website Trusted by over 30% of the world's websites
Starts at just | $3.78/mo
Servers
Virtual Private Servers
The Dedicated server experience made affordable Build high-performance websites and applications
Starts at just | $11.88/mo
Dedicated Servers
Rock-solid performance on dedicated hardware Perfect for larger websites and apps
Starts at just | $78/mo
Virtual Private Servers
The Dedicated server experience made affordable Build high-performance websites and applications
Starts at just | $11.88/mo
Dedicated Servers
Rock-solid performance on dedicated hardware Perfect for larger websites and apps
Starts at just | $78/mo
Email
Business Email
Simple & Easy to use Branded Email Ideal for beginners & small businesses
5 GB Storage | $0.98/acc/mo
Enterprise Email
Advanced Email for growing businesses & teams Includes Shared Contacts & Calendars
30 GB Storage | $2.88/acc/mo
Google Workspace
Intelligent Email for seamless collaboration Includes Google Docs, Sheets & Drive
30 GB Storage + Collaboration Suite
Business Email
Simple & Easy to use Branded Email Ideal for beginners & small businesses
5 GB Storage | $0.98/acc/mo
Enterprise Email
Advanced Email for growing businesses & teams Includes Shared Contacts & Calendars
30 GB Storage | $2.88/acc/mo
Google Workspace
Intelligent Email for seamless collaboration Includes Google Docs, Sheets & Drive
30 GB Storage + Collaboration Suite
Security
Secure your website and customer data
Starts at just | $9.48/yr
Protect your website from Viruses & Hackers
Starts at just | $14.28/yr
Cloud backup for your website
Starts at just | $1.07/mo
Secure your website and customer data
Starts at just | $9.48/yr
Protect your website from Viruses & Hackers
Starts at just | $14.28/yr
Cloud backup for your website
Starts at just | $1.07/mo
Whois
Support
Contact Us
Getting in touch is easy!
Knowledge Base
Detailed information regarding all our current Product and Service offerings
Contact Us
Getting in touch is easy!
Knowledge Base
Detailed information regarding all our current Product and Service offerings
0
Login
Login
Create an Account
Forgot Password
Login
Create an Account
Forgot Password
LoginSign up
Domains
Register a Domain
Transfer your Domain
Domain Prices
Special Offers
Domain Suggestions
Free with Every Domain
Whois Lookup
Register a Domain
Transfer your Domain
Domain Prices
Special Offers
Domain Suggestions
Free with Every Domain
Whois Lookup
Website
Website Builder
Website Builder
Cloud
Cloud Hosting
Cloud Hosting
Hosting
Shared Hosting
Linux Hosting
Windows Hosting
Reseller Hosting
Linux Reseller Hosting
Windows Reseller Hosting
Specialized Hosting
WordPress Hosting
Shared Hosting
Linux Hosting
Windows Hosting
Reseller Hosting
Linux Reseller Hosting
Windows Reseller Hosting
Specialized Hosting
WordPress Hosting
Servers
Virtual Private Servers
Dedicated Servers
Virtual Private Servers
Dedicated Servers
Email
Business Email
Enterprise Email
Google Workspace
Business Email
Enterprise Email
Google Workspace
Security
SSL Certificates
SiteLock Malware Detector
CodeGuard Website Backup
SSL Certificates
SiteLock Malware Detector
CodeGuard Website Backup
Whois
Support
Knowledge Base
Contact Us
About Us
Knowledge Base
Contact Us
About Us
Domain Name: TUTORIALSPOINT.COM
Registry Domain ID: 613404007_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.godaddy.com
Registrar URL: https://www.godaddy.com
Updated Date: 2020-09-21T02:47:14Z
Creation Date: 2006-09-30T02:23:20Z
Registrar Registration Expiration Date: 2025-09-30T02:23:20Z
Registrar: GoDaddy.com, LLC
Registrar IANA ID: 146
Registrar Abuse Contact Email: @godaddy.com
Registrar Abuse Contact Phone: +1.4806242505
Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited
Domain Status: clientRenewProhibited https://icann.org/epp#clientRenewProhibited
Domain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited
Registrant Organization: Tutorials Point India Limited
Registrant State/Province: Andhra Pradesh
Registrant Country: IN
Registrant Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM
Tech Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM
Admin Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM
Name Server: PDNS13.DOMAINCONTROL.COM
Name Server: PDNS14.DOMAINCONTROL.COM
DNSSEC: unsigned
URL of the ICANN WHOIS Data Problem Reporting System: http://wdprs.internic.net/
>>> Last update of WHOIS database: 2022-03-29T09:15:12Z <<<
For more information on Whois status codes, please visit https://icann.org/epp
TERMS OF USE: The data contained in this registrar's Whois database, while believed by the
registrar to be reliable, is provided "as is" with no guarantee or warranties regarding its
accuracy. This information is provided for the sole purpose of assisting you in obtaining
information about domain name registration records. Any use of this data for any other purpose
is expressly forbidden without the prior written permission of this registrar. By submitting
an inquiry, you agree to these terms and limitations of warranty. In particular, you agree not
to use this data to allow, enable, or otherwise support the dissemination or collection of this
data, in part or in its entirety, for any purpose, such as transmission by e-mail, telephone,
postal mail, facsimile or other means of mass unsolicited, commercial advertising or solicitations
of any kind, including spam. You further agree not to use this data to enable high volume, automated
or robotic electronic processes designed to collect or compile this data for any purpose, including
mining this data for your own personal or commercial purposes. Failure to comply with these terms
may result in termination of access to the Whois database. These terms may be subject to modification
at any time without notice.
$24.88 $0.88Buy Now
*Offer ends 30th April 2022
godaddy.com
icann.org
domaincontrol.com
internic.net
Leading provider of web presence solutions that empower you to establish and grow your online presence.
Learn more About Us
Register Domain Name
Transfer Domain Name
View Domain Pricing
Whois Lookup
Name Suggestion Tool
Free with Every Domain
Domain Offers
Linux Hosting
Windows Hosting
WordPress Hosting
Linux Reseller Hosting
Windows Reseller Hosting
Dedicated Servers
Cloud Hosting
Website Builder
Business Email
Enterprise Email
Google Workspace
SSL Certificates
Sitelock
CodeGuard
Datacenter Details
Hosting Security
24 x 7 Servers Monitoring
Backup and Recovery
View Knowledge Base
Contact Support
Report Abuse
About Whois
View Knowledge Base
|
[
{
"code": null,
"e": 402,
"s": 0,
"text": "\nRegister a Domain \n Get your domain name now\n\n\n\n\nDomain Suggestions \nGet help picking a domain name\n\n\n\n\n\n\nDomain Prices \nCompare prices across TLDs\n\n\n\n\nSpecial Offers \nTake advantage of our unbeatable promotions\n\n\n\n\n\n Domain Services\n\n\n\nTransfer your Domain \nConsolidate your domains quickly & easily\n\n\n\n\nFree with Every Domain \nGet over $100 worth of free services\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 451,
"s": 402,
"text": "\n\nRegister a Domain \n Get your domain name now\n\n"
},
{
"code": null,
"e": 506,
"s": 451,
"text": "\n\nDomain Suggestions \nGet help picking a domain name\n\n"
},
{
"code": null,
"e": 552,
"s": 506,
"text": "\n\nDomain Prices \nCompare prices across TLDs\n\n"
},
{
"code": null,
"e": 616,
"s": 552,
"text": "\n\nSpecial Offers \nTake advantage of our unbeatable promotions\n\n"
},
{
"code": null,
"e": 684,
"s": 616,
"text": "\n\nTransfer your Domain \nConsolidate your domains quickly & easily\n\n"
},
{
"code": null,
"e": 749,
"s": 684,
"text": "\n\nFree with Every Domain \nGet over $100 worth of free services\n\n"
},
{
"code": null,
"e": 887,
"s": 749,
"text": "\nWebsite\n\n\n\n\n\nDIY Website Builder \nCreate a stunning website in minutes using our intuitive builder tool\nStarts at just | $1.58/mo\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 1008,
"s": 887,
"text": "\n\nDIY Website Builder \nCreate a stunning website in minutes using our intuitive builder tool\nStarts at just | $1.58/mo\n\n"
},
{
"code": null,
"e": 1141,
"s": 1008,
"text": "\nCloud\n\n\n\n\n\nCloud Hosting \nNext-level performance and reliability with simplified cPanel management\nStarts at just | $6.88/mo\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 1259,
"s": 1141,
"text": "\n\nCloud Hosting \nNext-level performance and reliability with simplified cPanel management\nStarts at just | $6.88/mo\n\n"
},
{
"code": null,
"e": 1922,
"s": 1259,
"text": "\nHosting\n\n\n\n Shared Hosting\n\n\n\nLinux Shared Hosting \nFully featured Linux plans with cPanel, Perl, PHP and more\nStarts at just | $1.68/mo\n\n\n\n\nWindows Shared Hosting \nComplete Windows Hosting with Plesk, IIS and more\nStarts at just | $1.68/mo\n\n\n\n\n\n\n Reseller Hosting\n\n\n\nLinux Reseller Hosting \nUse the power of WHM to start your Hosting business today\nStarts at just | $14.88/mo\n\n\n\n\nWindows Reseller Hosting \nPlesk-enabled plans to kickoff your Hosting business\nStarts at just | $25.88/mo\n\n\n\n\n\n\n Specialized Hosting\n\n\n\nWordPress Hosting \nThe easiest way to start your blog/website Trusted by over 30% of the world's websites\nStarts at just | $3.78/mo\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 2034,
"s": 1922,
"text": "\n\nLinux Shared Hosting \nFully featured Linux plans with cPanel, Perl, PHP and more\nStarts at just | $1.68/mo\n\n"
},
{
"code": null,
"e": 2139,
"s": 2034,
"text": "\n\nWindows Shared Hosting \nComplete Windows Hosting with Plesk, IIS and more\nStarts at just | $1.68/mo\n\n"
},
{
"code": null,
"e": 2253,
"s": 2139,
"text": "\n\nLinux Reseller Hosting \nUse the power of WHM to start your Hosting business today\nStarts at just | $14.88/mo\n\n"
},
{
"code": null,
"e": 2364,
"s": 2253,
"text": "\n\nWindows Reseller Hosting \nPlesk-enabled plans to kickoff your Hosting business\nStarts at just | $25.88/mo\n\n"
},
{
"code": null,
"e": 2501,
"s": 2364,
"text": "\n\nWordPress Hosting \nThe easiest way to start your blog/website Trusted by over 30% of the world's websites\nStarts at just | $3.78/mo\n\n"
},
{
"code": null,
"e": 2809,
"s": 2501,
"text": "\nServers\n\n\n\n\n\n\nVirtual Private Servers \nThe Dedicated server experience made affordable Build high-performance websites and applications\nStarts at just | $11.88/mo\n\n\n\n\n\n\n\n\nDedicated Servers \nRock-solid performance on dedicated hardware Perfect for larger websites and apps\nStarts at just | $78/mo\n\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 2963,
"s": 2809,
"text": "\n\nVirtual Private Servers \nThe Dedicated server experience made affordable Build high-performance websites and applications\nStarts at just | $11.88/mo\n\n"
},
{
"code": null,
"e": 3093,
"s": 2963,
"text": "\n\nDedicated Servers \nRock-solid performance on dedicated hardware Perfect for larger websites and apps\nStarts at just | $78/mo\n\n"
},
{
"code": null,
"e": 3514,
"s": 3093,
"text": "\nEmail\n\n\n\n\n\n\nBusiness Email \nSimple & Easy to use Branded Email Ideal for beginners & small businesses\n5 GB Storage | $0.98/acc/mo\n\n\n\n\n\n\n\n\nEnterprise Email \nAdvanced Email for growing businesses & teams Includes Shared Contacts & Calendars\n30 GB Storage | $2.88/acc/mo\n\n\n\n\n\n\n\n\nGoogle Workspace\nIntelligent Email for seamless collaboration Includes Google Docs, Sheets & Drive\n30 GB Storage + Collaboration Suite \n\n\n\n\n\n\n"
},
{
"code": null,
"e": 3637,
"s": 3514,
"text": "\n\nBusiness Email \nSimple & Easy to use Branded Email Ideal for beginners & small businesses\n5 GB Storage | $0.98/acc/mo\n\n"
},
{
"code": null,
"e": 3771,
"s": 3637,
"text": "\n\nEnterprise Email \nAdvanced Email for growing businesses & teams Includes Shared Contacts & Calendars\n30 GB Storage | $2.88/acc/mo\n\n"
},
{
"code": null,
"e": 3911,
"s": 3771,
"text": "\n\nGoogle Workspace\nIntelligent Email for seamless collaboration Includes Google Docs, Sheets & Drive\n30 GB Storage + Collaboration Suite \n\n"
},
{
"code": null,
"e": 4145,
"s": 3911,
"text": "\nSecurity\n\n\n\n\n\n\n\nSecure your website and customer data\n Starts at just | $9.48/yr\n\n\n\n\n\n\n\n\n\nProtect your website from Viruses & Hackers\nStarts at just | $14.28/yr\n\n\n\n\n\n\n\n\n\nCloud backup for your website\nStarts at just | $1.07/mo\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 4215,
"s": 4145,
"text": "\n\n\nSecure your website and customer data\n Starts at just | $9.48/yr\n\n"
},
{
"code": null,
"e": 4291,
"s": 4215,
"text": "\n\n\nProtect your website from Viruses & Hackers\nStarts at just | $14.28/yr\n\n"
},
{
"code": null,
"e": 4352,
"s": 4291,
"text": "\n\n\nCloud backup for your website\nStarts at just | $1.07/mo\n\n"
},
{
"code": null,
"e": 4360,
"s": 4352,
"text": "\nWhois\n"
},
{
"code": null,
"e": 4524,
"s": 4360,
"text": "\nSupport\n\n\n\n\n\n\nContact Us \nGetting in touch is easy!\n\n\n\n\n\n\n\n\nKnowledge Base \nDetailed information regarding all our current Product and Service offerings\n\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 4566,
"s": 4524,
"text": "\n\nContact Us \nGetting in touch is easy!\n\n"
},
{
"code": null,
"e": 4664,
"s": 4566,
"text": "\n\nKnowledge Base \nDetailed information regarding all our current Product and Service offerings\n\n"
},
{
"code": null,
"e": 4671,
"s": 4664,
"text": "\n\n\n0\n\n"
},
{
"code": null,
"e": 4726,
"s": 4671,
"text": "\n\n\nLogin\n\n\n\nLogin\nCreate an Account\nForgot Password\n\n\n"
},
{
"code": null,
"e": 4732,
"s": 4726,
"text": "Login"
},
{
"code": null,
"e": 4750,
"s": 4732,
"text": "Create an Account"
},
{
"code": null,
"e": 4766,
"s": 4750,
"text": "Forgot Password"
},
{
"code": null,
"e": 4779,
"s": 4766,
"text": "LoginSign up"
},
{
"code": null,
"e": 4913,
"s": 4779,
"text": "Domains\n\nRegister a Domain\nTransfer your Domain\nDomain Prices\nSpecial Offers\nDomain Suggestions\nFree with Every Domain\nWhois Lookup\n\n"
},
{
"code": null,
"e": 4931,
"s": 4913,
"text": "Register a Domain"
},
{
"code": null,
"e": 4952,
"s": 4931,
"text": "Transfer your Domain"
},
{
"code": null,
"e": 4966,
"s": 4952,
"text": "Domain Prices"
},
{
"code": null,
"e": 4981,
"s": 4966,
"text": "Special Offers"
},
{
"code": null,
"e": 5000,
"s": 4981,
"text": "Domain Suggestions"
},
{
"code": null,
"e": 5023,
"s": 5000,
"text": "Free with Every Domain"
},
{
"code": null,
"e": 5036,
"s": 5023,
"text": "Whois Lookup"
},
{
"code": null,
"e": 5063,
"s": 5036,
"text": "Website\n\nWebsite Builder\n\n"
},
{
"code": null,
"e": 5079,
"s": 5063,
"text": "Website Builder"
},
{
"code": null,
"e": 5102,
"s": 5079,
"text": "Cloud\n\nCloud Hosting\n\n"
},
{
"code": null,
"e": 5116,
"s": 5102,
"text": "Cloud Hosting"
},
{
"code": null,
"e": 5277,
"s": 5116,
"text": "Hosting\n\nShared Hosting\nLinux Hosting\nWindows Hosting\n\nReseller Hosting\nLinux Reseller Hosting\nWindows Reseller Hosting\n\nSpecialized Hosting\nWordPress Hosting\n\n"
},
{
"code": null,
"e": 5292,
"s": 5277,
"text": "Shared Hosting"
},
{
"code": null,
"e": 5306,
"s": 5292,
"text": "Linux Hosting"
},
{
"code": null,
"e": 5322,
"s": 5306,
"text": "Windows Hosting"
},
{
"code": null,
"e": 5339,
"s": 5322,
"text": "Reseller Hosting"
},
{
"code": null,
"e": 5362,
"s": 5339,
"text": "Linux Reseller Hosting"
},
{
"code": null,
"e": 5387,
"s": 5362,
"text": "Windows Reseller Hosting"
},
{
"code": null,
"e": 5407,
"s": 5387,
"text": "Specialized Hosting"
},
{
"code": null,
"e": 5425,
"s": 5407,
"text": "WordPress Hosting"
},
{
"code": null,
"e": 5478,
"s": 5425,
"text": "Servers\n\nVirtual Private Servers\nDedicated Servers\n\n"
},
{
"code": null,
"e": 5502,
"s": 5478,
"text": "Virtual Private Servers"
},
{
"code": null,
"e": 5520,
"s": 5502,
"text": "Dedicated Servers"
},
{
"code": null,
"e": 5578,
"s": 5520,
"text": "Email\n\nBusiness Email\nEnterprise Email\nGoogle Workspace\n\n"
},
{
"code": null,
"e": 5593,
"s": 5578,
"text": "Business Email"
},
{
"code": null,
"e": 5610,
"s": 5593,
"text": "Enterprise Email"
},
{
"code": null,
"e": 5627,
"s": 5610,
"text": "Google Workspace"
},
{
"code": null,
"e": 5707,
"s": 5627,
"text": "Security\n\nSSL Certificates\nSiteLock Malware Detector\nCodeGuard Website Backup\n\n"
},
{
"code": null,
"e": 5724,
"s": 5707,
"text": "SSL Certificates"
},
{
"code": null,
"e": 5750,
"s": 5724,
"text": "SiteLock Malware Detector"
},
{
"code": null,
"e": 5775,
"s": 5750,
"text": "CodeGuard Website Backup"
},
{
"code": null,
"e": 5781,
"s": 5775,
"text": "Whois"
},
{
"code": null,
"e": 5827,
"s": 5781,
"text": "Support\n\nKnowledge Base\nContact Us\nAbout Us\n\n"
},
{
"code": null,
"e": 5842,
"s": 5827,
"text": "Knowledge Base"
},
{
"code": null,
"e": 5853,
"s": 5842,
"text": "Contact Us"
},
{
"code": null,
"e": 5862,
"s": 5853,
"text": "About Us"
},
{
"code": null,
"e": 8697,
"s": 5862,
"text": "Domain Name: TUTORIALSPOINT.COM\nRegistry Domain ID: 613404007_DOMAIN_COM-VRSN\nRegistrar WHOIS Server: whois.godaddy.com\nRegistrar URL: https://www.godaddy.com\nUpdated Date: 2020-09-21T02:47:14Z\nCreation Date: 2006-09-30T02:23:20Z\nRegistrar Registration Expiration Date: 2025-09-30T02:23:20Z\nRegistrar: GoDaddy.com, LLC\nRegistrar IANA ID: 146\nRegistrar Abuse Contact Email: @godaddy.com\nRegistrar Abuse Contact Phone: +1.4806242505\nDomain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited\nDomain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited\nDomain Status: clientRenewProhibited https://icann.org/epp#clientRenewProhibited\nDomain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited\nRegistrant Organization: Tutorials Point India Limited\nRegistrant State/Province: Andhra Pradesh\nRegistrant Country: IN\nRegistrant Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM\nTech Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM\nAdmin Email: Select Contact Domain Holder link at https://www.godaddy.com/whois/results.aspx?domain=TUTORIALSPOINT.COM\nName Server: PDNS13.DOMAINCONTROL.COM\nName Server: PDNS14.DOMAINCONTROL.COM\nDNSSEC: unsigned\nURL of the ICANN WHOIS Data Problem Reporting System: http://wdprs.internic.net/\n>>> Last update of WHOIS database: 2022-03-29T09:15:12Z <<<\nFor more information on Whois status codes, please visit https://icann.org/epp\n\nTERMS OF USE: The data contained in this registrar's Whois database, while believed by the\nregistrar to be reliable, is provided \"as is\" with no guarantee or warranties regarding its\naccuracy. This information is provided for the sole purpose of assisting you in obtaining\ninformation about domain name registration records. Any use of this data for any other purpose\nis expressly forbidden without the prior written permission of this registrar. By submitting\nan inquiry, you agree to these terms and limitations of warranty. In particular, you agree not\nto use this data to allow, enable, or otherwise support the dissemination or collection of this\ndata, in part or in its entirety, for any purpose, such as transmission by e-mail, telephone,\npostal mail, facsimile or other means of mass unsolicited, commercial advertising or solicitations\nof any kind, including spam. You further agree not to use this data to enable high volume, automated\nor robotic electronic processes designed to collect or compile this data for any purpose, including\nmining this data for your own personal or commercial purposes. Failure to comply with these terms\nmay result in termination of access to the Whois database. These terms may be subject to modification\nat any time without notice.\n"
},
{
"code": null,
"e": 8717,
"s": 8697,
"text": "$24.88 $0.88Buy Now"
},
{
"code": null,
"e": 8745,
"s": 8717,
"text": "*Offer ends 30th April 2022"
},
{
"code": null,
"e": 8757,
"s": 8745,
"text": "godaddy.com"
},
{
"code": null,
"e": 8767,
"s": 8757,
"text": "icann.org"
},
{
"code": null,
"e": 8785,
"s": 8767,
"text": "domaincontrol.com"
},
{
"code": null,
"e": 8798,
"s": 8785,
"text": "internic.net"
},
{
"code": null,
"e": 8902,
"s": 8798,
"text": "Leading provider of web presence solutions that empower you to establish and grow your online presence."
},
{
"code": null,
"e": 8922,
"s": 8902,
"text": "Learn more About Us"
},
{
"code": null,
"e": 8943,
"s": 8922,
"text": "Register Domain Name"
},
{
"code": null,
"e": 8964,
"s": 8943,
"text": "Transfer Domain Name"
},
{
"code": null,
"e": 8984,
"s": 8964,
"text": "View Domain Pricing"
},
{
"code": null,
"e": 8997,
"s": 8984,
"text": "Whois Lookup"
},
{
"code": null,
"e": 9018,
"s": 8997,
"text": "Name Suggestion Tool"
},
{
"code": null,
"e": 9041,
"s": 9018,
"text": "Free with Every Domain"
},
{
"code": null,
"e": 9055,
"s": 9041,
"text": "Domain Offers"
},
{
"code": null,
"e": 9069,
"s": 9055,
"text": "Linux Hosting"
},
{
"code": null,
"e": 9085,
"s": 9069,
"text": "Windows Hosting"
},
{
"code": null,
"e": 9103,
"s": 9085,
"text": "WordPress Hosting"
},
{
"code": null,
"e": 9126,
"s": 9103,
"text": "Linux Reseller Hosting"
},
{
"code": null,
"e": 9151,
"s": 9126,
"text": "Windows Reseller Hosting"
},
{
"code": null,
"e": 9169,
"s": 9151,
"text": "Dedicated Servers"
},
{
"code": null,
"e": 9183,
"s": 9169,
"text": "Cloud Hosting"
},
{
"code": null,
"e": 9199,
"s": 9183,
"text": "Website Builder"
},
{
"code": null,
"e": 9214,
"s": 9199,
"text": "Business Email"
},
{
"code": null,
"e": 9231,
"s": 9214,
"text": "Enterprise Email"
},
{
"code": null,
"e": 9248,
"s": 9231,
"text": "Google Workspace"
},
{
"code": null,
"e": 9265,
"s": 9248,
"text": "SSL Certificates"
},
{
"code": null,
"e": 9274,
"s": 9265,
"text": "Sitelock"
},
{
"code": null,
"e": 9284,
"s": 9274,
"text": "CodeGuard"
},
{
"code": null,
"e": 9303,
"s": 9284,
"text": "Datacenter Details"
},
{
"code": null,
"e": 9320,
"s": 9303,
"text": "Hosting Security"
},
{
"code": null,
"e": 9346,
"s": 9320,
"text": "24 x 7 Servers Monitoring"
},
{
"code": null,
"e": 9366,
"s": 9346,
"text": "Backup and Recovery"
},
{
"code": null,
"e": 9386,
"s": 9366,
"text": "View Knowledge Base"
},
{
"code": null,
"e": 9402,
"s": 9386,
"text": "Contact Support"
},
{
"code": null,
"e": 9415,
"s": 9402,
"text": "Report Abuse"
},
{
"code": null,
"e": 9427,
"s": 9415,
"text": "About Whois"
}
] |
How to clear console in MongoDB?
|
To clear console in MongoDB, you can use any of the following two syntaxes.
The first syntax is as follows, which is the usage of keyboard shortcut −
Ctrl + L
After pressing the above key, you can clear console in MongoDB.
The second syntax is as follows −
cls
To understand the above syntaxes, let us implement them one by one. Here is the snapshot of my console.
The first query is as follows to clear console in MongoDB −
Ctrl+L;
The following is the output −
Look at the above sample output, the console has been cleared. Let us check the console once again.
The second query is as follows to clear console i.e. type “cls” −
After pressing enter key, the console will clear. The screenshot of the sample output is as follows −
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To clear console in MongoDB, you can use any of the following two syntaxes."
},
{
"code": null,
"e": 1212,
"s": 1138,
"text": "The first syntax is as follows, which is the usage of keyboard shortcut −"
},
{
"code": null,
"e": 1221,
"s": 1212,
"text": "Ctrl + L"
},
{
"code": null,
"e": 1285,
"s": 1221,
"text": "After pressing the above key, you can clear console in MongoDB."
},
{
"code": null,
"e": 1319,
"s": 1285,
"text": "The second syntax is as follows −"
},
{
"code": null,
"e": 1323,
"s": 1319,
"text": "cls"
},
{
"code": null,
"e": 1427,
"s": 1323,
"text": "To understand the above syntaxes, let us implement them one by one. Here is the snapshot of my console."
},
{
"code": null,
"e": 1487,
"s": 1427,
"text": "The first query is as follows to clear console in MongoDB −"
},
{
"code": null,
"e": 1495,
"s": 1487,
"text": "Ctrl+L;"
},
{
"code": null,
"e": 1525,
"s": 1495,
"text": "The following is the output −"
},
{
"code": null,
"e": 1625,
"s": 1525,
"text": "Look at the above sample output, the console has been cleared. Let us check the console once again."
},
{
"code": null,
"e": 1691,
"s": 1625,
"text": "The second query is as follows to clear console i.e. type “cls” −"
},
{
"code": null,
"e": 1793,
"s": 1691,
"text": "After pressing enter key, the console will clear. The screenshot of the sample output is as follows −"
}
] |
Program for credit card number validation - GeeksforGeeks
|
16 Feb, 2021
Write a program that prompts the user to enter a credit card number as a long integer and Display whether that card is valid or invalid.Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits. It must start with:
4 for Visa cards
5 for Master cards
37 for American Express cards
6 for Discover cards
The problem can be solved by using Luhn algorithm. Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388576018402626):Step 1. Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number (like for 12:1+2, 18=1+8).Step 2. Now add all single-digit numbers from Step 1. 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37Step 3. Add all digits in the odd places from right to left in the card number. 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38Step 4. Sum the results from Step 2 and Step 3. 37 + 38 = 75Step 5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. Examples :
Input : 379354508162306
Output : 379354508162306 is Valid
Input : 4388576018402626
Output : 4388576018402626 is invalid
C++
Java
C#
// C++ program to check if a given credit// card is valid or not.#include <iostream>using namespace std; // Return this number if it is a single digit, otherwise,// return the sum of the two digitsint getDigit(int number){ if (number < 9) return number; return number / 10 + number % 10;} // Return the number of digits in dint getSize(long d){ string num = to_string(d); return num.length();} // Return the first k number of digits from// number. If the number of digits in number// is less than k, return number.long getPrefix(long number, int k){ if (getSize(number) > k) { string num = to_string(number); return stol(num.substr(0, k)); } return number;} // Return true if the digit d is a prefix for numberbool prefixMatched(long number, int d){ return getPrefix(number, getSize(d)) == d;} // Get the result from Step 2int sumOfDoubleEvenPlace(long int number){ int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int(num[i] - '0') * 2); return sum;} // Return sum of odd-place digits in numberint sumOfOddPlace(long number){ int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += num[i] - '0'; return sum;} // Return true if the card number is validbool isValid(long int number){ return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0);} // Driver Codeint main(){ long int number = 5196081888500645L; cout << number << " is " << (isValid(number) ? "valid" : "invalid"); return 0;} // This code is contributed by yuvraj_chandra
// Java program to check if a given credit// card is valid or not.import java.util.Scanner; public class CreditCard { // Main Method public static void main(String[] args) { long number = 5196081888500645L; System.out.println(number + " is " + (isValid(number) ? "valid" : "invalid")); } // Return true if the card number is valid public static boolean isValid(long number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Get the result from Step 2 public static int sumOfDoubleEvenPlace(long number) { int sum = 0; String num = number + ""; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(Integer.parseInt(num.charAt(i) + "") * 2); return sum; } // Return this number if it is a single digit, otherwise, // return the sum of the two digits public static int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return sum of odd-place digits in number public static int sumOfOddPlace(long number) { int sum = 0; String num = number + ""; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += Integer.parseInt(num.charAt(i) + ""); return sum; } // Return true if the digit d is a prefix for number public static boolean prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Return the number of digits in d public static int getSize(long d) { String num = d + ""; return num.length(); } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. public static long getPrefix(long number, int k) { if (getSize(number) > k) { String num = number + ""; return Long.parseLong(num.substring(0, k)); } return number; }}
// C# program to check if a given// credit card is valid or not.using System; class CreditCard { // Main Method public static void Main() { long number = 5196081888500645L; Console.Write(number + " is " + (isValid(number) ? "valid" : "invalid")); } // Return true if the card number is valid public static bool isValid(long number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Get the result from Step 2 public static int sumOfDoubleEvenPlace(long number) { int sum = 0; String num = number + ""; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int.Parse(num[i] + "") * 2); return sum; } // Return this number if it is a // single digit, otherwise, return // the sum of the two digits public static int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return sum of odd-place digits in number public static int sumOfOddPlace(long number) { int sum = 0; String num = number + ""; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += int.Parse(num[i] + ""); return sum; } // Return true if the digit d // is a prefix for number public static bool prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Return the number of digits in d public static int getSize(long d) { String num = d + ""; return num.Length; } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. public static long getPrefix(long number, int k) { if (getSize(number) > k) { String num = number + ""; return long.Parse(num.Substring(0, k)); } return number; }} // This code is contributed by nitin mittal.
Output:
5196081888500645 is valid
This article is contributed by Vishal Kumar Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
yuvraj_chandra
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
|
[
{
"code": null,
"e": 24817,
"s": 24789,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 25076,
"s": 24817,
"text": "Write a program that prompts the user to enter a credit card number as a long integer and Display whether that card is valid or invalid.Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits. It must start with: "
},
{
"code": null,
"e": 25093,
"s": 25076,
"text": "4 for Visa cards"
},
{
"code": null,
"e": 25112,
"s": 25093,
"text": "5 for Master cards"
},
{
"code": null,
"e": 25142,
"s": 25112,
"text": "37 for American Express cards"
},
{
"code": null,
"e": 25163,
"s": 25142,
"text": "6 for Discover cards"
},
{
"code": null,
"e": 25908,
"s": 25163,
"text": "The problem can be solved by using Luhn algorithm. Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388576018402626):Step 1. Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number (like for 12:1+2, 18=1+8).Step 2. Now add all single-digit numbers from Step 1. 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37Step 3. Add all digits in the odd places from right to left in the card number. 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38Step 4. Sum the results from Step 2 and Step 3. 37 + 38 = 75Step 5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. Examples : "
},
{
"code": null,
"e": 26029,
"s": 25908,
"text": "Input : 379354508162306\nOutput : 379354508162306 is Valid\n\nInput : 4388576018402626\nOutput : 4388576018402626 is invalid"
},
{
"code": null,
"e": 26037,
"s": 26033,
"text": "C++"
},
{
"code": null,
"e": 26042,
"s": 26037,
"text": "Java"
},
{
"code": null,
"e": 26045,
"s": 26042,
"text": "C#"
},
{
"code": "// C++ program to check if a given credit// card is valid or not.#include <iostream>using namespace std; // Return this number if it is a single digit, otherwise,// return the sum of the two digitsint getDigit(int number){ if (number < 9) return number; return number / 10 + number % 10;} // Return the number of digits in dint getSize(long d){ string num = to_string(d); return num.length();} // Return the first k number of digits from// number. If the number of digits in number// is less than k, return number.long getPrefix(long number, int k){ if (getSize(number) > k) { string num = to_string(number); return stol(num.substr(0, k)); } return number;} // Return true if the digit d is a prefix for numberbool prefixMatched(long number, int d){ return getPrefix(number, getSize(d)) == d;} // Get the result from Step 2int sumOfDoubleEvenPlace(long int number){ int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int(num[i] - '0') * 2); return sum;} // Return sum of odd-place digits in numberint sumOfOddPlace(long number){ int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += num[i] - '0'; return sum;} // Return true if the card number is validbool isValid(long int number){ return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0);} // Driver Codeint main(){ long int number = 5196081888500645L; cout << number << \" is \" << (isValid(number) ? \"valid\" : \"invalid\"); return 0;} // This code is contributed by yuvraj_chandra",
"e": 27840,
"s": 26045,
"text": null
},
{
"code": "// Java program to check if a given credit// card is valid or not.import java.util.Scanner; public class CreditCard { // Main Method public static void main(String[] args) { long number = 5196081888500645L; System.out.println(number + \" is \" + (isValid(number) ? \"valid\" : \"invalid\")); } // Return true if the card number is valid public static boolean isValid(long number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Get the result from Step 2 public static int sumOfDoubleEvenPlace(long number) { int sum = 0; String num = number + \"\"; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(Integer.parseInt(num.charAt(i) + \"\") * 2); return sum; } // Return this number if it is a single digit, otherwise, // return the sum of the two digits public static int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return sum of odd-place digits in number public static int sumOfOddPlace(long number) { int sum = 0; String num = number + \"\"; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += Integer.parseInt(num.charAt(i) + \"\"); return sum; } // Return true if the digit d is a prefix for number public static boolean prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Return the number of digits in d public static int getSize(long d) { String num = d + \"\"; return num.length(); } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. public static long getPrefix(long number, int k) { if (getSize(number) > k) { String num = number + \"\"; return Long.parseLong(num.substring(0, k)); } return number; }}",
"e": 30134,
"s": 27840,
"text": null
},
{
"code": "// C# program to check if a given// credit card is valid or not.using System; class CreditCard { // Main Method public static void Main() { long number = 5196081888500645L; Console.Write(number + \" is \" + (isValid(number) ? \"valid\" : \"invalid\")); } // Return true if the card number is valid public static bool isValid(long number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Get the result from Step 2 public static int sumOfDoubleEvenPlace(long number) { int sum = 0; String num = number + \"\"; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int.Parse(num[i] + \"\") * 2); return sum; } // Return this number if it is a // single digit, otherwise, return // the sum of the two digits public static int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return sum of odd-place digits in number public static int sumOfOddPlace(long number) { int sum = 0; String num = number + \"\"; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += int.Parse(num[i] + \"\"); return sum; } // Return true if the digit d // is a prefix for number public static bool prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Return the number of digits in d public static int getSize(long d) { String num = d + \"\"; return num.Length; } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. public static long getPrefix(long number, int k) { if (getSize(number) > k) { String num = number + \"\"; return long.Parse(num.Substring(0, k)); } return number; }} // This code is contributed by nitin mittal.",
"e": 32420,
"s": 30134,
"text": null
},
{
"code": null,
"e": 32430,
"s": 32420,
"text": "Output: "
},
{
"code": null,
"e": 32456,
"s": 32430,
"text": "5196081888500645 is valid"
},
{
"code": null,
"e": 32887,
"s": 32456,
"text": "This article is contributed by Vishal Kumar Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32900,
"s": 32887,
"text": "nitin mittal"
},
{
"code": null,
"e": 32915,
"s": 32900,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 32923,
"s": 32915,
"text": "Strings"
},
{
"code": null,
"e": 32931,
"s": 32923,
"text": "Strings"
},
{
"code": null,
"e": 33029,
"s": 32931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33038,
"s": 33029,
"text": "Comments"
},
{
"code": null,
"e": 33051,
"s": 33038,
"text": "Old Comments"
},
{
"code": null,
"e": 33108,
"s": 33051,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 33183,
"s": 33108,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 33219,
"s": 33183,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33266,
"s": 33219,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 33302,
"s": 33266,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 33355,
"s": 33302,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33393,
"s": 33355,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 33425,
"s": 33393,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 33455,
"s": 33425,
"text": "Caesar Cipher in Cryptography"
}
] |
How to perform right click on an element in Selenium with python?
|
We can perform right click on an element in Selenium with the help of
Action Chains class. These classes are generally used for automating interactions
like context menu click, mouse button actions, key press and mouse movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
context_click() − This method performs right click operation on an element of the
page.
context_click(args)
Where args is the element which has to be right clicked. If omitted, the click on
the present mouse position is performed.
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# right click operation
action.context_click(source)
Code Implementation for right click operation.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='Company']");
# action chain object creation
action = ActionChains(driver)
# right click operation and then perform
action.context_click(source).perform()
#to close the browser
driver.close()
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "We can perform right click on an element in Selenium with the help of\nAction Chains class. These classes are generally used for automating interactions\nlike context menu click, mouse button actions, key press and mouse movements."
},
{
"code": null,
"e": 1554,
"s": 1292,
"text": "These types of actions are mainly common in complex scenarios like drag and drop\nand hovering over an element on the page. The methods of the Action Chains class\nare utilized by advanced scripts. We can manipulate DOM with the help of Action\nChains in Selenium."
},
{
"code": null,
"e": 1754,
"s": 1554,
"text": "The action chain object implements the ActionChains in the form of a queue and\nthen executes the perform() method. On calling the method perform(), all the\nactions on action chains will be performed."
},
{
"code": null,
"e": 1818,
"s": 1754,
"text": "The method of creating an Action Chain object is listed below −"
},
{
"code": null,
"e": 1922,
"s": 1818,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2026,
"s": 1922,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2108,
"s": 2026,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2190,
"s": 2108,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2239,
"s": 2190,
"text": "Syntax for creating an object of Action Chains −"
},
{
"code": null,
"e": 2270,
"s": 2239,
"text": "from selenium import webdriver"
},
{
"code": null,
"e": 2451,
"s": 2270,
"text": "# import Action chains\nfrom selenium.webdriver import ActionChains\n# create webdriver object\ndriver = webdriver.Firefox()\n# create action chain object\naction = ActionChains(driver)"
},
{
"code": null,
"e": 2570,
"s": 2451,
"text": "After creating an object of Action Chains, we can perform numerous operations\none by one like a chain which is queued."
},
{
"code": null,
"e": 2658,
"s": 2570,
"text": "context_click() − This method performs right click operation on an element of the\npage."
},
{
"code": null,
"e": 2678,
"s": 2658,
"text": "context_click(args)"
},
{
"code": null,
"e": 2801,
"s": 2678,
"text": "Where args is the element which has to be right clicked. If omitted, the click on\nthe present mouse position is performed."
},
{
"code": null,
"e": 2957,
"s": 2801,
"text": "#element\nsource = driver.find_element_by_id(\"name\")\n#action chain object\naction = ActionChains(driver)\n# right click operation\naction.context_click(source)"
},
{
"code": null,
"e": 3004,
"s": 2957,
"text": "Code Implementation for right click operation."
},
{
"code": null,
"e": 3798,
"s": 3004,
"text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the source element\nsource= driver.find_element_by_xpath(\"//*[text()='Company']\");\n# action chain object creation\naction = ActionChains(driver)\n# right click operation and then perform\naction.context_click(source).perform()\n#to close the browser\ndriver.close()"
}
] |
How to run Python Program?
|
After writing the code, we need to run the code to execute and obtain the output. On running the program, we can check whether the code is written is correct and produces the desired output.
Running a python program is quite an easy task.
To run a python program on IDLE, follow the given steps −
Write the python code and save it.
Write the python code and save it.
To run the program, go to Run > Run Module or simply click F5.
To run the program, go to Run > Run Module or simply click F5.
The python script file is saved with ‘.py’ extension. After saving the python script, we can run it from the Command Line. In the cmd, type keyword ‘python’ followed by the name of the file with which you saved the python script.
Example
Let us suppose, we have a python script saved with the name ‘hello.py’. To run it on command line, type the following −
python hello.py
To run a python program on an IDE like PyCharm, we need to follow the given steps −
Create a new python file and save it with some name, say “hello.py”.You don’t need to specify the extension as it will pick it automatically.
Create a new python file and save it with some name, say “hello.py”.You don’t need to specify the extension as it will pick it automatically.
After writing the required code in the python file, we need to run it.
After writing the required code in the python file, we need to run it.
To run, Click on the Green Play Button at the top right corner of the IDE. The second way to run is, Right click and select ‘Run File in Python Console’ option.This will open a console box at the bottom and output will be shown there.
To run, Click on the Green Play Button at the top right corner of the IDE. The second way to run is, Right click and select ‘Run File in Python Console’ option.
This will open a console box at the bottom and output will be shown there.
Interactive mode is the method to type and run python code in command line. In interactive mode, the python code is written and run line by line in a sequential manner.To enter into interactive mode, open Command Prompt and type ‘python’ and press Enter.
Write one line of code and press enter to execute it and enter the second line.
Example
To run the code in interactive mode, You must have python installed on your system. On typing ‘python’ , the version of the python installed on your system is displayed. This means that python is installed on your system and we can move forward in running python scripts. On entering one line of code i.e. print(“Hello World”) ,after pressing enter the “Hello World” is displayed.
We can run python script on a text editor. To do so,follow the following steps −
Create a file with a name ,let “hello.py”.
Create a file with a name ,let “hello.py”.
Write some python code in the file.
Write some python code in the file.
To run the code, Right Click > Select Run Code. Else, press ‘Ctrl+Alt+N’ to run the code.
To run the code, Right Click > Select Run Code. Else, press ‘Ctrl+Alt+N’ to run the code.
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "After writing the code, we need to run the code to execute and obtain the output. On running the program, we can check whether the code is written is correct and produces the desired output."
},
{
"code": null,
"e": 1301,
"s": 1253,
"text": "Running a python program is quite an easy task."
},
{
"code": null,
"e": 1359,
"s": 1301,
"text": "To run a python program on IDLE, follow the given steps −"
},
{
"code": null,
"e": 1394,
"s": 1359,
"text": "Write the python code and save it."
},
{
"code": null,
"e": 1429,
"s": 1394,
"text": "Write the python code and save it."
},
{
"code": null,
"e": 1492,
"s": 1429,
"text": "To run the program, go to Run > Run Module or simply click F5."
},
{
"code": null,
"e": 1555,
"s": 1492,
"text": "To run the program, go to Run > Run Module or simply click F5."
},
{
"code": null,
"e": 1785,
"s": 1555,
"text": "The python script file is saved with ‘.py’ extension. After saving the python script, we can run it from the Command Line. In the cmd, type keyword ‘python’ followed by the name of the file with which you saved the python script."
},
{
"code": null,
"e": 1793,
"s": 1785,
"text": "Example"
},
{
"code": null,
"e": 1913,
"s": 1793,
"text": "Let us suppose, we have a python script saved with the name ‘hello.py’. To run it on command line, type the following −"
},
{
"code": null,
"e": 1929,
"s": 1913,
"text": "python hello.py"
},
{
"code": null,
"e": 2013,
"s": 1929,
"text": "To run a python program on an IDE like PyCharm, we need to follow the given steps −"
},
{
"code": null,
"e": 2155,
"s": 2013,
"text": "Create a new python file and save it with some name, say “hello.py”.You don’t need to specify the extension as it will pick it automatically."
},
{
"code": null,
"e": 2297,
"s": 2155,
"text": "Create a new python file and save it with some name, say “hello.py”.You don’t need to specify the extension as it will pick it automatically."
},
{
"code": null,
"e": 2368,
"s": 2297,
"text": "After writing the required code in the python file, we need to run it."
},
{
"code": null,
"e": 2439,
"s": 2368,
"text": "After writing the required code in the python file, we need to run it."
},
{
"code": null,
"e": 2674,
"s": 2439,
"text": "To run, Click on the Green Play Button at the top right corner of the IDE. The second way to run is, Right click and select ‘Run File in Python Console’ option.This will open a console box at the bottom and output will be shown there."
},
{
"code": null,
"e": 2835,
"s": 2674,
"text": "To run, Click on the Green Play Button at the top right corner of the IDE. The second way to run is, Right click and select ‘Run File in Python Console’ option."
},
{
"code": null,
"e": 2910,
"s": 2835,
"text": "This will open a console box at the bottom and output will be shown there."
},
{
"code": null,
"e": 3165,
"s": 2910,
"text": "Interactive mode is the method to type and run python code in command line. In interactive mode, the python code is written and run line by line in a sequential manner.To enter into interactive mode, open Command Prompt and type ‘python’ and press Enter."
},
{
"code": null,
"e": 3245,
"s": 3165,
"text": "Write one line of code and press enter to execute it and enter the second line."
},
{
"code": null,
"e": 3253,
"s": 3245,
"text": "Example"
},
{
"code": null,
"e": 3634,
"s": 3253,
"text": "To run the code in interactive mode, You must have python installed on your system. On typing ‘python’ , the version of the python installed on your system is displayed. This means that python is installed on your system and we can move forward in running python scripts. On entering one line of code i.e. print(“Hello World”) ,after pressing enter the “Hello World” is displayed."
},
{
"code": null,
"e": 3715,
"s": 3634,
"text": "We can run python script on a text editor. To do so,follow the following steps −"
},
{
"code": null,
"e": 3758,
"s": 3715,
"text": "Create a file with a name ,let “hello.py”."
},
{
"code": null,
"e": 3801,
"s": 3758,
"text": "Create a file with a name ,let “hello.py”."
},
{
"code": null,
"e": 3837,
"s": 3801,
"text": "Write some python code in the file."
},
{
"code": null,
"e": 3873,
"s": 3837,
"text": "Write some python code in the file."
},
{
"code": null,
"e": 3963,
"s": 3873,
"text": "To run the code, Right Click > Select Run Code. Else, press ‘Ctrl+Alt+N’ to run the code."
},
{
"code": null,
"e": 4053,
"s": 3963,
"text": "To run the code, Right Click > Select Run Code. Else, press ‘Ctrl+Alt+N’ to run the code."
}
] |
Efficient Cardinality Estimation using HLL with Spark and Postgres | by Ankit Prakash Gupta | Towards Data Science
|
A complete guide that assists you to do end-to-end efficient cardinality estimation using HyperLogLog Algorithm.
The cardinality estimation problem is the problem of finding the number of distinct elements in a chunk of data with the same elements being repeated multiple times. The problem is very generic and has a lot of applications in the real world like active-unique users of a website, unique live sessions and many more.
The problem seems to be child’s play, but we have to keep all the values in a set to keep a track of what all values we have already taken into consideration and this will eventually be a problem when we talk of Millions or Billions of Users/ Sessions. We surely cannot keep and process sets having such big cardinalities in memory.
We can use any of the following approaches for doing the cardinality estimation:
Distinct CountingLinear CountingLogLog AlgorithmHyperLogLog Algorithm
Distinct Counting
Linear Counting
LogLog Algorithm
HyperLogLog Algorithm
Distinct Counting
Brute-force approach of finding the cardinality, what we discussed above about keeping all unique elements in a set and finding out the cardinality. It is linear O(n) in terms of time and space complexities, storing all objects as is.
Linear Counting
This technique uses a hash table with capacity B bits, all bits initialised to 0. As soon as an entry arrives we hash it and that bit’s value is changed to 1. Deduplication is being taken care of by hashing the inputs. This algorithm is also linear in terms of time and space complexities but takes much less space as we are only saving bits and not the exact values. Now, let’s compare the size of the hash table with the size of Unique Elements we can have. Suppose, N unique entries can come in your set:
When N << B, then hash collisions would be less and the count of 1 bit in the hash table would be a good estimate of the cardinality.When N ≈ B, then a significant number of hash collisions would surely occur. But we can estimate the number of collisions by checking how full the hash table is. Using this estimation of the number of collisions we can extrapolate to the approximate cardinality of the set.When N >> B, then every bit in the hash table would be set to 1 and it won’t be possible to calculate the true cardinality.
When N << B, then hash collisions would be less and the count of 1 bit in the hash table would be a good estimate of the cardinality.
When N ≈ B, then a significant number of hash collisions would surely occur. But we can estimate the number of collisions by checking how full the hash table is. Using this estimation of the number of collisions we can extrapolate to the approximate cardinality of the set.
When N >> B, then every bit in the hash table would be set to 1 and it won’t be possible to calculate the true cardinality.
This approach seems to be a good fit when we have knowledge about the maximum possible unique elements we can have priori.
LogLog Algorithm
This algorithm is also based on hashing, it keeps a track of the maximum number of zeroes appearing in the binary representation of the hashed values. Let’s assume that the maximum number of zeroes appearing is k, then the estimated count would be 2^k.
It is based on the idea that one-half of the values would start with 1 and one-fourth with 01 and one-eighth with 001 and so on, the probability of getting the k leading zeroes would be 1/2^(k+1). Now, this estimation would be very unstable and would have a very high variance as we can have the very first hashed value having 5 leading zeroes also.
To make it more stable we take average (arithmetic mean) values of the estimates given by multiple hash functions. Bringing us to another computationally expensive process, hashing. Now, to cater for this issue, LogLog converts the value attained from the already hashed value into 2 values, taking the first m bits, which points to a specific bucket of values and then the rest of the bits as the value to get the maximum number of zeroes.
So, if we assume that our hash function returned 32 bits, and we took the first 14 bits to decide the bucket to which it points, so we will have 2^14 buckets to average the value of k from.
Suppose in each bucket we wanted to store N elements then we will have to store only a single number which is of log(N) magnitude and to store that we need only log(log(N)) number of bits, which gives it its name.
Taking as an example, if we take 5 bits register for each bucket to store the max-value of k for that bucket and 2^14 buckets, which will allow us to have values for each bucket from 0–31, which means that we might have 2^31 elements in each bucket (Using the above probability), which implies that we can approximately keep 2^(31+14) distinct elements at max, by using space (214 * 5) = 81920 bits (10 KBs) only.
It defines the estimated count as follows:
where, α → estimation factor (constant value) registers(i) → value of the max-leading-zero count for the ith bucket
This is an improvement algorithm on LogLog Algorithm. It uses Harmonic mean in place of arithmetic mean when combining the results of multiple buckets, which caters unusually high values of max-leading-zero counts. Additionally, it provides corrections for two extreme cases when not all of the buckets are occupied and when a hash collision causes underestimation.
Different libraries are implementing the HLL algorithm, we chose to use Aggregate Knowledge’s HLL implementation, because of the following factors:
Has an inter-operable library with Postgres DB (postgresql-hll) as well as same has been used by Swoop’s Spark-Alchemy.
Has an ability to union two HLLs.
Easy to use APIs.
To try out the postgresql-hll extension on Mac Systems, Please use the following steps:
So, the extension is installed in Postgres. Now, we need to run the following query to activate the extension in a particular DB.
To test the above example, Create a table and inserted some data with the following queries:
Then tried the interoperability of the HLLs in Postgres with Java APIs. Created another table using the following query
Then used a Java Program to Create HLLs using a range of numbers from 0 to n, so that we know how many unique entries are there in it, pushed them to Postgres and then aggregated and did a count on them. Since we know the unique entries this way, we can calculate the error percentages for user_id and session_id.
A few things to note here are:
If we want to union two HLLs or merge two HLLs, then we should always hash them with the same seed, or else the same value will also give two different hashed value and will be counted as two.
Standard Error for the HLLs can be given by the following formula and the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.σ = (1.04)/√(number of buckets)
We used the Java APIs to write the UDFs
Let’s visit the types of the HLLs AgKn has come up with to increase the accuracy of Cardinality Estimation.
EmptyA constant value denotes the empty set.
ExplicitAn explicit, unique, sorted list of hashed integers in the set, which is maintained up to a fixed cardinality [If using the Auto expthresh (-1) that number can be defined by (regwidth * 2^log2m)/64 )]. This is done to increase accuracy at low cardinalities, as we can directly keep the explicit set of hashed inputs as a sorted list of 64-bit integers. We can also tweak the expthresh, to keep more numbers or fewer numbers according to our use-case, but the auto mode supports optimal memory usage.
SparseIts idea is based on Sparse Arrays, in which we keep the values of indexes that have only non-zero values. Similarly, it is a map-based implementation of HLL, which stores only the indices values of non-zero registers in a map, until the number of non-zero registers exceeds a fixed cardinality. So, it actually keeps the registers value of only those buckets whose register is having at least 1 non-0 bit.
FullA fully materialised, list-based implementation of HLL. Explicitly stores the values of every register in a list ordered by register index.
Not, visiting the Schema Layout and how data is arranged in the byte array format, it can be visited here.
This value decides the number of buckets or registers, m is the actual number of registers here, and we can calculate the number of registers by 2(Log2m). Also, this value decides the accuracy of the HLLs. The following expression gives the standard error estimate. Also, one important thing to note is the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.σ = (1.04)/√(m)
This is the width of the Register/Bucket or the number of bits to be used per register in the HLL Algorithm. Must be at least 1 and at most 8. This parameter, in conjunction with log2m, tunes the maximum cardinality of the set whose cardinality can be estimated. Please refer to the table for the clarification of the HLL sizes and Maximum Cardinalities.
3. ExpThresh
Tunes when the EXPLICIT to SPARSE promotion occurs, based on the set’s cardinality.
If the `EXPLICIT` representation is turned off, the `EMPTY` set is promoted directly to `SPARSE`. Must be -1 {Promote at whatever cutoff makes sense for optimal memory usage. ('auto' mode)}, 0 {Skip EXPLICIT representation in hierarchy. (Promotes directly to Sparse.)}, or 1-18 inclusive {Promote at 2^expthresh - 1 cardinality}.
You can choose the EXPLICIT cutoff such that it will end up taking more memory than a FULL hll representation. This is allowed for those cases where perfect precision and accuracy are required up through some pre-set cardinality range, after which estimates of the cardinality are sufficient.
4. SparseOn
Enables or disables the SPARSE representation. If both the EXPLICIT and SPARSE representations are disabled, an EMPTY set will be promoted directly to a FULL set. If SPARSE is enabled, the promotion from SPARSE to FULL will occur when the internal SPARSE representation’s memory footprint would exceed that of the FULL version. Must be either true or false. True means enabled and false means disabled.
HyperLogLog Algorithm helps solve the cardinality estimation problem up to a certain threshold without overburdening the storage space to keep all the elements.
Additionally, Aggregate knowledge provides great Support for HLL Algorithms. Other libraries which can be tried are Datasketch, Zetasketch.
|
[
{
"code": null,
"e": 285,
"s": 172,
"text": "A complete guide that assists you to do end-to-end efficient cardinality estimation using HyperLogLog Algorithm."
},
{
"code": null,
"e": 602,
"s": 285,
"text": "The cardinality estimation problem is the problem of finding the number of distinct elements in a chunk of data with the same elements being repeated multiple times. The problem is very generic and has a lot of applications in the real world like active-unique users of a website, unique live sessions and many more."
},
{
"code": null,
"e": 935,
"s": 602,
"text": "The problem seems to be child’s play, but we have to keep all the values in a set to keep a track of what all values we have already taken into consideration and this will eventually be a problem when we talk of Millions or Billions of Users/ Sessions. We surely cannot keep and process sets having such big cardinalities in memory."
},
{
"code": null,
"e": 1016,
"s": 935,
"text": "We can use any of the following approaches for doing the cardinality estimation:"
},
{
"code": null,
"e": 1086,
"s": 1016,
"text": "Distinct CountingLinear CountingLogLog AlgorithmHyperLogLog Algorithm"
},
{
"code": null,
"e": 1104,
"s": 1086,
"text": "Distinct Counting"
},
{
"code": null,
"e": 1120,
"s": 1104,
"text": "Linear Counting"
},
{
"code": null,
"e": 1137,
"s": 1120,
"text": "LogLog Algorithm"
},
{
"code": null,
"e": 1159,
"s": 1137,
"text": "HyperLogLog Algorithm"
},
{
"code": null,
"e": 1177,
"s": 1159,
"text": "Distinct Counting"
},
{
"code": null,
"e": 1412,
"s": 1177,
"text": "Brute-force approach of finding the cardinality, what we discussed above about keeping all unique elements in a set and finding out the cardinality. It is linear O(n) in terms of time and space complexities, storing all objects as is."
},
{
"code": null,
"e": 1428,
"s": 1412,
"text": "Linear Counting"
},
{
"code": null,
"e": 1936,
"s": 1428,
"text": "This technique uses a hash table with capacity B bits, all bits initialised to 0. As soon as an entry arrives we hash it and that bit’s value is changed to 1. Deduplication is being taken care of by hashing the inputs. This algorithm is also linear in terms of time and space complexities but takes much less space as we are only saving bits and not the exact values. Now, let’s compare the size of the hash table with the size of Unique Elements we can have. Suppose, N unique entries can come in your set:"
},
{
"code": null,
"e": 2466,
"s": 1936,
"text": "When N << B, then hash collisions would be less and the count of 1 bit in the hash table would be a good estimate of the cardinality.When N ≈ B, then a significant number of hash collisions would surely occur. But we can estimate the number of collisions by checking how full the hash table is. Using this estimation of the number of collisions we can extrapolate to the approximate cardinality of the set.When N >> B, then every bit in the hash table would be set to 1 and it won’t be possible to calculate the true cardinality."
},
{
"code": null,
"e": 2600,
"s": 2466,
"text": "When N << B, then hash collisions would be less and the count of 1 bit in the hash table would be a good estimate of the cardinality."
},
{
"code": null,
"e": 2874,
"s": 2600,
"text": "When N ≈ B, then a significant number of hash collisions would surely occur. But we can estimate the number of collisions by checking how full the hash table is. Using this estimation of the number of collisions we can extrapolate to the approximate cardinality of the set."
},
{
"code": null,
"e": 2998,
"s": 2874,
"text": "When N >> B, then every bit in the hash table would be set to 1 and it won’t be possible to calculate the true cardinality."
},
{
"code": null,
"e": 3121,
"s": 2998,
"text": "This approach seems to be a good fit when we have knowledge about the maximum possible unique elements we can have priori."
},
{
"code": null,
"e": 3138,
"s": 3121,
"text": "LogLog Algorithm"
},
{
"code": null,
"e": 3391,
"s": 3138,
"text": "This algorithm is also based on hashing, it keeps a track of the maximum number of zeroes appearing in the binary representation of the hashed values. Let’s assume that the maximum number of zeroes appearing is k, then the estimated count would be 2^k."
},
{
"code": null,
"e": 3741,
"s": 3391,
"text": "It is based on the idea that one-half of the values would start with 1 and one-fourth with 01 and one-eighth with 001 and so on, the probability of getting the k leading zeroes would be 1/2^(k+1). Now, this estimation would be very unstable and would have a very high variance as we can have the very first hashed value having 5 leading zeroes also."
},
{
"code": null,
"e": 4182,
"s": 3741,
"text": "To make it more stable we take average (arithmetic mean) values of the estimates given by multiple hash functions. Bringing us to another computationally expensive process, hashing. Now, to cater for this issue, LogLog converts the value attained from the already hashed value into 2 values, taking the first m bits, which points to a specific bucket of values and then the rest of the bits as the value to get the maximum number of zeroes."
},
{
"code": null,
"e": 4372,
"s": 4182,
"text": "So, if we assume that our hash function returned 32 bits, and we took the first 14 bits to decide the bucket to which it points, so we will have 2^14 buckets to average the value of k from."
},
{
"code": null,
"e": 4586,
"s": 4372,
"text": "Suppose in each bucket we wanted to store N elements then we will have to store only a single number which is of log(N) magnitude and to store that we need only log(log(N)) number of bits, which gives it its name."
},
{
"code": null,
"e": 5000,
"s": 4586,
"text": "Taking as an example, if we take 5 bits register for each bucket to store the max-value of k for that bucket and 2^14 buckets, which will allow us to have values for each bucket from 0–31, which means that we might have 2^31 elements in each bucket (Using the above probability), which implies that we can approximately keep 2^(31+14) distinct elements at max, by using space (214 * 5) = 81920 bits (10 KBs) only."
},
{
"code": null,
"e": 5043,
"s": 5000,
"text": "It defines the estimated count as follows:"
},
{
"code": null,
"e": 5160,
"s": 5043,
"text": "where, α → estimation factor (constant value) registers(i) → value of the max-leading-zero count for the ith bucket"
},
{
"code": null,
"e": 5526,
"s": 5160,
"text": "This is an improvement algorithm on LogLog Algorithm. It uses Harmonic mean in place of arithmetic mean when combining the results of multiple buckets, which caters unusually high values of max-leading-zero counts. Additionally, it provides corrections for two extreme cases when not all of the buckets are occupied and when a hash collision causes underestimation."
},
{
"code": null,
"e": 5674,
"s": 5526,
"text": "Different libraries are implementing the HLL algorithm, we chose to use Aggregate Knowledge’s HLL implementation, because of the following factors:"
},
{
"code": null,
"e": 5794,
"s": 5674,
"text": "Has an inter-operable library with Postgres DB (postgresql-hll) as well as same has been used by Swoop’s Spark-Alchemy."
},
{
"code": null,
"e": 5828,
"s": 5794,
"text": "Has an ability to union two HLLs."
},
{
"code": null,
"e": 5846,
"s": 5828,
"text": "Easy to use APIs."
},
{
"code": null,
"e": 5934,
"s": 5846,
"text": "To try out the postgresql-hll extension on Mac Systems, Please use the following steps:"
},
{
"code": null,
"e": 6064,
"s": 5934,
"text": "So, the extension is installed in Postgres. Now, we need to run the following query to activate the extension in a particular DB."
},
{
"code": null,
"e": 6157,
"s": 6064,
"text": "To test the above example, Create a table and inserted some data with the following queries:"
},
{
"code": null,
"e": 6277,
"s": 6157,
"text": "Then tried the interoperability of the HLLs in Postgres with Java APIs. Created another table using the following query"
},
{
"code": null,
"e": 6591,
"s": 6277,
"text": "Then used a Java Program to Create HLLs using a range of numbers from 0 to n, so that we know how many unique entries are there in it, pushed them to Postgres and then aggregated and did a count on them. Since we know the unique entries this way, we can calculate the error percentages for user_id and session_id."
},
{
"code": null,
"e": 6622,
"s": 6591,
"text": "A few things to note here are:"
},
{
"code": null,
"e": 6815,
"s": 6622,
"text": "If we want to union two HLLs or merge two HLLs, then we should always hash them with the same seed, or else the same value will also give two different hashed value and will be counted as two."
},
{
"code": null,
"e": 7043,
"s": 6815,
"text": "Standard Error for the HLLs can be given by the following formula and the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.σ = (1.04)/√(number of buckets)"
},
{
"code": null,
"e": 7083,
"s": 7043,
"text": "We used the Java APIs to write the UDFs"
},
{
"code": null,
"e": 7191,
"s": 7083,
"text": "Let’s visit the types of the HLLs AgKn has come up with to increase the accuracy of Cardinality Estimation."
},
{
"code": null,
"e": 7236,
"s": 7191,
"text": "EmptyA constant value denotes the empty set."
},
{
"code": null,
"e": 7744,
"s": 7236,
"text": "ExplicitAn explicit, unique, sorted list of hashed integers in the set, which is maintained up to a fixed cardinality [If using the Auto expthresh (-1) that number can be defined by (regwidth * 2^log2m)/64 )]. This is done to increase accuracy at low cardinalities, as we can directly keep the explicit set of hashed inputs as a sorted list of 64-bit integers. We can also tweak the expthresh, to keep more numbers or fewer numbers according to our use-case, but the auto mode supports optimal memory usage."
},
{
"code": null,
"e": 8157,
"s": 7744,
"text": "SparseIts idea is based on Sparse Arrays, in which we keep the values of indexes that have only non-zero values. Similarly, it is a map-based implementation of HLL, which stores only the indices values of non-zero registers in a map, until the number of non-zero registers exceeds a fixed cardinality. So, it actually keeps the registers value of only those buckets whose register is having at least 1 non-0 bit."
},
{
"code": null,
"e": 8301,
"s": 8157,
"text": "FullA fully materialised, list-based implementation of HLL. Explicitly stores the values of every register in a list ordered by register index."
},
{
"code": null,
"e": 8408,
"s": 8301,
"text": "Not, visiting the Schema Layout and how data is arranged in the byte array format, it can be visited here."
},
{
"code": null,
"e": 8853,
"s": 8408,
"text": "This value decides the number of buckets or registers, m is the actual number of registers here, and we can calculate the number of registers by 2(Log2m). Also, this value decides the accuracy of the HLLs. The following expression gives the standard error estimate. Also, one important thing to note is the calculated values are expected to be within the σ, 2σ, 3σ of the actual count for 65%, 95%, 99% of the cases respectively.σ = (1.04)/√(m)"
},
{
"code": null,
"e": 9208,
"s": 8853,
"text": "This is the width of the Register/Bucket or the number of bits to be used per register in the HLL Algorithm. Must be at least 1 and at most 8. This parameter, in conjunction with log2m, tunes the maximum cardinality of the set whose cardinality can be estimated. Please refer to the table for the clarification of the HLL sizes and Maximum Cardinalities."
},
{
"code": null,
"e": 9221,
"s": 9208,
"text": "3. ExpThresh"
},
{
"code": null,
"e": 9305,
"s": 9221,
"text": "Tunes when the EXPLICIT to SPARSE promotion occurs, based on the set’s cardinality."
},
{
"code": null,
"e": 9635,
"s": 9305,
"text": "If the `EXPLICIT` representation is turned off, the `EMPTY` set is promoted directly to `SPARSE`. Must be -1 {Promote at whatever cutoff makes sense for optimal memory usage. ('auto' mode)}, 0 {Skip EXPLICIT representation in hierarchy. (Promotes directly to Sparse.)}, or 1-18 inclusive {Promote at 2^expthresh - 1 cardinality}."
},
{
"code": null,
"e": 9928,
"s": 9635,
"text": "You can choose the EXPLICIT cutoff such that it will end up taking more memory than a FULL hll representation. This is allowed for those cases where perfect precision and accuracy are required up through some pre-set cardinality range, after which estimates of the cardinality are sufficient."
},
{
"code": null,
"e": 9940,
"s": 9928,
"text": "4. SparseOn"
},
{
"code": null,
"e": 10343,
"s": 9940,
"text": "Enables or disables the SPARSE representation. If both the EXPLICIT and SPARSE representations are disabled, an EMPTY set will be promoted directly to a FULL set. If SPARSE is enabled, the promotion from SPARSE to FULL will occur when the internal SPARSE representation’s memory footprint would exceed that of the FULL version. Must be either true or false. True means enabled and false means disabled."
},
{
"code": null,
"e": 10504,
"s": 10343,
"text": "HyperLogLog Algorithm helps solve the cardinality estimation problem up to a certain threshold without overburdening the storage space to keep all the elements."
}
] |
Concatenate two lists element-wise in Python
|
Pyhton has great data manipulation features. In this article we will see how to combine the elements from two lists in the same order as they are present in the lists.
The zip function can take in the two lists as parameters and concatenate them. We design a for loop to capture these combinations and put them into a new list.
Live Demo
listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use zip
res = [i + j for i, j in zip(listA, listB)]
# Result
print("The concatenated lists: ",res)
Running the above code gives us the following result −
Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
The map function will apply the same function again and again to the parameters passed onto it. We will also use a lambda function to combine the individual elements one by one from the two lists through zip.
Live Demo
listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use map
res = list(map(lambda(i, j): i + j, zip(listA, listB)))
# Result
print("The concatenated lists: ",res)
Running the above code gives us the following result −
Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "Pyhton has great data manipulation features. In this article we will see how to combine the elements from two lists in the same order as they are present in the lists."
},
{
"code": null,
"e": 1390,
"s": 1230,
"text": "The zip function can take in the two lists as parameters and concatenate them. We design a for loop to capture these combinations and put them into a new list."
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": " Live Demo"
},
{
"code": null,
"e": 1648,
"s": 1401,
"text": "listA = [\"Outer-\", \"Frost-\", \"Sun-\"]\nlistB = ['Space', 'bite', 'rise']\n# Given lists\nprint(\"Given list A: \", listA)\nprint(\"Given list B: \",listB)\n# Use zip\nres = [i + j for i, j in zip(listA, listB)]\n# Result\nprint(\"The concatenated lists: \",res)"
},
{
"code": null,
"e": 1703,
"s": 1648,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1852,
"s": 1703,
"text": "Given list A: ['Outer-', 'Frost-', 'Sun-']\nGiven list B: ['Space', 'bite', 'rise']\nThe concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']"
},
{
"code": null,
"e": 2061,
"s": 1852,
"text": "The map function will apply the same function again and again to the parameters passed onto it. We will also use a lambda function to combine the individual elements one by one from the two lists through zip."
},
{
"code": null,
"e": 2072,
"s": 2061,
"text": " Live Demo"
},
{
"code": null,
"e": 2331,
"s": 2072,
"text": "listA = [\"Outer-\", \"Frost-\", \"Sun-\"]\nlistB = ['Space', 'bite', 'rise']\n# Given lists\nprint(\"Given list A: \", listA)\nprint(\"Given list B: \",listB)\n# Use map\nres = list(map(lambda(i, j): i + j, zip(listA, listB)))\n# Result\nprint(\"The concatenated lists: \",res)"
},
{
"code": null,
"e": 2386,
"s": 2331,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2535,
"s": 2386,
"text": "Given list A: ['Outer-', 'Frost-', 'Sun-']\nGiven list B: ['Space', 'bite', 'rise']\nThe concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']"
}
] |
Data lake on GCP using Terraform. Use Terraform to set up... | by Tuan Nguyen | Towards Data Science
|
Back in the old days, dealing with physical infrastructure is a huge burden, which not only requires teams of experts to manage but also is time-consuming. In the modern cloud computing era, however, you can deploy hundreds of computers instantly to solve your problems with the click of a button. Well, to be realistic, most day to day problems that we are trying to solve won’t require that much computing power.
Infrastructure as code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.
Wikipedia
So instead of placing a physical server on a rack, setting up all the cables, configuring the network, installing all the required operating system, you can write codes to do all that. To use IaC, you typically would use a source code control repository, write code to configure your infrastructures, run the code locally, or set up an automation to execute your code on every commit.
Why bother setting up and learning new stuff to manage your infrastructure while you can do that through the interface of all cloud providers, you ask? There are many advantages to having version control of our infrastructure.
IaC enables you to create different environments with ease, especially when your project is complex, and there are a lot of moving parts. For example, after setting up a development environment with multiple projects, VPCs, storage, compute instances, and IAM, it is counter-productive to do the same thing for staging and production environment.
With IaC, you can replicate your environment with some minor changes to your codebase. You can even customize your environment to suit your needs. For instance, you can set up different machine types for prod and dev, or set up a more permissive IAM for dev.
Imagine if an intern mess up your production environment, you can tear down everything and build up your environments with ease (given that your underlying data are unscathed)
On a large project, you can have environments with complex permissions and policies. Not only do you have to worry about designing and setting up these environments, enforcing the policies and permissions can also be challenging.
With IaC, every change in your environment is versioned, so you know who makes what changes (given that you limit admin permissions to only your IaC service). You can also periodically scan your environments for differences between the configurations and the actual environments. Most IaC service would then be able to revert your environment to the configurations if they detect any alternations.
When your infrastructures are managed by code, you can share them between teams or use them for later projects. You can also generate infrastructure documentation automatically based on the configurations.
Great, so let’s get started setting up the infrastructure for a data lake on Google Cloud Platform using Terraform. You can use any other IaC tool on any other cloud provider, and I choose this combination since it is familiar to me.
Terraform is an open-source infrastructure as code software tool created by HashiCorp. It enables users to define and provision data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language, or optionally JSON. Terraform manages external resources with “providers”. Wikipedia
In this project, we will use terraform code to provision resources and permissions for a data lake on GCP. The diagram above is a simplified version of a data lake, and we will write code to provision and set up everything on GCP.
Let me briefly walk through the architecture of a typical data lake on GCP (for simplicity, I only consider batch pipeline). You would generally have systems producing data, running on-premise, or other cloud providers/project that you need to connect to. You would connect to these systems via VPN or interconnect for security purposes. Then you will need an orchestration/staging server to extract data and load them to your storage buckets.
The data will then be classified and load into different buckets. Raw data would typically be ingested in the landing bucket. Data with sensitive customer information would be treated separately (masking, deidentification, separate permission policy) and load to the sensitive bucket. The work bucket is used for work in process data of data engineers and data scientists, and the backup bucket is for backup of cleansed data.
The data then would be loaded to the data warehouse, where it would be separated based on the system of ingestion (different companies may do this differently). Data here is cleansed normalize/denormalize based on the needs, and model for later use. Data from the data warehouse will be further modeled and aggregated and load to data marts. Data marts are often organized by business functions, such as marketing, sales, and finance.
You can see that we have several layers and different teams accessing these layers. The architecture above is based on our work and specific business problems. Any constructive feedback is welcomed :)
You will need to do the following for this project:
Download and setup Terraform CLI: Use this getting started guide to install terraform CLI on your local machine.
Create a Google Cloud account: Sign up for a Google Cloud account, if you haven’t already. You will get $300 credit when signing up, more than enough to get you through this tutorial without spending a dollar.
Get your billing ID: Follow the guide here to find out your billing ID on GCP. You will need it for later use.
Install gcloud CLI: Use this link to help you install gcloud CLI locally.
You can view the full code for this project here.
github.com
First thing first, we need to authenticate with GCP. Paste the following comment to a terminal and follow the instructions.
gcloud auth application-default login
Create a main.tf file with the following content:
provider "google" {}
This will set the provider for our terraform project.
terraform init
Now we can start setting up our infrastructure. We will start by creating two projects for the data lake and the data warehouse. You can have all of your settings in a giant main.tf file, but I recommend separating based on services. Let’s create a new project.tf file where we will define our project.
The first line will define the resource that we want to create: google_project. The next bit data-lake is the name of the resource to refer to by other services. Replace project_id with a globally unique ID (include your name or your project), and billing_account with your own.
terraform apply
You will see output like so:
# google_project.data-lake will be created + resource "google_project" "data-lake" { + auto_create_network = true + billing_account = "" + folder_id = (known after apply) + id = (known after apply) + name = "Data Lake" + number = (known after apply) + org_id = (known after apply) + project_id = "cloud-iac-data-lake" + skip_delete = true }# google_project.data-warehouse will be created + resource "google_project" "data-warehouse" { + auto_create_network = true + billing_account = "" + folder_id = (known after apply) + id = (known after apply) + name = "Data Warehouse" + number = (known after apply) + org_id = (known after apply) + project_id = "cloud-iac-data-warehouse" + skip_delete = true }# google_project.data-marts will be created + resource "google_project" "data-marts" { + auto_create_network = true + billing_account = "" + folder_id = (known after apply) + id = (known after apply) + name = "Data Marts" + number = (known after apply) + org_id = (known after apply) + project_id = "cloud-iac-data-marts" + skip_delete = true }
This is the prompt detailing what terraform will create. Study these to make sure that the results match what you are trying to do, and type yes to the terminal.
You have successfully created three projects: Data Lake, Data Warehouse, and Data Marts! Go to the GCP console to verify your results. Note that you may have a limit of three projects per billing account that may prevent you from proceeding further.
Before moving on, let’s talk about variables. You can see that in the terraform code in our project.tf above, we use specific names for our project ID. That is not always the best way to go. Imagine if we want to use the code somewhere else, we would have to change all the names manually.
Instead, we can define a variables.tf file that will be used throughout the project. We can have commonly used variables stored there. There are different types of variables that we can use, but I will use local variables for simplicity. You can read more about Terraform variables here.
locals { region = "asia-southeast1" unique_id = "cloud-iac" billing_id = ""}
In a similar fashion to create the three projects, we can create 4 GCS buckets that we would require: landing, sensitive, work, and backup bucket. Create a gcs.tf file and paste in the following:
Run terraform apply and input yes , and you will have created four buckets in our data lake project. In the code above, you see that we are using variables to refer to the project and the regions of the buckets. If we need to create the data lake again (perhaps for a different client, or different company), we only need to change the values in variables.tf. Pretty powerful stuff!
Now we need different permissions for different teams. For example, DE should have access to all buckets, while DS cannot access thesensitive bucket, can only read on landing and backup, but can write on work. We can set that up easily with the following codes:
We would create Google groups to manage people in different teams, making it easier for permission control (instead of having ten different emails here for permission, we only need one email per team).
Keep in mind that if the email does not exist, terraform command will fail.
Next, we will create datasets for our data warehouse. Referring back to the diagram, we have three systems, and thus, will create three corresponding datasets. Unlike GCS, we can define Bigquery ACL in google_bigquery_dataset definition.
We will configure the same ACL for data warehouse datasets. DE will be the owner of those datasets (in a production environment, it recommended to set up a service account to be the owner), DS will be the writer, and DA will be the reader.
For our data marts, we will have similar configurations to the data warehouse, but with different access permissions.
For the orchestration part, we will build a VPC network, an orchestration instance, and a static external IP address. If you read through the code below, there is nothing complicated going on here. You can read the Terraform documentation on how to create an instance here.
Last but not least, we need to set up the IAM permissions for our project. I will only provide an example for this part, but we can map each group to any roles like below.
In this mini-project, we have created most of the infrastructures necessary to run a data lake on Google Cloud. You might need to dive deeper to customize the code for your particular needs.
Don’t forget to clean up the unused resources to avoid any accidental charges. With terraform, you can run a single command to tear everything down.
terraform destroy
Hope you learned something :)
|
[
{
"code": null,
"e": 587,
"s": 172,
"text": "Back in the old days, dealing with physical infrastructure is a huge burden, which not only requires teams of experts to manage but also is time-consuming. In the modern cloud computing era, however, you can deploy hundreds of computers instantly to solve your problems with the click of a button. Well, to be realistic, most day to day problems that we are trying to solve won’t require that much computing power."
},
{
"code": null,
"e": 805,
"s": 587,
"text": "Infrastructure as code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools."
},
{
"code": null,
"e": 815,
"s": 805,
"text": "Wikipedia"
},
{
"code": null,
"e": 1200,
"s": 815,
"text": "So instead of placing a physical server on a rack, setting up all the cables, configuring the network, installing all the required operating system, you can write codes to do all that. To use IaC, you typically would use a source code control repository, write code to configure your infrastructures, run the code locally, or set up an automation to execute your code on every commit."
},
{
"code": null,
"e": 1427,
"s": 1200,
"text": "Why bother setting up and learning new stuff to manage your infrastructure while you can do that through the interface of all cloud providers, you ask? There are many advantages to having version control of our infrastructure."
},
{
"code": null,
"e": 1774,
"s": 1427,
"text": "IaC enables you to create different environments with ease, especially when your project is complex, and there are a lot of moving parts. For example, after setting up a development environment with multiple projects, VPCs, storage, compute instances, and IAM, it is counter-productive to do the same thing for staging and production environment."
},
{
"code": null,
"e": 2033,
"s": 1774,
"text": "With IaC, you can replicate your environment with some minor changes to your codebase. You can even customize your environment to suit your needs. For instance, you can set up different machine types for prod and dev, or set up a more permissive IAM for dev."
},
{
"code": null,
"e": 2209,
"s": 2033,
"text": "Imagine if an intern mess up your production environment, you can tear down everything and build up your environments with ease (given that your underlying data are unscathed)"
},
{
"code": null,
"e": 2439,
"s": 2209,
"text": "On a large project, you can have environments with complex permissions and policies. Not only do you have to worry about designing and setting up these environments, enforcing the policies and permissions can also be challenging."
},
{
"code": null,
"e": 2837,
"s": 2439,
"text": "With IaC, every change in your environment is versioned, so you know who makes what changes (given that you limit admin permissions to only your IaC service). You can also periodically scan your environments for differences between the configurations and the actual environments. Most IaC service would then be able to revert your environment to the configurations if they detect any alternations."
},
{
"code": null,
"e": 3043,
"s": 2837,
"text": "When your infrastructures are managed by code, you can share them between teams or use them for later projects. You can also generate infrastructure documentation automatically based on the configurations."
},
{
"code": null,
"e": 3277,
"s": 3043,
"text": "Great, so let’s get started setting up the infrastructure for a data lake on Google Cloud Platform using Terraform. You can use any other IaC tool on any other cloud provider, and I choose this combination since it is familiar to me."
},
{
"code": null,
"e": 3603,
"s": 3277,
"text": "Terraform is an open-source infrastructure as code software tool created by HashiCorp. It enables users to define and provision data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language, or optionally JSON. Terraform manages external resources with “providers”. Wikipedia"
},
{
"code": null,
"e": 3834,
"s": 3603,
"text": "In this project, we will use terraform code to provision resources and permissions for a data lake on GCP. The diagram above is a simplified version of a data lake, and we will write code to provision and set up everything on GCP."
},
{
"code": null,
"e": 4278,
"s": 3834,
"text": "Let me briefly walk through the architecture of a typical data lake on GCP (for simplicity, I only consider batch pipeline). You would generally have systems producing data, running on-premise, or other cloud providers/project that you need to connect to. You would connect to these systems via VPN or interconnect for security purposes. Then you will need an orchestration/staging server to extract data and load them to your storage buckets."
},
{
"code": null,
"e": 4705,
"s": 4278,
"text": "The data will then be classified and load into different buckets. Raw data would typically be ingested in the landing bucket. Data with sensitive customer information would be treated separately (masking, deidentification, separate permission policy) and load to the sensitive bucket. The work bucket is used for work in process data of data engineers and data scientists, and the backup bucket is for backup of cleansed data."
},
{
"code": null,
"e": 5140,
"s": 4705,
"text": "The data then would be loaded to the data warehouse, where it would be separated based on the system of ingestion (different companies may do this differently). Data here is cleansed normalize/denormalize based on the needs, and model for later use. Data from the data warehouse will be further modeled and aggregated and load to data marts. Data marts are often organized by business functions, such as marketing, sales, and finance."
},
{
"code": null,
"e": 5341,
"s": 5140,
"text": "You can see that we have several layers and different teams accessing these layers. The architecture above is based on our work and specific business problems. Any constructive feedback is welcomed :)"
},
{
"code": null,
"e": 5393,
"s": 5341,
"text": "You will need to do the following for this project:"
},
{
"code": null,
"e": 5506,
"s": 5393,
"text": "Download and setup Terraform CLI: Use this getting started guide to install terraform CLI on your local machine."
},
{
"code": null,
"e": 5716,
"s": 5506,
"text": "Create a Google Cloud account: Sign up for a Google Cloud account, if you haven’t already. You will get $300 credit when signing up, more than enough to get you through this tutorial without spending a dollar."
},
{
"code": null,
"e": 5827,
"s": 5716,
"text": "Get your billing ID: Follow the guide here to find out your billing ID on GCP. You will need it for later use."
},
{
"code": null,
"e": 5901,
"s": 5827,
"text": "Install gcloud CLI: Use this link to help you install gcloud CLI locally."
},
{
"code": null,
"e": 5951,
"s": 5901,
"text": "You can view the full code for this project here."
},
{
"code": null,
"e": 5962,
"s": 5951,
"text": "github.com"
},
{
"code": null,
"e": 6086,
"s": 5962,
"text": "First thing first, we need to authenticate with GCP. Paste the following comment to a terminal and follow the instructions."
},
{
"code": null,
"e": 6124,
"s": 6086,
"text": "gcloud auth application-default login"
},
{
"code": null,
"e": 6174,
"s": 6124,
"text": "Create a main.tf file with the following content:"
},
{
"code": null,
"e": 6195,
"s": 6174,
"text": "provider \"google\" {}"
},
{
"code": null,
"e": 6249,
"s": 6195,
"text": "This will set the provider for our terraform project."
},
{
"code": null,
"e": 6264,
"s": 6249,
"text": "terraform init"
},
{
"code": null,
"e": 6567,
"s": 6264,
"text": "Now we can start setting up our infrastructure. We will start by creating two projects for the data lake and the data warehouse. You can have all of your settings in a giant main.tf file, but I recommend separating based on services. Let’s create a new project.tf file where we will define our project."
},
{
"code": null,
"e": 6846,
"s": 6567,
"text": "The first line will define the resource that we want to create: google_project. The next bit data-lake is the name of the resource to refer to by other services. Replace project_id with a globally unique ID (include your name or your project), and billing_account with your own."
},
{
"code": null,
"e": 6862,
"s": 6846,
"text": "terraform apply"
},
{
"code": null,
"e": 6891,
"s": 6862,
"text": "You will see output like so:"
},
{
"code": null,
"e": 8350,
"s": 6891,
"text": "# google_project.data-lake will be created + resource \"google_project\" \"data-lake\" { + auto_create_network = true + billing_account = \"\" + folder_id = (known after apply) + id = (known after apply) + name = \"Data Lake\" + number = (known after apply) + org_id = (known after apply) + project_id = \"cloud-iac-data-lake\" + skip_delete = true }# google_project.data-warehouse will be created + resource \"google_project\" \"data-warehouse\" { + auto_create_network = true + billing_account = \"\" + folder_id = (known after apply) + id = (known after apply) + name = \"Data Warehouse\" + number = (known after apply) + org_id = (known after apply) + project_id = \"cloud-iac-data-warehouse\" + skip_delete = true }# google_project.data-marts will be created + resource \"google_project\" \"data-marts\" { + auto_create_network = true + billing_account = \"\" + folder_id = (known after apply) + id = (known after apply) + name = \"Data Marts\" + number = (known after apply) + org_id = (known after apply) + project_id = \"cloud-iac-data-marts\" + skip_delete = true }"
},
{
"code": null,
"e": 8512,
"s": 8350,
"text": "This is the prompt detailing what terraform will create. Study these to make sure that the results match what you are trying to do, and type yes to the terminal."
},
{
"code": null,
"e": 8762,
"s": 8512,
"text": "You have successfully created three projects: Data Lake, Data Warehouse, and Data Marts! Go to the GCP console to verify your results. Note that you may have a limit of three projects per billing account that may prevent you from proceeding further."
},
{
"code": null,
"e": 9052,
"s": 8762,
"text": "Before moving on, let’s talk about variables. You can see that in the terraform code in our project.tf above, we use specific names for our project ID. That is not always the best way to go. Imagine if we want to use the code somewhere else, we would have to change all the names manually."
},
{
"code": null,
"e": 9340,
"s": 9052,
"text": "Instead, we can define a variables.tf file that will be used throughout the project. We can have commonly used variables stored there. There are different types of variables that we can use, but I will use local variables for simplicity. You can read more about Terraform variables here."
},
{
"code": null,
"e": 9420,
"s": 9340,
"text": "locals { region = \"asia-southeast1\" unique_id = \"cloud-iac\" billing_id = \"\"}"
},
{
"code": null,
"e": 9616,
"s": 9420,
"text": "In a similar fashion to create the three projects, we can create 4 GCS buckets that we would require: landing, sensitive, work, and backup bucket. Create a gcs.tf file and paste in the following:"
},
{
"code": null,
"e": 9999,
"s": 9616,
"text": "Run terraform apply and input yes , and you will have created four buckets in our data lake project. In the code above, you see that we are using variables to refer to the project and the regions of the buckets. If we need to create the data lake again (perhaps for a different client, or different company), we only need to change the values in variables.tf. Pretty powerful stuff!"
},
{
"code": null,
"e": 10261,
"s": 9999,
"text": "Now we need different permissions for different teams. For example, DE should have access to all buckets, while DS cannot access thesensitive bucket, can only read on landing and backup, but can write on work. We can set that up easily with the following codes:"
},
{
"code": null,
"e": 10463,
"s": 10261,
"text": "We would create Google groups to manage people in different teams, making it easier for permission control (instead of having ten different emails here for permission, we only need one email per team)."
},
{
"code": null,
"e": 10539,
"s": 10463,
"text": "Keep in mind that if the email does not exist, terraform command will fail."
},
{
"code": null,
"e": 10777,
"s": 10539,
"text": "Next, we will create datasets for our data warehouse. Referring back to the diagram, we have three systems, and thus, will create three corresponding datasets. Unlike GCS, we can define Bigquery ACL in google_bigquery_dataset definition."
},
{
"code": null,
"e": 11017,
"s": 10777,
"text": "We will configure the same ACL for data warehouse datasets. DE will be the owner of those datasets (in a production environment, it recommended to set up a service account to be the owner), DS will be the writer, and DA will be the reader."
},
{
"code": null,
"e": 11135,
"s": 11017,
"text": "For our data marts, we will have similar configurations to the data warehouse, but with different access permissions."
},
{
"code": null,
"e": 11409,
"s": 11135,
"text": "For the orchestration part, we will build a VPC network, an orchestration instance, and a static external IP address. If you read through the code below, there is nothing complicated going on here. You can read the Terraform documentation on how to create an instance here."
},
{
"code": null,
"e": 11581,
"s": 11409,
"text": "Last but not least, we need to set up the IAM permissions for our project. I will only provide an example for this part, but we can map each group to any roles like below."
},
{
"code": null,
"e": 11772,
"s": 11581,
"text": "In this mini-project, we have created most of the infrastructures necessary to run a data lake on Google Cloud. You might need to dive deeper to customize the code for your particular needs."
},
{
"code": null,
"e": 11921,
"s": 11772,
"text": "Don’t forget to clean up the unused resources to avoid any accidental charges. With terraform, you can run a single command to tear everything down."
},
{
"code": null,
"e": 11939,
"s": 11921,
"text": "terraform destroy"
}
] |
Initialization of a multidimensional array in C
|
Array is a collection of same type of elements at contiguous memory location. The lowest address corresponds to the first element while highest corresponds to last element. Array index starts with zero(0) and ends with the size of array minus one(array size - 1). Array size must be integer greater than zero.
Let us see an example,
If array size = 10
First index of array = 0
Last index of array = array size - 1 = 10-1 = 9
Multi-dimensional arrays are arrays of array. The data is stored in tabular form in row major order.
The following is the syntax of multi-dimensional arrays.
type array_name[array_size1][array_size2].......[array_sizeN];
Here,
array_name − Any name given to an array.
array_size − Size of array.
The following is how you can initialize a multi-dimensional array.
type array_name[array_size1][array_size2].......[array_sizeN]; = { {elements} , {elements} , ... , {elements} }
The following is an example of multi-dimensional array.
Live Demo
#include <stdio.h>
int main () {
int arr[2][3] = { {5,2,3}, {28,8,30}};
int i, j;
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 3; j++ )
printf("arr[%d][%d] = %d\n", i, j, arr[i][j] );
}
return 0;
}
arr[0][0] = 5
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 28
arr[1][1] = 8
arr[1][2] = 30
In the above program, a two-dimensional array is declared.
int arr[2][3] = { {5,2,3}, {28,8,30}};
The elements of array are printed using nested for loop.
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 3; j++ )
printf("arr[%d][%d] = %d\n", i, j, arr[i][j] );
}
|
[
{
"code": null,
"e": 1372,
"s": 1062,
"text": "Array is a collection of same type of elements at contiguous memory location. The lowest address corresponds to the first element while highest corresponds to last element. Array index starts with zero(0) and ends with the size of array minus one(array size - 1). Array size must be integer greater than zero."
},
{
"code": null,
"e": 1395,
"s": 1372,
"text": "Let us see an example,"
},
{
"code": null,
"e": 1487,
"s": 1395,
"text": "If array size = 10\nFirst index of array = 0\nLast index of array = array size - 1 = 10-1 = 9"
},
{
"code": null,
"e": 1588,
"s": 1487,
"text": "Multi-dimensional arrays are arrays of array. The data is stored in tabular form in row major order."
},
{
"code": null,
"e": 1645,
"s": 1588,
"text": "The following is the syntax of multi-dimensional arrays."
},
{
"code": null,
"e": 1708,
"s": 1645,
"text": "type array_name[array_size1][array_size2].......[array_sizeN];"
},
{
"code": null,
"e": 1714,
"s": 1708,
"text": "Here,"
},
{
"code": null,
"e": 1755,
"s": 1714,
"text": "array_name − Any name given to an array."
},
{
"code": null,
"e": 1783,
"s": 1755,
"text": "array_size − Size of array."
},
{
"code": null,
"e": 1850,
"s": 1783,
"text": "The following is how you can initialize a multi-dimensional array."
},
{
"code": null,
"e": 1962,
"s": 1850,
"text": "type array_name[array_size1][array_size2].......[array_sizeN]; = { {elements} , {elements} , ... , {elements} }"
},
{
"code": null,
"e": 2018,
"s": 1962,
"text": "The following is an example of multi-dimensional array."
},
{
"code": null,
"e": 2029,
"s": 2018,
"text": " Live Demo"
},
{
"code": null,
"e": 2254,
"s": 2029,
"text": "#include <stdio.h>\nint main () {\n int arr[2][3] = { {5,2,3}, {28,8,30}};\n int i, j;\n for ( i = 0; i < 2; i++ ) {\n for ( j = 0; j < 3; j++ )\n printf(\"arr[%d][%d] = %d\\n\", i, j, arr[i][j] );\n }\n return 0;\n}"
},
{
"code": null,
"e": 2340,
"s": 2254,
"text": "arr[0][0] = 5\narr[0][1] = 2\narr[0][2] = 3\narr[1][0] = 28\narr[1][1] = 8\narr[1][2] = 30"
},
{
"code": null,
"e": 2399,
"s": 2340,
"text": "In the above program, a two-dimensional array is declared."
},
{
"code": null,
"e": 2438,
"s": 2399,
"text": "int arr[2][3] = { {5,2,3}, {28,8,30}};"
},
{
"code": null,
"e": 2495,
"s": 2438,
"text": "The elements of array are printed using nested for loop."
},
{
"code": null,
"e": 2605,
"s": 2495,
"text": "for ( i = 0; i < 2; i++ ) {\n for ( j = 0; j < 3; j++ )\n printf(\"arr[%d][%d] = %d\\n\", i, j, arr[i][j] );\n}"
}
] |
Display minutes with SimpleDateFormat('mm') in Java
|
To work with SimpleDateFormat class in Java, import the following package.
import java.text.SimpleDateFormat;
Now, set the format with SimpleDateFormat(“mm”) to display minutes in two-digits.
Format f = new SimpleDateFormat(‘”mm”);
Now, get the minutes in a string.
String strMinute = f.format(new Date());
The following is an example −
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
// displaying hour
Format f = new SimpleDateFormat("H");
String strHour = f.format(new Date());
System.out.println("Current Hour = "+strHour);
// displaying minutes in two-digits
f = new SimpleDateFormat("mm");
String strMinute = f.format(new Date());
System.out.println("Current Minutes = "+strMinute);
}
}
Today's date = 26/November/2018 08:03:40
Current Hour = 8
Current Minutes = 03
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To work with SimpleDateFormat class in Java, import the following package."
},
{
"code": null,
"e": 1172,
"s": 1137,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1254,
"s": 1172,
"text": "Now, set the format with SimpleDateFormat(“mm”) to display minutes in two-digits."
},
{
"code": null,
"e": 1294,
"s": 1254,
"text": "Format f = new SimpleDateFormat(‘”mm”);"
},
{
"code": null,
"e": 1328,
"s": 1294,
"text": "Now, get the minutes in a string."
},
{
"code": null,
"e": 1369,
"s": 1328,
"text": "String strMinute = f.format(new Date());"
},
{
"code": null,
"e": 1399,
"s": 1369,
"text": "The following is an example −"
},
{
"code": null,
"e": 1410,
"s": 1399,
"text": " Live Demo"
},
{
"code": null,
"e": 2211,
"s": 1410,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy hh:mm:s\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // displaying hour\n Format f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes in two-digits\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n }\n}"
},
{
"code": null,
"e": 2290,
"s": 2211,
"text": "Today's date = 26/November/2018 08:03:40\nCurrent Hour = 8\nCurrent Minutes = 03"
}
] |
Find indices of all occurrence of one string in other in C++
|
Suppose we have string str, and another substring sub_str, we have to find the indices for all occurrences of the sub_str in str. Suppose the str is “aabbababaabbbabbaaabba”, and sub_str is “abb”, then the indices will be 1 9 13 18.
To solve this problem, we can use the substr() function in C++ STL. This function takes the initial position from where it will start checking, and the length of the substring, if that is the same as the sub_str, then returns the position.
Live Demo
#include<iostream>
using namespace std;
void substrPosition(string str, string sub_str) {
bool flag = false;
for (int i = 0; i < str.length(); i++) {
if (str.substr(i, sub_str.length()) == sub_str) {
cout << i << " ";
flag = true;
}
}
if (flag == false)
cout << "NONE";
}
int main() {
string str = "aabbababaabbbabbaaabba";
string sub_str = "abb";
cout << "Substrings are present at: ";
substrPosition(str, sub_str);
}
Substrings are present at: 1 9 13 18
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Suppose we have string str, and another substring sub_str, we have to find the indices for all occurrences of the sub_str in str. Suppose the str is “aabbababaabbbabbaaabba”, and sub_str is “abb”, then the indices will be 1 9 13 18."
},
{
"code": null,
"e": 1535,
"s": 1295,
"text": "To solve this problem, we can use the substr() function in C++ STL. This function takes the initial position from where it will start checking, and the length of the substring, if that is the same as the sub_str, then returns the position."
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": " Live Demo"
},
{
"code": null,
"e": 2025,
"s": 1546,
"text": "#include<iostream>\nusing namespace std;\nvoid substrPosition(string str, string sub_str) {\n bool flag = false;\n for (int i = 0; i < str.length(); i++) {\n if (str.substr(i, sub_str.length()) == sub_str) {\n cout << i << \" \";\n flag = true;\n }\n }\n if (flag == false)\n cout << \"NONE\";\n}\nint main() {\n string str = \"aabbababaabbbabbaaabba\";\n string sub_str = \"abb\";\n cout << \"Substrings are present at: \";\n substrPosition(str, sub_str);\n}"
},
{
"code": null,
"e": 2062,
"s": 2025,
"text": "Substrings are present at: 1 9 13 18"
}
] |
How to create a rating component in ReactJS ? - GeeksforGeeks
|
03 Mar, 2021
The following approach covers how to create a rating component in React JS.
Prerequisite:
Basic knowledge of npm & create-react-app command.
Basic Knowledge of styled-components.
Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app command:
npx create-react-app react-rating
Now go to your react-rating folder by typing the given command in the terminal.
cd react-rating
Required module: Install the dependencies required in this project by typing the given command in the terminal.
npm install --save styled-components
npm install --save react-icons
Now create the components folder in src then go to the components folder and create two files Rating.js and RatingStyles.js.
Project Structure: The file structure in the project will look like this.
Example: In this example, we will design a rating component, for that we will need to manipulate the App.js file and other created components file.
We create a state with the first element rate as an initial state having a value of 0 and the second element as function setRate() for updating the state. Index numbers ranging from 0 to 4 are assigned with an addition of 1 to the newly initialized variable givenRating . While mapping the array using Map() method, we associate the value of givenRating variable with each of the five radio buttons (for example, 1 for the first button and so on).
We update the value of the state with the help of onClick function which sets its value equal to givenRating whenever it is called. For example, if we click on the 4th star (from left), we know the value of givenRating associated with this star (or radio button) is 4. This value of 4 gets assigned to our state. Now the role of the conditional operator comes into play. Only those radio buttons get selected (or change their color) which have a value equal to or less than 4. So as a result, we get a four-star rating.
Rating.js
import React, { useState } from "react";import { FaStar } from "react-icons/fa";import { Container, Radio, Rating } from "./RatingStyles";const Rate = () => { const [rate, setRate] = useState(0); return ( <Container> {[...Array(5)].map((item, index) => { const givenRating = index + 1; return ( <label> <Radio type="radio" value={givenRating} onClick={() => { setRate(givenRating); alert(`Are you sure you want to give ${givenRating} stars ?`); }} /> <Rating> <FaStar color={ givenRating < rate || givenRating === rate ? "000" : "rgb(192,192,192)" } /> </Rating> </label> ); })} </Container> );}; export default Rate;
RatingStyles.js
import styled from 'styled-components'; export const Container = styled.div` display: flex; justify-content: center; align-items: center; min-height: 60vh; font-size: 60px;`export const Radio = styled.input` display: none;`export const Rating = styled.div` cursor: pointer;`
App.js
import './App.css';import Rating from './components/Rating'; function App() { return ( <Rating /> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24423,
"s": 24395,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24499,
"s": 24423,
"text": "The following approach covers how to create a rating component in React JS."
},
{
"code": null,
"e": 24513,
"s": 24499,
"text": "Prerequisite:"
},
{
"code": null,
"e": 24564,
"s": 24513,
"text": "Basic knowledge of npm & create-react-app command."
},
{
"code": null,
"e": 24602,
"s": 24564,
"text": "Basic Knowledge of styled-components."
},
{
"code": null,
"e": 24645,
"s": 24602,
"text": "Basic Knowledge of useState() React hooks."
},
{
"code": null,
"e": 24719,
"s": 24645,
"text": "Basic Setup: You will start a new project using create-react-app command:"
},
{
"code": null,
"e": 24753,
"s": 24719,
"text": "npx create-react-app react-rating"
},
{
"code": null,
"e": 24833,
"s": 24753,
"text": "Now go to your react-rating folder by typing the given command in the terminal."
},
{
"code": null,
"e": 24849,
"s": 24833,
"text": "cd react-rating"
},
{
"code": null,
"e": 24961,
"s": 24849,
"text": "Required module: Install the dependencies required in this project by typing the given command in the terminal."
},
{
"code": null,
"e": 25029,
"s": 24961,
"text": "npm install --save styled-components\nnpm install --save react-icons"
},
{
"code": null,
"e": 25154,
"s": 25029,
"text": "Now create the components folder in src then go to the components folder and create two files Rating.js and RatingStyles.js."
},
{
"code": null,
"e": 25228,
"s": 25154,
"text": "Project Structure: The file structure in the project will look like this."
},
{
"code": null,
"e": 25376,
"s": 25228,
"text": "Example: In this example, we will design a rating component, for that we will need to manipulate the App.js file and other created components file."
},
{
"code": null,
"e": 25824,
"s": 25376,
"text": "We create a state with the first element rate as an initial state having a value of 0 and the second element as function setRate() for updating the state. Index numbers ranging from 0 to 4 are assigned with an addition of 1 to the newly initialized variable givenRating . While mapping the array using Map() method, we associate the value of givenRating variable with each of the five radio buttons (for example, 1 for the first button and so on)."
},
{
"code": null,
"e": 26344,
"s": 25824,
"text": "We update the value of the state with the help of onClick function which sets its value equal to givenRating whenever it is called. For example, if we click on the 4th star (from left), we know the value of givenRating associated with this star (or radio button) is 4. This value of 4 gets assigned to our state. Now the role of the conditional operator comes into play. Only those radio buttons get selected (or change their color) which have a value equal to or less than 4. So as a result, we get a four-star rating."
},
{
"code": null,
"e": 26354,
"s": 26344,
"text": "Rating.js"
},
{
"code": "import React, { useState } from \"react\";import { FaStar } from \"react-icons/fa\";import { Container, Radio, Rating } from \"./RatingStyles\";const Rate = () => { const [rate, setRate] = useState(0); return ( <Container> {[...Array(5)].map((item, index) => { const givenRating = index + 1; return ( <label> <Radio type=\"radio\" value={givenRating} onClick={() => { setRate(givenRating); alert(`Are you sure you want to give ${givenRating} stars ?`); }} /> <Rating> <FaStar color={ givenRating < rate || givenRating === rate ? \"000\" : \"rgb(192,192,192)\" } /> </Rating> </label> ); })} </Container> );}; export default Rate;",
"e": 27268,
"s": 26354,
"text": null
},
{
"code": null,
"e": 27284,
"s": 27268,
"text": "RatingStyles.js"
},
{
"code": "import styled from 'styled-components'; export const Container = styled.div` display: flex; justify-content: center; align-items: center; min-height: 60vh; font-size: 60px;`export const Radio = styled.input` display: none;`export const Rating = styled.div` cursor: pointer;`",
"e": 27574,
"s": 27284,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27574,
"text": "App.js"
},
{
"code": "import './App.css';import Rating from './components/Rating'; function App() { return ( <Rating /> );} export default App;",
"e": 27711,
"s": 27581,
"text": null
},
{
"code": null,
"e": 27824,
"s": 27711,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27834,
"s": 27824,
"text": "npm start"
},
{
"code": null,
"e": 27933,
"s": 27834,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 27949,
"s": 27933,
"text": "React-Questions"
},
{
"code": null,
"e": 27957,
"s": 27949,
"text": "ReactJS"
},
{
"code": null,
"e": 27974,
"s": 27957,
"text": "Web Technologies"
},
{
"code": null,
"e": 28072,
"s": 27974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28081,
"s": 28072,
"text": "Comments"
},
{
"code": null,
"e": 28094,
"s": 28081,
"text": "Old Comments"
},
{
"code": null,
"e": 28136,
"s": 28094,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28171,
"s": 28136,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28229,
"s": 28171,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28281,
"s": 28229,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 28338,
"s": 28281,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 28394,
"s": 28338,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28427,
"s": 28394,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28489,
"s": 28427,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28539,
"s": 28489,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Find Factors of Number using Python?
|
In order to find factors of a number, we have to run a loop over all numbers from 1 to itself and see if it is divisible.
num=int(input("enter a number"))
factors=[]
for i in range(1,num+1):
if num%i==0:
factors.append(i)
print ("Factors of {} = {}".format(num,factors))
If i is able to divide num completely, it is added in the list. Finally the list is diaplayed as the factors of given number
enter a number75
Factors of 75 = [3, 5, 15, 25, 75]
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "In order to find factors of a number, we have to run a loop over all numbers from 1 to itself and see if it is divisible."
},
{
"code": null,
"e": 1345,
"s": 1184,
"text": "num=int(input(\"enter a number\"))\nfactors=[]\nfor i in range(1,num+1):\n if num%i==0:\n factors.append(i)\n\nprint (\"Factors of {} = {}\".format(num,factors))"
},
{
"code": null,
"e": 1470,
"s": 1345,
"text": "If i is able to divide num completely, it is added in the list. Finally the list is diaplayed as the factors of given number"
},
{
"code": null,
"e": 1522,
"s": 1470,
"text": "enter a number75\nFactors of 75 = [3, 5, 15, 25, 75]"
}
] |
Count N-length Binary Strings consisting of "11" as substring - GeeksforGeeks
|
21 May, 2021
Given a positive integer N, the task is to find the number of binary strings of length N which contains “11” as a substring.
Examples:
Input: N = 2Output: 1Explanation: The only string of length 2 that has “11” as a substring is “11”.
Input: N = 12Output: 3719
Approach: The idea is to derive the number of possibilities of having “11” as a substring for binary representations starting with 0 or 1 based on the following observations:
If the first bit is 0, then the starting bit does not contribute to the string having “11” as a substring. Therefore, the remaining (N – 1) bits have to form a string having “11” as a substring.
If the first bit is 1 and the following bit is also 1, then there exists 2(N – 2) strings having “11” as a substring.
If the first bit is 1 but the following bit is 0, then a string having “11” as a substring can be formed with remaining (N – 2) bits.
Therefore, the recurrence relation to generate all the binary strings of length N is:
dp[i] = dp[i – 1] + dp[i – 2] + 2(i – 2)where, dp[i] is the string of length i having “11” as a substring.and dp[0] = dp[1] = 0.
Follow the steps below to solve the problem:
Initialize an array, say dp[], of size (N + 1) and assign dp[0] as 0 and dp[1] as 0.
Precompute the first N powers of 2 and store it in an array, say power[].
Iterate over the range [2, N] and update dp[i] as (dp[i – 1] + dp[i – 2] + power[i – 2]).
After completing the above steps, print the value of dp[N] as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count binary strings// of length N having substring "11"void binaryStrings(int N){ // Initialize dp[] of size N + 1 int dp[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Iterate over the range [2, N] for (int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + (1<<(i-2)); // 1<<(i-2) means power of 2^(i-2) } // Print total count of substrings cout << dp[N];} // Driver Codeint main(){ int N = 12; binaryStrings(N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count binary strings// of length N having substring "11"static void binaryStrings(int N){ // Initialize dp[] of size N + 1 int[] dp = new int[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 int[] power = new int[N + 1]; power[0] = 1; // Generate for(int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for(int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings System.out.println(dp[N]);} // Driver Codepublic static void main(String[] args){ int N = 12; binaryStrings(N);}} // This code is contributed by ukasp
# Python3 program for the above approach # Function to count binary strings# of length N having substring "11"def binaryStrings(N): # Initialize dp[] of size N + 1 dp = [0]*(N + 1) # Base Cases dp[0] = 0 dp[1] = 0 # Stores the first N powers of 2 power = [0]*(N + 1) power[0] = 1 # Generate for i in range(1, N + 1): power[i] = 2 * power[i - 1] # Iterate over the range [2, N] for i in range(2, N + 1): dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2] # Prtotal count of substrings print (dp[N]) # Driver Codeif __name__ == '__main__': N = 12 binaryStrings(N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count binary strings // of length N having substring "11" static void binaryStrings(int N) { // Initialize dp[] of size N + 1 int []dp = new int[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 int []power = new int[N + 1]; power[0] = 1; // Generate for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for (int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings Console.WriteLine(dp[N]); } // Driver Code public static void Main() { int N = 12; binaryStrings(N); }} // This code is contributed by bgangwar59.
<script> // JavaScript program for the above approach // Function to count binary strings // of length N having substring "11" function binaryStrings(N) { // Initialize dp of size N + 1 var dp = Array(N + 1).fill(0); // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 var power = Array(N+1).fill(0); power[0] = 1; // Generate for (i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for (i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings document.write(dp[N]); } // Driver Code var N = 12; binaryStrings(N); // This code contributed by aashish1995 </script>
3719
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
bgangwar59
ukasp
aashish1995
algo_plus_plus
binary-string
maths-power
substring
Combinatorial
Dynamic Programming
Mathematical
Recursion
Dynamic Programming
Mathematical
Recursion
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Largest substring with same Characters
Combinations with repetitions
Generate all possible combinations of at most X characters from a given array
Combinations from n arrays picking one element from each array
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
|
[
{
"code": null,
"e": 25061,
"s": 25033,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 25186,
"s": 25061,
"text": "Given a positive integer N, the task is to find the number of binary strings of length N which contains “11” as a substring."
},
{
"code": null,
"e": 25196,
"s": 25186,
"text": "Examples:"
},
{
"code": null,
"e": 25296,
"s": 25196,
"text": "Input: N = 2Output: 1Explanation: The only string of length 2 that has “11” as a substring is “11”."
},
{
"code": null,
"e": 25322,
"s": 25296,
"text": "Input: N = 12Output: 3719"
},
{
"code": null,
"e": 25497,
"s": 25322,
"text": "Approach: The idea is to derive the number of possibilities of having “11” as a substring for binary representations starting with 0 or 1 based on the following observations:"
},
{
"code": null,
"e": 25692,
"s": 25497,
"text": "If the first bit is 0, then the starting bit does not contribute to the string having “11” as a substring. Therefore, the remaining (N – 1) bits have to form a string having “11” as a substring."
},
{
"code": null,
"e": 25810,
"s": 25692,
"text": "If the first bit is 1 and the following bit is also 1, then there exists 2(N – 2) strings having “11” as a substring."
},
{
"code": null,
"e": 25944,
"s": 25810,
"text": "If the first bit is 1 but the following bit is 0, then a string having “11” as a substring can be formed with remaining (N – 2) bits."
},
{
"code": null,
"e": 26030,
"s": 25944,
"text": "Therefore, the recurrence relation to generate all the binary strings of length N is:"
},
{
"code": null,
"e": 26159,
"s": 26030,
"text": "dp[i] = dp[i – 1] + dp[i – 2] + 2(i – 2)where, dp[i] is the string of length i having “11” as a substring.and dp[0] = dp[1] = 0."
},
{
"code": null,
"e": 26204,
"s": 26159,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26289,
"s": 26204,
"text": "Initialize an array, say dp[], of size (N + 1) and assign dp[0] as 0 and dp[1] as 0."
},
{
"code": null,
"e": 26363,
"s": 26289,
"text": "Precompute the first N powers of 2 and store it in an array, say power[]."
},
{
"code": null,
"e": 26453,
"s": 26363,
"text": "Iterate over the range [2, N] and update dp[i] as (dp[i – 1] + dp[i – 2] + power[i – 2])."
},
{
"code": null,
"e": 26527,
"s": 26453,
"text": "After completing the above steps, print the value of dp[N] as the result."
},
{
"code": null,
"e": 26578,
"s": 26527,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26582,
"s": 26578,
"text": "C++"
},
{
"code": null,
"e": 26587,
"s": 26582,
"text": "Java"
},
{
"code": null,
"e": 26595,
"s": 26587,
"text": "Python3"
},
{
"code": null,
"e": 26598,
"s": 26595,
"text": "C#"
},
{
"code": null,
"e": 26609,
"s": 26598,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count binary strings// of length N having substring \"11\"void binaryStrings(int N){ // Initialize dp[] of size N + 1 int dp[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Iterate over the range [2, N] for (int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + (1<<(i-2)); // 1<<(i-2) means power of 2^(i-2) } // Print total count of substrings cout << dp[N];} // Driver Codeint main(){ int N = 12; binaryStrings(N); return 0;}",
"e": 27227,
"s": 26609,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to count binary strings// of length N having substring \"11\"static void binaryStrings(int N){ // Initialize dp[] of size N + 1 int[] dp = new int[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 int[] power = new int[N + 1]; power[0] = 1; // Generate for(int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for(int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings System.out.println(dp[N]);} // Driver Codepublic static void main(String[] args){ int N = 12; binaryStrings(N);}} // This code is contributed by ukasp",
"e": 28038,
"s": 27227,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count binary strings# of length N having substring \"11\"def binaryStrings(N): # Initialize dp[] of size N + 1 dp = [0]*(N + 1) # Base Cases dp[0] = 0 dp[1] = 0 # Stores the first N powers of 2 power = [0]*(N + 1) power[0] = 1 # Generate for i in range(1, N + 1): power[i] = 2 * power[i - 1] # Iterate over the range [2, N] for i in range(2, N + 1): dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2] # Prtotal count of substrings print (dp[N]) # Driver Codeif __name__ == '__main__': N = 12 binaryStrings(N) # This code is contributed by mohit kumar 29.",
"e": 28716,
"s": 28038,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count binary strings // of length N having substring \"11\" static void binaryStrings(int N) { // Initialize dp[] of size N + 1 int []dp = new int[N + 1]; // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 int []power = new int[N + 1]; power[0] = 1; // Generate for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for (int i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings Console.WriteLine(dp[N]); } // Driver Code public static void Main() { int N = 12; binaryStrings(N); }} // This code is contributed by bgangwar59.",
"e": 29554,
"s": 28716,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to count binary strings // of length N having substring \"11\" function binaryStrings(N) { // Initialize dp of size N + 1 var dp = Array(N + 1).fill(0); // Base Cases dp[0] = 0; dp[1] = 0; // Stores the first N powers of 2 var power = Array(N+1).fill(0); power[0] = 1; // Generate for (i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; } // Iterate over the range [2, N] for (i = 2; i <= N; i++) { dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]; } // Print total count of substrings document.write(dp[N]); } // Driver Code var N = 12; binaryStrings(N); // This code contributed by aashish1995 </script>",
"e": 30397,
"s": 29554,
"text": null
},
{
"code": null,
"e": 30402,
"s": 30397,
"text": "3719"
},
{
"code": null,
"e": 30445,
"s": 30402,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 30460,
"s": 30445,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30471,
"s": 30460,
"text": "bgangwar59"
},
{
"code": null,
"e": 30477,
"s": 30471,
"text": "ukasp"
},
{
"code": null,
"e": 30489,
"s": 30477,
"text": "aashish1995"
},
{
"code": null,
"e": 30504,
"s": 30489,
"text": "algo_plus_plus"
},
{
"code": null,
"e": 30518,
"s": 30504,
"text": "binary-string"
},
{
"code": null,
"e": 30530,
"s": 30518,
"text": "maths-power"
},
{
"code": null,
"e": 30540,
"s": 30530,
"text": "substring"
},
{
"code": null,
"e": 30554,
"s": 30540,
"text": "Combinatorial"
},
{
"code": null,
"e": 30574,
"s": 30554,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 30587,
"s": 30574,
"text": "Mathematical"
},
{
"code": null,
"e": 30597,
"s": 30587,
"text": "Recursion"
},
{
"code": null,
"e": 30617,
"s": 30597,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 30630,
"s": 30617,
"text": "Mathematical"
},
{
"code": null,
"e": 30640,
"s": 30630,
"text": "Recursion"
},
{
"code": null,
"e": 30654,
"s": 30640,
"text": "Combinatorial"
},
{
"code": null,
"e": 30752,
"s": 30654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30761,
"s": 30752,
"text": "Comments"
},
{
"code": null,
"e": 30774,
"s": 30761,
"text": "Old Comments"
},
{
"code": null,
"e": 30846,
"s": 30774,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 30885,
"s": 30846,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 30915,
"s": 30885,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 30993,
"s": 30915,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 31056,
"s": 30993,
"text": "Combinations from n arrays picking one element from each array"
},
{
"code": null,
"e": 31085,
"s": 31056,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 31115,
"s": 31085,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31147,
"s": 31115,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 31181,
"s": 31147,
"text": "Longest Common Subsequence | DP-4"
}
] |
Batch Script - FIND
|
This batch command searches for a string in files or input, outputting matching lines.
FIND [text] [destination]
Where text is the string which needs to be searched for and destination is the source in which the search needs to take place.
@echo off
FIND "Application" C:\tp\lists.txt
If the word “Application” resides in the file lists.txt, the line containing the string will be displayed in the command prompt.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2256,
"s": 2169,
"text": "This batch command searches for a string in files or input, outputting matching lines."
},
{
"code": null,
"e": 2283,
"s": 2256,
"text": "FIND [text] [destination]\n"
},
{
"code": null,
"e": 2410,
"s": 2283,
"text": "Where text is the string which needs to be searched for and destination is the source in which the search needs to take place."
},
{
"code": null,
"e": 2456,
"s": 2410,
"text": "@echo off \nFIND \"Application\" C:\\tp\\lists.txt"
},
{
"code": null,
"e": 2585,
"s": 2456,
"text": "If the word “Application” resides in the file lists.txt, the line containing the string will be displayed in the command prompt."
},
{
"code": null,
"e": 2592,
"s": 2585,
"text": " Print"
},
{
"code": null,
"e": 2603,
"s": 2592,
"text": " Add Notes"
}
] |
Pre-training BERT from scratch with cloud TPU | by Denis Antyukhov | Towards Data Science
|
In this experiment, we will be pre-training a state-of-the-art Natural Language Understanding model BERT on arbitrary text data using Google Cloud infrastructure.
This guide covers all stages of the procedure, including:
Setting up the training environmentDownloading raw text dataPreprocessing text dataLearning a new vocabularyCreating sharded pre-training dataSetting up GCS storage for data and modelTraining the model on a cloud TPU
Setting up the training environment
Downloading raw text data
Preprocessing text data
Learning a new vocabulary
Creating sharded pre-training data
Setting up GCS storage for data and model
Training the model on a cloud TPU
With this guide, you will be able to train a BERT model on arbitrary text data. This is useful if a pre-trained model for your language or use case is not available in open source.
This guide is intended for NLP researchers who are excited with the BERT technology but are not satisfied with the performance of the availableopen-sourced models.
For persistent storage of training data and model, you will require a Google Cloud Storage bucket. Please follow the Google Cloud TPU quickstart to create a GCP account and GCS bucket. New Google Cloud users have $300 free credit to get started with any GCP product.
Steps 1–5 of this tutorial can be run without a GCS bucket for demonstration purposes. In that case, however, you will not be able to train the model.
Pre-training a BERT-Base model on a TPUv2 will take about 54 hours. Google Colab is not designed for executing such long-running jobs and will interrupt the training process every 8 hours or so. For uninterrupted training, consider using a paid pre-emptible TPUv2 instance.
That said, at the time of writing (09.05.2019), with a Colab TPU, pre-training a BERT model from scratch can be achieved at a negligible cost of storing the said model and data in GCS (~1 USD).
The code below is a combination of Python and Bash. It was designed to run in a Colab Jupyter environment. Therefore, it would be most convenient to simply run it there.
However, all steps of the guide, except for the actual training part, might be run on a separate machine. This could be useful if your dataset is too large (or too private) to preprocess inside a Colab environment.
Here you go.
The only parameter you really have to set is your GCS BUCKET_NAME. Everything else has default values which should work for most use-cases.
Now, let’s get to business.
First and foremost, we get the packages required to train the model. The Jupyter environment allows executing bash commands directly from the notebook by using an exclamation mark ‘!’, like this:
!pip install sentencepiece!git clone https://github.com/google-research/bert
I will be exploiting this approach to make use of several other bash commands throughout the experiment.Now, let’s import the packages and authorize ourselves in Google Cloud.
We proceed with obtaining a corpus of text data. For this experiment, we will be using the OpenSubtitles dataset, which is available for 65 languages here.
Unlike more commonly used text datasets (like Wikipedia) it does not require any complex pre-processing. It also comes pre-formatted with one sentence per line, which is a requirement for further processing steps.
Feel free to use the dataset for your language instead by setting the corresponding language code.
For demonstration purposes, we will only use a small fraction of the whole corpus by default.
When training the real model, make sure to uncheck the DEMO_MODE checkbox to use a 100x larger dataset.
Rest assured, 100M lines are perfectly sufficient to train a reasonably good BERT-base model.
The raw text data we have downloaded contains punctuation, uppercase letters and non-UTF symbols which we will remove before proceeding. During inference, we will apply the same procedure to new data.
If your use-case requires different preprocessing (e.g. if uppercase letters or punctuation are expected during inference), feel free to modify the function below to accommodate for your needs.
Now let’s preprocess the whole dataset.
For the next step, we will learn a new vocabulary that we will use to represent our dataset.
The BERT paper uses a WordPiece tokenizer, which is not available in opensource. Instead, we will be using SentencePiece tokenizer in unigram mode. While it is not directly compatible with BERT, with a small hack we can make it work.
SentencePiece requires quite a lot of RAM, so running it on the full dataset in Colab will crash the kernel. To avoid this, we will randomly subsample a fraction of the dataset for building the vocabulary. Another option would be to use a machine with more RAM for this step — that decision is up to you.
Also, SentencePiece adds BOS and EOS control symbols to the vocabulary by default. We disable them explicitly by setting their indices to -1.
The typical values for VOC_SIZE are somewhere in between 32000 and 128000. We reserve NUM_PLACEHOLDERS tokens in case one wants to update the vocabulary and fine-tune the model after the pre-training phase is finished.
Now, let’s see how we can make SentencePiece work for the BERT model.
Below is a sentence tokenized using the WordPiece vocabulary from a pre-trained English BERT-base model from the official repo.
>>> wordpiece.tokenize("Colorless geothermal substations are generating furiously")['color', '##less', 'geo', '##thermal', 'sub', '##station', '##s', 'are', 'generating', 'furiously']
As we can see, the WordPiece tokenizer prepends the subwords which occur in the middle of words with ‘##’. The subwords occurring at the beginning of words are unchanged. If the subword occurs both in the beginning and in the middle of words, both versions (with and without ‘##’) are added to the vocabulary.
SentencePiece has created two files: tokenizer.model and tokenizer.vocab. Let’s have a look at the learned vocabulary:
This gives:
Learnt vocab size: 31743 Sample tokens: ['▁cafe', '▁slippery', 'xious', '▁resonate', '▁terrier', '▁feat', '▁frequencies', 'ainty', '▁punning', 'modern']
As we may observe, SentencePiece does quite the opposite to WordPiece. From the documentation:
SentencePiece first escapes the whitespace with a meta-symbol “▁” (U+2581) as follows:
Hello▁World.
Then, this text is segmented into small pieces, for example:
[Hello] [▁Wor] [ld] [.]
Subwords which occur after whitespace (which are also those that most words begin with) are prepended with ‘▁’, while others are unchanged. This excludes subwords which only occur at the beginning of sentences and nowhere else. These cases should be quite rare, however.
So, in order to obtain a vocabulary analogous to WordPiece, we need to perform a simple conversion, removing “▁” from the tokens that contain it and adding “##” to the ones that don’t.
We also add some special control symbols which are required by the BERT architecture. By convention, we put those at the beginning of the vocabulary.
Additionally, we append some placeholder tokens to the vocabulary. Those are useful if one wishes to update the pre-trained model with new, task-specific tokens. In that case, the placeholder tokens are replaced with new real ones, the pre-training data is re-generated, and the model is fine-tuned on new data.
Finally, we write the obtained vocabulary to file.
Now let’s see how the new vocabulary works in practice:
>>> testcase = "Colorless geothermal substations are generating furiously">>> bert_tokenizer = tokenization.FullTokenizer(VOC_FNAME)>>> bert_tokenizer.tokenize(testcase)['color', '##less', 'geo', '##ther', '##mal', 'sub', '##station', '##s', 'are', 'generat', '##ing', 'furious', '##ly']
Looking good!
With the vocabulary at hand, we are ready to generate pre-training data for the BERT model. Since our dataset might be quite large, we will split it into shards:
Now, for each shard we need to call create_pretraining_data.py script from the BERT repo. To that end, we will employ the xargs command.
Before we start generating, we need to set some parameters to pass to the script. You can find out more about the meaning of them in the README.
Running this might take quite some time depending on the size of your dataset.
To preserve our hard-earned assets, we will persist them to Google Cloud Storage. Provided that you have created the GCS bucket, this should be easy.
We will create two directories in GCS, one for the data and one for the model. In the model directory, we will put the model vocabulary and configuration file.
Configure your BUCKET_NAME variable here before proceeding, otherwise you will not be able to train the model.
Below is the sample hyperparameter configuration for BERT-base. Change at your own risk!
Now, we are ready to push our assets to GCS
We are almost ready to begin training our model.
Be advised that some of the parameters from previous steps are duplicated here, so as to allow for convenient restart of the training procedure.
Make sure that the parameters set are exactly the same across the experiment.
Prepare the training run configuration, build the estimator and input function, power up the bass cannon.
Execute!
Training the model with the default parameters for 1 million steps will take ~54 hours of run time. In case the kernel restarts for some reason, you may always continue training from the latest checkpoint.
This concludes the guide to pre-training BERT from scratch on a cloud TPU.
Okay, we’ve trained the model, now what?
That is a topic for a whole new discussion. There are a couple of things you could do:
Use the pre-trained model as a general-purpose NLU moduleFine-tune the model for some specific classification taskCreate another DL model using BERT as a building block???
Use the pre-trained model as a general-purpose NLU module
Fine-tune the model for some specific classification task
Create another DL model using BERT as a building block
???
The really fun stuff is still to come, so stay woke. Meanwhile, check out the awesome bert-as-a-service project and start serving your newly trained model in production.
Keep learning!
Pre-training BERT from scratch with cloud TPU [you are here]Building a Search Engine with BERT and TensorflowFine-tuning BERT with Keras and tf.ModuleImproving sentence embeddings with BERT and Representation Learning
Pre-training BERT from scratch with cloud TPU [you are here]
Building a Search Engine with BERT and Tensorflow
Fine-tuning BERT with Keras and tf.Module
Improving sentence embeddings with BERT and Representation Learning
|
[
{
"code": null,
"e": 334,
"s": 171,
"text": "In this experiment, we will be pre-training a state-of-the-art Natural Language Understanding model BERT on arbitrary text data using Google Cloud infrastructure."
},
{
"code": null,
"e": 392,
"s": 334,
"text": "This guide covers all stages of the procedure, including:"
},
{
"code": null,
"e": 609,
"s": 392,
"text": "Setting up the training environmentDownloading raw text dataPreprocessing text dataLearning a new vocabularyCreating sharded pre-training dataSetting up GCS storage for data and modelTraining the model on a cloud TPU"
},
{
"code": null,
"e": 645,
"s": 609,
"text": "Setting up the training environment"
},
{
"code": null,
"e": 671,
"s": 645,
"text": "Downloading raw text data"
},
{
"code": null,
"e": 695,
"s": 671,
"text": "Preprocessing text data"
},
{
"code": null,
"e": 721,
"s": 695,
"text": "Learning a new vocabulary"
},
{
"code": null,
"e": 756,
"s": 721,
"text": "Creating sharded pre-training data"
},
{
"code": null,
"e": 798,
"s": 756,
"text": "Setting up GCS storage for data and model"
},
{
"code": null,
"e": 832,
"s": 798,
"text": "Training the model on a cloud TPU"
},
{
"code": null,
"e": 1013,
"s": 832,
"text": "With this guide, you will be able to train a BERT model on arbitrary text data. This is useful if a pre-trained model for your language or use case is not available in open source."
},
{
"code": null,
"e": 1177,
"s": 1013,
"text": "This guide is intended for NLP researchers who are excited with the BERT technology but are not satisfied with the performance of the availableopen-sourced models."
},
{
"code": null,
"e": 1444,
"s": 1177,
"text": "For persistent storage of training data and model, you will require a Google Cloud Storage bucket. Please follow the Google Cloud TPU quickstart to create a GCP account and GCS bucket. New Google Cloud users have $300 free credit to get started with any GCP product."
},
{
"code": null,
"e": 1595,
"s": 1444,
"text": "Steps 1–5 of this tutorial can be run without a GCS bucket for demonstration purposes. In that case, however, you will not be able to train the model."
},
{
"code": null,
"e": 1869,
"s": 1595,
"text": "Pre-training a BERT-Base model on a TPUv2 will take about 54 hours. Google Colab is not designed for executing such long-running jobs and will interrupt the training process every 8 hours or so. For uninterrupted training, consider using a paid pre-emptible TPUv2 instance."
},
{
"code": null,
"e": 2063,
"s": 1869,
"text": "That said, at the time of writing (09.05.2019), with a Colab TPU, pre-training a BERT model from scratch can be achieved at a negligible cost of storing the said model and data in GCS (~1 USD)."
},
{
"code": null,
"e": 2233,
"s": 2063,
"text": "The code below is a combination of Python and Bash. It was designed to run in a Colab Jupyter environment. Therefore, it would be most convenient to simply run it there."
},
{
"code": null,
"e": 2448,
"s": 2233,
"text": "However, all steps of the guide, except for the actual training part, might be run on a separate machine. This could be useful if your dataset is too large (or too private) to preprocess inside a Colab environment."
},
{
"code": null,
"e": 2461,
"s": 2448,
"text": "Here you go."
},
{
"code": null,
"e": 2601,
"s": 2461,
"text": "The only parameter you really have to set is your GCS BUCKET_NAME. Everything else has default values which should work for most use-cases."
},
{
"code": null,
"e": 2629,
"s": 2601,
"text": "Now, let’s get to business."
},
{
"code": null,
"e": 2825,
"s": 2629,
"text": "First and foremost, we get the packages required to train the model. The Jupyter environment allows executing bash commands directly from the notebook by using an exclamation mark ‘!’, like this:"
},
{
"code": null,
"e": 2902,
"s": 2825,
"text": "!pip install sentencepiece!git clone https://github.com/google-research/bert"
},
{
"code": null,
"e": 3078,
"s": 2902,
"text": "I will be exploiting this approach to make use of several other bash commands throughout the experiment.Now, let’s import the packages and authorize ourselves in Google Cloud."
},
{
"code": null,
"e": 3234,
"s": 3078,
"text": "We proceed with obtaining a corpus of text data. For this experiment, we will be using the OpenSubtitles dataset, which is available for 65 languages here."
},
{
"code": null,
"e": 3448,
"s": 3234,
"text": "Unlike more commonly used text datasets (like Wikipedia) it does not require any complex pre-processing. It also comes pre-formatted with one sentence per line, which is a requirement for further processing steps."
},
{
"code": null,
"e": 3547,
"s": 3448,
"text": "Feel free to use the dataset for your language instead by setting the corresponding language code."
},
{
"code": null,
"e": 3641,
"s": 3547,
"text": "For demonstration purposes, we will only use a small fraction of the whole corpus by default."
},
{
"code": null,
"e": 3745,
"s": 3641,
"text": "When training the real model, make sure to uncheck the DEMO_MODE checkbox to use a 100x larger dataset."
},
{
"code": null,
"e": 3839,
"s": 3745,
"text": "Rest assured, 100M lines are perfectly sufficient to train a reasonably good BERT-base model."
},
{
"code": null,
"e": 4040,
"s": 3839,
"text": "The raw text data we have downloaded contains punctuation, uppercase letters and non-UTF symbols which we will remove before proceeding. During inference, we will apply the same procedure to new data."
},
{
"code": null,
"e": 4234,
"s": 4040,
"text": "If your use-case requires different preprocessing (e.g. if uppercase letters or punctuation are expected during inference), feel free to modify the function below to accommodate for your needs."
},
{
"code": null,
"e": 4274,
"s": 4234,
"text": "Now let’s preprocess the whole dataset."
},
{
"code": null,
"e": 4367,
"s": 4274,
"text": "For the next step, we will learn a new vocabulary that we will use to represent our dataset."
},
{
"code": null,
"e": 4601,
"s": 4367,
"text": "The BERT paper uses a WordPiece tokenizer, which is not available in opensource. Instead, we will be using SentencePiece tokenizer in unigram mode. While it is not directly compatible with BERT, with a small hack we can make it work."
},
{
"code": null,
"e": 4906,
"s": 4601,
"text": "SentencePiece requires quite a lot of RAM, so running it on the full dataset in Colab will crash the kernel. To avoid this, we will randomly subsample a fraction of the dataset for building the vocabulary. Another option would be to use a machine with more RAM for this step — that decision is up to you."
},
{
"code": null,
"e": 5048,
"s": 4906,
"text": "Also, SentencePiece adds BOS and EOS control symbols to the vocabulary by default. We disable them explicitly by setting their indices to -1."
},
{
"code": null,
"e": 5267,
"s": 5048,
"text": "The typical values for VOC_SIZE are somewhere in between 32000 and 128000. We reserve NUM_PLACEHOLDERS tokens in case one wants to update the vocabulary and fine-tune the model after the pre-training phase is finished."
},
{
"code": null,
"e": 5337,
"s": 5267,
"text": "Now, let’s see how we can make SentencePiece work for the BERT model."
},
{
"code": null,
"e": 5465,
"s": 5337,
"text": "Below is a sentence tokenized using the WordPiece vocabulary from a pre-trained English BERT-base model from the official repo."
},
{
"code": null,
"e": 5649,
"s": 5465,
"text": ">>> wordpiece.tokenize(\"Colorless geothermal substations are generating furiously\")['color', '##less', 'geo', '##thermal', 'sub', '##station', '##s', 'are', 'generating', 'furiously']"
},
{
"code": null,
"e": 5959,
"s": 5649,
"text": "As we can see, the WordPiece tokenizer prepends the subwords which occur in the middle of words with ‘##’. The subwords occurring at the beginning of words are unchanged. If the subword occurs both in the beginning and in the middle of words, both versions (with and without ‘##’) are added to the vocabulary."
},
{
"code": null,
"e": 6078,
"s": 5959,
"text": "SentencePiece has created two files: tokenizer.model and tokenizer.vocab. Let’s have a look at the learned vocabulary:"
},
{
"code": null,
"e": 6090,
"s": 6078,
"text": "This gives:"
},
{
"code": null,
"e": 6243,
"s": 6090,
"text": "Learnt vocab size: 31743 Sample tokens: ['▁cafe', '▁slippery', 'xious', '▁resonate', '▁terrier', '▁feat', '▁frequencies', 'ainty', '▁punning', 'modern']"
},
{
"code": null,
"e": 6338,
"s": 6243,
"text": "As we may observe, SentencePiece does quite the opposite to WordPiece. From the documentation:"
},
{
"code": null,
"e": 6425,
"s": 6338,
"text": "SentencePiece first escapes the whitespace with a meta-symbol “▁” (U+2581) as follows:"
},
{
"code": null,
"e": 6438,
"s": 6425,
"text": "Hello▁World."
},
{
"code": null,
"e": 6499,
"s": 6438,
"text": "Then, this text is segmented into small pieces, for example:"
},
{
"code": null,
"e": 6523,
"s": 6499,
"text": "[Hello] [▁Wor] [ld] [.]"
},
{
"code": null,
"e": 6794,
"s": 6523,
"text": "Subwords which occur after whitespace (which are also those that most words begin with) are prepended with ‘▁’, while others are unchanged. This excludes subwords which only occur at the beginning of sentences and nowhere else. These cases should be quite rare, however."
},
{
"code": null,
"e": 6979,
"s": 6794,
"text": "So, in order to obtain a vocabulary analogous to WordPiece, we need to perform a simple conversion, removing “▁” from the tokens that contain it and adding “##” to the ones that don’t."
},
{
"code": null,
"e": 7129,
"s": 6979,
"text": "We also add some special control symbols which are required by the BERT architecture. By convention, we put those at the beginning of the vocabulary."
},
{
"code": null,
"e": 7441,
"s": 7129,
"text": "Additionally, we append some placeholder tokens to the vocabulary. Those are useful if one wishes to update the pre-trained model with new, task-specific tokens. In that case, the placeholder tokens are replaced with new real ones, the pre-training data is re-generated, and the model is fine-tuned on new data."
},
{
"code": null,
"e": 7492,
"s": 7441,
"text": "Finally, we write the obtained vocabulary to file."
},
{
"code": null,
"e": 7548,
"s": 7492,
"text": "Now let’s see how the new vocabulary works in practice:"
},
{
"code": null,
"e": 7860,
"s": 7548,
"text": ">>> testcase = \"Colorless geothermal substations are generating furiously\">>> bert_tokenizer = tokenization.FullTokenizer(VOC_FNAME)>>> bert_tokenizer.tokenize(testcase)['color', '##less', 'geo', '##ther', '##mal', 'sub', '##station', '##s', 'are', 'generat', '##ing', 'furious', '##ly']"
},
{
"code": null,
"e": 7874,
"s": 7860,
"text": "Looking good!"
},
{
"code": null,
"e": 8036,
"s": 7874,
"text": "With the vocabulary at hand, we are ready to generate pre-training data for the BERT model. Since our dataset might be quite large, we will split it into shards:"
},
{
"code": null,
"e": 8173,
"s": 8036,
"text": "Now, for each shard we need to call create_pretraining_data.py script from the BERT repo. To that end, we will employ the xargs command."
},
{
"code": null,
"e": 8318,
"s": 8173,
"text": "Before we start generating, we need to set some parameters to pass to the script. You can find out more about the meaning of them in the README."
},
{
"code": null,
"e": 8397,
"s": 8318,
"text": "Running this might take quite some time depending on the size of your dataset."
},
{
"code": null,
"e": 8547,
"s": 8397,
"text": "To preserve our hard-earned assets, we will persist them to Google Cloud Storage. Provided that you have created the GCS bucket, this should be easy."
},
{
"code": null,
"e": 8707,
"s": 8547,
"text": "We will create two directories in GCS, one for the data and one for the model. In the model directory, we will put the model vocabulary and configuration file."
},
{
"code": null,
"e": 8818,
"s": 8707,
"text": "Configure your BUCKET_NAME variable here before proceeding, otherwise you will not be able to train the model."
},
{
"code": null,
"e": 8907,
"s": 8818,
"text": "Below is the sample hyperparameter configuration for BERT-base. Change at your own risk!"
},
{
"code": null,
"e": 8951,
"s": 8907,
"text": "Now, we are ready to push our assets to GCS"
},
{
"code": null,
"e": 9000,
"s": 8951,
"text": "We are almost ready to begin training our model."
},
{
"code": null,
"e": 9145,
"s": 9000,
"text": "Be advised that some of the parameters from previous steps are duplicated here, so as to allow for convenient restart of the training procedure."
},
{
"code": null,
"e": 9223,
"s": 9145,
"text": "Make sure that the parameters set are exactly the same across the experiment."
},
{
"code": null,
"e": 9329,
"s": 9223,
"text": "Prepare the training run configuration, build the estimator and input function, power up the bass cannon."
},
{
"code": null,
"e": 9338,
"s": 9329,
"text": "Execute!"
},
{
"code": null,
"e": 9544,
"s": 9338,
"text": "Training the model with the default parameters for 1 million steps will take ~54 hours of run time. In case the kernel restarts for some reason, you may always continue training from the latest checkpoint."
},
{
"code": null,
"e": 9619,
"s": 9544,
"text": "This concludes the guide to pre-training BERT from scratch on a cloud TPU."
},
{
"code": null,
"e": 9660,
"s": 9619,
"text": "Okay, we’ve trained the model, now what?"
},
{
"code": null,
"e": 9747,
"s": 9660,
"text": "That is a topic for a whole new discussion. There are a couple of things you could do:"
},
{
"code": null,
"e": 9919,
"s": 9747,
"text": "Use the pre-trained model as a general-purpose NLU moduleFine-tune the model for some specific classification taskCreate another DL model using BERT as a building block???"
},
{
"code": null,
"e": 9977,
"s": 9919,
"text": "Use the pre-trained model as a general-purpose NLU module"
},
{
"code": null,
"e": 10035,
"s": 9977,
"text": "Fine-tune the model for some specific classification task"
},
{
"code": null,
"e": 10090,
"s": 10035,
"text": "Create another DL model using BERT as a building block"
},
{
"code": null,
"e": 10094,
"s": 10090,
"text": "???"
},
{
"code": null,
"e": 10264,
"s": 10094,
"text": "The really fun stuff is still to come, so stay woke. Meanwhile, check out the awesome bert-as-a-service project and start serving your newly trained model in production."
},
{
"code": null,
"e": 10279,
"s": 10264,
"text": "Keep learning!"
},
{
"code": null,
"e": 10497,
"s": 10279,
"text": "Pre-training BERT from scratch with cloud TPU [you are here]Building a Search Engine with BERT and TensorflowFine-tuning BERT with Keras and tf.ModuleImproving sentence embeddings with BERT and Representation Learning"
},
{
"code": null,
"e": 10558,
"s": 10497,
"text": "Pre-training BERT from scratch with cloud TPU [you are here]"
},
{
"code": null,
"e": 10608,
"s": 10558,
"text": "Building a Search Engine with BERT and Tensorflow"
},
{
"code": null,
"e": 10650,
"s": 10608,
"text": "Fine-tuning BERT with Keras and tf.Module"
}
] |
Maximum Sum SubArray using Divide and Conquer in C++
|
Suppose we have one list of data with positive and negative values. We have to find the sum of contiguous subarray whose sum is largest. Suppose the list is containing {-2, -5, 6, -2, -3, 1, 5, -6}, then the sum of maximum subarray is 7. It is the sum of {6, -2, -3, 1, 5}
We will solve this problem using Divide and Conquer method. The steps will be look like below −
Steps −
Divide the array into two parts
Find the maximum of following threeMaximum subarray sum of left subarrayMaximum subarray sum of right subarrayMaximum subarray sum such that subarray crosses the midpoint
Maximum subarray sum of left subarray
Maximum subarray sum of right subarray
Maximum subarray sum such that subarray crosses the midpoint
#include <iostream>
using namespace std;
int max(int a, int b) {
return (a > b)? a : b;
}
int max(int a, int b, int c) {
return max(max(a, b), c);
}
int getMaxCrossingSum(int arr[], int l, int m, int h) {
int sum = 0;
int left = INT_MIN;
for (int i = m; i >= l; i--) {
sum = sum + arr[i];
if (sum > left)
left = sum;
}
sum = 0;
int right = INT_MIN;
for (int i = m+1; i <= h; i++) {
sum = sum + arr[i];
if (sum > right)
right = sum;
}
return left + right;
}
int maxSubArraySum(int arr[], int low, int high) {
if (low == high)
return arr[low];
int mid = (low + high)/2;
return max(maxSubArraySum(arr, low, mid), maxSubArraySum(arr, mid+1, high), getMaxCrossingSum(arr, low, mid, high));
}
int main() {
int arr[] = {-2, -5, 6, -2, -3, 1, 5, -6};
int n = sizeof(arr)/sizeof(arr[0]);
int max_sum = maxSubArraySum(arr, 0, n-1);
printf("Maximum contiguous sum is %d", max_sum);
}
Valid String
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Suppose we have one list of data with positive and negative values. We have to find the sum of contiguous subarray whose sum is largest. Suppose the list is containing {-2, -5, 6, -2, -3, 1, 5, -6}, then the sum of maximum subarray is 7. It is the sum of {6, -2, -3, 1, 5}"
},
{
"code": null,
"e": 1431,
"s": 1335,
"text": "We will solve this problem using Divide and Conquer method. The steps will be look like below −"
},
{
"code": null,
"e": 1439,
"s": 1431,
"text": "Steps −"
},
{
"code": null,
"e": 1471,
"s": 1439,
"text": "Divide the array into two parts"
},
{
"code": null,
"e": 1642,
"s": 1471,
"text": "Find the maximum of following threeMaximum subarray sum of left subarrayMaximum subarray sum of right subarrayMaximum subarray sum such that subarray crosses the midpoint"
},
{
"code": null,
"e": 1680,
"s": 1642,
"text": "Maximum subarray sum of left subarray"
},
{
"code": null,
"e": 1719,
"s": 1680,
"text": "Maximum subarray sum of right subarray"
},
{
"code": null,
"e": 1780,
"s": 1719,
"text": "Maximum subarray sum such that subarray crosses the midpoint"
},
{
"code": null,
"e": 2749,
"s": 1780,
"text": "#include <iostream>\nusing namespace std;\nint max(int a, int b) {\n return (a > b)? a : b;\n}\nint max(int a, int b, int c) {\n return max(max(a, b), c);\n}\nint getMaxCrossingSum(int arr[], int l, int m, int h) {\n int sum = 0;\n int left = INT_MIN;\n for (int i = m; i >= l; i--) {\n sum = sum + arr[i];\n if (sum > left)\n left = sum;\n }\n sum = 0;\n int right = INT_MIN;\n for (int i = m+1; i <= h; i++) {\n sum = sum + arr[i];\n if (sum > right)\n right = sum;\n }\n return left + right;\n}\nint maxSubArraySum(int arr[], int low, int high) {\n if (low == high)\n return arr[low];\n int mid = (low + high)/2;\n return max(maxSubArraySum(arr, low, mid), maxSubArraySum(arr, mid+1, high), getMaxCrossingSum(arr, low, mid, high));\n}\nint main() {\n int arr[] = {-2, -5, 6, -2, -3, 1, 5, -6};\n int n = sizeof(arr)/sizeof(arr[0]);\n int max_sum = maxSubArraySum(arr, 0, n-1);\n printf(\"Maximum contiguous sum is %d\", max_sum);\n}"
},
{
"code": null,
"e": 2762,
"s": 2749,
"text": "Valid String"
}
] |
A Binary String Game - GeeksforGeeks
|
24 Feb, 2022
Given a Binary String S. The task is to determine the winner of the game when two players play a game optimally with the string as per the given conditions:
Player 1 always starts first.
Two players take turns choosing a whole block of consecutive equal characters and deleting them from a given binary String S.
Player 1 can choose only an odd number of consecutive equal characters and Player 2 can choose only an even number of consecutive equal characters. The player may choose nothing and count it as their turn only if it is impossible to choose anything.
After all the characters are removed, the player with maximum scores wins the game and if scores are equal then print “-1”
Input: S = “1110011001010”Output: Player 1Explanation: The selected characters will be in bold and Player 1’s score is Score_1 and Player 2’s score is Score_2 :Turn 1 : (Player 1) “1110011001010” → “0011001010” Score_1 = 3Turn 2 : (Player 2) “0011001010” → “00001010” Score_2 = 2Turn 3 : (Player 1) “00001010”→ “0000010” Score_1 = 4Turn 4: (Player 2) “0000010” He cannot do anything as only one ‘1’ is present which is an odd number. Also, he can’t choose the ‘0’s as they are odd (5 and 1), Therefore, Score_2 =2Turn 5:(Player 1) “0000010”→ “000000” Score_1=5Turn 6:(Player 2) “000000” → “” Score_2 = 2 (No ‘1’ was deleted in this turn)
Final scores: Score_1 = 5 and Score_2 = 2Therefore, Player 1 wins.
Input : S = “11111101”Output: Player 2Explanation: Turn 1 : (Player 1) “11111101” → “1111110” Score_1 = 3Turn 2 : (Player 2) “1111110” → “0” Score_2 = 6Turn 3 : (Player 1) “0” → “” Score_1 = 3
Final scores: Score_1 = 3 and Score_2 = 6Therefore, Player 2 wins.
Approach:
If we observe this game carefully, we understand that the only consecutive 1s are contributing to the scores of these players.Create a list to store the lengths of the consecutive 1s in the string.Sort the list in descending order.Now iterate over the list and if the list element is odd it will be added to the score of the Player 1 and if it is even it will be added to the score of the Player 2.Now if the score of the Player 1 is greater than the score of the Player 2 then print “Player 1” and if the score of the Player 2 is greater than the score of the Player 1 then print “Player 2”.Print “-1” if there is a tie i.e., scores are the same.
If we observe this game carefully, we understand that the only consecutive 1s are contributing to the scores of these players.
Create a list to store the lengths of the consecutive 1s in the string.
Sort the list in descending order.
Now iterate over the list and if the list element is odd it will be added to the score of the Player 1 and if it is even it will be added to the score of the Player 2.
Now if the score of the Player 1 is greater than the score of the Player 2 then print “Player 1” and if the score of the Player 2 is greater than the score of the Player 1 then print “Player 2”.
Print “-1” if there is a tie i.e., scores are the same.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to return the result of// the gamestring gameMax(string S){ // length of the string int N = S.length(); // List to maintain the lengths of // consecutive '1's in the string vector<int> list; // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for(int i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.push_back(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.push_back(one); } // Sorts the lengths in // descending order sort(list.begin(), list.end(), greater<int>()); // Scores of the 2 players int score_1 = 0, score_2 = 0; for(int i = 0; i < list.size(); i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return "-1"; // Print the result return (score_1 > score_2) ? "Player 1" : "Player 2";} // Driver Codeint main(){ // Given string S string S = "11111101"; // Function call cout << gameMax(S);} // This code is contributed by rutvik_56
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to return the result of // the game public static String gameMax(String S) { // length of the string int N = S.length(); // List to maintain the lengths of // consecutive '1's in the string List<Integer> list = new ArrayList<>(); // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for (int i = 0; i < N; i++) { if (S.charAt(i) == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.add(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.add(one); } // Sorts the lengths in // descending order Collections.sort(list, Collections.reverseOrder()); // Scores of the 2 players int score_1 = 0, score_2 = 0; for (int i = 0; i < list.size(); i++) { // For player 1 if (list.get(i) % 2 == 1) { score_1 += list.get(i); } // For player 2 else { score_2 += list.get(i); } } // In case of a tie if (score_1 == score_2) return "-1"; // Print the result return (score_1 > score_2) ? "Player 1" : "Player 2"; } // Driver Code public static void main(String[] args) { // Given string S String S = "11111101"; // Function Call System.out.println(gameMax(S)); }}
# Python3 program for# the above approach # Function to return the# result of the gamedef gameMax(S): # Length of the string N = len(S) # List to maintain the lengths of # consecutive '1's in the string list = [] # Variable that keeps a track of # the current length of the block # of consecutive '1's one = 0 for i in range(N): if(S[i] == '1'): one += 1 else: # Adds non-zero lengths if(one != 0): list.append(one) one = 0 # This takes care of the case # when the last character is '1' if(one != 0): list.append(one) # Sorts the lengths in # descending order list.sort(reverse = True) # Scores of the 2 players score_1 = 0 score_2 = 0 for i in range(len(list)): # For player 1 if(list[i] % 2 == 1): score_1 += list[i] # For player 2 else: score_2 += list[i] # In case of a tie if(score_1 == score_2): return '-1' # Print the result if(score_1 > score_2): return "Player 1" else: return "Player 2" # Driver Code # Given string SS = "11111101" # Function callprint(gameMax(S)) # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the result of// the gamepublic static String gameMax(String S){ // length of the string int N = S.Length; // List to maintain the lengths of // consecutive '1's in the string List<int> list = new List<int>(); // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for(int i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.Add(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.Add(one); } // Sorts the lengths in // descending order list.Sort(); list.Reverse(); // Scores of the 2 players int score_1 = 0, score_2 = 0; for(int i = 0; i < list.Count; i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return "-1"; // Print the result return (score_1 > score_2) ? "Player 1" : "Player 2";} // Driver Codepublic static void Main(String[] args){ // Given string S String S = "11111101"; // Function Call Console.WriteLine(gameMax(S));}} // This code is contributed by Amit Katiyar
<script>// javascript program for the// above approach // Function to return the result of// the gamefunction gameMax(S){ // length of the string let N = S.length; // List to maintain the lengths of // consecutive '1's in the string let list = []; // Variable that keeps a track of // the current length of the block // of consecutive '1's let one = 0; for(let i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.push(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.push(one); } // Sorts the lengths in // descending order list.sort(); list.reverse(); // Scores of the 2 players let score_1 = 0, score_2 = 0; for(let i = 0; i < list.length; i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return "-1"; // Print the result return (score_1 > score_2) ? "Player 1" : "Player 2";} // Driver Code // Given string S let S = "11111101"; // Function Call document.write(gameMax(S)); // This code is contributed by target_2.</script>
Output:
Player 2
Time Complexity: O(N)Auxiliary Space: O(N)
amit143katiyar
rutvik_56
avanitrachhadiya2155
target_2
adnanirshad158
simranarora5sos
binary-string
Game Theory
Greedy
Strings
Strings
Greedy
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinatorial Game Theory | Set 2 (Game of Nim)
Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)
Expectimax Algorithm in Game Theory
Find the winner in nim-game
Combinatorial Game Theory | Set 1 (Introduction)
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 24941,
"s": 24913,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 25098,
"s": 24941,
"text": "Given a Binary String S. The task is to determine the winner of the game when two players play a game optimally with the string as per the given conditions:"
},
{
"code": null,
"e": 25128,
"s": 25098,
"text": "Player 1 always starts first."
},
{
"code": null,
"e": 25254,
"s": 25128,
"text": "Two players take turns choosing a whole block of consecutive equal characters and deleting them from a given binary String S."
},
{
"code": null,
"e": 25504,
"s": 25254,
"text": "Player 1 can choose only an odd number of consecutive equal characters and Player 2 can choose only an even number of consecutive equal characters. The player may choose nothing and count it as their turn only if it is impossible to choose anything."
},
{
"code": null,
"e": 25627,
"s": 25504,
"text": "After all the characters are removed, the player with maximum scores wins the game and if scores are equal then print “-1”"
},
{
"code": null,
"e": 26265,
"s": 25627,
"text": "Input: S = “1110011001010”Output: Player 1Explanation: The selected characters will be in bold and Player 1’s score is Score_1 and Player 2’s score is Score_2 :Turn 1 : (Player 1) “1110011001010” → “0011001010” Score_1 = 3Turn 2 : (Player 2) “0011001010” → “00001010” Score_2 = 2Turn 3 : (Player 1) “00001010”→ “0000010” Score_1 = 4Turn 4: (Player 2) “0000010” He cannot do anything as only one ‘1’ is present which is an odd number. Also, he can’t choose the ‘0’s as they are odd (5 and 1), Therefore, Score_2 =2Turn 5:(Player 1) “0000010”→ “000000” Score_1=5Turn 6:(Player 2) “000000” → “” Score_2 = 2 (No ‘1’ was deleted in this turn)"
},
{
"code": null,
"e": 26332,
"s": 26265,
"text": "Final scores: Score_1 = 5 and Score_2 = 2Therefore, Player 1 wins."
},
{
"code": null,
"e": 26525,
"s": 26332,
"text": "Input : S = “11111101”Output: Player 2Explanation: Turn 1 : (Player 1) “11111101” → “1111110” Score_1 = 3Turn 2 : (Player 2) “1111110” → “0” Score_2 = 6Turn 3 : (Player 1) “0” → “” Score_1 = 3"
},
{
"code": null,
"e": 26592,
"s": 26525,
"text": "Final scores: Score_1 = 3 and Score_2 = 6Therefore, Player 2 wins."
},
{
"code": null,
"e": 26603,
"s": 26592,
"text": "Approach: "
},
{
"code": null,
"e": 27251,
"s": 26603,
"text": "If we observe this game carefully, we understand that the only consecutive 1s are contributing to the scores of these players.Create a list to store the lengths of the consecutive 1s in the string.Sort the list in descending order.Now iterate over the list and if the list element is odd it will be added to the score of the Player 1 and if it is even it will be added to the score of the Player 2.Now if the score of the Player 1 is greater than the score of the Player 2 then print “Player 1” and if the score of the Player 2 is greater than the score of the Player 1 then print “Player 2”.Print “-1” if there is a tie i.e., scores are the same."
},
{
"code": null,
"e": 27378,
"s": 27251,
"text": "If we observe this game carefully, we understand that the only consecutive 1s are contributing to the scores of these players."
},
{
"code": null,
"e": 27450,
"s": 27378,
"text": "Create a list to store the lengths of the consecutive 1s in the string."
},
{
"code": null,
"e": 27485,
"s": 27450,
"text": "Sort the list in descending order."
},
{
"code": null,
"e": 27653,
"s": 27485,
"text": "Now iterate over the list and if the list element is odd it will be added to the score of the Player 1 and if it is even it will be added to the score of the Player 2."
},
{
"code": null,
"e": 27848,
"s": 27653,
"text": "Now if the score of the Player 1 is greater than the score of the Player 2 then print “Player 1” and if the score of the Player 2 is greater than the score of the Player 1 then print “Player 2”."
},
{
"code": null,
"e": 27904,
"s": 27848,
"text": "Print “-1” if there is a tie i.e., scores are the same."
},
{
"code": null,
"e": 27955,
"s": 27904,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 27959,
"s": 27955,
"text": "C++"
},
{
"code": null,
"e": 27964,
"s": 27959,
"text": "Java"
},
{
"code": null,
"e": 27972,
"s": 27964,
"text": "Python3"
},
{
"code": null,
"e": 27975,
"s": 27972,
"text": "C#"
},
{
"code": null,
"e": 27986,
"s": 27975,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to return the result of// the gamestring gameMax(string S){ // length of the string int N = S.length(); // List to maintain the lengths of // consecutive '1's in the string vector<int> list; // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for(int i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.push_back(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.push_back(one); } // Sorts the lengths in // descending order sort(list.begin(), list.end(), greater<int>()); // Scores of the 2 players int score_1 = 0, score_2 = 0; for(int i = 0; i < list.size(); i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return \"-1\"; // Print the result return (score_1 > score_2) ? \"Player 1\" : \"Player 2\";} // Driver Codeint main(){ // Given string S string S = \"11111101\"; // Function call cout << gameMax(S);} // This code is contributed by rutvik_56",
"e": 29603,
"s": 27986,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to return the result of // the game public static String gameMax(String S) { // length of the string int N = S.length(); // List to maintain the lengths of // consecutive '1's in the string List<Integer> list = new ArrayList<>(); // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for (int i = 0; i < N; i++) { if (S.charAt(i) == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.add(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.add(one); } // Sorts the lengths in // descending order Collections.sort(list, Collections.reverseOrder()); // Scores of the 2 players int score_1 = 0, score_2 = 0; for (int i = 0; i < list.size(); i++) { // For player 1 if (list.get(i) % 2 == 1) { score_1 += list.get(i); } // For player 2 else { score_2 += list.get(i); } } // In case of a tie if (score_1 == score_2) return \"-1\"; // Print the result return (score_1 > score_2) ? \"Player 1\" : \"Player 2\"; } // Driver Code public static void main(String[] args) { // Given string S String S = \"11111101\"; // Function Call System.out.println(gameMax(S)); }}",
"e": 31441,
"s": 29603,
"text": null
},
{
"code": "# Python3 program for# the above approach # Function to return the# result of the gamedef gameMax(S): # Length of the string N = len(S) # List to maintain the lengths of # consecutive '1's in the string list = [] # Variable that keeps a track of # the current length of the block # of consecutive '1's one = 0 for i in range(N): if(S[i] == '1'): one += 1 else: # Adds non-zero lengths if(one != 0): list.append(one) one = 0 # This takes care of the case # when the last character is '1' if(one != 0): list.append(one) # Sorts the lengths in # descending order list.sort(reverse = True) # Scores of the 2 players score_1 = 0 score_2 = 0 for i in range(len(list)): # For player 1 if(list[i] % 2 == 1): score_1 += list[i] # For player 2 else: score_2 += list[i] # In case of a tie if(score_1 == score_2): return '-1' # Print the result if(score_1 > score_2): return \"Player 1\" else: return \"Player 2\" # Driver Code # Given string SS = \"11111101\" # Function callprint(gameMax(S)) # This code is contributed by avanitrachhadiya2155",
"e": 32711,
"s": 31441,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the result of// the gamepublic static String gameMax(String S){ // length of the string int N = S.Length; // List to maintain the lengths of // consecutive '1's in the string List<int> list = new List<int>(); // Variable that keeps a track of // the current length of the block // of consecutive '1's int one = 0; for(int i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.Add(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.Add(one); } // Sorts the lengths in // descending order list.Sort(); list.Reverse(); // Scores of the 2 players int score_1 = 0, score_2 = 0; for(int i = 0; i < list.Count; i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return \"-1\"; // Print the result return (score_1 > score_2) ? \"Player 1\" : \"Player 2\";} // Driver Codepublic static void Main(String[] args){ // Given string S String S = \"11111101\"; // Function Call Console.WriteLine(gameMax(S));}} // This code is contributed by Amit Katiyar",
"e": 34332,
"s": 32711,
"text": null
},
{
"code": "<script>// javascript program for the// above approach // Function to return the result of// the gamefunction gameMax(S){ // length of the string let N = S.length; // List to maintain the lengths of // consecutive '1's in the string let list = []; // Variable that keeps a track of // the current length of the block // of consecutive '1's let one = 0; for(let i = 0; i < N; i++) { if (S[i] == '1') { one++; } else { // Adds non-zero lengths if (one != 0) { list.push(one); } one = 0; } } // This takes care of the case // when the last character is '1' if (one != 0) { list.push(one); } // Sorts the lengths in // descending order list.sort(); list.reverse(); // Scores of the 2 players let score_1 = 0, score_2 = 0; for(let i = 0; i < list.length; i++) { // For player 1 if (list[i] % 2 == 1) { score_1 += list[i]; } // For player 2 else { score_2 += list[i]; } } // In case of a tie if (score_1 == score_2) return \"-1\"; // Print the result return (score_1 > score_2) ? \"Player 1\" : \"Player 2\";} // Driver Code // Given string S let S = \"11111101\"; // Function Call document.write(gameMax(S)); // This code is contributed by target_2.</script>",
"e": 35855,
"s": 34332,
"text": null
},
{
"code": null,
"e": 35864,
"s": 35855,
"text": "Output: "
},
{
"code": null,
"e": 35873,
"s": 35864,
"text": "Player 2"
},
{
"code": null,
"e": 35916,
"s": 35873,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 35931,
"s": 35916,
"text": "amit143katiyar"
},
{
"code": null,
"e": 35941,
"s": 35931,
"text": "rutvik_56"
},
{
"code": null,
"e": 35962,
"s": 35941,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35971,
"s": 35962,
"text": "target_2"
},
{
"code": null,
"e": 35986,
"s": 35971,
"text": "adnanirshad158"
},
{
"code": null,
"e": 36002,
"s": 35986,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36016,
"s": 36002,
"text": "binary-string"
},
{
"code": null,
"e": 36028,
"s": 36016,
"text": "Game Theory"
},
{
"code": null,
"e": 36035,
"s": 36028,
"text": "Greedy"
},
{
"code": null,
"e": 36043,
"s": 36035,
"text": "Strings"
},
{
"code": null,
"e": 36051,
"s": 36043,
"text": "Strings"
},
{
"code": null,
"e": 36058,
"s": 36051,
"text": "Greedy"
},
{
"code": null,
"e": 36070,
"s": 36058,
"text": "Game Theory"
},
{
"code": null,
"e": 36168,
"s": 36070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36177,
"s": 36168,
"text": "Comments"
},
{
"code": null,
"e": 36190,
"s": 36177,
"text": "Old Comments"
},
{
"code": null,
"e": 36238,
"s": 36190,
"text": "Combinatorial Game Theory | Set 2 (Game of Nim)"
},
{
"code": null,
"e": 36317,
"s": 36238,
"text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)"
},
{
"code": null,
"e": 36353,
"s": 36317,
"text": "Expectimax Algorithm in Game Theory"
},
{
"code": null,
"e": 36381,
"s": 36353,
"text": "Find the winner in nim-game"
},
{
"code": null,
"e": 36430,
"s": 36381,
"text": "Combinatorial Game Theory | Set 1 (Introduction)"
},
{
"code": null,
"e": 36481,
"s": 36430,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 36532,
"s": 36481,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 36559,
"s": 36532,
"text": "Program for array rotation"
},
{
"code": null,
"e": 36617,
"s": 36559,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Concurrency in Python - Quick Guide
|
In this chapter, we will understand the concept of concurrency in Python and learn about the different threads and processes.
In simple words, concurrency is the occurrence of two or more events at the same time. Concurrency is a natural phenomenon because many events occur simultaneously at any given time.
In terms of programming, concurrency is when two tasks overlap in execution. With concurrent programming, the performance of our applications and software systems can be improved because we can concurrently deal with the requests rather than waiting for a previous one to be completed.
Following points will give us the brief historical review of concurrency −
Concurrency is closely related with the concept of railroads. With the railroads, there was a need to handle multiple trains on the same railroad system in such a way that every train would get to its destination safely.
The interest in computer science concurrency began with the research paper published by Edsger W. Dijkstra in 1965. In this paper, he identified and solved the problem of mutual exclusion, the property of concurrency control.
In recent times, programmers are getting improved concurrent solutions because of the introduction of high-level concurrency primitives.
Programming languages such as Google’s Golang, Rust and Python have made incredible developments in areas which help us get better concurrent solutions.
Thread is the smallest unit of execution that can be performed in an operating system. It is not itself a program but runs within a program. In other words, threads are not independent of one other. Each thread shares code section, data section, etc. with other threads. They are also known as lightweight processes.
A thread consists of the following components −
Program counter which consist of the address of the next executable instruction
Program counter which consist of the address of the next executable instruction
Stack
Stack
Set of registers
Set of registers
A unique id
A unique id
Multithreading, on the other hand, is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads. The concept of multithreading can be understood with the help of the following example.
Suppose we are running a particular process wherein we open MS Word to type content into it. One thread will be assigned to open MS Word and another thread will be required to type content in it. And now, if we want to edit the existing then another thread will be required to do the editing task and so on.
Aprocessis defined as an entity, which represents the basic unit of work to be implemented in the system. To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process that performs all the tasks mentioned in the program. During the process life cycle, it passes through different stages – Start, Ready, Running, Waiting and Terminating.
Following diagram shows the different stages of a process −
A process can have only one thread, called primary thread, or multiple threads having their own set of registers, program counter and stack. Following diagram will show us the difference −
Multiprocessing, on the other hand, is the use of two or more CPUs units within a single computer system. Our primary goal is to get the full potential from our hardware. To achieve this, we need to utilize full number of CPU cores available in our computer system. Multiprocessing is the best approach to do so.
Python is one of the most popular programming languages. Followings are some reasons that make it suitable for concurrent applications −
Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style based on preference. Python comes with Magic methods, which can be defined to act on objects. These Magic methods are used as syntactic sugar and bound to more easy-to-understand keywords.
Python language has witnessed a massive adoption rate amongst data scientists and mathematicians, working in the field of AI, machine learning, deep learning and quantitative analysis.
Python 2 and 3 have large number of APIs dedicated for parallel/concurrent programming. Most popular of them are threading, concurrent.features, multiprocessing, asyncio, gevent and greenlets, etc.
Python comes with a limitation for concurrent applications. This limitation is called GIL (Global Interpreter Lock) is present within Python. GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. We can understand the concept of GIL as follows −
It is one of the most controversial topics in the Python world. In CPython, GIL is the mutex - the mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first. The diagram shown below will help you understand the working of GIL.
However, there are some libraries and implementations in Python such as Numpy, Jpython and IronPytbhon. These libraries work without any interaction with GIL.
Both concurrency and parallelism are used in relation to multithreaded programs but there is a lot of confusion about the similarity and difference between them. The big question in this regard: is concurrency parallelism or not? Although both the terms appear quite similar but the answer to the above question is NO, concurrency and parallelism are not same. Now, if they are not same then what is the basic difference between them?
In simple terms, concurrency deals with managing the access to shared state from different threads and on the other side, parallelism deals with utilizing multiple CPUs or its cores to improve the performance of hardware.
Concurrency is when two tasks overlap in execution. It could be a situation where an application is progressing on more than one task at the same time. We can understand it diagrammatically; multiple tasks are making progress at the same time, as follows −
In this section, we will discuss the three important levels of concurrency in terms of programming −
In this level of concurrency, there is explicit use of atomic operations. We cannot use such kind of concurrency for application building, as it is very error-prone and difficult to debug. Even Python does not support such kind of concurrency.
In this concurrency, there is no use of explicit atomic operations. It uses the explicit locks. Python and other programming languages support such kind of concurrency. Mostly application programmers use this concurrency.
In this concurrency, neither explicit atomic operations nor explicit locks are used. Python has concurrent.futures module to support such kind of concurrency.
For a program or concurrent system to be correct, some properties must be satisfied by it. Properties related to the termination of system are as follows −
The correctness property means that the program or the system must provide the desired correct answer. To keep it simple, we can say that the system must map the starting program state to final state correctly.
The safety property means that the program or the system must remain in a “good” or “safe” state and never does anything “bad”.
This property means that a program or system must “make progress” and it would reach at some desirable state.
This is one common property of concurrent system in which there can be multiple processes and threads, which run at the same time to make progress on their own tasks. These processes and threads are called actors of the concurrent system.
The actors must utilize the resources such as memory, disk, printer etc. in order to perform their tasks.
Every concurrent system must possess a set of rules to define the kind of tasks to be performed by the actors and the timing for each. The tasks could be acquiring of locks, memory sharing, modifying the state, etc.
An important issue while implementing the concurrent systems is the sharing of data among multiple threads or processes. Actually, the programmer must ensure that locks protect the shared data so that all the accesses to it are serialized and only one thread or process can access the shared data at a time. In case, when multiple threads or processes are all trying to access the same shared data then not all but at least one of them would be blocked and would remain idle. In other words, we can say that we would be able to use only one process or thread at a time when lock is in force. There can be some simple solutions to remove the above-mentioned barriers −
The simplest solution is not to share any mutable data. In this case, we need not to use explicit locking and the barrier of concurrency due to mutual data would be solved.
Many times the concurrent processes need to access the same data at the same time. Another solution, than using of explicit locks, is to use a data structure that supports concurrent access. For example, we can use the queue module, which provides thread-safe queues. We can also use multiprocessing.JoinableQueue classes for multiprocessing-based concurrency.
Sometimes, the data structure that we are using, say concurrency queue, is not suitable then we can pass the immutable data without locking it.
In continuation of the above solution, suppose if it is required to pass only mutable data, rather than immutable data, then we can pass mutable data that is read only.
Another important issue in implementing concurrent systems is the use of I/O resources by threads or processes. The problem arises when one thread or process is using the I/O for such a long time and other is sitting idle. We can see such kind of barrier while working with an I/O heavy application. It can be understood with the help of an example, the requesting of pages from web browser. It is a heavy application. Here, if the rate at which the data is requested is slower than the rate at which it is consumed then we have I/O barrier in our concurrent system.
The following Python script is for requesting a web page and getting the time our network took to get the requested page −
import urllib.request
import time
ts = time.time()
req = urllib.request.urlopen('http://www.tutorialspoint.com')
pageHtml = req.read()
te = time.time()
print("Page Fetching Time : {} Seconds".format (te-ts))
After executing the above script, we can get the page fetching time as shown below.
Page Fetching Time: 1.0991398811340332 Seconds
We can see that the time to fetch the page is more than one second. Now what if we want to fetch thousands of different web pages, you can understand how much time our network would take.
Parallelism may be defined as the art of splitting the tasks into subtasks that can be processed simultaneously. It is opposite to the concurrency, as discussed above, in which two or more events are happening at the same time. We can understand it diagrammatically; a task is broken into a number of subtasks that can be processed in parallel, as follows −
To get more idea about the distinction between concurrency and parallelism, consider the following points −
An application can be concurrent but not parallel means that it processes more than one task at the same time but the tasks are not broken down into subtasks.
An application can be parallel but not concurrent means that it only works on one task at a time and the tasks broken down into subtasks can be processed in parallel.
An application can be neither parallel nor concurrent. This means that it works on only one task at a time and the task is never broken into subtasks.
An application can be both parallel and concurrent means that it both works on multiple tasks at a time and the task is broken into subtasks for executing them in parallel.
We can achieve parallelism by distributing the subtasks among different cores of single CPU or among multiple computers connected within a network.
Consider the following important points to understand why it is necessary to achieve parallelism −
With the help of parallelism, we can run our code efficiently. It will save our time because the same code in parts is running in parallel.
Sequential computing is constrained by physical and practical factors due to which it is not possible to get faster computing results. On the other hand, this issue is solved by parallel computing and gives us faster computing results than sequential computing.
Parallel processing reduces the execution time of program code.
If we talk about real life example of parallelism, the graphics card of our computer is the example that highlights the true power of parallel processing because it has hundreds of individual processing cores that work independently and can do the execution at the same time. Due to this reason, we are able to run high-end applications and games as well.
We know about concurrency, parallelism and the difference between them but what about the system on which it is to be implemented. It is very necessary to have the understanding of the system, on which we are going to implement, because it gives us the benefit to take informed decision while designing the software. We have the following two kinds of processors −
Single-core processors are capable of executing one thread at any given time. These processors use context switching to store all the necessary information for a thread at a specific time and then restoring the information later. The context switching mechanism helps us make progress on a number of threads within a given second and it looks as if the system is working on multiple things.
Single-core processors come with many advantages. These processors require less power and there is no complex communication protocol between multiple cores. On the other hand, the speed of single-core processors is limited and it is not suitable for larger applications.
Multi-core processors have multiple independent processing units also called cores.
Such processors do not need context switching mechanism as each core contains everything it needs to execute a sequence of stored instructions.
The cores of multi-core processors follow a cycle for executing. This cycle is called the Fetch-Decode-Execute cycle. It involves the following steps −
This is the first step of cycle, which involves the fetching of instructions from the program memory.
Recently fetched instructions would be converted to a series of signals that will trigger other parts of the CPU.
It is the final step in which the fetched and the decoded instructions would be executed. The result of execution will be stored in a CPU register.
One advantage over here is that the execution in multi-core processors are faster than that of single-core processors. It is suitable for larger applications. On the other hand, complex communication protocol between multiple cores is an issue. Multiple cores require more power than single-core processors.
There are different system and memory architecture styles that need to be considered while designing the program or concurrent system. It is very necessary because one system & memory style may be suitable for one task but may be error prone to other task.
Michael Flynn in 1972 gave taxonomy for categorizing different styles of computer system architecture. This taxonomy defines four different styles as follows −
Single instruction stream, single data stream (SISD)
Single instruction stream, multiple data stream (SIMD)
Multiple instruction stream, single data stream (MISD)
Multiple instruction stream, multiple data stream (MIMD).
As the name suggests, such kind of systems would have one sequential incoming data stream and one single processing unit to execute the data stream. They are just like uniprocessor systems having parallel computing architecture. Following is the architecture of SISD −
The advantages of SISD architecture are as follows −
It requires less power.
There is no issue of complex communication protocol between multiple cores.
The disadvantages of SISD architecture are as follows −
The speed of SISD architecture is limited just like single-core processors.
It is not suitable for larger applications.
As the name suggests, such kind of systems would have multiple incoming data streams and number of processing units that can act on a single instruction at any given time. They are just like multiprocessor systems having parallel computing architecture. Following is the architecture of SIMD −
The best example for SIMD is the graphics cards. These cards have hundreds of individual processing units. If we talk about computational difference between SISD and SIMD then for the adding arrays [5, 15, 20] and [15, 25, 10], SISD architecture would have to perform three different add operations. On the other hand, with the SIMD architecture, we can add then in a single add operation.
The advantages of SIMD architecture are as follows −
Same operation on multiple elements can be performed using one instruction only.
Same operation on multiple elements can be performed using one instruction only.
Throughput of the system can be increased by increasing the number of cores of the processor.
Throughput of the system can be increased by increasing the number of cores of the processor.
Processing speed is higher than SISD architecture.
Processing speed is higher than SISD architecture.
The disadvantages of SIMD architecture are as follows −
There is complex communication between numbers of cores of processor.
The cost is higher than SISD architecture.
Systems with MISD stream have number of processing units performing different operations by executing different instructions on the same data set. Following is the architecture of MISD −
The representatives of MISD architecture do not yet exist commercially.
In the system using MIMD architecture, each processor in a multiprocessor system can execute different sets of instructions independently on the different set of data set in parallel. It is opposite to SIMD architecture in which single operation is executed on multiple data sets. Following is the architecture of MIMD −
A normal multiprocessor uses the MIMD architecture. These architectures are basically used in a number of application areas such as computer-aided design/computer-aided manufacturing, simulation, modeling, communication switches, etc.
While working with the concepts like concurrency and parallelism, there is always a need to speed up the programs. One solution found by computer designers is to create shared-memory multi-computers, i.e., computers having single physical address space, which is accessed by all the cores that a processor is having. In this scenario, there can be a number of different styles of architecture but following are the three important architecture styles −
In this model, all the processors share the physical memory uniformly. All the processors have equal access time to all the memory words. Each processor may have a private cache memory. The peripheral devices follow a set of rules.
When all the processors have equal access to all the peripheral devices, the system is called a symmetric multiprocessor. When only one or a few processors can access the peripheral devices, the system is called an asymmetric multiprocessor.
In the NUMA multiprocessor model, the access time varies with the location of the memory word. Here, the shared memory is physically distributed among all the processors, called local memories. The collection of all local memories forms a global address space which can be accessed by all the processors.
The COMA model is a specialized version of the NUMA model. Here, all the distributed main memories are converted to cache memories.
In general, as we know that thread is a very thin twisted string usually of the cotton or silk fabric and used for sewing clothes and such. The same term thread is also used in the world of computer programming. Now, how do we relate the thread used for sewing clothes and the thread used for computer programming? The roles performed by the two threads is similar here. In clothes, thread hold the cloth together and on the other side, in computer programming, thread hold the computer program and allow the program to execute sequential actions or many actions at once.
Threadis the smallest unit of execution in an operating system. It is not in itself a program but runs within a program. In other words, threads are not independent of one other and share code section, data section, etc. with other threads. These threads are also known as lightweight processes.
To understand the functionality of threads in depth, we need to learn about the lifecycle of the threads or the different thread states. Typically, a thread can exist in five distinct states. The different states are shown below −
A new thread begins its life cycle in the new state. However, at this stage, it has not yet started and it has not been allocated any resources. We can say that it is just an instance of an object.
As the newly born thread is started, the thread becomes runnable i.e. waiting to run. In this state, it has all the resources but still task scheduler have not scheduled it to run.
In this state, the thread makes progress and executes the task, which has been chosen by task scheduler to run. Now, the thread can go to either the dead state or the non-runnable/ waiting state.
In this state, the thread is paused because it is either waiting for the response of some I/O request or waiting for the completion of the execution of other thread.
A runnable thread enters the terminated state when it completes its task or otherwise terminates.
The following diagram shows the complete life cycle of a thread −
In this section, we will see the different types of thread. The types are described below −
These are user-managed threads.
In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread.
The examples of user level threads are −
Java threads
POSIX threads
Following are the different advantages of user level threads −
Thread switching does not require Kernel mode privileges.
User level thread can run on any operating system.
Scheduling can be application specific in the user level thread.
User level threads are fast to create and manage.
Following are the different disadvantages of user level threads −
In a typical operating system, most system calls are blocking.
Multithreaded application cannot take advantage of multiprocessing.
Operating System managed threads act on kernel, which is an operating system core.
In this case, the Kernel does thread management. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process.
The Kernel maintains context information for the process as a whole and for individual threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads. The examples of kernel level threads are Windows, Solaris.
Following are the different advantages of kernel level threads −
Kernel can simultaneously schedule multiple threads from the same process on multiple processes.
Kernel can simultaneously schedule multiple threads from the same process on multiple processes.
If one thread in a process is blocked, the Kernel can schedule another thread of the same process.
If one thread in a process is blocked, the Kernel can schedule another thread of the same process.
Kernel routines themselves can be multithreaded.
Kernel routines themselves can be multithreaded.
Kernel threads are generally slower to create and manage than the user threads.
Kernel threads are generally slower to create and manage than the user threads.
Transfer of control from one thread to another within the same process requires a mode switch to the Kernel.
Transfer of control from one thread to another within the same process requires a mode switch to the Kernel.
Thread Control Block (TCB) may be defined as the data structure in the kernel of operating system that mainly contains information about thread. Thread-specific information stored in TCB would highlight some important information about each process.
Consider the following points related to the threads contained in TCB −
Thread identification − It is the unique thread id (tid) assigned to every new thread.
Thread identification − It is the unique thread id (tid) assigned to every new thread.
Thread state − It contains the information related to the state (Running, Runnable, Non-Running, Dead) of the thread.
Thread state − It contains the information related to the state (Running, Runnable, Non-Running, Dead) of the thread.
Program Counter (PC) − It points to the current program instruction of the thread.
Program Counter (PC) − It points to the current program instruction of the thread.
Register set − It contains the thread’s register values assigned to them for computations.
Register set − It contains the thread’s register values assigned to them for computations.
Stack Pointer − It points to the thread’s stack in the process. It contains the local variables under thread’s scope.
Stack Pointer − It points to the thread’s stack in the process. It contains the local variables under thread’s scope.
Pointer to PCB − It contains the pointer to the process that created that thread.
Pointer to PCB − It contains the pointer to the process that created that thread.
In multithreading, process and thread are two very closely related terms having the same goal to make computer able to do more than one thing at a time. A process can contain one or more threads but on the contrary, thread cannot contain a process. However, they both remain the two basic units of execution. A program, executing a series of instructions, initiates process and thread both.
The following table shows the comparison between process and thread −
As we have discussed earlier that Multithreading is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads. In a more simple way, we can say that multithreading is the way of achieving multitasking by using the concept of threads.
The concept of multithreading can be understood with the help of the following example.
Suppose we are running a process. The process could be for opening MS word for writing something. In such process, one thread will be assigned to open MS word and another thread will be required to write. Now, suppose if we want to edit something then another thread will be required to do the editing task and so on.
The following diagram helps us understand how multiple threads exist in memory −
We can see in the above diagram that more than one thread can exist within one process where every thread contains its own register set and local variables. Other than that, all the threads in a process share global variables.
Let us now see a few advantages of multithreading. The advantages are as follows −
Speed of communication − Multithreading improves the speed of computation because each core or processor handles separate threads concurrently.
Speed of communication − Multithreading improves the speed of computation because each core or processor handles separate threads concurrently.
Program remains responsive − It allows a program to remain responsive because one thread waits for the input and another runs a GUI at the same time.
Program remains responsive − It allows a program to remain responsive because one thread waits for the input and another runs a GUI at the same time.
Access to global variables − In multithreading, all the threads of a particular process can access the global variables and if there is any change in global variable then it is visible to other threads too.
Access to global variables − In multithreading, all the threads of a particular process can access the global variables and if there is any change in global variable then it is visible to other threads too.
Utilization of resources − Running of several threads in each program makes better use of CPU and the idle time of CPU becomes less.
Utilization of resources − Running of several threads in each program makes better use of CPU and the idle time of CPU becomes less.
Sharing of data − There is no requirement of extra space for each thread because threads within a program can share same data.
Sharing of data − There is no requirement of extra space for each thread because threads within a program can share same data.
Let us now see a few disadvantages of multithreading. The disadvantages are as follows −
Not suitable for single processor system − Multithreading finds it difficult to achieve performance in terms of speed of computation on single processor system as compared with the performance on multi-processor system.
Not suitable for single processor system − Multithreading finds it difficult to achieve performance in terms of speed of computation on single processor system as compared with the performance on multi-processor system.
Issue of security − As we know that all the threads within a program share same data, hence there is always an issue of security because any unknown thread can change the data.
Issue of security − As we know that all the threads within a program share same data, hence there is always an issue of security because any unknown thread can change the data.
Increase in complexity − Multithreading can increase the complexity of the program and debugging becomes difficult.
Increase in complexity − Multithreading can increase the complexity of the program and debugging becomes difficult.
Lead to deadlock state − Multithreading can lead the program to potential risk of attaining the deadlock state.
Lead to deadlock state − Multithreading can lead the program to potential risk of attaining the deadlock state.
Synchronization required − Synchronization is required to avoid mutual exclusion. This leads to more memory and CPU utilization.
Synchronization required − Synchronization is required to avoid mutual exclusion. This leads to more memory and CPU utilization.
In this chapter, we will learn how to implement threads in Python.
Python threads are sometimes called lightweight processes because threads occupy much less memory than processes. Threads allow performing multiple tasks at once. In Python, we have the following two modules that implement threads in a program −
<_thread>module
<_thread>module
<threading>module
<threading>module
The main difference between these two modules is that <_thread> module treats a thread as a function whereas, the <threading> module treats every thread as an object and implements it in an object oriented way. Moreover, the <_thread>module is effective in low level threading and has fewer capabilities than the <threading> module.
In the earlier version of Python, we had the <thread> module but it has been considered as "deprecated" for quite a long time. Users have been encouraged to use the <threading> module instead. Therefore, in Python 3 the module "thread" is not available anymore. It has been renamed to "<_thread>" for backwards incompatibilities in Python3.
To generate new thread with the help of the <_thread> module, we need to call the start_new_thread method of it. The working of this method can be understood with the help of following syntax −
_thread.start_new_thread ( function, args[, kwargs] )
Here −
args is a tuple of arguments
args is a tuple of arguments
kwargs is an optional dictionary of keyword arguments
kwargs is an optional dictionary of keyword arguments
If we want to call function without passing an argument then we need to use an empty tuple of arguments in args.
This method call returns immediately, the child thread starts, and calls function with the passed list, if any, of args. The thread terminates as and when the function returns.
Following is an example for generating new thread by using the <_thread> module. We are using the start_new_thread() method here.
import _thread
import time
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")
while 1:
pass
The following output will help us understand the generation of new threads bwith the help of the <_thread> module.
Thread-1: Mon Apr 23 10:03:33 2018
Thread-2: Mon Apr 23 10:03:35 2018
Thread-1: Mon Apr 23 10:03:35 2018
Thread-1: Mon Apr 23 10:03:37 2018
Thread-2: Mon Apr 23 10:03:39 2018
Thread-1: Mon Apr 23 10:03:39 2018
Thread-1: Mon Apr 23 10:03:41 2018
Thread-2: Mon Apr 23 10:03:43 2018
Thread-2: Mon Apr 23 10:03:47 2018
Thread-2: Mon Apr 23 10:03:51 2018
The <threading> module implements in an object oriented way and treats every thread as an object. Therefore, it provides much more powerful, high-level support for threads than the <_thread> module. This module is included with Python 2.4.
The <threading> module comprises all the methods of the <_thread> module but it provides additional methods as well. The additional methods are as follows −
threading.activeCount() − This method returns the number of thread objects that are active
threading.activeCount() − This method returns the number of thread objects that are active
threading.currentThread() − This method returns the number of thread objects in the caller's thread control.
threading.currentThread() − This method returns the number of thread objects in the caller's thread control.
threading.enumerate() − This method returns a list of all thread objects that are currently active.
threading.enumerate() − This method returns a list of all thread objects that are currently active.
For implementing threading, the <threading> module has the Thread class which provides the following methods −
run() − The run() method is the entry point for a thread.
run() − The run() method is the entry point for a thread.
start() − The start() method starts a thread by calling the run method.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread.
setName() − The setName() method sets the name of a thread.
In this section, we will learn how to create threads using the <threading> module. Follow these steps to create a new thread using the <threading> module −
Step 1 − In this step, we need to define a new subclass of the Thread class.
Step 1 − In this step, we need to define a new subclass of the Thread class.
Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method.
Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method.
Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started.
Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started.
Now, after creating the new Thread subclass, we can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run() method.
Consider this example to learn how to generate a new thread by using the <threading> module.
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")
Starting Thread-1
Starting Thread-2
Now, consider the following output −
Thread-1: Mon Apr 23 10:52:09 2018
Thread-1: Mon Apr 23 10:52:10 2018
Thread-2: Mon Apr 23 10:52:10 2018
Thread-1: Mon Apr 23 10:52:11 2018
Thread-1: Mon Apr 23 10:52:12 2018
Thread-2: Mon Apr 23 10:52:12 2018
Thread-1: Mon Apr 23 10:52:13 2018
Exiting Thread-1
Thread-2: Mon Apr 23 10:52:14 2018
Thread-2: Mon Apr 23 10:52:16 2018
Thread-2: Mon Apr 23 10:52:18 2018
Exiting Thread-2
Exiting Main Thread
There are five thread states - new, runnable, running, waiting and dead. Among these five Of these five, we will majorly focus on three states - running, waiting and dead. A thread gets its resources in the running state, waits for the resources in the waiting state; the final release of the resource, if executing and acquired is in the dead state.
The following Python program with the help of start(), sleep() and join() methods will show how a thread entered in running, waiting and dead state respectively.
Step 1 − Import the necessary modules, <threading> and <time>
import threading
import time
Step 2 − Define a function, which will be called while creating a thread.
def thread_states():
print("Thread entered in running state")
Step 3 − We are using the sleep() method of time module to make our thread waiting for say 2 seconds.
time.sleep(2)
Step 4 − Now, we are creating a thread named T1, which takes the argument of the function defined above.
T1 = threading.Thread(target=thread_states)
Step 5 − Now, with the help of the start() function we can start our thread. It will produce the message, which has been set by us while defining the function.
T1.start()
Thread entered in running state
Step 6 − Now, at last we can kill the thread with the join() method after it finishes its execution.
T1.join()
In python, we can start a new thread by different ways but the easiest one among them is to define it as a single function. After defining the function, we can pass this as the target for a new threading.Thread object and so on. Execute the following Python code to understand how the function works −
import threading
import time
import random
def Thread_execution(i):
print("Execution of Thread {} started\n".format(i))
sleepTime = random.randint(1,4)
time.sleep(sleepTime)
print("Execution of Thread {} finished".format(i))
for i in range(4):
thread = threading.Thread(target=Thread_execution, args=(i,))
thread.start()
print("Active Threads:" , threading.enumerate())
Execution of Thread 0 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>]
Execution of Thread 1 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>]
Execution of Thread 2 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>,
<Thread(Thread-3578, started 2268)>]
Execution of Thread 3 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>,
<Thread(Thread-3578, started 2268)>,
<Thread(Thread-3579, started 4520)>]
Execution of Thread 0 finished
Execution of Thread 1 finished
Execution of Thread 2 finished
Execution of Thread 3 finished
Before implementing the daemon threads in Python, we need to know about daemon threads and their usage. In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. It would be dormant if it is not required any more. The same task can be done with the help of non-daemon threads also. However, in this case, the main thread has to keep track of the non-daemon threads manually. On the other hand, if we are using daemon threads then the main thread can completely forget about this and it will be killed when main thread exits. Another important point about daemon threads is that we can opt to use them only for non-essential tasks that would not affect us if it does not complete or gets killed in between. Following is the implementation of daemon threads in python −
import threading
import time
def nondaemonThread():
print("starting my thread")
time.sleep(8)
print("ending my thread")
def daemonThread():
while True:
print("Hello")
time.sleep(2)
if __name__ == '__main__':
nondaemonThread = threading.Thread(target = nondaemonThread)
daemonThread = threading.Thread(target = daemonThread)
daemonThread.setDaemon(True)
daemonThread.start()
nondaemonThread.start()
In the above code, there are two functions namely >nondaemonThread() and >daemonThread(). The first function prints its state and sleeps after 8 seconds while the the deamonThread() function prints Hello after every 2 seconds indefinitely. We can understand the difference between nondaemon and daemon threads with the help of following output −
Hello
starting my thread
Hello
Hello
Hello
Hello
ending my thread
Hello
Hello
Hello
Hello
Hello
Thread synchronization may be defined as a method with the help of which we can be assured that two or more concurrent threads are not simultaneously accessing the program segment known as critical section. On the other hand, as we know that critical section is the part of the program where the shared resource is accessed. Hence we can say that synchronization is the process of making sure that two or more threads do not interface with each other by accessing the resources at the same time. The diagram below shows that four threads trying to access the critical section of a program at the same time.
To make it clearer, suppose two or more threads trying to add the object in the list at the same time. This act cannot lead to a successful end because either it will drop one or all the objects or it will completely corrupt the state of the list. Here the role of the synchronization is that only one thread at a time can access the list.
We might encounter issues while implementing concurrent programming or applying synchronizing primitives. In this section, we will discuss two major issues. The issues are −
Deadlock
Race condition
This is one of the major issues in concurrent programming. Concurrent access to shared resources can lead to race condition. A race condition may be defined as the occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes.
Consider this example to understand the concept of race condition −
Step 1 − In this step, we need to import threading module −
import threading
Step 2 − Now, define a global variable, say x, along with its value as 0 −
x = 0
Step 3 − Now, we need to define the increment_global() function, which will do the increment by 1 in this global function x −
def increment_global():
global x
x += 1
Step 4 − In this step, we will define the taskofThread() function, which will call the increment_global() function for a specified number of times; for our example it is 50000 times −
def taskofThread():
for _ in range(50000):
increment_global()
Step 5 − Now, define the main() function in which threads t1 and t2 are created. Both will be started with the help of the start() function and wait until they finish their jobs with the help of join() function.
def main():
global x
x = 0
t1 = threading.Thread(target= taskofThread)
t2 = threading.Thread(target= taskofThread)
t1.start()
t2.start()
t1.join()
t2.join()
Step 6 − Now, we need to give the range as in for how many iterations we want to call the main() function. Here, we are calling it for 5 times.
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
In the output shown below, we can see the effect of race condition as the value of x after each iteration is expected 100000. However, there is lots of variation in the value. This is due to the concurrent access of threads to the shared global variable x.
x = 100000 after Iteration 0
x = 54034 after Iteration 1
x = 80230 after Iteration 2
x = 93602 after Iteration 3
x = 93289 after Iteration 4
As we have seen the effect of race condition in the above program, we need a synchronization tool, which can deal with race condition between multiple threads. In Python, the <threading> module provides Lock class to deal with race condition. Further, the Lock class provides different methods with the help of which we can handle race condition between multiple threads. The methods are described below −
This method is used to acquire, i.e., blocking a lock. A lock can be blocking or non-blocking depending upon the following true or false value −
With value set to True − If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked.
With value set to True − If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked.
With value set to False − If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked.
With value set to False − If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked.
This method is used to release a lock. Following are a few important tasks related to this method −
If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked.
If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked.
It will raise a ThreadError if lock is already unlocked.
It will raise a ThreadError if lock is already unlocked.
Now, we can rewrite the above program with the lock class and its methods to avoid the race condition. We need to define the taskofThread() method with lock argument and then need to use the acquire() and release() methods for blocking and non-blocking of locks to avoid race condition.
Following is example of python program to understand the concept of locks for dealing with race condition −
import threading
x = 0
def increment_global():
global x
x += 1
def taskofThread(lock):
for _ in range(50000):
lock.acquire()
increment_global()
lock.release()
def main():
global x
x = 0
lock = threading.Lock()
t1 = threading.Thread(target = taskofThread, args = (lock,))
t2 = threading.Thread(target = taskofThread, args = (lock,))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
The following output shows that the effect of race condition is neglected; as the value of x, after each & every iteration, is now 100000, which is as per the expectation of this program.
x = 100000 after Iteration 0
x = 100000 after Iteration 1
x = 100000 after Iteration 2
x = 100000 after Iteration 3
x = 100000 after Iteration 4
Deadlock is a troublesome issue one can face while designing the concurrent systems. We can illustrate this issue with the help of the dining philosopher problem as follows −
Edsger Dijkstra originally introduced the dining philosopher problem, one of the famous illustrations of one of the biggest problem of concurrent system called deadlock.
In this problem, there are five famous philosophers sitting at a round table eating some food from their bowls. There are five forks that can be used by the five philosophers to eat their food. However, the philosophers decide to use two forks at the same time to eat their food.
Now, there are two main conditions for the philosophers. First, each of the philosophers can be either in eating or in thinking state and second, they must first obtain both the forks, i.e., left and right. The issue arises when each of the five philosophers manages to pick the left fork at the same time. Now they all are waiting for the right fork to be free but they will never relinquish their fork until they have eaten their food and the right fork would never be available. Hence, there would be a deadlock state at the dinner table.
Now if we see, the same issue can arise in our concurrent systems too. The forks in the above example would be the system resources and each philosopher can represent the process, which is competing to get the resources.
The solution of this problem can be found by splitting the philosophers into two types – greedy philosophers and generous philosophers. Mainly a greedy philosopher will try to pick up the left fork and wait until it is there. He will then wait for the right fork to be there, pick it up, eat and then put it down. On the other hand, a generous philosopher will try to pick up the left fork and if it is not there, he will wait and try again after some time. If they get the left fork then they will try to get the right one. If they will get the right fork too then they will eat and release both the forks. However, if they will not get the right fork then they will release the left fork.
The following Python program will help us find a solution to the dining philosopher problem −
import threading
import random
import time
class DiningPhilosopher(threading.Thread):
running = True
def __init__(self, xname, Leftfork, Rightfork):
threading.Thread.__init__(self)
self.name = xname
self.Leftfork = Leftfork
self.Rightfork = Rightfork
def run(self):
while(self.running):
time.sleep( random.uniform(3,13))
print ('%s is hungry.' % self.name)
self.dine()
def dine(self):
fork1, fork2 = self.Leftfork, self.Rightfork
while self.running:
fork1.acquire(True)
locked = fork2.acquire(False)
if locked: break
fork1.release()
print ('%s swaps forks' % self.name)
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print ('%s starts eating '% self.name)
time.sleep(random.uniform(1,10))
print ('%s finishes eating and now thinking.' % self.name)
def Dining_Philosophers():
forks = [threading.Lock() for n in range(5)]
philosopherNames = ('1st','2nd','3rd','4th', '5th')
philosophers= [DiningPhilosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
for i in range(5)]
random.seed()
DiningPhilosopher.running = True
for p in philosophers: p.start()
time.sleep(30)
DiningPhilosopher.running = False
print (" It is finishing.")
Dining_Philosophers()
The above program uses the concept of greedy and generous philosophers. The program has also used the acquire() and release() methods of the Lock class of the <threading> module. We can see the solution in the following output −
4th is hungry.
4th starts eating
1st is hungry.
1st starts eating
2nd is hungry.
5th is hungry.
3rd is hungry.
1st finishes eating and now thinking.3rd swaps forks
2nd starts eating
4th finishes eating and now thinking.
3rd swaps forks5th starts eating
5th finishes eating and now thinking.
4th is hungry.
4th starts eating
2nd finishes eating and now thinking.
3rd swaps forks
1st is hungry.
1st starts eating
4th finishes eating and now thinking.
3rd starts eating
5th is hungry.
5th swaps forks
1st finishes eating and now thinking.
5th starts eating
2nd is hungry.
2nd swaps forks
4th is hungry.
5th finishes eating and now thinking.
3rd finishes eating and now thinking.
2nd starts eating 4th starts eating
It is finishing.
In real life, if a team of people is working on a common task then there should be communication between them for finishing the task properly. The same analogy is applicable to threads also. In programming, to reduce the ideal time of the processor we create multiple threads and assign different sub tasks to every thread. Hence, there must be a communication facility and they should interact with each other to finish the job in a synchronized manner.
Consider the following important points related to thread intercommunication −
No performance gain − If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use.
No performance gain − If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use.
Accomplish task properly − Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly.
Accomplish task properly − Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly.
More efficient than inter-process communication − Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory.
More efficient than inter-process communication − Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory.
Multithreaded code comes up with a problem of passing information from one thread to another thread. The standard communication primitives do not solve this issue. Hence, we need to implement our own composite object in order to share objects between threads to make the communication thread-safe. Following are a few data structures, which provide thread-safe communication after making some changes in them −
For using set data structure in a thread-safe manner, we need to extend the set class to implement our own locking mechanism.
Here is a Python example of extending the class −
class extend_class(set):
def __init__(self, *args, **kwargs):
self._lock = Lock()
super(extend_class, self).__init__(*args, **kwargs)
def add(self, elem):
self._lock.acquire()
try:
super(extend_class, self).add(elem)
finally:
self._lock.release()
def delete(self, elem):
self._lock.acquire()
try:
super(extend_class, self).delete(elem)
finally:
self._lock.release()
In the above example, a class object named extend_class has been defined which is further inherited from the Python set class. A lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on the super class functionality with one key exception.
This is another key method for thread-safe communication is the use of decorators.
Consider a Python example that shows how to use decorators &mminus;
def lock_decorator(method):
def new_deco_method(self, *args, **kwargs):
with self._lock:
return method(self, *args, **kwargs)
return new_deco_method
class Decorator_class(set):
def __init__(self, *args, **kwargs):
self._lock = Lock()
super(Decorator_class, self).__init__(*args, **kwargs)
@lock_decorator
def add(self, *args, **kwargs):
return super(Decorator_class, self).add(elem)
@lock_decorator
def delete(self, *args, **kwargs):
return super(Decorator_class, self).delete(elem)
In the above example, a decorator method named lock_decorator has been defined which is further inherited from the Python method class. Then a lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on super class functionality with one key exception.
The list data structure is thread-safe, quick as well as easy structure for temporary, in-memory storage. In Cpython, the GIL protects against concurrent access to them. As we came to know that lists are thread-safe but what about the data lying in them. Actually, the list’s data is not protected. For example, L.append(x) is not guarantee to return the expected result if another thread is trying to do the same thing. This is because, although append() is an atomic operation and thread-safe but the other thread is trying to modify the list’s data in concurrent fashion hence we can see the side effects of race conditions on the output.
To resolve this kind of issue and safely modify the data, we must implement a proper locking mechanism, which further ensures that multiple threads cannot potentially run into race conditions. To implement proper locking mechanism, we can extend the class as we did in the previous examples.
Some other atomic operations on lists are as follows −
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
Here −
L,L1,L2 all are lists
D,D1,D2 are dicts
x,y are objects
i, j are ints
If the list’s data is not protected, we might have to face the consequences. We may get or delete wrong data item, of race conditions. That is why it is recommended to use the queue data structure. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen of the queues at the ticket windows and bus-stops.
Queues are by default, thread-safe data structure and we need not worry about implementing complex locking mechanism. Python provides us the module to use different types of queues in our application.
In this section, we will earn about the different types of queues. Python provides three options of queues to use from the <queue> module −
Normal Queues (FIFO, First in First out)
LIFO, Last in First Out
Priority
We will learn about the different queues in the subsequent sections.
It is most commonly used queue implementations offered by Python. In this queuing mechanism whosoever will come first, will get the service first. FIFO is also called normal queues. FIFO queues can be represented as follows −
In python, FIFO queue can be implemented with single thread as well as multithreads.
For implementing FIFO queue with single thread, the Queue class will implement a basic first-in, first-out container. Elements will be added to one “end” of the sequence using put(), and removed from the other end using get().
Following is a Python program for implementation of FIFO queue with single thread −
import queue
q = queue.Queue()
for i in range(8):
q.put("item-" + str(i))
while not q.empty():
print (q.get(), end = " ")
item-0 item-1 item-2 item-3 item-4 item-5 item-6 item-7
The output shows that above program uses a single thread to illustrate that the elements are removed from the queue in the same order they are inserted.
For implementing FIFO with multiple threads, we need to define the myqueue() function, which is extended from the queue module. The working of get() and put() methods are same as discussed above while implementing FIFO queue with single thread. Then to make it multithreaded, we need to declare and instantiate the threads. These threads will consume the queue in FIFO manner.
Following is a Python program for implementation of FIFO queue with multiple threads
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(2)
q = queue.Queue()
for i in range(5):
q.put(i)
threads = []
for i in range(4):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-3654, started 5044)> removed 0 from the queue
<Thread(Thread-3655, started 3144)> removed 1 from the queue
<Thread(Thread-3656, started 6996)> removed 2 from the queue
<Thread(Thread-3657, started 2672)> removed 3 from the queue
<Thread(Thread-3654, started 5044)> removed 4 from the queue
This queue uses totally opposite analogy than FIFO(First in First Out) queues. In this queuing mechanism, the one who comes last, will get the service first. This is similar to implement stack data structure. LIFO queues prove useful while implementing Depth-first search like algorithms of artificial intelligence.
In python, LIFO queue can be implemented with single thread as well as multithreads.
For implementing LIFO queue with single thread, the Queue class will implement a basic last-in, first-out container by using the structure Queue.LifoQueue. Now, on calling put(), the elements are added in the head of the container and removed from the head also on using get().
Following is a Python program for implementation of the LIFO queue with single thread −
import queue
q = queue.LifoQueue()
for i in range(8):
q.put("item-" + str(i))
while not q.empty():
print (q.get(), end=" ")
Output:
item-7 item-6 item-5 item-4 item-3 item-2 item-1 item-0
The output shows that the above program uses a single thread to illustrate that elements are removed from the queue in the opposite order they are inserted.
The implementation is similar as we have done the implementation of FIFO queues with multiple threads. The only difference is that we need to use the Queue class that will implement a basic last-in, first-out container by using the structure Queue.LifoQueue.
Following is a Python program for implementation of LIFO queue with multiple threads −
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(2)
q = queue.LifoQueue()
for i in range(5):
q.put(i)
threads = []
for i in range(4):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-3882, started 4928)> removed 4 from the queue
<Thread(Thread-3883, started 4364)> removed 3 from the queue
<Thread(Thread-3884, started 6908)> removed 2 from the queue
<Thread(Thread-3885, started 3584)> removed 1 from the queue
<Thread(Thread-3882, started 4928)> removed 0 from the queue
In FIFO and LIFO queues, the order of items are related to the order of insertion. However, there are many cases when the priority is more important than the order of insertion. Let us consider a real world example. Suppose the security at the airport is checking people of different categories. People of the VVIP, airline staff, custom officer, categories may be checked on priority instead of being checked on the basis of arrival like it is for the commoners.
Another important aspect that needs to be considered for priority queue is how to develop a task scheduler. One common design is to serve the most agent task on priority basis in the queue. This data structure can be used to pick up the items from the queue based on their priority value.
In python, priority queue can be implemented with single thread as well as multithreads.
For implementing priority queue with single thread, the Queue class will implement a task on priority container by using the structure Queue.PriorityQueue. Now, on calling put(), the elements are added with a value where the lowest value will have the highest priority and hence retrieved first by using get().
Consider the following Python program for implementation of Priority queue with single thread −
import queue as Q
p_queue = Q.PriorityQueue()
p_queue.put((2, 'Urgent'))
p_queue.put((1, 'Most Urgent'))
p_queue.put((10, 'Nothing important'))
prio_queue.put((5, 'Important'))
while not p_queue.empty():
item = p_queue.get()
print('%s - %s' % item)
1 – Most Urgent
2 - Urgent
5 - Important
10 – Nothing important
In the above output, we can see that the queue has stored the items based on priority – less value is having high priority.
The implementation is similar to the implementation of FIFO and LIFO queues with multiple threads. The only difference is that we need to use the Queue class for initializing the priority by using the structure Queue.PriorityQueue. Another difference is with the way the queue would be generated. In the example given below, it will be generated with two identical data sets.
The following Python program helps in the implementation of priority queue with multiple threads −
import threading
import queue
import random
import time
def myqueue(queue):
while not queue.empty():
item = queue.get()
if item is None:
break
print("{} removed {} from the queue".format(threading.current_thread(), item))
queue.task_done()
time.sleep(1)
q = queue.PriorityQueue()
for i in range(5):
q.put(i,1)
for i in range(5):
q.put(i,1)
threads = []
for i in range(2):
thread = threading.Thread(target=myqueue, args=(q,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
<Thread(Thread-4939, started 2420)> removed 0 from the queue
<Thread(Thread-4940, started 3284)> removed 0 from the queue
<Thread(Thread-4939, started 2420)> removed 1 from the queue
<Thread(Thread-4940, started 3284)> removed 1 from the queue
<Thread(Thread-4939, started 2420)> removed 2 from the queue
<Thread(Thread-4940, started 3284)> removed 2 from the queue
<Thread(Thread-4939, started 2420)> removed 3 from the queue
<Thread(Thread-4940, started 3284)> removed 3 from the queue
<Thread(Thread-4939, started 2420)> removed 4 from the queue
<Thread(Thread-4940, started 3284)> removed 4 from the queue
In this chapter, we will learn about testing of thread applications. We will also learn the importance of testing.
Before we dive into the discussion about the importance of testing, we need to know what is testing. In general terms, testing is a technique of finding out how well something is working. On the other hand, specifically if we talk about computer programs or software then testing is the technique of accessing the functionality of a software program.
In this section, we will discuss the importance of software testing. In software development, there must be double-checking before the releasing of software to the client. That is why it is very important to test the software by experienced testing team. Consider the following points to understand the importance of software testing −
Certainly, no company wants to deliver low quality software and no client wants to buy low quality software. Testing improves the quality of software by finding and fixing the bugs in that.
The most important part of any business is the satisfaction of their customers. By providing bug free and good quality software, the companies can achieve customer satisfaction.
Suppose we have made a software system of 10000 lines and we need to add a new feature then the development team would have the concern about the impact of this new feature on whole software. Here, also, testing plays a vital role because if the testing team has made a good suite of tests then it can save us from any potential catastrophic breaks.
Another most important part of any business is the experience of the users of that product. Only testing can assure that the end user finds it simple and easy to use the product.
Testing can cut down the total cost of software by finding and fixing the bugs in testing phase of its development rather than fixing it after delivery. If there is a major bug after the delivery of the software then it would increase its tangible cost say in terms of expenses and intangible cost say in terms of customer dissatisfaction, company’s negative reputation etc.
It is always recommended to have appropriate knowledge of what is to be tested. In this section, we will first understand be the prime motive of tester while testing any software. Code coverage, i.e., how many lines of code our test suite hits, while testing, should be avoided. It is because, while testing, focusing only on the number of lines of codes adds no real value to our system. There may remain some bugs, which reflect later at a later stage even after deployment.
Consider the following important points related to what to test −
We need to focus on testing the functionality of the code rather than the code coverage.
We need to focus on testing the functionality of the code rather than the code coverage.
We need to test the most important parts of the code first and then move towards the less important parts of the code. It will definitely save time.
We need to test the most important parts of the code first and then move towards the less important parts of the code. It will definitely save time.
The tester must have multitude different tests that can push the software up to its limits.
The tester must have multitude different tests that can push the software up to its limits.
Due to the capability of utilizing the true capability of multi-core architecture, concurrent software systems are replacing sequential systems. In recent times, concurrent system programs are being used in everything from mobile phones to washing machines, from cars to airplanes, etc. We need to be more careful about testing the concurrent software programs because if we have added multiple threads to single thread application having already a bug, then we would end up with multiple bugs.
Testing techniques for concurrent software programs are extensively focusing on selecting interleaving that expose potentially harmful patterns like race conditions, deadlocks and violation of atomicity. Following are two approaches for testing concurrent software programs −
This approach aims to explore the space of the interleavings as broadly as possible. Such approaches can adopt a brute-force technique and others adopt partial order reduction technique or heuristic technique to explore the space of interleavings.
Property-driven approaches rely on the observation that concurrency faults are more likely to occur under interleavings that expose specific properties such as suspicious memory access pattern. Different property-driven approaches target different faults like race conditions, deadlocks and violation of atomicity, which further depends on one or other specific properties.
Test Strategy is also known as test approach. The strategy defines how testing would be carried out. Test approach has two techniques −
An approach in which the test design process is initiated as early as possible in order to find and fix the defects before the build is created.
An approach in which the testing does not start until the completion of the development process.
Before applying any test strategy or approach on python program, we must have a basic idea about the kind of errors a software program may have. The errors are as follows −
During program development, there can be many small errors. The errors are mostly due to typing mistakes. For example, missing colon or a wrong spelling of a keyword, etc. Such errors are due to the mistake in program syntax and not in logic. Hence, these errors are called syntactical errors.
The semantic errors are also called logical errors. If there is a logical or semantic error in software program then the statement will compile and run correctly but it will not give the desired output because the logic is not correct.
This is one of the most used testing strategies for testing python programs. This strategy is used for testing units or components of the code. By units or components, we mean classes or functions of the code. Unit testing simplifies the testing of large programming systems by testing “small” units. With the help of the above concept, unit testing may be defined as a method where individual units of source code are tested to determine if they return the desired output.
In our subsequent sections, we will learn about the different Python modules for unit testing.
The very first module for unit testing is the unittest module. It is inspired by JUnit and by default included in Python3.6. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.
Following are a few important concepts supported by the unittest module
It is used to set up a test so that it can be run before starting the test and tear down after the finish of test. It may involve creation of temporary database, directories, etc. needed before starting the test.
The test case checks whether a required response is coming from the specific set of inputs or not. The unittest module includes a base class named TestCase which can be used to create new test cases. It includes two by default methods −
setUp() − a hook method for setting up the test fixture before exercising it. This is called before calling the implemented test methods.
setUp() − a hook method for setting up the test fixture before exercising it. This is called before calling the implemented test methods.
tearDown( − a hook method for deconstructing the class fixture after running all tests in the class.
tearDown( − a hook method for deconstructing the class fixture after running all tests in the class.
It is a collection of test suites, test cases or both.
It controls the running of the test cases or suits and provides the outcome to the user. It may use GUI or simple text interface for providing the outcome.
Example
The following Python program uses the unittest module to test a module named Fibonacci. The program helps in calculating the Fibonacci series of a number. In this example, we have created a class named Fibo_test, to define the test cases by using different methods. These methods are inherited from unittest.TestCase. We are using two by default methods – setUp() and tearDown(). We also define the testfibocal method. The name of the test must be started with the letter test. In the final block, unittest.main() provides a command-line interface to the test script.
import unittest
def fibonacci(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
class Fibo_Test(unittest.TestCase):
def setUp(self):
print("This is run before our tests would be executed")
def tearDown(self):
print("This is run after the completion of execution of our tests")
def testfibocal(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(5), 5)
self.assertEqual(fib(10), 55)
self.assertEqual(fib(20), 6765)
if __name__ == "__main__":
unittest.main()
When run from the command line, the above script produces an output that looks like this −
This runs before our tests would be executed.
This runs after the completion of execution of our tests.
.
----------------------------------------------------------------------
Ran 1 test in 0.006s
OK
Now, to make it clearer, we are changing our code which helped in defining the Fibonacci module.
Consider the following code block as an example −
def fibonacci(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
A few changes to the code block are made as shown below −
def fibonacci(n):
a, b = 1, 1
for i in range(n):
a, b = b, a + b
return a
Now, after running the script with the changed code, we will get the following output −
This runs before our tests would be executed.
This runs after the completion of execution of our tests.
F
======================================================================
FAIL: testCalculation (__main__.Fibo_Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unitg.py", line 15, in testCalculation
self.assertEqual(fib(0), 0)
AssertionError: 1 != 0
----------------------------------------------------------------------
Ran 1 test in 0.007s
FAILED (failures = 1)
The above output shows that the module has failed to give the desired output.
The docktest module also helps in unit testing. It also comes prepackaged with python. It is easier to use than the unittest module. The unittest module is more suitable for complex tests. For using the doctest module, we need to import it. The docstring of the corresponding function must have interactive python session along with their outputs.
If everything is fine in our code then there will be no output from the docktest module; otherwise, it will provide the output.
The following Python example uses the docktest module to test a module named Fibonacci , which helps in calculating the Fibonacci series of a number.
import doctest
def fibonacci(n):
"""
Calculates the Fibonacci number
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
>>> fibonacci(20)
6765
>>>
"""
a, b = 1, 1
for i in range(n):
a, b = b, a + b
return a
if __name__ == "__main__":
doctest.testmod()
We can see that the docstring of the corresponding function named fib had interactive python session along with the outputs. If our code is fine then there would be no output from the doctest module. But to see how it works we can run it with the –v option.
(base) D:\ProgramData>python dock_test.py -v
Trying:
fibonacci(0)
Expecting:
0
ok
Trying:
fibonacci(1)
Expecting:
1
ok
Trying:
fibonacci(10)
Expecting:
55
ok
Trying:
fibonacci(20)
Expecting:
6765
ok
1 items had no tests:
__main__
1 items passed all tests:
4 tests in __main__.fibonacci
4 tests in 2 items.
4 passed and 0 failed.
Test passed.
Now, we will change the code that helped in defining the Fibonacci module
Consider the following code block as an example −
def fibonacci(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
The following code block helps with the changes −
def fibonacci(n):
a, b = 1, 1
for i in range(n):
a, b = b, a + b
return a
After running the script even without the –v option, with the changed code, we will get the output as shown below.
(base) D:\ProgramData>python dock_test.py
**********************************************************************
File "unitg.py", line 6, in __main__.fibonacci
Failed example:
fibonacci(0)
Expected:
0
Got:
1
**********************************************************************
File "unitg.py", line 10, in __main__.fibonacci
Failed example:
fibonacci(10)
Expected:
55
Got:
89
**********************************************************************
File "unitg.py", line 12, in __main__.fibonacci
Failed example:
fibonacci(20)
Expected:
6765
Got:
10946
**********************************************************************
1 items had failures:
3 of 4 in __main__.fibonacci
***Test Failed*** 3 failures.
We can see in the above output that three tests have failed.
In this chapter, we will learn how to debug thread applications. We will also learn the importance of debugging.
In computer programming, debugging is the process of finding and removing the bugs, errors and abnormalities from computer program. This process starts as soon as the code is written and continues in successive stages as code is combined with other units of programming to form a software product. Debugging is part of the software testing process and is an integral part of the entire software development life cycle.
The Python debugger or the pdb is part of the Python standard library. It is a good fallback tool for tracking down hard-to-find bugs and allows us to fix faulty code quickly and reliably. Followings are the two most important tasks of the pdp debugger −
It allows us to check the values of variables at runtime.
We can step through the code and set breakpoints also.
We can work with pdb in the following two ways −
Through the command-line; this is also called postmortem debugging.
By interactively running pdb.
For working with the Python debugger, we need to use the following code at the location where we want to break into the debugger −
import pdb;
pdb.set_trace()
Consider the following commands to work with pdb through command-line.
h(help)
d(down)
u(up)
b(break)
cl(clear)
l(list))
n(next))
c(continue)
s(step)
r(return))
b(break)
Following is a demo of the h(help) command of the Python debugger −
import pdb
pdb.set_trace()
--Call--
>d:\programdata\lib\site-packages\ipython\core\displayhook.py(247)__call__()
-> def __call__(self, result = None):
(Pdb) h
Documented commands (type help <topic>):
========================================
EOF c d h list q rv undisplay
a cl debug help ll quit s unt
alias clear disable ignore longlist r source until
args commands display interact n restart step up
b condition down j next return tbreak w
break cont enable jump p retval u whatis
bt continue exit l pp run unalias where
Miscellaneous help topics:
==========================
exec pdb
While working with Python debugger, we can set the breakpoint anywhere in the script by using the following lines −
import pdb;
pdb.set_trace()
After setting the breakpoint, we can run the script normally. The script will execute until a certain point; until where a line has been set. Consider the following example where we will run the script by using the above-mentioned lines at various places in the script −
import pdb;
a = "aaa"
pdb.set_trace()
b = "bbb"
c = "ccc"
final = a + b + c
print (final)
When the above script is run, it will execute the program till a = “aaa”, we can check this in the following output.
--Return--
> <ipython-input-7-8a7d1b5cc854>(3)<module>()->None
-> pdb.set_trace()
(Pdb) p a
'aaa'
(Pdb) p b
*** NameError: name 'b' is not defined
(Pdb) p c
*** NameError: name 'c' is not defined
After using the command ‘p(print)’ in pdb, this script is only printing ‘aaa’. This is followed by an error because we have set the breakpoint till a = "aaa".
Similarly, we can run the script by changing the breakpoints and see the difference in the output −
import pdb
a = "aaa"
b = "bbb"
c = "ccc"
pdb.set_trace()
final = a + b + c
print (final)
--Return--
> <ipython-input-9-a59ef5caf723>(5)<module>()->None
-> pdb.set_trace()
(Pdb) p a
'aaa'
(Pdb) p b
'bbb'
(Pdb) p c
'ccc'
(Pdb) p final
*** NameError: name 'final' is not defined
(Pdb) exit
In the following script, we are setting the breakpoint in the last line of the program −
import pdb
a = "aaa"
b = "bbb"
c = "ccc"
final = a + b + c
pdb.set_trace()
print (final)
The output is as follows −
--Return--
> <ipython-input-11-8019b029997d>(6)<module>()->None
-> pdb.set_trace()
(Pdb) p a
'aaa'
(Pdb) p b
'bbb'
(Pdb) p c
'ccc'
(Pdb) p final
'aaabbbccc'
(Pdb)
In this chapter, we will learn how benchmarking and profiling help in addressing performance issues.
Suppose we had written a code and it is giving the desired result too but what if we want to run this code a bit faster because the needs have changed. In this case, we need to find out what parts of our code are slowing down the entire program. In this case, benchmarking and profiling can be useful.
Benchmarking aims at evaluating something by comparison with a standard. However, the question that arises here is that what would be the benchmarking and why we need it in case of software programming. Benchmarking the code means how fast the code is executing and where the bottleneck is. One major reason for benchmarking is that it optimizes the code.
If we talk about the working of benchmarking, we need to start by benchmarking the whole program as one current state then we can combine micro benchmarks and then decompose a program into smaller programs. In order to find the bottlenecks within our program and optimize it. In other words, we can understand it as breaking the big and hard problem into series of smaller and a bit easier problems for optimizing them.
In Python, we have a by default module for benchmarking which is called timeit. With the help of the timeit module, we can measure the performance of small bit of Python code within our main program.
In the following Python script, we are importing the timeit module, which further measures the time taken to execute two functions – functionA and functionB −
import timeit
import time
def functionA():
print("Function A starts the execution:")
print("Function A completes the execution:")
def functionB():
print("Function B starts the execution")
print("Function B completes the execution")
start_time = timeit.default_timer()
functionA()
print(timeit.default_timer() - start_time)
start_time = timeit.default_timer()
functionB()
print(timeit.default_timer() - start_time)
After running the above script, we will get the execution time of both the functions as shown below.
Function A starts the execution:
Function A completes the execution:
0.0014599495514175942
Function B starts the execution
Function B completes the execution
0.0017024724827479076
In Python, we can create our own timer, which will act just like the timeit module. It can be done with the help of the decorator function. Following is an example of the custom timer −
import random
import time
def timer_func(func):
def function_timer(*args, **kwargs):
start = time.time()
value = func(*args, **kwargs)
end = time.time()
runtime = end - start
msg = "{func} took {time} seconds to complete its execution."
print(msg.format(func = func.__name__,time = runtime))
return value
return function_timer
@timer_func
def Myfunction():
for x in range(5):
sleep_time = random.choice(range(1,3))
time.sleep(sleep_time)
if __name__ == '__main__':
Myfunction()
The above python script helps in importing random time modules. We have created the timer_func() decorator function. This has the function_timer() function inside it. Now, the nested function will grab the time before calling the passed in function. Then it waits for the function to return and grabs the end time. In this way, we can finally make python script print the execution time. The script will generate the output as shown below.
Myfunction took 8.000457763671875 seconds to complete its execution.
Sometimes the programmer wants to measure some attributes like the use of memory, time complexity or usage of particular instructions about the programs to measure the real capability of that program. Such kind of measuring about program is called profiling. Profiling uses dynamic program analysis to do such measuring.
In the subsequent sections, we will learn about the different Python Modules for Profiling.
cProfile is a Python built-in module for profiling. The module is a C-extension with reasonable overhead that makes it suitable for profiling long-running programs. After running it, it logs all the functions and execution times. It is very powerful but sometimes a bit difficult to interpret and act on. In the following example, we are using cProfile on the code below −
def increment_global():
global x
x += 1
def taskofThread(lock):
for _ in range(50000):
lock.acquire()
increment_global()
lock.release()
def main():
global x
x = 0
lock = threading.Lock()
t1 = threading.Thread(target=taskofThread, args=(lock,))
t2 = threading.Thread(target= taskofThread, args=(lock,))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
The above code is saved in the thread_increment.py file. Now, execute the code with cProfile on the command line as follows −
(base) D:\ProgramData>python -m cProfile thread_increment.py
x = 100000 after Iteration 0
x = 100000 after Iteration 1
x = 100000 after Iteration 2
x = 100000 after Iteration 3
x = 100000 after Iteration 4
3577 function calls (3522 primitive calls) in 1.688 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:103(release)
5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:143(__init__)
5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:147(__enter__)
... ... ... ...
From the above output, it is clear that cProfile prints out all the 3577 functions called, with the time spent in each and the number of times they have been called. Followings are the columns we got in output −
ncalls − It is the number of calls made.
ncalls − It is the number of calls made.
tottime − It is the total time spent in the given function.
tottime − It is the total time spent in the given function.
percall − It refers to the quotient of tottime divided by ncalls.
percall − It refers to the quotient of tottime divided by ncalls.
cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions.
cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions.
percall − It is the quotient of cumtime divided by primitive calls.
percall − It is the quotient of cumtime divided by primitive calls.
filename:lineno(function) − It basically provides the respective data of each function.
filename:lineno(function) − It basically provides the respective data of each function.
Suppose we had to create a large number of threads for our multithreaded tasks. It would be computationally most expensive as there can be many performance issues, due to too many threads. A major issue could be in the throughput getting limited. We can solve this problem by creating a pool of threads. A thread pool may be defined as the group of pre-instantiated and idle threads, which stand ready to be given work. Creating thread pool is preferred over instantiating new threads for every task when we need to do large number of tasks. A thread pool can manage concurrent execution of large number of threads as follows −
If a thread in a thread pool completes its execution then that thread can be reused.
If a thread in a thread pool completes its execution then that thread can be reused.
If a thread is terminated, another thread will be created to replace that thread.
If a thread is terminated, another thread will be created to replace that thread.
Python standard library includes the concurrent.futures module. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes.
In our subsequent sections, we will learn about the different classes of the concurrent.futures module.
Executoris an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses −
ThreadPoolExecutor
ProcessPoolExecutor
It is one of the concrete subclasses of the Executor class. The subclass uses multi-threading and we get a pool of thread for submitting the tasks. This pool assigns tasks to the available threads and schedules them to run.
With the help of concurrent.futures module and its concrete subclass Executor, we can easily create a pool of threads. For this, we need to construct a ThreadPoolExecutor with the number of threads we want in the pool. By default, the number is 5. Then we can submit a task to the thread pool. When we submit() a task, we get back a Future. The Future object has a method called done(), which tells if the future has resolved. With this, a value has been set for that particular future object. When a task finishes, the thread pool executor sets the value to the future object.
from concurrent.futures import ThreadPoolExecutor
from time import sleep
def task(message):
sleep(2)
return message
def main():
executor = ThreadPoolExecutor(5)
future = executor.submit(task, ("Completed"))
print(future.done())
sleep(2)
print(future.done())
print(future.result())
if __name__ == '__main__':
main()
False
True
Completed
In the above example, a ThreadPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the thread pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it.
Another way to instantiate ThreadPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code −
with ThreadPoolExecutor(max_workers = 5) as executor
The following example is borrowed from the Python docs. In this example, first of all the concurrent.futures module has to be imported. Then a function named load_url() is created which will load the requested url. The function then creates ThreadPoolExecutor
with the 5 threads in the pool. The ThreadPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it.
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout = timeout) as conn:
return conn.read()
with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor:
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
Following would be the output of the above Python script −
'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>
'http://www.foxnews.com/' page is 229313 bytes
'http://www.cnn.com/' page is 168933 bytes
'http://www.bbc.co.uk/' page is 283893 bytes
'http://europe.wsj.com/' page is 938109 bytes
The Python map() function is widely used in a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to out ThreadPoolExecutor. Consider the following example of Python script to understand how the function works.
In this example below, the map function is used to apply the square() function to every value in the values array.
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
values = [2,3,4,5]
def square(n):
return n * n
def main():
with ThreadPoolExecutor(max_workers = 3) as executor:
results = executor.map(square, values)
for result in results:
print(result)
if __name__ == '__main__':
main()
The above Python script generates the following output −
4
9
16
25
Pool of process can be created and used in the same way as we have created and used the pool of threads. Process pool can be defined as the group of pre-instantiated and idle processes, which stand ready to be given work. Creating process pool is preferred over instantiating new processes for every task when we need to do a large number of tasks.
Python standard library has a module called the concurrent.futures. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes.
In our subsequent sections, we will look at the different subclasses of the concurrent.futures module.
Executor is an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses −
ThreadPoolExecutor
ProcessPoolExecutor
It is one of the concrete subclasses of the Executor class. It uses multi-processing and we get a pool of processes for submitting the tasks. This pool assigns tasks to the available processes and schedule them to run.
With the help of the concurrent.futures module and its concrete subclass Executor, we can easily create a pool of process. For this, we need to construct a ProcessPoolExecutor with the number of processes we want in the pool. By default, the number is 5. This is followed by submitting a task to the process pool.
We will now consider the same example that we used while creating thread pool, the only difference being that now we will use ProcessPoolExecutor instead of ThreadPoolExecutor .
from concurrent.futures import ProcessPoolExecutor
from time import sleep
def task(message):
sleep(2)
return message
def main():
executor = ProcessPoolExecutor(5)
future = executor.submit(task, ("Completed"))
print(future.done())
sleep(2)
print(future.done())
print(future.result())
if __name__ == '__main__':
main()
False
False
Completed
In the above example, a ProcessPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the process pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it.
Another way to instantiate ProcessPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code −
with ProcessPoolExecutor(max_workers = 5) as executor
For better understanding, we are taking the same example as used while creating thread pool. In this example, we need to start by importing the concurrent.futures module. Then a function named load_url() is created which will load the requested url. The ProcessPoolExecutor is then created with the 5 number of threads in the pool. The ProcessPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it.
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout = timeout) as conn:
return conn.read()
def main():
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
if __name__ == '__main__':
main()
The above Python script will generate the following output −
'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>
'http://www.foxnews.com/' page is 229476 bytes
'http://www.cnn.com/' page is 165323 bytes
'http://www.bbc.co.uk/' page is 284981 bytes
'http://europe.wsj.com/' page is 967575 bytes
The Python map() function is widely used to perform a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to the ProcessPoolExecutor. Consider the following example of Python script to understand this.
We will consider the same example that we used while creating thread pool using the Executor.map() function. In the example givenbelow, the map function is used to apply square() function to every value in the values array.
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import as_completed
values = [2,3,4,5]
def square(n):
return n * n
def main():
with ProcessPoolExecutor(max_workers = 3) as executor:
results = executor.map(square, values)
for result in results:
print(result)
if __name__ == '__main__':
main()
The above Python script will generate the following output
4
9
16
25
Now that we have studied about both the Executor classes – ThreadPoolExecutor and ProcessPoolExecutor, we need to know when to use which executor. We need to choose ProcessPoolExecutor in case of CPU-bound workloads and ThreadPoolExecutor in case of I/O-bound workloads.
If we use ProcessPoolExecutor, then we do not need to worry about GIL because it uses multiprocessing. Moreover, the execution time will be less when compared to ThreadPoolExecution. Consider the following Python script example to understand this.
import time
import concurrent.futures
value = [8000000, 7000000]
def counting(n):
start = time.time()
while n > 0:
n -= 1
return time.time() - start
def main():
start = time.time()
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, time_taken in zip(value, executor.map(counting, value)):
print('Start: {} Time taken: {}'.format(number, time_taken))
print('Total time taken: {}'.format(time.time() - start))
if __name__ == '__main__':
main()
Start: 8000000 Time taken: 1.5509998798370361
Start: 7000000 Time taken: 1.3259999752044678
Total time taken: 2.0840001106262207
Example- Python script with ThreadPoolExecutor:
import time
import concurrent.futures
value = [8000000, 7000000]
def counting(n):
start = time.time()
while n > 0:
n -= 1
return time.time() - start
def main():
start = time.time()
with concurrent.futures.ThreadPoolExecutor() as executor:
for number, time_taken in zip(value, executor.map(counting, value)):
print('Start: {} Time taken: {}'.format(number, time_taken))
print('Total time taken: {}'.format(time.time() - start))
if __name__ == '__main__':
main()
Start: 8000000 Time taken: 3.8420000076293945
Start: 7000000 Time taken: 3.6010000705718994
Total time taken: 3.8480000495910645
From the outputs of both the programs above, we can see the difference of execution time while using ProcessPoolExecutor and ThreadPoolExecutor.
In this chapter, we will focus more on the comparison between multiprocessing and multithreading.
It is the use of two or more CPUs units within a single computer system. It is the best approach to get the full potential from our hardware by utilizing full number of CPU cores available in our computer system.
It is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads.
The following table shows some of the important differences between them −
While working with concurrent applications, there is a limitation present in Python called the GIL (Global Interpreter Lock). GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. GIL is the mutex – mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first.
With the use of multiprocessing, we can effectively bypass the limitation caused by GIL −
By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL.
By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL.
Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time.
Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time.
The following three methods can be used to start a process in Python within the multiprocessing module −
Fork
Spawn
Forkserver
Fork command is a standard command found in UNIX. It is used to create new processes called child processes. This child process runs concurrently with the process called the parent process. These child processes are also identical to their parent processes and inherit all of the resources available to the parent. The following system calls are used while creating a process with Fork −
fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>
fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>
getpid() − This system call returns the process ID(PID) of the calling process.
getpid() − This system call returns the process ID(PID) of the calling process.
The following Python script example will help you understabd how to create a new child process and get the PIDs of child and parent processes −
import os
def child():
n = os.fork()
if n > 0:
print("PID of Parent process is : ", os.getpid())
else:
print("PID of Child process is : ", os.getpid())
child()
PID of Parent process is : 25989
PID of Child process is : 25990
Spawn means to start something new. Hence, spawning a process means the creation of a new process by a parent process. The parent process continues its execution asynchronously or waits until the child process ends its execution. Follow these steps for spawning a process −
Importing multiprocessing module.
Importing multiprocessing module.
Creating the object process.
Creating the object process.
Starting the process activity by calling start() method.
Starting the process activity by calling start() method.
Waiting until the process has finished its work and exit by calling join() method.
Waiting until the process has finished its work and exit by calling join() method.
The following example of Python script helps in spawning three processes
import multiprocessing
def spawn_process(i):
print ('This is process: %s' %i)
return
if __name__ == '__main__':
Process_jobs = []
for i in range(3):
p = multiprocessing.Process(target = spawn_process, args = (i,))
Process_jobs.append(p)
p.start()
p.join()
This is process: 0
This is process: 1
This is process: 2
Forkserver mechanism is only available on those selected UNIX platforms that support passing the file descriptors over Unix Pipes. Consider the following points to understand the working of Forkserver mechanism −
A server is instantiated on using Forkserver mechanism for starting new process.
A server is instantiated on using Forkserver mechanism for starting new process.
The server then receives the command and handles all the requests for creating new processes.
The server then receives the command and handles all the requests for creating new processes.
For creating a new process, our python program will send a request to Forkserver and it will create a process for us.
For creating a new process, our python program will send a request to Forkserver and it will create a process for us.
At last, we can use this new created process in our programs.
At last, we can use this new created process in our programs.
Python multiprocessing module allows us to have daemon processes through its daemonic option. Daemon processes or the processes that are running in the background follow similar concept as the daemon threads. To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.
Here, we are using the same example as used in the daemon threads. The only difference is the change of module from multithreading to multiprocessing and setting the daemonic flag to true. However, there would be a change in output as shown below −
import multiprocessing
import time
def nondaemonProcess():
print("starting my Process")
time.sleep(8)
print("ending my Process")
def daemonProcess():
while True:
print("Hello")
time.sleep(2)
if __name__ == '__main__':
nondaemonProcess = multiprocessing.Process(target = nondaemonProcess)
daemonProcess = multiprocessing.Process(target = daemonProcess)
daemonProcess.daemon = True
nondaemonProcess.daemon = False
daemonProcess.start()
nondaemonProcess.start()
starting my Process
ending my Process
The output is different when compared to the one generated by daemon threads, because the process in no daemon mode have an output. Hence, the daemonic process ends automatically after the main programs end to avoid the persistence of running processes.
We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution.
import multiprocessing
import time
def Child_process():
print ('Starting function')
time.sleep(5)
print ('Finished function')
P = multiprocessing.Process(target = Child_process)
P.start()
print("My Process has terminated, terminating main thread")
print("Terminating Child Process")
P.terminate()
print("Child Process successfully terminated")
My Process has terminated, terminating main thread
Terminating Child Process
Child Process successfully terminated
The output shows that the program terminates before the execution of child process that has been created with the help of the Child_process() function. This implies that the child process has been terminated successfully.
Every process in the operating system is having process identity known as PID. In Python, we can find out the PID of current process with the help of the following command −
import multiprocessing
print(multiprocessing.current_process().pid)
The following example of Python script helps find out the PID of main process as well as PID of child process −
import multiprocessing
import time
def Child_process():
print("PID of Child Process is: {}".format(multiprocessing.current_process().pid))
print("PID of Main process is: {}".format(multiprocessing.current_process().pid))
P = multiprocessing.Process(target=Child_process)
P.start()
P.join()
PID of Main process is: 9401
PID of Child Process is: 9402
We can create threads by sub-classing the threading.Thread class. In addition, we can also create processes by sub-classing the multiprocessing.Process class. For using a process in subclass, we need to consider the following points −
We need to define a new subclass of the Process class.
We need to define a new subclass of the Process class.
We need to override the _init_(self [,args] ) class.
We need to override the _init_(self [,args] ) class.
We need to override the of the run(self [,args] ) method to implement what Process
We need to override the of the run(self [,args] ) method to implement what Process
We need to start the process by invoking thestart() method.
We need to start the process by invoking thestart() method.
import multiprocessing
class MyProcess(multiprocessing.Process):
def run(self):
print ('called run method in process: %s' %self.name)
return
if __name__ == '__main__':
jobs = []
for i in range(5):
P = MyProcess()
jobs.append(P)
P.start()
P.join()
called run method in process: MyProcess-1
called run method in process: MyProcess-2
called run method in process: MyProcess-3
called run method in process: MyProcess-4
called run method in process: MyProcess-5
If we talk about simple parallel processing tasks in our Python applications, then multiprocessing module provide us the Pool class. The following methods of Pool class can be used to spin up number of child processes within our main program
This method is similar to the.submit()method of .ThreadPoolExecutor.It blocks until the result is ready.
When we need parallel execution of our tasks then we need to use theapply_async()method to submit tasks to the pool. It is an asynchronous operation that will not lock the main thread until all the child processes are executed.
Just like the apply() method, it also blocks until the result is ready. It is equivalent to the built-in map() function that splits the iterable data in a number of chunks and submits to the process pool as separate tasks.
It is a variant of the map() method as apply_async() is to the apply() method. It returns a result object. When the result becomes ready, a callable is applied to it. The callable must be completed immediately; otherwise, the thread that handles the results will get blocked.
The following example will help you implement a process pool for performing parallel execution. A simple calculation of square of number has been performed by applying the square() function through the multiprocessing.Pool method. Then pool.map() has been used to submit the 5, because input is a list of integers from 0 to 4. The result would be stored in p_outputs and it is printed.
def square(n):
result = n*n
return result
if __name__ == '__main__':
inputs = list(range(5))
p = multiprocessing.Pool(processes = 4)
p_outputs = pool.map(function_square, inputs)
p.close()
p.join()
print ('Pool :', p_outputs)
Pool : [0, 1, 4, 9, 16]
Process intercommunication means the exchange of data between processes. It is necessary to exchange the data between processes for the development of parallel application. Following diagram shows the various communication mechanisms for synchronization between multiple sub processes −
In this section, we will learn about the various communication mechanisms. The mechanisms are described below −
Queues can be used with multi-process programs. The Queue class of multiprocessing module is similar to the Queue.Queue class. Hence, the same API can be used. Multiprocessing.Queue provides us a thread and process safe FIFO (first-in first-out) mechanism of communication between processes.
Following is a simple example taken from python official docs on multiprocessing to understand the concept of Queue class of multiprocessing.
from multiprocessing import Process, Queue
import queue
import random
def f(q):
q.put([42, None, 'hello'])
def main():
q = Queue()
p = Process(target = f, args = (q,))
p.start()
print (q.get())
if __name__ == '__main__':
main()
[42, None, 'hello']
It is a data structure, which is used to communicate between processes in multi-process programs. The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex(two way). It works in the following manner −
It returns a pair of connection objects that represent the two ends of pipe.
It returns a pair of connection objects that represent the two ends of pipe.
Every object has two methods – send() and recv(), to communicate between processes.
Every object has two methods – send() and recv(), to communicate between processes.
Following is a simple example taken from python official docs on multiprocessing to understand the concept of Pipe() function of multiprocessing.
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target = f, args = (child_conn,))
p.start()
print (parent_conn.recv())
p.join()
[42, None, 'hello']
Manager is a class of multiprocessing module that provides a way to coordinate shared information between all its users. A manager object controls a server process, which manages shared objects and allows other processes to manipulate them. In other words, managers provide a way to create data that can be shared between different processes. Following are the different properties of manager object −
The main property of manager is to control a server process, which manages the shared objects.
The main property of manager is to control a server process, which manages the shared objects.
Another important property is to update all the shared objects when any process modifies it.
Another important property is to update all the shared objects when any process modifies it.
Following is an example which uses the manager object for creating a list record in server process and then adding a new record in that list.
import multiprocessing
def print_records(records):
for record in records:
print("Name: {0}\nScore: {1}\n".format(record[0], record[1]))
def insert_record(record, records):
records.append(record)
print("A New record is added\n")
if __name__ == '__main__':
with multiprocessing.Manager() as manager:
records = manager.list([('Computers', 1), ('Histoty', 5), ('Hindi',9)])
new_record = ('English', 3)
p1 = multiprocessing.Process(target = insert_record, args = (new_record, records))
p2 = multiprocessing.Process(target = print_records, args = (records,))
p1.start()
p1.join()
p2.start()
p2.join()
A New record is added
Name: Computers
Score: 1
Name: Histoty
Score: 5
Name: Hindi
Score: 9
Name: English
Score: 3
Manager Class comes with the concept of namespaces, which is a quick way method for sharing several attributes across multiple processes. Namespaces do not feature any public method, which can be called, but they have writable attributes.
The following Python script example helps us utilize namespaces for sharing data across main process and child process −
import multiprocessing
def Mng_NaSp(using_ns):
using_ns.x +=5
using_ns.y *= 10
if __name__ == '__main__':
manager = multiprocessing.Manager()
using_ns = manager.Namespace()
using_ns.x = 1
using_ns.y = 1
print ('before', using_ns)
p = multiprocessing.Process(target = Mng_NaSp, args = (using_ns,))
p.start()
p.join()
print ('after', using_ns)
before Namespace(x = 1, y = 1)
after Namespace(x = 6, y = 10)
Multiprocessing module provides Array and Value objects for storing the data in a shared memory map. Array is a ctypes array allocated from shared memory and Value is a ctypes object allocated from shared memory.
To being with, import Process, Value, Array from multiprocessing.
Following Python script is an example taken from python docs to utilize Ctypes Array and Value for sharing some data between processes.
def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i]
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
p = Process(target = f, args = (num, arr))
p.start()
p.join()
print (num.value)
print (arr[:])
3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
CSP is used to illustrate the interaction of systems with other systems featuring concurrent models. CSP is a framework for writing concurrent or program via message passing and hence it is effective for describing concurrency.
For implementing core primitives found in CSP, Python has a library called PyCSP. It keeps the implementation very short and readable so that it can be understood very easily. Following is the basic process network of PyCSP −
In the above PyCSP process network, there are two processes – Process1 and Process 2. These processes communicate by passing messages through two channels – channel 1 and channel 2.
With the help of following command, we can install Python library PyCSP −
pip install PyCSP
Following Python script is a simple example for running two processes in parallel to each other. It is done with the help of the PyCSP python libabary −
from pycsp.parallel import *
import time
@process
def P1():
time.sleep(1)
print('P1 exiting')
@process
def P2():
time.sleep(1)
print('P2 exiting')
def main():
Parallel(P1(), P2())
print('Terminating')
if __name__ == '__main__':
main()
In the above script, two functions namely P1 and P2 have been created and then decorated with @process for converting them into processes.
P2 exiting
P1 exiting
Terminating
Event-driven programming focuses on events. Eventually, the flow of program depends upon events. Until now, we were dealing with either sequential or parallel execution model but the model having the concept of event-driven programming is called asynchronous model. Event-driven programming depends upon an event loop that is always listening for the new incoming events. The working of event-driven programming is dependent upon events. Once an event loops, then events decide what to execute and in what order. Following flowchart will help you understand how this works −
Asyncio module was added in Python 3.4 and it provides infrastructure for writing single-threaded concurrent code using co-routines. Following are the different concepts used by the Asyncio module −
Event-loop is a functionality to handle all the events in a computational code. It acts round the way during the execution of whole program and keeps track of the incoming and execution of events. The Asyncio module allows a single event loop per process. Followings are some methods provided by Asyncio module to manage an event loop −
loop = get_event_loop() − This method will provide the event loop for the current context.
loop = get_event_loop() − This method will provide the event loop for the current context.
loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds.
loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds.
loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop.
loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop.
loop.time() − This method is used to return the current time according to the event loop’s internal clock.
loop.time() − This method is used to return the current time according to the event loop’s internal clock.
asyncio.set_event_loop() − This method will set the event loop for the current context to the loop.
asyncio.set_event_loop() − This method will set the event loop for the current context to the loop.
asyncio.new_event_loop() − This method will create and return a new event loop object.
asyncio.new_event_loop() − This method will create and return a new event loop object.
loop.run_forever() − This method will run until stop() method is called.
loop.run_forever() − This method will run until stop() method is called.
The following example of event loop helps in printing hello world by using the get_event_loop() method. This example is taken from the Python official docs.
import asyncio
def hello_world(loop):
print('Hello World')
loop.stop()
loop = asyncio.get_event_loop()
loop.call_soon(hello_world, loop)
loop.run_forever()
loop.close()
Hello World
This is compatible with the concurrent.futures.Future class that represents a computation that has not been accomplished. There are following differences between asyncio.futures.Future and concurrent.futures.Future −
result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet.
result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet.
Callbacks registered with add_done_callback() are always called via the event loop’s call_soon().
Callbacks registered with add_done_callback() are always called via the event loop’s call_soon().
asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package.
asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package.
The following is an example that will help you understand how to use asyncio.futures.future class.
import asyncio
async def Myoperation(future):
await asyncio.sleep(2)
future.set_result('Future Completed')
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(Myoperation(future))
try:
loop.run_until_complete(future)
print(future.result())
finally:
loop.close()
Future Completed
The concept of coroutines in Asyncio is similar to the concept of standard Thread object under threading module. This is the generalization of the subroutine concept. A coroutine can be suspended during the execution so that it waits for the external processing and returns from the point at which it had stopped when the external processing was done. The following two ways help us in implementing coroutines −
This is a method for implementation of coroutines under Asyncio module. Following is a Python script for the same −
import asyncio
async def Myoperation():
print("First Coroutine")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(Myoperation())
finally:
loop.close()
First Coroutine
Another method for implementation of coroutines is to utilize generators with the @asyncio.coroutine decorator. Following is a Python script for the same −
import asyncio
@asyncio.coroutine
def Myoperation():
print("First Coroutine")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(Myoperation())
finally:
loop.close()
First Coroutine
This subclass of Asyncio module is responsible for execution of coroutines within an event loop in parallel manner. Following Python script is an example of processing some tasks in parallel.
import asyncio
import time
async def Task_ex(n):
time.sleep(1)
print("Processing {}".format(n))
async def Generator_task():
for i in range(10):
asyncio.ensure_future(Task_ex(i))
int("Tasks Completed")
asyncio.sleep(2)
loop = asyncio.get_event_loop()
loop.run_until_complete(Generator_task())
loop.close()
Tasks Completed
Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9
Asyncio module provides transport classes for implementing various types of communication. These classes are not thread safe and always paired with a protocol instance after establishment of communication channel.
Following are distinct types of transports inherited from the BaseTransport −
ReadTransport − This is an interface for read-only transports.
ReadTransport − This is an interface for read-only transports.
WriteTransport − This is an interface for write-only transports.
WriteTransport − This is an interface for write-only transports.
DatagramTransport − This is an interface for sending the data.
DatagramTransport − This is an interface for sending the data.
BaseSubprocessTransport − Similar to BaseTransport class.
BaseSubprocessTransport − Similar to BaseTransport class.
Followings are five distinct methods of BaseTransport class that are subsequently transient across the four transport types −
close() − It closes the transport.
close() − It closes the transport.
is_closing() − This method will return true if the transport is closing or is already closed.transports.
is_closing() − This method will return true if the transport is closing or is already closed.transports.
get_extra_info(name, default = none) − This will give us some extra information about transport.
get_extra_info(name, default = none) − This will give us some extra information about transport.
get_protocol() − This method will return the current protocol.
get_protocol() − This method will return the current protocol.
Asyncio module provides base classes that you can subclass to implement your network protocols. Those classes are used in conjunction with transports; the protocol parses incoming data and asks for the writing of outgoing data, while the transport is responsible for the actual I/O and buffering. Following are three classes of Protocol −
Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports.
Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports.
DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports..
DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports..
SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes.
SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes.
Reactive programming is a programming paradigm that deals with data flows and the propagation of change. It means that when a data flow is emitted by one component, the change will be propagated to other components by reactive programming library. The propagation of change will continue until it reaches the final receiver. The difference between event-driven and reactive programming is that event-driven programming revolves around events and reactive programming revolves around data.
ReactiveX or Raective Extension is the most famous implementation of reactive programming. The working of ReactiveX depends upon the following two classes −
This class is the source of data stream or events and it packs the incoming data so that the data can be passed from one thread to another. It will not give data until some observer subscribe to it.
This class consumes the data stream emitted by observable. There can be multiple observers with observable and each observer will receive each data item that is emitted. The observer can receive three type of events by subscribing to observable −
on_next() event − It implies there is an element in the data stream.
on_next() event − It implies there is an element in the data stream.
on_completed() event − It implies end of emission and no more items are coming.
on_completed() event − It implies end of emission and no more items are coming.
on_error() event − It also implies end of emission but in case when an error is thrown by observable.
on_error() event − It also implies end of emission but in case when an error is thrown by observable.
RxPY is a Python module which can be used for reactive programming. We need to ensure that the module is installed. The following command can be used to install the RxPY module −
pip install RxPY
Following is a Python script, which uses RxPY module and its classes Observable and Observe for reactive programming. There are basically two classes −
get_strings() − for getting the strings from observer.
get_strings() − for getting the strings from observer.
PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class.
PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class.
from rx import Observable, Observer
def get_strings(observer):
observer.on_next("Ram")
observer.on_next("Mohan")
observer.on_next("Shyam")
observer.on_completed()
class PrintObserver(Observer):
def on_next(self, value):
print("Received {0}".format(value))
def on_completed(self):
print("Finished")
def on_error(self, error):
print("Error: {0}".format(error))
source = Observable.create(get_strings)
source.subscribe(PrintObserver())
Received Ram
Received Mohan
Received Shyam
Finished
PyFunctionalis another Python library that can be used for reactive programming. It enables us to create functional programs using the Python programming language. It is useful because it allows us to create data pipelines by using chained functional operators.
Both the libraries are used for reactive programming and handle the stream in similar fashion but the main difference between both of them depends upon the handling of data. RxPY handles data and events in the system while PyFunctional is focused on transformation of data using functional programming paradigms.
We need to install this module before using it. It can be installed with the help of pip command as follows −
pip install pyfunctional
Following example uses the PyFunctional module and its seq class which act as the stream object with which we can iterate and manipulate. In this program, it maps the sequence by using the lamda function that doubles every value, then filters the value where x is greater than 4 and finally it reduces the sequence into a sum of all the remaining values.
from functional import seq
result = seq(1,2,3).map(lambda x: x*2).filter(lambda x: x > 4).reduce(lambda x, y: x + y)
print ("Result: {}".format(result))
Result: 6
57 Lectures
8 hours
Denis Tishkov
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2048,
"s": 1922,
"text": "In this chapter, we will understand the concept of concurrency in Python and learn about the different threads and processes."
},
{
"code": null,
"e": 2231,
"s": 2048,
"text": "In simple words, concurrency is the occurrence of two or more events at the same time. Concurrency is a natural phenomenon because many events occur simultaneously at any given time."
},
{
"code": null,
"e": 2517,
"s": 2231,
"text": "In terms of programming, concurrency is when two tasks overlap in execution. With concurrent programming, the performance of our applications and software systems can be improved because we can concurrently deal with the requests rather than waiting for a previous one to be completed."
},
{
"code": null,
"e": 2592,
"s": 2517,
"text": "Following points will give us the brief historical review of concurrency −"
},
{
"code": null,
"e": 2813,
"s": 2592,
"text": "Concurrency is closely related with the concept of railroads. With the railroads, there was a need to handle multiple trains on the same railroad system in such a way that every train would get to its destination safely."
},
{
"code": null,
"e": 3039,
"s": 2813,
"text": "The interest in computer science concurrency began with the research paper published by Edsger W. Dijkstra in 1965. In this paper, he identified and solved the problem of mutual exclusion, the property of concurrency control."
},
{
"code": null,
"e": 3176,
"s": 3039,
"text": "In recent times, programmers are getting improved concurrent solutions because of the introduction of high-level concurrency primitives."
},
{
"code": null,
"e": 3329,
"s": 3176,
"text": "Programming languages such as Google’s Golang, Rust and Python have made incredible developments in areas which help us get better concurrent solutions."
},
{
"code": null,
"e": 3646,
"s": 3329,
"text": "Thread is the smallest unit of execution that can be performed in an operating system. It is not itself a program but runs within a program. In other words, threads are not independent of one other. Each thread shares code section, data section, etc. with other threads. They are also known as lightweight processes."
},
{
"code": null,
"e": 3694,
"s": 3646,
"text": "A thread consists of the following components −"
},
{
"code": null,
"e": 3774,
"s": 3694,
"text": "Program counter which consist of the address of the next executable instruction"
},
{
"code": null,
"e": 3854,
"s": 3774,
"text": "Program counter which consist of the address of the next executable instruction"
},
{
"code": null,
"e": 3860,
"s": 3854,
"text": "Stack"
},
{
"code": null,
"e": 3866,
"s": 3860,
"text": "Stack"
},
{
"code": null,
"e": 3883,
"s": 3866,
"text": "Set of registers"
},
{
"code": null,
"e": 3900,
"s": 3883,
"text": "Set of registers"
},
{
"code": null,
"e": 3912,
"s": 3900,
"text": "A unique id"
},
{
"code": null,
"e": 3924,
"s": 3912,
"text": "A unique id"
},
{
"code": null,
"e": 4256,
"s": 3924,
"text": "Multithreading, on the other hand, is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads. The concept of multithreading can be understood with the help of the following example."
},
{
"code": null,
"e": 4564,
"s": 4256,
"text": "Suppose we are running a particular process wherein we open MS Word to type content into it. One thread will be assigned to open MS Word and another thread will be required to type content in it. And now, if we want to edit the existing then another thread will be required to do the editing task and so on."
},
{
"code": null,
"e": 4968,
"s": 4564,
"text": "Aprocessis defined as an entity, which represents the basic unit of work to be implemented in the system. To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process that performs all the tasks mentioned in the program. During the process life cycle, it passes through different stages – Start, Ready, Running, Waiting and Terminating."
},
{
"code": null,
"e": 5028,
"s": 4968,
"text": "Following diagram shows the different stages of a process −"
},
{
"code": null,
"e": 5217,
"s": 5028,
"text": "A process can have only one thread, called primary thread, or multiple threads having their own set of registers, program counter and stack. Following diagram will show us the difference −"
},
{
"code": null,
"e": 5530,
"s": 5217,
"text": "Multiprocessing, on the other hand, is the use of two or more CPUs units within a single computer system. Our primary goal is to get the full potential from our hardware. To achieve this, we need to utilize full number of CPU cores available in our computer system. Multiprocessing is the best approach to do so."
},
{
"code": null,
"e": 5667,
"s": 5530,
"text": "Python is one of the most popular programming languages. Followings are some reasons that make it suitable for concurrent applications −"
},
{
"code": null,
"e": 6102,
"s": 5667,
"text": "Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style based on preference. Python comes with Magic methods, which can be defined to act on objects. These Magic methods are used as syntactic sugar and bound to more easy-to-understand keywords."
},
{
"code": null,
"e": 6287,
"s": 6102,
"text": "Python language has witnessed a massive adoption rate amongst data scientists and mathematicians, working in the field of AI, machine learning, deep learning and quantitative analysis."
},
{
"code": null,
"e": 6485,
"s": 6287,
"text": "Python 2 and 3 have large number of APIs dedicated for parallel/concurrent programming. Most popular of them are threading, concurrent.features, multiprocessing, asyncio, gevent and greenlets, etc."
},
{
"code": null,
"e": 6793,
"s": 6485,
"text": "Python comes with a limitation for concurrent applications. This limitation is called GIL (Global Interpreter Lock) is present within Python. GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. We can understand the concept of GIL as follows −"
},
{
"code": null,
"e": 7240,
"s": 6793,
"text": "It is one of the most controversial topics in the Python world. In CPython, GIL is the mutex - the mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first. The diagram shown below will help you understand the working of GIL."
},
{
"code": null,
"e": 7399,
"s": 7240,
"text": "However, there are some libraries and implementations in Python such as Numpy, Jpython and IronPytbhon. These libraries work without any interaction with GIL."
},
{
"code": null,
"e": 7834,
"s": 7399,
"text": "Both concurrency and parallelism are used in relation to multithreaded programs but there is a lot of confusion about the similarity and difference between them. The big question in this regard: is concurrency parallelism or not? Although both the terms appear quite similar but the answer to the above question is NO, concurrency and parallelism are not same. Now, if they are not same then what is the basic difference between them?"
},
{
"code": null,
"e": 8056,
"s": 7834,
"text": "In simple terms, concurrency deals with managing the access to shared state from different threads and on the other side, parallelism deals with utilizing multiple CPUs or its cores to improve the performance of hardware."
},
{
"code": null,
"e": 8313,
"s": 8056,
"text": "Concurrency is when two tasks overlap in execution. It could be a situation where an application is progressing on more than one task at the same time. We can understand it diagrammatically; multiple tasks are making progress at the same time, as follows −"
},
{
"code": null,
"e": 8414,
"s": 8313,
"text": "In this section, we will discuss the three important levels of concurrency in terms of programming −"
},
{
"code": null,
"e": 8658,
"s": 8414,
"text": "In this level of concurrency, there is explicit use of atomic operations. We cannot use such kind of concurrency for application building, as it is very error-prone and difficult to debug. Even Python does not support such kind of concurrency."
},
{
"code": null,
"e": 8880,
"s": 8658,
"text": "In this concurrency, there is no use of explicit atomic operations. It uses the explicit locks. Python and other programming languages support such kind of concurrency. Mostly application programmers use this concurrency."
},
{
"code": null,
"e": 9039,
"s": 8880,
"text": "In this concurrency, neither explicit atomic operations nor explicit locks are used. Python has concurrent.futures module to support such kind of concurrency."
},
{
"code": null,
"e": 9195,
"s": 9039,
"text": "For a program or concurrent system to be correct, some properties must be satisfied by it. Properties related to the termination of system are as follows −"
},
{
"code": null,
"e": 9406,
"s": 9195,
"text": "The correctness property means that the program or the system must provide the desired correct answer. To keep it simple, we can say that the system must map the starting program state to final state correctly."
},
{
"code": null,
"e": 9534,
"s": 9406,
"text": "The safety property means that the program or the system must remain in a “good” or “safe” state and never does anything “bad”."
},
{
"code": null,
"e": 9644,
"s": 9534,
"text": "This property means that a program or system must “make progress” and it would reach at some desirable state."
},
{
"code": null,
"e": 9883,
"s": 9644,
"text": "This is one common property of concurrent system in which there can be multiple processes and threads, which run at the same time to make progress on their own tasks. These processes and threads are called actors of the concurrent system."
},
{
"code": null,
"e": 9989,
"s": 9883,
"text": "The actors must utilize the resources such as memory, disk, printer etc. in order to perform their tasks."
},
{
"code": null,
"e": 10205,
"s": 9989,
"text": "Every concurrent system must possess a set of rules to define the kind of tasks to be performed by the actors and the timing for each. The tasks could be acquiring of locks, memory sharing, modifying the state, etc."
},
{
"code": null,
"e": 10873,
"s": 10205,
"text": "An important issue while implementing the concurrent systems is the sharing of data among multiple threads or processes. Actually, the programmer must ensure that locks protect the shared data so that all the accesses to it are serialized and only one thread or process can access the shared data at a time. In case, when multiple threads or processes are all trying to access the same shared data then not all but at least one of them would be blocked and would remain idle. In other words, we can say that we would be able to use only one process or thread at a time when lock is in force. There can be some simple solutions to remove the above-mentioned barriers −"
},
{
"code": null,
"e": 11046,
"s": 10873,
"text": "The simplest solution is not to share any mutable data. In this case, we need not to use explicit locking and the barrier of concurrency due to mutual data would be solved."
},
{
"code": null,
"e": 11407,
"s": 11046,
"text": "Many times the concurrent processes need to access the same data at the same time. Another solution, than using of explicit locks, is to use a data structure that supports concurrent access. For example, we can use the queue module, which provides thread-safe queues. We can also use multiprocessing.JoinableQueue classes for multiprocessing-based concurrency."
},
{
"code": null,
"e": 11551,
"s": 11407,
"text": "Sometimes, the data structure that we are using, say concurrency queue, is not suitable then we can pass the immutable data without locking it."
},
{
"code": null,
"e": 11720,
"s": 11551,
"text": "In continuation of the above solution, suppose if it is required to pass only mutable data, rather than immutable data, then we can pass mutable data that is read only."
},
{
"code": null,
"e": 12287,
"s": 11720,
"text": "Another important issue in implementing concurrent systems is the use of I/O resources by threads or processes. The problem arises when one thread or process is using the I/O for such a long time and other is sitting idle. We can see such kind of barrier while working with an I/O heavy application. It can be understood with the help of an example, the requesting of pages from web browser. It is a heavy application. Here, if the rate at which the data is requested is slower than the rate at which it is consumed then we have I/O barrier in our concurrent system."
},
{
"code": null,
"e": 12410,
"s": 12287,
"text": "The following Python script is for requesting a web page and getting the time our network took to get the requested page −"
},
{
"code": null,
"e": 12618,
"s": 12410,
"text": "import urllib.request\nimport time\nts = time.time()\nreq = urllib.request.urlopen('http://www.tutorialspoint.com')\npageHtml = req.read()\nte = time.time()\nprint(\"Page Fetching Time : {} Seconds\".format (te-ts))"
},
{
"code": null,
"e": 12702,
"s": 12618,
"text": "After executing the above script, we can get the page fetching time as shown below."
},
{
"code": null,
"e": 12750,
"s": 12702,
"text": "Page Fetching Time: 1.0991398811340332 Seconds\n"
},
{
"code": null,
"e": 12938,
"s": 12750,
"text": "We can see that the time to fetch the page is more than one second. Now what if we want to fetch thousands of different web pages, you can understand how much time our network would take."
},
{
"code": null,
"e": 13296,
"s": 12938,
"text": "Parallelism may be defined as the art of splitting the tasks into subtasks that can be processed simultaneously. It is opposite to the concurrency, as discussed above, in which two or more events are happening at the same time. We can understand it diagrammatically; a task is broken into a number of subtasks that can be processed in parallel, as follows −"
},
{
"code": null,
"e": 13404,
"s": 13296,
"text": "To get more idea about the distinction between concurrency and parallelism, consider the following points −"
},
{
"code": null,
"e": 13563,
"s": 13404,
"text": "An application can be concurrent but not parallel means that it processes more than one task at the same time but the tasks are not broken down into subtasks."
},
{
"code": null,
"e": 13730,
"s": 13563,
"text": "An application can be parallel but not concurrent means that it only works on one task at a time and the tasks broken down into subtasks can be processed in parallel."
},
{
"code": null,
"e": 13881,
"s": 13730,
"text": "An application can be neither parallel nor concurrent. This means that it works on only one task at a time and the task is never broken into subtasks."
},
{
"code": null,
"e": 14054,
"s": 13881,
"text": "An application can be both parallel and concurrent means that it both works on multiple tasks at a time and the task is broken into subtasks for executing them in parallel."
},
{
"code": null,
"e": 14202,
"s": 14054,
"text": "We can achieve parallelism by distributing the subtasks among different cores of single CPU or among multiple computers connected within a network."
},
{
"code": null,
"e": 14301,
"s": 14202,
"text": "Consider the following important points to understand why it is necessary to achieve parallelism −"
},
{
"code": null,
"e": 14441,
"s": 14301,
"text": "With the help of parallelism, we can run our code efficiently. It will save our time because the same code in parts is running in parallel."
},
{
"code": null,
"e": 14703,
"s": 14441,
"text": "Sequential computing is constrained by physical and practical factors due to which it is not possible to get faster computing results. On the other hand, this issue is solved by parallel computing and gives us faster computing results than sequential computing."
},
{
"code": null,
"e": 14767,
"s": 14703,
"text": "Parallel processing reduces the execution time of program code."
},
{
"code": null,
"e": 15123,
"s": 14767,
"text": "If we talk about real life example of parallelism, the graphics card of our computer is the example that highlights the true power of parallel processing because it has hundreds of individual processing cores that work independently and can do the execution at the same time. Due to this reason, we are able to run high-end applications and games as well."
},
{
"code": null,
"e": 15488,
"s": 15123,
"text": "We know about concurrency, parallelism and the difference between them but what about the system on which it is to be implemented. It is very necessary to have the understanding of the system, on which we are going to implement, because it gives us the benefit to take informed decision while designing the software. We have the following two kinds of processors −"
},
{
"code": null,
"e": 15880,
"s": 15488,
"text": "Single-core processors are capable of executing one thread at any given time. These processors use context switching to store all the necessary information for a thread at a specific time and then restoring the information later. The context switching mechanism helps us make progress on a number of threads within a given second and it looks as if the system is working on multiple things.\n"
},
{
"code": null,
"e": 16151,
"s": 15880,
"text": "Single-core processors come with many advantages. These processors require less power and there is no complex communication protocol between multiple cores. On the other hand, the speed of single-core processors is limited and it is not suitable for larger applications."
},
{
"code": null,
"e": 16235,
"s": 16151,
"text": "Multi-core processors have multiple independent processing units also called cores."
},
{
"code": null,
"e": 16379,
"s": 16235,
"text": "Such processors do not need context switching mechanism as each core contains everything it needs to execute a sequence of stored instructions."
},
{
"code": null,
"e": 16531,
"s": 16379,
"text": "The cores of multi-core processors follow a cycle for executing. This cycle is called the Fetch-Decode-Execute cycle. It involves the following steps −"
},
{
"code": null,
"e": 16633,
"s": 16531,
"text": "This is the first step of cycle, which involves the fetching of instructions from the program memory."
},
{
"code": null,
"e": 16747,
"s": 16633,
"text": "Recently fetched instructions would be converted to a series of signals that will trigger other parts of the CPU."
},
{
"code": null,
"e": 16895,
"s": 16747,
"text": "It is the final step in which the fetched and the decoded instructions would be executed. The result of execution will be stored in a CPU register."
},
{
"code": null,
"e": 17203,
"s": 16895,
"text": "One advantage over here is that the execution in multi-core processors are faster than that of single-core processors. It is suitable for larger applications. On the other hand, complex communication protocol between multiple cores is an issue. Multiple cores require more power than single-core processors."
},
{
"code": null,
"e": 17460,
"s": 17203,
"text": "There are different system and memory architecture styles that need to be considered while designing the program or concurrent system. It is very necessary because one system & memory style may be suitable for one task but may be error prone to other task."
},
{
"code": null,
"e": 17620,
"s": 17460,
"text": "Michael Flynn in 1972 gave taxonomy for categorizing different styles of computer system architecture. This taxonomy defines four different styles as follows −"
},
{
"code": null,
"e": 17673,
"s": 17620,
"text": "Single instruction stream, single data stream (SISD)"
},
{
"code": null,
"e": 17728,
"s": 17673,
"text": "Single instruction stream, multiple data stream (SIMD)"
},
{
"code": null,
"e": 17783,
"s": 17728,
"text": "Multiple instruction stream, single data stream (MISD)"
},
{
"code": null,
"e": 17841,
"s": 17783,
"text": "Multiple instruction stream, multiple data stream (MIMD)."
},
{
"code": null,
"e": 18110,
"s": 17841,
"text": "As the name suggests, such kind of systems would have one sequential incoming data stream and one single processing unit to execute the data stream. They are just like uniprocessor systems having parallel computing architecture. Following is the architecture of SISD −"
},
{
"code": null,
"e": 18163,
"s": 18110,
"text": "The advantages of SISD architecture are as follows −"
},
{
"code": null,
"e": 18187,
"s": 18163,
"text": "It requires less power."
},
{
"code": null,
"e": 18263,
"s": 18187,
"text": "There is no issue of complex communication protocol between multiple cores."
},
{
"code": null,
"e": 18319,
"s": 18263,
"text": "The disadvantages of SISD architecture are as follows −"
},
{
"code": null,
"e": 18395,
"s": 18319,
"text": "The speed of SISD architecture is limited just like single-core processors."
},
{
"code": null,
"e": 18439,
"s": 18395,
"text": "It is not suitable for larger applications."
},
{
"code": null,
"e": 18733,
"s": 18439,
"text": "As the name suggests, such kind of systems would have multiple incoming data streams and number of processing units that can act on a single instruction at any given time. They are just like multiprocessor systems having parallel computing architecture. Following is the architecture of SIMD −"
},
{
"code": null,
"e": 19123,
"s": 18733,
"text": "The best example for SIMD is the graphics cards. These cards have hundreds of individual processing units. If we talk about computational difference between SISD and SIMD then for the adding arrays [5, 15, 20] and [15, 25, 10], SISD architecture would have to perform three different add operations. On the other hand, with the SIMD architecture, we can add then in a single add operation."
},
{
"code": null,
"e": 19176,
"s": 19123,
"text": "The advantages of SIMD architecture are as follows −"
},
{
"code": null,
"e": 19257,
"s": 19176,
"text": "Same operation on multiple elements can be performed using one instruction only."
},
{
"code": null,
"e": 19338,
"s": 19257,
"text": "Same operation on multiple elements can be performed using one instruction only."
},
{
"code": null,
"e": 19432,
"s": 19338,
"text": "Throughput of the system can be increased by increasing the number of cores of the processor."
},
{
"code": null,
"e": 19526,
"s": 19432,
"text": "Throughput of the system can be increased by increasing the number of cores of the processor."
},
{
"code": null,
"e": 19577,
"s": 19526,
"text": "Processing speed is higher than SISD architecture."
},
{
"code": null,
"e": 19628,
"s": 19577,
"text": "Processing speed is higher than SISD architecture."
},
{
"code": null,
"e": 19684,
"s": 19628,
"text": "The disadvantages of SIMD architecture are as follows −"
},
{
"code": null,
"e": 19754,
"s": 19684,
"text": "There is complex communication between numbers of cores of processor."
},
{
"code": null,
"e": 19797,
"s": 19754,
"text": "The cost is higher than SISD architecture."
},
{
"code": null,
"e": 19985,
"s": 19797,
"text": "Systems with MISD stream have number of processing units performing different operations by executing different instructions on the same data set. Following is the architecture of MISD − "
},
{
"code": null,
"e": 20057,
"s": 19985,
"text": "The representatives of MISD architecture do not yet exist commercially."
},
{
"code": null,
"e": 20378,
"s": 20057,
"text": "In the system using MIMD architecture, each processor in a multiprocessor system can execute different sets of instructions independently on the different set of data set in parallel. It is opposite to SIMD architecture in which single operation is executed on multiple data sets. Following is the architecture of MIMD −"
},
{
"code": null,
"e": 20613,
"s": 20378,
"text": "A normal multiprocessor uses the MIMD architecture. These architectures are basically used in a number of application areas such as computer-aided design/computer-aided manufacturing, simulation, modeling, communication switches, etc."
},
{
"code": null,
"e": 21066,
"s": 20613,
"text": "While working with the concepts like concurrency and parallelism, there is always a need to speed up the programs. One solution found by computer designers is to create shared-memory multi-computers, i.e., computers having single physical address space, which is accessed by all the cores that a processor is having. In this scenario, there can be a number of different styles of architecture but following are the three important architecture styles −"
},
{
"code": null,
"e": 21298,
"s": 21066,
"text": "In this model, all the processors share the physical memory uniformly. All the processors have equal access time to all the memory words. Each processor may have a private cache memory. The peripheral devices follow a set of rules."
},
{
"code": null,
"e": 21540,
"s": 21298,
"text": "When all the processors have equal access to all the peripheral devices, the system is called a symmetric multiprocessor. When only one or a few processors can access the peripheral devices, the system is called an asymmetric multiprocessor."
},
{
"code": null,
"e": 21845,
"s": 21540,
"text": "In the NUMA multiprocessor model, the access time varies with the location of the memory word. Here, the shared memory is physically distributed among all the processors, called local memories. The collection of all local memories forms a global address space which can be accessed by all the processors."
},
{
"code": null,
"e": 21977,
"s": 21845,
"text": "The COMA model is a specialized version of the NUMA model. Here, all the distributed main memories are converted to cache memories."
},
{
"code": null,
"e": 22549,
"s": 21977,
"text": "In general, as we know that thread is a very thin twisted string usually of the cotton or silk fabric and used for sewing clothes and such. The same term thread is also used in the world of computer programming. Now, how do we relate the thread used for sewing clothes and the thread used for computer programming? The roles performed by the two threads is similar here. In clothes, thread hold the cloth together and on the other side, in computer programming, thread hold the computer program and allow the program to execute sequential actions or many actions at once."
},
{
"code": null,
"e": 22845,
"s": 22549,
"text": "Threadis the smallest unit of execution in an operating system. It is not in itself a program but runs within a program. In other words, threads are not independent of one other and share code section, data section, etc. with other threads. These threads are also known as lightweight processes."
},
{
"code": null,
"e": 23076,
"s": 22845,
"text": "To understand the functionality of threads in depth, we need to learn about the lifecycle of the threads or the different thread states. Typically, a thread can exist in five distinct states. The different states are shown below −"
},
{
"code": null,
"e": 23274,
"s": 23076,
"text": "A new thread begins its life cycle in the new state. However, at this stage, it has not yet started and it has not been allocated any resources. We can say that it is just an instance of an object."
},
{
"code": null,
"e": 23455,
"s": 23274,
"text": "As the newly born thread is started, the thread becomes runnable i.e. waiting to run. In this state, it has all the resources but still task scheduler have not scheduled it to run."
},
{
"code": null,
"e": 23651,
"s": 23455,
"text": "In this state, the thread makes progress and executes the task, which has been chosen by task scheduler to run. Now, the thread can go to either the dead state or the non-runnable/ waiting state."
},
{
"code": null,
"e": 23817,
"s": 23651,
"text": "In this state, the thread is paused because it is either waiting for the response of some I/O request or waiting for the completion of the execution of other thread."
},
{
"code": null,
"e": 23915,
"s": 23817,
"text": "A runnable thread enters the terminated state when it completes its task or otherwise terminates."
},
{
"code": null,
"e": 23981,
"s": 23915,
"text": "The following diagram shows the complete life cycle of a thread −"
},
{
"code": null,
"e": 24073,
"s": 23981,
"text": "In this section, we will see the different types of thread. The types are described below −"
},
{
"code": null,
"e": 24105,
"s": 24073,
"text": "These are user-managed threads."
},
{
"code": null,
"e": 24429,
"s": 24105,
"text": "In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread."
},
{
"code": null,
"e": 24470,
"s": 24429,
"text": "The examples of user level threads are −"
},
{
"code": null,
"e": 24483,
"s": 24470,
"text": "Java threads"
},
{
"code": null,
"e": 24497,
"s": 24483,
"text": "POSIX threads"
},
{
"code": null,
"e": 24560,
"s": 24497,
"text": "Following are the different advantages of user level threads −"
},
{
"code": null,
"e": 24618,
"s": 24560,
"text": "Thread switching does not require Kernel mode privileges."
},
{
"code": null,
"e": 24669,
"s": 24618,
"text": "User level thread can run on any operating system."
},
{
"code": null,
"e": 24734,
"s": 24669,
"text": "Scheduling can be application specific in the user level thread."
},
{
"code": null,
"e": 24784,
"s": 24734,
"text": "User level threads are fast to create and manage."
},
{
"code": null,
"e": 24850,
"s": 24784,
"text": "Following are the different disadvantages of user level threads −"
},
{
"code": null,
"e": 24913,
"s": 24850,
"text": "In a typical operating system, most system calls are blocking."
},
{
"code": null,
"e": 24981,
"s": 24913,
"text": "Multithreaded application cannot take advantage of multiprocessing."
},
{
"code": null,
"e": 25064,
"s": 24981,
"text": "Operating System managed threads act on kernel, which is an operating system core."
},
{
"code": null,
"e": 25371,
"s": 25064,
"text": "In this case, the Kernel does thread management. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process."
},
{
"code": null,
"e": 25757,
"s": 25371,
"text": "The Kernel maintains context information for the process as a whole and for individual threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads. The examples of kernel level threads are Windows, Solaris."
},
{
"code": null,
"e": 25822,
"s": 25757,
"text": "Following are the different advantages of kernel level threads −"
},
{
"code": null,
"e": 25919,
"s": 25822,
"text": "Kernel can simultaneously schedule multiple threads from the same process on multiple processes."
},
{
"code": null,
"e": 26016,
"s": 25919,
"text": "Kernel can simultaneously schedule multiple threads from the same process on multiple processes."
},
{
"code": null,
"e": 26115,
"s": 26016,
"text": "If one thread in a process is blocked, the Kernel can schedule another thread of the same process."
},
{
"code": null,
"e": 26214,
"s": 26115,
"text": "If one thread in a process is blocked, the Kernel can schedule another thread of the same process."
},
{
"code": null,
"e": 26263,
"s": 26214,
"text": "Kernel routines themselves can be multithreaded."
},
{
"code": null,
"e": 26312,
"s": 26263,
"text": "Kernel routines themselves can be multithreaded."
},
{
"code": null,
"e": 26392,
"s": 26312,
"text": "Kernel threads are generally slower to create and manage than the user threads."
},
{
"code": null,
"e": 26472,
"s": 26392,
"text": "Kernel threads are generally slower to create and manage than the user threads."
},
{
"code": null,
"e": 26581,
"s": 26472,
"text": "Transfer of control from one thread to another within the same process requires a mode switch to the Kernel."
},
{
"code": null,
"e": 26690,
"s": 26581,
"text": "Transfer of control from one thread to another within the same process requires a mode switch to the Kernel."
},
{
"code": null,
"e": 26940,
"s": 26690,
"text": "Thread Control Block (TCB) may be defined as the data structure in the kernel of operating system that mainly contains information about thread. Thread-specific information stored in TCB would highlight some important information about each process."
},
{
"code": null,
"e": 27012,
"s": 26940,
"text": "Consider the following points related to the threads contained in TCB −"
},
{
"code": null,
"e": 27099,
"s": 27012,
"text": "Thread identification − It is the unique thread id (tid) assigned to every new thread."
},
{
"code": null,
"e": 27186,
"s": 27099,
"text": "Thread identification − It is the unique thread id (tid) assigned to every new thread."
},
{
"code": null,
"e": 27304,
"s": 27186,
"text": "Thread state − It contains the information related to the state (Running, Runnable, Non-Running, Dead) of the thread."
},
{
"code": null,
"e": 27422,
"s": 27304,
"text": "Thread state − It contains the information related to the state (Running, Runnable, Non-Running, Dead) of the thread."
},
{
"code": null,
"e": 27505,
"s": 27422,
"text": "Program Counter (PC) − It points to the current program instruction of the thread."
},
{
"code": null,
"e": 27588,
"s": 27505,
"text": "Program Counter (PC) − It points to the current program instruction of the thread."
},
{
"code": null,
"e": 27679,
"s": 27588,
"text": "Register set − It contains the thread’s register values assigned to them for computations."
},
{
"code": null,
"e": 27770,
"s": 27679,
"text": "Register set − It contains the thread’s register values assigned to them for computations."
},
{
"code": null,
"e": 27888,
"s": 27770,
"text": "Stack Pointer − It points to the thread’s stack in the process. It contains the local variables under thread’s scope."
},
{
"code": null,
"e": 28006,
"s": 27888,
"text": "Stack Pointer − It points to the thread’s stack in the process. It contains the local variables under thread’s scope."
},
{
"code": null,
"e": 28088,
"s": 28006,
"text": "Pointer to PCB − It contains the pointer to the process that created that thread."
},
{
"code": null,
"e": 28170,
"s": 28088,
"text": "Pointer to PCB − It contains the pointer to the process that created that thread."
},
{
"code": null,
"e": 28561,
"s": 28170,
"text": "In multithreading, process and thread are two very closely related terms having the same goal to make computer able to do more than one thing at a time. A process can contain one or more threads but on the contrary, thread cannot contain a process. However, they both remain the two basic units of execution. A program, executing a series of instructions, initiates process and thread both."
},
{
"code": null,
"e": 28631,
"s": 28561,
"text": "The following table shows the comparison between process and thread −"
},
{
"code": null,
"e": 29012,
"s": 28631,
"text": "As we have discussed earlier that Multithreading is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads. In a more simple way, we can say that multithreading is the way of achieving multitasking by using the concept of threads."
},
{
"code": null,
"e": 29100,
"s": 29012,
"text": "The concept of multithreading can be understood with the help of the following example."
},
{
"code": null,
"e": 29418,
"s": 29100,
"text": "Suppose we are running a process. The process could be for opening MS word for writing something. In such process, one thread will be assigned to open MS word and another thread will be required to write. Now, suppose if we want to edit something then another thread will be required to do the editing task and so on."
},
{
"code": null,
"e": 29499,
"s": 29418,
"text": "The following diagram helps us understand how multiple threads exist in memory −"
},
{
"code": null,
"e": 29726,
"s": 29499,
"text": "We can see in the above diagram that more than one thread can exist within one process where every thread contains its own register set and local variables. Other than that, all the threads in a process share global variables."
},
{
"code": null,
"e": 29809,
"s": 29726,
"text": "Let us now see a few advantages of multithreading. The advantages are as follows −"
},
{
"code": null,
"e": 29953,
"s": 29809,
"text": "Speed of communication − Multithreading improves the speed of computation because each core or processor handles separate threads concurrently."
},
{
"code": null,
"e": 30097,
"s": 29953,
"text": "Speed of communication − Multithreading improves the speed of computation because each core or processor handles separate threads concurrently."
},
{
"code": null,
"e": 30247,
"s": 30097,
"text": "Program remains responsive − It allows a program to remain responsive because one thread waits for the input and another runs a GUI at the same time."
},
{
"code": null,
"e": 30397,
"s": 30247,
"text": "Program remains responsive − It allows a program to remain responsive because one thread waits for the input and another runs a GUI at the same time."
},
{
"code": null,
"e": 30604,
"s": 30397,
"text": "Access to global variables − In multithreading, all the threads of a particular process can access the global variables and if there is any change in global variable then it is visible to other threads too."
},
{
"code": null,
"e": 30811,
"s": 30604,
"text": "Access to global variables − In multithreading, all the threads of a particular process can access the global variables and if there is any change in global variable then it is visible to other threads too."
},
{
"code": null,
"e": 30944,
"s": 30811,
"text": "Utilization of resources − Running of several threads in each program makes better use of CPU and the idle time of CPU becomes less."
},
{
"code": null,
"e": 31077,
"s": 30944,
"text": "Utilization of resources − Running of several threads in each program makes better use of CPU and the idle time of CPU becomes less."
},
{
"code": null,
"e": 31204,
"s": 31077,
"text": "Sharing of data − There is no requirement of extra space for each thread because threads within a program can share same data."
},
{
"code": null,
"e": 31331,
"s": 31204,
"text": "Sharing of data − There is no requirement of extra space for each thread because threads within a program can share same data."
},
{
"code": null,
"e": 31420,
"s": 31331,
"text": "Let us now see a few disadvantages of multithreading. The disadvantages are as follows −"
},
{
"code": null,
"e": 31640,
"s": 31420,
"text": "Not suitable for single processor system − Multithreading finds it difficult to achieve performance in terms of speed of computation on single processor system as compared with the performance on multi-processor system."
},
{
"code": null,
"e": 31860,
"s": 31640,
"text": "Not suitable for single processor system − Multithreading finds it difficult to achieve performance in terms of speed of computation on single processor system as compared with the performance on multi-processor system."
},
{
"code": null,
"e": 32037,
"s": 31860,
"text": "Issue of security − As we know that all the threads within a program share same data, hence there is always an issue of security because any unknown thread can change the data."
},
{
"code": null,
"e": 32214,
"s": 32037,
"text": "Issue of security − As we know that all the threads within a program share same data, hence there is always an issue of security because any unknown thread can change the data."
},
{
"code": null,
"e": 32330,
"s": 32214,
"text": "Increase in complexity − Multithreading can increase the complexity of the program and debugging becomes difficult."
},
{
"code": null,
"e": 32446,
"s": 32330,
"text": "Increase in complexity − Multithreading can increase the complexity of the program and debugging becomes difficult."
},
{
"code": null,
"e": 32558,
"s": 32446,
"text": "Lead to deadlock state − Multithreading can lead the program to potential risk of attaining the deadlock state."
},
{
"code": null,
"e": 32670,
"s": 32558,
"text": "Lead to deadlock state − Multithreading can lead the program to potential risk of attaining the deadlock state."
},
{
"code": null,
"e": 32799,
"s": 32670,
"text": "Synchronization required − Synchronization is required to avoid mutual exclusion. This leads to more memory and CPU utilization."
},
{
"code": null,
"e": 32928,
"s": 32799,
"text": "Synchronization required − Synchronization is required to avoid mutual exclusion. This leads to more memory and CPU utilization."
},
{
"code": null,
"e": 32995,
"s": 32928,
"text": "In this chapter, we will learn how to implement threads in Python."
},
{
"code": null,
"e": 33241,
"s": 32995,
"text": "Python threads are sometimes called lightweight processes because threads occupy much less memory than processes. Threads allow performing multiple tasks at once. In Python, we have the following two modules that implement threads in a program −"
},
{
"code": null,
"e": 33257,
"s": 33241,
"text": "<_thread>module"
},
{
"code": null,
"e": 33273,
"s": 33257,
"text": "<_thread>module"
},
{
"code": null,
"e": 33291,
"s": 33273,
"text": "<threading>module"
},
{
"code": null,
"e": 33309,
"s": 33291,
"text": "<threading>module"
},
{
"code": null,
"e": 33642,
"s": 33309,
"text": "The main difference between these two modules is that <_thread> module treats a thread as a function whereas, the <threading> module treats every thread as an object and implements it in an object oriented way. Moreover, the <_thread>module is effective in low level threading and has fewer capabilities than the <threading> module."
},
{
"code": null,
"e": 33983,
"s": 33642,
"text": "In the earlier version of Python, we had the <thread> module but it has been considered as \"deprecated\" for quite a long time. Users have been encouraged to use the <threading> module instead. Therefore, in Python 3 the module \"thread\" is not available anymore. It has been renamed to \"<_thread>\" for backwards incompatibilities in Python3."
},
{
"code": null,
"e": 34177,
"s": 33983,
"text": "To generate new thread with the help of the <_thread> module, we need to call the start_new_thread method of it. The working of this method can be understood with the help of following syntax −"
},
{
"code": null,
"e": 34232,
"s": 34177,
"text": "_thread.start_new_thread ( function, args[, kwargs] )\n"
},
{
"code": null,
"e": 34239,
"s": 34232,
"text": "Here −"
},
{
"code": null,
"e": 34268,
"s": 34239,
"text": "args is a tuple of arguments"
},
{
"code": null,
"e": 34297,
"s": 34268,
"text": "args is a tuple of arguments"
},
{
"code": null,
"e": 34351,
"s": 34297,
"text": "kwargs is an optional dictionary of keyword arguments"
},
{
"code": null,
"e": 34405,
"s": 34351,
"text": "kwargs is an optional dictionary of keyword arguments"
},
{
"code": null,
"e": 34518,
"s": 34405,
"text": "If we want to call function without passing an argument then we need to use an empty tuple of arguments in args."
},
{
"code": null,
"e": 34695,
"s": 34518,
"text": "This method call returns immediately, the child thread starts, and calls function with the passed list, if any, of args. The thread terminates as and when the function returns."
},
{
"code": null,
"e": 34825,
"s": 34695,
"text": "Following is an example for generating new thread by using the <_thread> module. We are using the start_new_thread() method here."
},
{
"code": null,
"e": 35224,
"s": 34825,
"text": "import _thread\nimport time\n\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print (\"%s: %s\" % ( threadName, time.ctime(time.time()) ))\n\ntry:\n _thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n _thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print (\"Error: unable to start thread\")\nwhile 1:\n pass"
},
{
"code": null,
"e": 35339,
"s": 35224,
"text": "The following output will help us understand the generation of new threads bwith the help of the <_thread> module."
},
{
"code": null,
"e": 35690,
"s": 35339,
"text": "Thread-1: Mon Apr 23 10:03:33 2018\nThread-2: Mon Apr 23 10:03:35 2018\nThread-1: Mon Apr 23 10:03:35 2018\nThread-1: Mon Apr 23 10:03:37 2018\nThread-2: Mon Apr 23 10:03:39 2018\nThread-1: Mon Apr 23 10:03:39 2018\nThread-1: Mon Apr 23 10:03:41 2018\nThread-2: Mon Apr 23 10:03:43 2018\nThread-2: Mon Apr 23 10:03:47 2018\nThread-2: Mon Apr 23 10:03:51 2018\n"
},
{
"code": null,
"e": 35930,
"s": 35690,
"text": "The <threading> module implements in an object oriented way and treats every thread as an object. Therefore, it provides much more powerful, high-level support for threads than the <_thread> module. This module is included with Python 2.4."
},
{
"code": null,
"e": 36087,
"s": 35930,
"text": "The <threading> module comprises all the methods of the <_thread> module but it provides additional methods as well. The additional methods are as follows −"
},
{
"code": null,
"e": 36178,
"s": 36087,
"text": "threading.activeCount() − This method returns the number of thread objects that are active"
},
{
"code": null,
"e": 36269,
"s": 36178,
"text": "threading.activeCount() − This method returns the number of thread objects that are active"
},
{
"code": null,
"e": 36378,
"s": 36269,
"text": "threading.currentThread() − This method returns the number of thread objects in the caller's thread control."
},
{
"code": null,
"e": 36487,
"s": 36378,
"text": "threading.currentThread() − This method returns the number of thread objects in the caller's thread control."
},
{
"code": null,
"e": 36587,
"s": 36487,
"text": "threading.enumerate() − This method returns a list of all thread objects that are currently active."
},
{
"code": null,
"e": 36687,
"s": 36587,
"text": "threading.enumerate() − This method returns a list of all thread objects that are currently active."
},
{
"code": null,
"e": 36798,
"s": 36687,
"text": "For implementing threading, the <threading> module has the Thread class which provides the following methods −"
},
{
"code": null,
"e": 36856,
"s": 36798,
"text": "run() − The run() method is the entry point for a thread."
},
{
"code": null,
"e": 36914,
"s": 36856,
"text": "run() − The run() method is the entry point for a thread."
},
{
"code": null,
"e": 36986,
"s": 36914,
"text": "start() − The start() method starts a thread by calling the run method."
},
{
"code": null,
"e": 37058,
"s": 36986,
"text": "start() − The start() method starts a thread by calling the run method."
},
{
"code": null,
"e": 37116,
"s": 37058,
"text": "join([time]) − The join() waits for threads to terminate."
},
{
"code": null,
"e": 37174,
"s": 37116,
"text": "join([time]) − The join() waits for threads to terminate."
},
{
"code": null,
"e": 37251,
"s": 37174,
"text": "isAlive() − The isAlive() method checks whether a thread is still executing."
},
{
"code": null,
"e": 37328,
"s": 37251,
"text": "isAlive() − The isAlive() method checks whether a thread is still executing."
},
{
"code": null,
"e": 37391,
"s": 37328,
"text": "getName() − The getName() method returns the name of a thread."
},
{
"code": null,
"e": 37454,
"s": 37391,
"text": "getName() − The getName() method returns the name of a thread."
},
{
"code": null,
"e": 37514,
"s": 37454,
"text": "setName() − The setName() method sets the name of a thread."
},
{
"code": null,
"e": 37574,
"s": 37514,
"text": "setName() − The setName() method sets the name of a thread."
},
{
"code": null,
"e": 37730,
"s": 37574,
"text": "In this section, we will learn how to create threads using the <threading> module. Follow these steps to create a new thread using the <threading> module −"
},
{
"code": null,
"e": 37807,
"s": 37730,
"text": "Step 1 − In this step, we need to define a new subclass of the Thread class."
},
{
"code": null,
"e": 37884,
"s": 37807,
"text": "Step 1 − In this step, we need to define a new subclass of the Thread class."
},
{
"code": null,
"e": 37986,
"s": 37884,
"text": "Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method."
},
{
"code": null,
"e": 38088,
"s": 37986,
"text": "Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method."
},
{
"code": null,
"e": 38213,
"s": 38088,
"text": "Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started."
},
{
"code": null,
"e": 38338,
"s": 38213,
"text": "Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started."
},
{
"code": null,
"e": 38506,
"s": 38338,
"text": "Now, after creating the new Thread subclass, we can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run() method."
},
{
"code": null,
"e": 38599,
"s": 38506,
"text": "Consider this example to learn how to generate a new thread by using the <threading> module."
},
{
"code": null,
"e": 39402,
"s": 38599,
"text": "import threading\nimport time\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print (\"Starting \" + self.name)\n print_time(self.name, self.counter, 5)\n print (\"Exiting \" + self.name)\ndef print_time(threadName, delay, counter):\n while counter:\n if exitFlag:\n threadName.exit()\n time.sleep(delay)\n print (\"%s: %s\" % (threadName, time.ctime(time.time())))\n counter -= 1\n\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\nthread1.start()\nthread2.start()\nthread1.join()\nthread2.join()\nprint (\"Exiting Main Thread\")\nStarting Thread-1\nStarting Thread-2"
},
{
"code": null,
"e": 39439,
"s": 39402,
"text": "Now, consider the following output −"
},
{
"code": null,
"e": 39844,
"s": 39439,
"text": "Thread-1: Mon Apr 23 10:52:09 2018\nThread-1: Mon Apr 23 10:52:10 2018\nThread-2: Mon Apr 23 10:52:10 2018\nThread-1: Mon Apr 23 10:52:11 2018\nThread-1: Mon Apr 23 10:52:12 2018\nThread-2: Mon Apr 23 10:52:12 2018\nThread-1: Mon Apr 23 10:52:13 2018\nExiting Thread-1\nThread-2: Mon Apr 23 10:52:14 2018\nThread-2: Mon Apr 23 10:52:16 2018\nThread-2: Mon Apr 23 10:52:18 2018\nExiting Thread-2\nExiting Main Thread\n"
},
{
"code": null,
"e": 40195,
"s": 39844,
"text": "There are five thread states - new, runnable, running, waiting and dead. Among these five Of these five, we will majorly focus on three states - running, waiting and dead. A thread gets its resources in the running state, waits for the resources in the waiting state; the final release of the resource, if executing and acquired is in the dead state."
},
{
"code": null,
"e": 40357,
"s": 40195,
"text": "The following Python program with the help of start(), sleep() and join() methods will show how a thread entered in running, waiting and dead state respectively."
},
{
"code": null,
"e": 40419,
"s": 40357,
"text": "Step 1 − Import the necessary modules, <threading> and <time>"
},
{
"code": null,
"e": 40448,
"s": 40419,
"text": "import threading\nimport time"
},
{
"code": null,
"e": 40522,
"s": 40448,
"text": "Step 2 − Define a function, which will be called while creating a thread."
},
{
"code": null,
"e": 40587,
"s": 40522,
"text": "def thread_states():\n print(\"Thread entered in running state\")"
},
{
"code": null,
"e": 40689,
"s": 40587,
"text": "Step 3 − We are using the sleep() method of time module to make our thread waiting for say 2 seconds."
},
{
"code": null,
"e": 40703,
"s": 40689,
"text": "time.sleep(2)"
},
{
"code": null,
"e": 40808,
"s": 40703,
"text": "Step 4 − Now, we are creating a thread named T1, which takes the argument of the function defined above."
},
{
"code": null,
"e": 40852,
"s": 40808,
"text": "T1 = threading.Thread(target=thread_states)"
},
{
"code": null,
"e": 41012,
"s": 40852,
"text": "Step 5 − Now, with the help of the start() function we can start our thread. It will produce the message, which has been set by us while defining the function."
},
{
"code": null,
"e": 41055,
"s": 41012,
"text": "T1.start()\nThread entered in running state"
},
{
"code": null,
"e": 41156,
"s": 41055,
"text": "Step 6 − Now, at last we can kill the thread with the join() method after it finishes its execution."
},
{
"code": null,
"e": 41166,
"s": 41156,
"text": "T1.join()"
},
{
"code": null,
"e": 41468,
"s": 41166,
"text": "In python, we can start a new thread by different ways but the easiest one among them is to define it as a single function. After defining the function, we can pass this as the target for a new threading.Thread object and so on. Execute the following Python code to understand how the function works −"
},
{
"code": null,
"e": 41859,
"s": 41468,
"text": "import threading\nimport time\nimport random\ndef Thread_execution(i):\n print(\"Execution of Thread {} started\\n\".format(i))\n sleepTime = random.randint(1,4)\n time.sleep(sleepTime)\n print(\"Execution of Thread {} finished\".format(i))\nfor i in range(4):\n thread = threading.Thread(target=Thread_execution, args=(i,))\n thread.start()\n print(\"Active Threads:\" , threading.enumerate())"
},
{
"code": null,
"e": 43065,
"s": 41859,
"text": "Execution of Thread 0 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>]\n\nExecution of Thread 1 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>]\n\nExecution of Thread 2 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>,\n <Thread(Thread-3578, started 2268)>]\n\nExecution of Thread 3 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>,\n <Thread(Thread-3578, started 2268)>,\n <Thread(Thread-3579, started 4520)>]\nExecution of Thread 0 finished\nExecution of Thread 1 finished\nExecution of Thread 2 finished\nExecution of Thread 3 finished\n"
},
{
"code": null,
"e": 43919,
"s": 43065,
"text": "Before implementing the daemon threads in Python, we need to know about daemon threads and their usage. In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. It would be dormant if it is not required any more. The same task can be done with the help of non-daemon threads also. However, in this case, the main thread has to keep track of the non-daemon threads manually. On the other hand, if we are using daemon threads then the main thread can completely forget about this and it will be killed when main thread exits. Another important point about daemon threads is that we can opt to use them only for non-essential tasks that would not affect us if it does not complete or gets killed in between. Following is the implementation of daemon threads in python −"
},
{
"code": null,
"e": 44351,
"s": 43919,
"text": "import threading\nimport time\n\ndef nondaemonThread():\n print(\"starting my thread\")\n time.sleep(8)\n print(\"ending my thread\")\ndef daemonThread():\n while True:\n print(\"Hello\")\n time.sleep(2)\nif __name__ == '__main__':\n nondaemonThread = threading.Thread(target = nondaemonThread)\n daemonThread = threading.Thread(target = daemonThread)\n daemonThread.setDaemon(True)\n daemonThread.start()\n nondaemonThread.start()"
},
{
"code": null,
"e": 44697,
"s": 44351,
"text": "In the above code, there are two functions namely >nondaemonThread() and >daemonThread(). The first function prints its state and sleeps after 8 seconds while the the deamonThread() function prints Hello after every 2 seconds indefinitely. We can understand the difference between nondaemon and daemon threads with the help of following output −"
},
{
"code": null,
"e": 44795,
"s": 44697,
"text": "Hello\n\nstarting my thread\nHello\nHello\nHello\nHello\nending my thread\nHello\nHello\nHello\nHello\nHello\n"
},
{
"code": null,
"e": 45402,
"s": 44795,
"text": "Thread synchronization may be defined as a method with the help of which we can be assured that two or more concurrent threads are not simultaneously accessing the program segment known as critical section. On the other hand, as we know that critical section is the part of the program where the shared resource is accessed. Hence we can say that synchronization is the process of making sure that two or more threads do not interface with each other by accessing the resources at the same time. The diagram below shows that four threads trying to access the critical section of a program at the same time."
},
{
"code": null,
"e": 45742,
"s": 45402,
"text": "To make it clearer, suppose two or more threads trying to add the object in the list at the same time. This act cannot lead to a successful end because either it will drop one or all the objects or it will completely corrupt the state of the list. Here the role of the synchronization is that only one thread at a time can access the list."
},
{
"code": null,
"e": 45916,
"s": 45742,
"text": "We might encounter issues while implementing concurrent programming or applying synchronizing primitives. In this section, we will discuss two major issues. The issues are −"
},
{
"code": null,
"e": 45925,
"s": 45916,
"text": "Deadlock"
},
{
"code": null,
"e": 45940,
"s": 45925,
"text": "Race condition"
},
{
"code": null,
"e": 46358,
"s": 45940,
"text": "This is one of the major issues in concurrent programming. Concurrent access to shared resources can lead to race condition. A race condition may be defined as the occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes."
},
{
"code": null,
"e": 46426,
"s": 46358,
"text": "Consider this example to understand the concept of race condition −"
},
{
"code": null,
"e": 46486,
"s": 46426,
"text": "Step 1 − In this step, we need to import threading module −"
},
{
"code": null,
"e": 46503,
"s": 46486,
"text": "import threading"
},
{
"code": null,
"e": 46578,
"s": 46503,
"text": "Step 2 − Now, define a global variable, say x, along with its value as 0 −"
},
{
"code": null,
"e": 46584,
"s": 46578,
"text": "x = 0"
},
{
"code": null,
"e": 46710,
"s": 46584,
"text": "Step 3 − Now, we need to define the increment_global() function, which will do the increment by 1 in this global function x −"
},
{
"code": null,
"e": 46757,
"s": 46710,
"text": "def increment_global():\n\n global x\n x += 1"
},
{
"code": null,
"e": 46941,
"s": 46757,
"text": "Step 4 − In this step, we will define the taskofThread() function, which will call the increment_global() function for a specified number of times; for our example it is 50000 times −"
},
{
"code": null,
"e": 47013,
"s": 46941,
"text": "def taskofThread():\n\n for _ in range(50000):\n increment_global()"
},
{
"code": null,
"e": 47225,
"s": 47013,
"text": "Step 5 − Now, define the main() function in which threads t1 and t2 are created. Both will be started with the help of the start() function and wait until they finish their jobs with the help of join() function."
},
{
"code": null,
"e": 47412,
"s": 47225,
"text": "def main():\n global x\n x = 0\n \n t1 = threading.Thread(target= taskofThread)\n t2 = threading.Thread(target= taskofThread)\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()"
},
{
"code": null,
"e": 47556,
"s": 47412,
"text": "Step 6 − Now, we need to give the range as in for how many iterations we want to call the main() function. Here, we are calling it for 5 times."
},
{
"code": null,
"e": 47673,
"s": 47556,
"text": "if __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))"
},
{
"code": null,
"e": 47930,
"s": 47673,
"text": "In the output shown below, we can see the effect of race condition as the value of x after each iteration is expected 100000. However, there is lots of variation in the value. This is due to the concurrent access of threads to the shared global variable x."
},
{
"code": null,
"e": 48072,
"s": 47930,
"text": "x = 100000 after Iteration 0\nx = 54034 after Iteration 1\nx = 80230 after Iteration 2\nx = 93602 after Iteration 3\nx = 93289 after Iteration 4\n"
},
{
"code": null,
"e": 48478,
"s": 48072,
"text": "As we have seen the effect of race condition in the above program, we need a synchronization tool, which can deal with race condition between multiple threads. In Python, the <threading> module provides Lock class to deal with race condition. Further, the Lock class provides different methods with the help of which we can handle race condition between multiple threads. The methods are described below −"
},
{
"code": null,
"e": 48623,
"s": 48478,
"text": "This method is used to acquire, i.e., blocking a lock. A lock can be blocking or non-blocking depending upon the following true or false value −"
},
{
"code": null,
"e": 48790,
"s": 48623,
"text": "With value set to True − If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked."
},
{
"code": null,
"e": 48957,
"s": 48790,
"text": "With value set to True − If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked."
},
{
"code": null,
"e": 49157,
"s": 48957,
"text": "With value set to False − If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked."
},
{
"code": null,
"e": 49357,
"s": 49157,
"text": "With value set to False − If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked."
},
{
"code": null,
"e": 49457,
"s": 49357,
"text": "This method is used to release a lock. Following are a few important tasks related to this method −"
},
{
"code": null,
"e": 49653,
"s": 49457,
"text": "If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked."
},
{
"code": null,
"e": 49849,
"s": 49653,
"text": "If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked."
},
{
"code": null,
"e": 49906,
"s": 49849,
"text": "It will raise a ThreadError if lock is already unlocked."
},
{
"code": null,
"e": 49963,
"s": 49906,
"text": "It will raise a ThreadError if lock is already unlocked."
},
{
"code": null,
"e": 50250,
"s": 49963,
"text": "Now, we can rewrite the above program with the lock class and its methods to avoid the race condition. We need to define the taskofThread() method with lock argument and then need to use the acquire() and release() methods for blocking and non-blocking of locks to avoid race condition."
},
{
"code": null,
"e": 50358,
"s": 50250,
"text": "Following is example of python program to understand the concept of locks for dealing with race condition −"
},
{
"code": null,
"e": 50913,
"s": 50358,
"text": "import threading\n\nx = 0\n\ndef increment_global():\n\n global x\n x += 1\n\ndef taskofThread(lock):\n\n for _ in range(50000):\n lock.acquire()\n increment_global()\n lock.release()\n\ndef main():\n global x\n x = 0\n\n lock = threading.Lock()\n t1 = threading.Thread(target = taskofThread, args = (lock,))\n t2 = threading.Thread(target = taskofThread, args = (lock,))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n\nif __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))"
},
{
"code": null,
"e": 51101,
"s": 50913,
"text": "The following output shows that the effect of race condition is neglected; as the value of x, after each & every iteration, is now 100000, which is as per the expectation of this program."
},
{
"code": null,
"e": 51247,
"s": 51101,
"text": "x = 100000 after Iteration 0\nx = 100000 after Iteration 1\nx = 100000 after Iteration 2\nx = 100000 after Iteration 3\nx = 100000 after Iteration 4\n"
},
{
"code": null,
"e": 51422,
"s": 51247,
"text": "Deadlock is a troublesome issue one can face while designing the concurrent systems. We can illustrate this issue with the help of the dining philosopher problem as follows −"
},
{
"code": null,
"e": 51592,
"s": 51422,
"text": "Edsger Dijkstra originally introduced the dining philosopher problem, one of the famous illustrations of one of the biggest problem of concurrent system called deadlock."
},
{
"code": null,
"e": 51872,
"s": 51592,
"text": "In this problem, there are five famous philosophers sitting at a round table eating some food from their bowls. There are five forks that can be used by the five philosophers to eat their food. However, the philosophers decide to use two forks at the same time to eat their food."
},
{
"code": null,
"e": 52414,
"s": 51872,
"text": "Now, there are two main conditions for the philosophers. First, each of the philosophers can be either in eating or in thinking state and second, they must first obtain both the forks, i.e., left and right. The issue arises when each of the five philosophers manages to pick the left fork at the same time. Now they all are waiting for the right fork to be free but they will never relinquish their fork until they have eaten their food and the right fork would never be available. Hence, there would be a deadlock state at the dinner table."
},
{
"code": null,
"e": 52635,
"s": 52414,
"text": "Now if we see, the same issue can arise in our concurrent systems too. The forks in the above example would be the system resources and each philosopher can represent the process, which is competing to get the resources."
},
{
"code": null,
"e": 53326,
"s": 52635,
"text": "The solution of this problem can be found by splitting the philosophers into two types – greedy philosophers and generous philosophers. Mainly a greedy philosopher will try to pick up the left fork and wait until it is there. He will then wait for the right fork to be there, pick it up, eat and then put it down. On the other hand, a generous philosopher will try to pick up the left fork and if it is not there, he will wait and try again after some time. If they get the left fork then they will try to get the right one. If they will get the right fork too then they will eat and release both the forks. However, if they will not get the right fork then they will release the left fork."
},
{
"code": null,
"e": 53420,
"s": 53326,
"text": "The following Python program will help us find a solution to the dining philosopher problem −"
},
{
"code": null,
"e": 54791,
"s": 53420,
"text": "import threading\nimport random\nimport time\n\nclass DiningPhilosopher(threading.Thread):\n\n running = True\n\n def __init__(self, xname, Leftfork, Rightfork):\n threading.Thread.__init__(self)\n self.name = xname\n self.Leftfork = Leftfork\n self.Rightfork = Rightfork\n\n def run(self):\n while(self.running):\n time.sleep( random.uniform(3,13))\n print ('%s is hungry.' % self.name)\n self.dine()\n\n def dine(self):\n fork1, fork2 = self.Leftfork, self.Rightfork\n\n while self.running:\n fork1.acquire(True)\n locked = fork2.acquire(False)\n\t if locked: break\n fork1.release()\n print ('%s swaps forks' % self.name)\n fork1, fork2 = fork2, fork1\n else:\n return\n\n self.dining()\n fork2.release()\n fork1.release()\n\n def dining(self):\n print ('%s starts eating '% self.name)\n time.sleep(random.uniform(1,10))\n print ('%s finishes eating and now thinking.' % self.name)\n\ndef Dining_Philosophers():\n forks = [threading.Lock() for n in range(5)]\n philosopherNames = ('1st','2nd','3rd','4th', '5th')\n\n philosophers= [DiningPhilosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n for i in range(5)]\n\n random.seed()\n DiningPhilosopher.running = True\n for p in philosophers: p.start()\n time.sleep(30)\n DiningPhilosopher.running = False\n print (\" It is finishing.\")\n\nDining_Philosophers()"
},
{
"code": null,
"e": 55020,
"s": 54791,
"text": "The above program uses the concept of greedy and generous philosophers. The program has also used the acquire() and release() methods of the Lock class of the <threading> module. We can see the solution in the following output −"
},
{
"code": null,
"e": 55750,
"s": 55020,
"text": "4th is hungry.\n4th starts eating\n1st is hungry.\n1st starts eating\n2nd is hungry.\n5th is hungry.\n3rd is hungry.\n1st finishes eating and now thinking.3rd swaps forks\n2nd starts eating\n4th finishes eating and now thinking.\n3rd swaps forks5th starts eating\n5th finishes eating and now thinking.\n4th is hungry.\n4th starts eating\n2nd finishes eating and now thinking.\n3rd swaps forks\n1st is hungry.\n1st starts eating\n4th finishes eating and now thinking.\n3rd starts eating\n5th is hungry.\n5th swaps forks\n1st finishes eating and now thinking.\n5th starts eating\n2nd is hungry.\n2nd swaps forks\n4th is hungry.\n5th finishes eating and now thinking.\n3rd finishes eating and now thinking.\n2nd starts eating 4th starts eating\nIt is finishing.\n"
},
{
"code": null,
"e": 56205,
"s": 55750,
"text": "In real life, if a team of people is working on a common task then there should be communication between them for finishing the task properly. The same analogy is applicable to threads also. In programming, to reduce the ideal time of the processor we create multiple threads and assign different sub tasks to every thread. Hence, there must be a communication facility and they should interact with each other to finish the job in a synchronized manner."
},
{
"code": null,
"e": 56284,
"s": 56205,
"text": "Consider the following important points related to thread intercommunication −"
},
{
"code": null,
"e": 56452,
"s": 56284,
"text": "No performance gain − If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use."
},
{
"code": null,
"e": 56620,
"s": 56452,
"text": "No performance gain − If we cannot achieve proper communication between threads and processes then the performance gains from concurrency and parallelism is of no use."
},
{
"code": null,
"e": 56756,
"s": 56620,
"text": "Accomplish task properly − Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly."
},
{
"code": null,
"e": 56892,
"s": 56756,
"text": "Accomplish task properly − Without proper intercommunication mechanism between threads, the assigned task cannot be completed properly."
},
{
"code": null,
"e": 57135,
"s": 56892,
"text": "More efficient than inter-process communication − Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory."
},
{
"code": null,
"e": 57378,
"s": 57135,
"text": "More efficient than inter-process communication − Inter-thread communication is more efficient and easy to use than inter-process communication because all threads within a process share same address space and they need not use shared memory."
},
{
"code": null,
"e": 57789,
"s": 57378,
"text": "Multithreaded code comes up with a problem of passing information from one thread to another thread. The standard communication primitives do not solve this issue. Hence, we need to implement our own composite object in order to share objects between threads to make the communication thread-safe. Following are a few data structures, which provide thread-safe communication after making some changes in them −"
},
{
"code": null,
"e": 57915,
"s": 57789,
"text": "For using set data structure in a thread-safe manner, we need to extend the set class to implement our own locking mechanism."
},
{
"code": null,
"e": 57965,
"s": 57915,
"text": "Here is a Python example of extending the class −"
},
{
"code": null,
"e": 58413,
"s": 57965,
"text": "class extend_class(set):\n def __init__(self, *args, **kwargs):\n self._lock = Lock()\n super(extend_class, self).__init__(*args, **kwargs)\n\n def add(self, elem):\n self._lock.acquire()\n\t try:\n super(extend_class, self).add(elem)\n finally:\n self._lock.release()\n \n def delete(self, elem):\n self._lock.acquire()\n try:\n super(extend_class, self).delete(elem)\n finally:\n self._lock.release()"
},
{
"code": null,
"e": 58775,
"s": 58413,
"text": "In the above example, a class object named extend_class has been defined which is further inherited from the Python set class. A lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on the super class functionality with one key exception."
},
{
"code": null,
"e": 58858,
"s": 58775,
"text": "This is another key method for thread-safe communication is the use of decorators."
},
{
"code": null,
"e": 58926,
"s": 58858,
"text": "Consider a Python example that shows how to use decorators &mminus;"
},
{
"code": null,
"e": 59469,
"s": 58926,
"text": "def lock_decorator(method):\n\n def new_deco_method(self, *args, **kwargs):\n with self._lock:\n return method(self, *args, **kwargs)\nreturn new_deco_method\n\nclass Decorator_class(set):\n def __init__(self, *args, **kwargs):\n self._lock = Lock()\n super(Decorator_class, self).__init__(*args, **kwargs)\n\n @lock_decorator\n def add(self, *args, **kwargs):\n return super(Decorator_class, self).add(elem)\n @lock_decorator\n def delete(self, *args, **kwargs):\n return super(Decorator_class, self).delete(elem)"
},
{
"code": null,
"e": 59841,
"s": 59469,
"text": "In the above example, a decorator method named lock_decorator has been defined which is further inherited from the Python method class. Then a lock object is created within the constructor of this class. Now, there are two functions - add() and delete(). These functions are defined and are thread-safe. They both rely on super class functionality with one key exception."
},
{
"code": null,
"e": 60483,
"s": 59841,
"text": "The list data structure is thread-safe, quick as well as easy structure for temporary, in-memory storage. In Cpython, the GIL protects against concurrent access to them. As we came to know that lists are thread-safe but what about the data lying in them. Actually, the list’s data is not protected. For example, L.append(x) is not guarantee to return the expected result if another thread is trying to do the same thing. This is because, although append() is an atomic operation and thread-safe but the other thread is trying to modify the list’s data in concurrent fashion hence we can see the side effects of race conditions on the output."
},
{
"code": null,
"e": 60775,
"s": 60483,
"text": "To resolve this kind of issue and safely modify the data, we must implement a proper locking mechanism, which further ensures that multiple threads cannot potentially run into race conditions. To implement proper locking mechanism, we can extend the class as we did in the previous examples."
},
{
"code": null,
"e": 60830,
"s": 60775,
"text": "Some other atomic operations on lists are as follows −"
},
{
"code": null,
"e": 60949,
"s": 60830,
"text": "L.append(x)\nL1.extend(L2)\nx = L[i]\nx = L.pop()\nL1[i:j] = L2\nL.sort()\nx = y\nx.field = y\nD[x] = y\nD1.update(D2)\nD.keys()"
},
{
"code": null,
"e": 60956,
"s": 60949,
"text": "Here −"
},
{
"code": null,
"e": 60978,
"s": 60956,
"text": "L,L1,L2 all are lists"
},
{
"code": null,
"e": 60996,
"s": 60978,
"text": "D,D1,D2 are dicts"
},
{
"code": null,
"e": 61012,
"s": 60996,
"text": "x,y are objects"
},
{
"code": null,
"e": 61026,
"s": 61012,
"text": "i, j are ints"
},
{
"code": null,
"e": 61422,
"s": 61026,
"text": "If the list’s data is not protected, we might have to face the consequences. We may get or delete wrong data item, of race conditions. That is why it is recommended to use the queue data structure. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen of the queues at the ticket windows and bus-stops."
},
{
"code": null,
"e": 61624,
"s": 61422,
"text": "Queues are by default, thread-safe data structure and we need not worry about implementing complex locking mechanism. Python provides us the module to use different types of queues in our application."
},
{
"code": null,
"e": 61764,
"s": 61624,
"text": "In this section, we will earn about the different types of queues. Python provides three options of queues to use from the <queue> module −"
},
{
"code": null,
"e": 61805,
"s": 61764,
"text": "Normal Queues (FIFO, First in First out)"
},
{
"code": null,
"e": 61829,
"s": 61805,
"text": "LIFO, Last in First Out"
},
{
"code": null,
"e": 61838,
"s": 61829,
"text": "Priority"
},
{
"code": null,
"e": 61907,
"s": 61838,
"text": "We will learn about the different queues in the subsequent sections."
},
{
"code": null,
"e": 62133,
"s": 61907,
"text": "It is most commonly used queue implementations offered by Python. In this queuing mechanism whosoever will come first, will get the service first. FIFO is also called normal queues. FIFO queues can be represented as follows −"
},
{
"code": null,
"e": 62218,
"s": 62133,
"text": "In python, FIFO queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 62445,
"s": 62218,
"text": "For implementing FIFO queue with single thread, the Queue class will implement a basic first-in, first-out container. Elements will be added to one “end” of the sequence using put(), and removed from the other end using get()."
},
{
"code": null,
"e": 62529,
"s": 62445,
"text": "Following is a Python program for implementation of FIFO queue with single thread −"
},
{
"code": null,
"e": 62660,
"s": 62529,
"text": "import queue\n\nq = queue.Queue()\n\nfor i in range(8):\n q.put(\"item-\" + str(i))\n\nwhile not q.empty():\n print (q.get(), end = \" \")"
},
{
"code": null,
"e": 62717,
"s": 62660,
"text": "item-0 item-1 item-2 item-3 item-4 item-5 item-6 item-7\n"
},
{
"code": null,
"e": 62870,
"s": 62717,
"text": "The output shows that above program uses a single thread to illustrate that the elements are removed from the queue in the same order they are inserted."
},
{
"code": null,
"e": 63247,
"s": 62870,
"text": "For implementing FIFO with multiple threads, we need to define the myqueue() function, which is extended from the queue module. The working of get() and put() methods are same as discussed above while implementing FIFO queue with single thread. Then to make it multithreaded, we need to declare and instantiate the threads. These threads will consume the queue in FIFO manner."
},
{
"code": null,
"e": 63332,
"s": 63247,
"text": "Following is a Python program for implementation of FIFO queue with multiple threads"
},
{
"code": null,
"e": 63828,
"s": 63332,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(2)\nq = queue.Queue()\nfor i in range(5):\n q.put(i)\nthreads = []\nfor i in range(4):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join()"
},
{
"code": null,
"e": 64134,
"s": 63828,
"text": "<Thread(Thread-3654, started 5044)> removed 0 from the queue\n<Thread(Thread-3655, started 3144)> removed 1 from the queue\n<Thread(Thread-3656, started 6996)> removed 2 from the queue\n<Thread(Thread-3657, started 2672)> removed 3 from the queue\n<Thread(Thread-3654, started 5044)> removed 4 from the queue\n"
},
{
"code": null,
"e": 64450,
"s": 64134,
"text": "This queue uses totally opposite analogy than FIFO(First in First Out) queues. In this queuing mechanism, the one who comes last, will get the service first. This is similar to implement stack data structure. LIFO queues prove useful while implementing Depth-first search like algorithms of artificial intelligence."
},
{
"code": null,
"e": 64535,
"s": 64450,
"text": "In python, LIFO queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 64813,
"s": 64535,
"text": "For implementing LIFO queue with single thread, the Queue class will implement a basic last-in, first-out container by using the structure Queue.LifoQueue. Now, on calling put(), the elements are added in the head of the container and removed from the head also on using get()."
},
{
"code": null,
"e": 64901,
"s": 64813,
"text": "Following is a Python program for implementation of the LIFO queue with single thread −"
},
{
"code": null,
"e": 65098,
"s": 64901,
"text": "import queue\n\nq = queue.LifoQueue()\n\nfor i in range(8):\n q.put(\"item-\" + str(i))\n\nwhile not q.empty():\n print (q.get(), end=\" \")\nOutput:\nitem-7 item-6 item-5 item-4 item-3 item-2 item-1 item-0"
},
{
"code": null,
"e": 65255,
"s": 65098,
"text": "The output shows that the above program uses a single thread to illustrate that elements are removed from the queue in the opposite order they are inserted."
},
{
"code": null,
"e": 65514,
"s": 65255,
"text": "The implementation is similar as we have done the implementation of FIFO queues with multiple threads. The only difference is that we need to use the Queue class that will implement a basic last-in, first-out container by using the structure Queue.LifoQueue."
},
{
"code": null,
"e": 65601,
"s": 65514,
"text": "Following is a Python program for implementation of LIFO queue with multiple threads −"
},
{
"code": null,
"e": 66117,
"s": 65601,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n\t print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(2)\nq = queue.LifoQueue()\nfor i in range(5):\n q.put(i)\nthreads = []\nfor i in range(4):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join() "
},
{
"code": null,
"e": 66423,
"s": 66117,
"text": "<Thread(Thread-3882, started 4928)> removed 4 from the queue\n<Thread(Thread-3883, started 4364)> removed 3 from the queue\n<Thread(Thread-3884, started 6908)> removed 2 from the queue\n<Thread(Thread-3885, started 3584)> removed 1 from the queue\n<Thread(Thread-3882, started 4928)> removed 0 from the queue\n"
},
{
"code": null,
"e": 66887,
"s": 66423,
"text": "In FIFO and LIFO queues, the order of items are related to the order of insertion. However, there are many cases when the priority is more important than the order of insertion. Let us consider a real world example. Suppose the security at the airport is checking people of different categories. People of the VVIP, airline staff, custom officer, categories may be checked on priority instead of being checked on the basis of arrival like it is for the commoners."
},
{
"code": null,
"e": 67176,
"s": 66887,
"text": "Another important aspect that needs to be considered for priority queue is how to develop a task scheduler. One common design is to serve the most agent task on priority basis in the queue. This data structure can be used to pick up the items from the queue based on their priority value."
},
{
"code": null,
"e": 67265,
"s": 67176,
"text": "In python, priority queue can be implemented with single thread as well as multithreads."
},
{
"code": null,
"e": 67576,
"s": 67265,
"text": "For implementing priority queue with single thread, the Queue class will implement a task on priority container by using the structure Queue.PriorityQueue. Now, on calling put(), the elements are added with a value where the lowest value will have the highest priority and hence retrieved first by using get()."
},
{
"code": null,
"e": 67672,
"s": 67576,
"text": "Consider the following Python program for implementation of Priority queue with single thread −"
},
{
"code": null,
"e": 67929,
"s": 67672,
"text": "import queue as Q\np_queue = Q.PriorityQueue()\n\np_queue.put((2, 'Urgent'))\np_queue.put((1, 'Most Urgent'))\np_queue.put((10, 'Nothing important'))\nprio_queue.put((5, 'Important'))\n\nwhile not p_queue.empty():\n item = p_queue.get()\n print('%s - %s' % item)"
},
{
"code": null,
"e": 67994,
"s": 67929,
"text": "1 – Most Urgent\n2 - Urgent\n5 - Important\n10 – Nothing important\n"
},
{
"code": null,
"e": 68118,
"s": 67994,
"text": "In the above output, we can see that the queue has stored the items based on priority – less value is having high priority."
},
{
"code": null,
"e": 68494,
"s": 68118,
"text": "The implementation is similar to the implementation of FIFO and LIFO queues with multiple threads. The only difference is that we need to use the Queue class for initializing the priority by using the structure Queue.PriorityQueue. Another difference is with the way the queue would be generated. In the example given below, it will be generated with two identical data sets."
},
{
"code": null,
"e": 68593,
"s": 68494,
"text": "The following Python program helps in the implementation of priority queue with multiple threads −"
},
{
"code": null,
"e": 69152,
"s": 68593,
"text": "import threading\nimport queue\nimport random\nimport time\ndef myqueue(queue):\n while not queue.empty():\n item = queue.get()\n if item is None:\n break\n print(\"{} removed {} from the queue\".format(threading.current_thread(), item))\n queue.task_done()\n time.sleep(1)\nq = queue.PriorityQueue()\nfor i in range(5):\n q.put(i,1)\n\nfor i in range(5):\n q.put(i,1)\n\nthreads = []\nfor i in range(2):\n thread = threading.Thread(target=myqueue, args=(q,))\n thread.start()\n threads.append(thread)\nfor thread in threads:\n thread.join()"
},
{
"code": null,
"e": 69763,
"s": 69152,
"text": "<Thread(Thread-4939, started 2420)> removed 0 from the queue\n<Thread(Thread-4940, started 3284)> removed 0 from the queue\n<Thread(Thread-4939, started 2420)> removed 1 from the queue\n<Thread(Thread-4940, started 3284)> removed 1 from the queue\n<Thread(Thread-4939, started 2420)> removed 2 from the queue\n<Thread(Thread-4940, started 3284)> removed 2 from the queue\n<Thread(Thread-4939, started 2420)> removed 3 from the queue\n<Thread(Thread-4940, started 3284)> removed 3 from the queue\n<Thread(Thread-4939, started 2420)> removed 4 from the queue\n<Thread(Thread-4940, started 3284)> removed 4 from the queue\n"
},
{
"code": null,
"e": 69878,
"s": 69763,
"text": "In this chapter, we will learn about testing of thread applications. We will also learn the importance of testing."
},
{
"code": null,
"e": 70229,
"s": 69878,
"text": "Before we dive into the discussion about the importance of testing, we need to know what is testing. In general terms, testing is a technique of finding out how well something is working. On the other hand, specifically if we talk about computer programs or software then testing is the technique of accessing the functionality of a software program."
},
{
"code": null,
"e": 70565,
"s": 70229,
"text": "In this section, we will discuss the importance of software testing. In software development, there must be double-checking before the releasing of software to the client. That is why it is very important to test the software by experienced testing team. Consider the following points to understand the importance of software testing −"
},
{
"code": null,
"e": 70755,
"s": 70565,
"text": "Certainly, no company wants to deliver low quality software and no client wants to buy low quality software. Testing improves the quality of software by finding and fixing the bugs in that."
},
{
"code": null,
"e": 70933,
"s": 70755,
"text": "The most important part of any business is the satisfaction of their customers. By providing bug free and good quality software, the companies can achieve customer satisfaction."
},
{
"code": null,
"e": 71283,
"s": 70933,
"text": "Suppose we have made a software system of 10000 lines and we need to add a new feature then the development team would have the concern about the impact of this new feature on whole software. Here, also, testing plays a vital role because if the testing team has made a good suite of tests then it can save us from any potential catastrophic breaks."
},
{
"code": null,
"e": 71462,
"s": 71283,
"text": "Another most important part of any business is the experience of the users of that product. Only testing can assure that the end user finds it simple and easy to use the product."
},
{
"code": null,
"e": 71837,
"s": 71462,
"text": "Testing can cut down the total cost of software by finding and fixing the bugs in testing phase of its development rather than fixing it after delivery. If there is a major bug after the delivery of the software then it would increase its tangible cost say in terms of expenses and intangible cost say in terms of customer dissatisfaction, company’s negative reputation etc."
},
{
"code": null,
"e": 72314,
"s": 71837,
"text": "It is always recommended to have appropriate knowledge of what is to be tested. In this section, we will first understand be the prime motive of tester while testing any software. Code coverage, i.e., how many lines of code our test suite hits, while testing, should be avoided. It is because, while testing, focusing only on the number of lines of codes adds no real value to our system. There may remain some bugs, which reflect later at a later stage even after deployment."
},
{
"code": null,
"e": 72380,
"s": 72314,
"text": "Consider the following important points related to what to test −"
},
{
"code": null,
"e": 72469,
"s": 72380,
"text": "We need to focus on testing the functionality of the code rather than the code coverage."
},
{
"code": null,
"e": 72558,
"s": 72469,
"text": "We need to focus on testing the functionality of the code rather than the code coverage."
},
{
"code": null,
"e": 72707,
"s": 72558,
"text": "We need to test the most important parts of the code first and then move towards the less important parts of the code. It will definitely save time."
},
{
"code": null,
"e": 72856,
"s": 72707,
"text": "We need to test the most important parts of the code first and then move towards the less important parts of the code. It will definitely save time."
},
{
"code": null,
"e": 72948,
"s": 72856,
"text": "The tester must have multitude different tests that can push the software up to its limits."
},
{
"code": null,
"e": 73040,
"s": 72948,
"text": "The tester must have multitude different tests that can push the software up to its limits."
},
{
"code": null,
"e": 73535,
"s": 73040,
"text": "Due to the capability of utilizing the true capability of multi-core architecture, concurrent software systems are replacing sequential systems. In recent times, concurrent system programs are being used in everything from mobile phones to washing machines, from cars to airplanes, etc. We need to be more careful about testing the concurrent software programs because if we have added multiple threads to single thread application having already a bug, then we would end up with multiple bugs."
},
{
"code": null,
"e": 73811,
"s": 73535,
"text": "Testing techniques for concurrent software programs are extensively focusing on selecting interleaving that expose potentially harmful patterns like race conditions, deadlocks and violation of atomicity. Following are two approaches for testing concurrent software programs −"
},
{
"code": null,
"e": 74059,
"s": 73811,
"text": "This approach aims to explore the space of the interleavings as broadly as possible. Such approaches can adopt a brute-force technique and others adopt partial order reduction technique or heuristic technique to explore the space of interleavings."
},
{
"code": null,
"e": 74433,
"s": 74059,
"text": "Property-driven approaches rely on the observation that concurrency faults are more likely to occur under interleavings that expose specific properties such as suspicious memory access pattern. Different property-driven approaches target different faults like race conditions, deadlocks and violation of atomicity, which further depends on one or other specific properties."
},
{
"code": null,
"e": 74569,
"s": 74433,
"text": "Test Strategy is also known as test approach. The strategy defines how testing would be carried out. Test approach has two techniques −"
},
{
"code": null,
"e": 74714,
"s": 74569,
"text": "An approach in which the test design process is initiated as early as possible in order to find and fix the defects before the build is created."
},
{
"code": null,
"e": 74811,
"s": 74714,
"text": "An approach in which the testing does not start until the completion of the development process."
},
{
"code": null,
"e": 74984,
"s": 74811,
"text": "Before applying any test strategy or approach on python program, we must have a basic idea about the kind of errors a software program may have. The errors are as follows −"
},
{
"code": null,
"e": 75278,
"s": 74984,
"text": "During program development, there can be many small errors. The errors are mostly due to typing mistakes. For example, missing colon or a wrong spelling of a keyword, etc. Such errors are due to the mistake in program syntax and not in logic. Hence, these errors are called syntactical errors."
},
{
"code": null,
"e": 75514,
"s": 75278,
"text": "The semantic errors are also called logical errors. If there is a logical or semantic error in software program then the statement will compile and run correctly but it will not give the desired output because the logic is not correct."
},
{
"code": null,
"e": 75988,
"s": 75514,
"text": "This is one of the most used testing strategies for testing python programs. This strategy is used for testing units or components of the code. By units or components, we mean classes or functions of the code. Unit testing simplifies the testing of large programming systems by testing “small” units. With the help of the above concept, unit testing may be defined as a method where individual units of source code are tested to determine if they return the desired output."
},
{
"code": null,
"e": 76083,
"s": 75988,
"text": "In our subsequent sections, we will learn about the different Python modules for unit testing."
},
{
"code": null,
"e": 76382,
"s": 76083,
"text": "The very first module for unit testing is the unittest module. It is inspired by JUnit and by default included in Python3.6. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework."
},
{
"code": null,
"e": 76454,
"s": 76382,
"text": "Following are a few important concepts supported by the unittest module"
},
{
"code": null,
"e": 76667,
"s": 76454,
"text": "It is used to set up a test so that it can be run before starting the test and tear down after the finish of test. It may involve creation of temporary database, directories, etc. needed before starting the test."
},
{
"code": null,
"e": 76904,
"s": 76667,
"text": "The test case checks whether a required response is coming from the specific set of inputs or not. The unittest module includes a base class named TestCase which can be used to create new test cases. It includes two by default methods −"
},
{
"code": null,
"e": 77042,
"s": 76904,
"text": "setUp() − a hook method for setting up the test fixture before exercising it. This is called before calling the implemented test methods."
},
{
"code": null,
"e": 77180,
"s": 77042,
"text": "setUp() − a hook method for setting up the test fixture before exercising it. This is called before calling the implemented test methods."
},
{
"code": null,
"e": 77281,
"s": 77180,
"text": "tearDown( − a hook method for deconstructing the class fixture after running all tests in the class."
},
{
"code": null,
"e": 77382,
"s": 77281,
"text": "tearDown( − a hook method for deconstructing the class fixture after running all tests in the class."
},
{
"code": null,
"e": 77437,
"s": 77382,
"text": "It is a collection of test suites, test cases or both."
},
{
"code": null,
"e": 77593,
"s": 77437,
"text": "It controls the running of the test cases or suits and provides the outcome to the user. It may use GUI or simple text interface for providing the outcome."
},
{
"code": null,
"e": 77601,
"s": 77593,
"text": "Example"
},
{
"code": null,
"e": 78169,
"s": 77601,
"text": "The following Python program uses the unittest module to test a module named Fibonacci. The program helps in calculating the Fibonacci series of a number. In this example, we have created a class named Fibo_test, to define the test cases by using different methods. These methods are inherited from unittest.TestCase. We are using two by default methods – setUp() and tearDown(). We also define the testfibocal method. The name of the test must be started with the letter test. In the final block, unittest.main() provides a command-line interface to the test script."
},
{
"code": null,
"e": 78715,
"s": 78169,
"text": "import unittest\ndef fibonacci(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n return a\nclass Fibo_Test(unittest.TestCase):\n def setUp(self):\n print(\"This is run before our tests would be executed\")\n def tearDown(self):\n print(\"This is run after the completion of execution of our tests\")\n\n def testfibocal(self):\n self.assertEqual(fib(0), 0)\n self.assertEqual(fib(1), 1)\n self.assertEqual(fib(5), 5)\n self.assertEqual(fib(10), 55)\n self.assertEqual(fib(20), 6765)\n\nif __name__ == \"__main__\":\n unittest.main()"
},
{
"code": null,
"e": 78806,
"s": 78715,
"text": "When run from the command line, the above script produces an output that looks like this −"
},
{
"code": null,
"e": 79008,
"s": 78806,
"text": "This runs before our tests would be executed.\nThis runs after the completion of execution of our tests.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.006s\nOK\n"
},
{
"code": null,
"e": 79105,
"s": 79008,
"text": "Now, to make it clearer, we are changing our code which helped in defining the Fibonacci module."
},
{
"code": null,
"e": 79155,
"s": 79105,
"text": "Consider the following code block as an example −"
},
{
"code": null,
"e": 79241,
"s": 79155,
"text": "def fibonacci(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n return a"
},
{
"code": null,
"e": 79299,
"s": 79241,
"text": "A few changes to the code block are made as shown below −"
},
{
"code": null,
"e": 79385,
"s": 79299,
"text": "def fibonacci(n):\n a, b = 1, 1\n for i in range(n):\n a, b = b, a + b\n return a"
},
{
"code": null,
"e": 79473,
"s": 79385,
"text": "Now, after running the script with the changed code, we will get the following output −"
},
{
"code": null,
"e": 80011,
"s": 79473,
"text": "This runs before our tests would be executed.\nThis runs after the completion of execution of our tests.\nF\n======================================================================\nFAIL: testCalculation (__main__.Fibo_Test)\n----------------------------------------------------------------------\nTraceback (most recent call last):\nFile \"unitg.py\", line 15, in testCalculation\nself.assertEqual(fib(0), 0)\nAssertionError: 1 != 0\n----------------------------------------------------------------------\nRan 1 test in 0.007s\n\nFAILED (failures = 1)\n"
},
{
"code": null,
"e": 80089,
"s": 80011,
"text": "The above output shows that the module has failed to give the desired output."
},
{
"code": null,
"e": 80437,
"s": 80089,
"text": "The docktest module also helps in unit testing. It also comes prepackaged with python. It is easier to use than the unittest module. The unittest module is more suitable for complex tests. For using the doctest module, we need to import it. The docstring of the corresponding function must have interactive python session along with their outputs."
},
{
"code": null,
"e": 80565,
"s": 80437,
"text": "If everything is fine in our code then there will be no output from the docktest module; otherwise, it will provide the output."
},
{
"code": null,
"e": 80715,
"s": 80565,
"text": "The following Python example uses the docktest module to test a module named Fibonacci , which helps in calculating the Fibonacci series of a number."
},
{
"code": null,
"e": 81034,
"s": 80715,
"text": "import doctest\ndef fibonacci(n):\n \"\"\"\n Calculates the Fibonacci number\n\n >>> fibonacci(0)\n 0\n >>> fibonacci(1)\n 1\n >>> fibonacci(10)\n 55\n >>> fibonacci(20)\n 6765\n >>>\n\n \"\"\"\n a, b = 1, 1\n for i in range(n):\n a, b = b, a + b\n return a\n if __name__ == \"__main__\":\n doctest.testmod()"
},
{
"code": null,
"e": 81292,
"s": 81034,
"text": "We can see that the docstring of the corresponding function named fib had interactive python session along with the outputs. If our code is fine then there would be no output from the doctest module. But to see how it works we can run it with the –v option."
},
{
"code": null,
"e": 81661,
"s": 81292,
"text": "(base) D:\\ProgramData>python dock_test.py -v\nTrying:\n fibonacci(0)\nExpecting:\n 0\nok\nTrying:\n fibonacci(1)\nExpecting:\n 1\nok\nTrying:\n fibonacci(10)\nExpecting:\n 55\nok\nTrying:\n fibonacci(20)\nExpecting:\n 6765\nok\n1 items had no tests:\n __main__\n1 items passed all tests:\n4 tests in __main__.fibonacci\n4 tests in 2 items.\n4 passed and 0 failed.\nTest passed."
},
{
"code": null,
"e": 81735,
"s": 81661,
"text": "Now, we will change the code that helped in defining the Fibonacci module"
},
{
"code": null,
"e": 81785,
"s": 81735,
"text": "Consider the following code block as an example −"
},
{
"code": null,
"e": 81871,
"s": 81785,
"text": "def fibonacci(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n return a"
},
{
"code": null,
"e": 81921,
"s": 81871,
"text": "The following code block helps with the changes −"
},
{
"code": null,
"e": 82007,
"s": 81921,
"text": "def fibonacci(n):\n a, b = 1, 1\n for i in range(n):\n a, b = b, a + b\n return a"
},
{
"code": null,
"e": 82122,
"s": 82007,
"text": "After running the script even without the –v option, with the changed code, we will get the output as shown below."
},
{
"code": null,
"e": 82858,
"s": 82122,
"text": "(base) D:\\ProgramData>python dock_test.py\n**********************************************************************\nFile \"unitg.py\", line 6, in __main__.fibonacci\nFailed example:\n fibonacci(0)\nExpected:\n 0\nGot:\n 1\n**********************************************************************\nFile \"unitg.py\", line 10, in __main__.fibonacci\nFailed example:\n fibonacci(10)\nExpected:\n 55\nGot:\n 89\n**********************************************************************\nFile \"unitg.py\", line 12, in __main__.fibonacci\nFailed example:\n fibonacci(20)\nExpected:\n 6765\nGot:\n 10946\n**********************************************************************\n1 items had failures:\n 3 of 4 in __main__.fibonacci\n***Test Failed*** 3 failures.\n"
},
{
"code": null,
"e": 82919,
"s": 82858,
"text": "We can see in the above output that three tests have failed."
},
{
"code": null,
"e": 83032,
"s": 82919,
"text": "In this chapter, we will learn how to debug thread applications. We will also learn the importance of debugging."
},
{
"code": null,
"e": 83451,
"s": 83032,
"text": "In computer programming, debugging is the process of finding and removing the bugs, errors and abnormalities from computer program. This process starts as soon as the code is written and continues in successive stages as code is combined with other units of programming to form a software product. Debugging is part of the software testing process and is an integral part of the entire software development life cycle."
},
{
"code": null,
"e": 83706,
"s": 83451,
"text": "The Python debugger or the pdb is part of the Python standard library. It is a good fallback tool for tracking down hard-to-find bugs and allows us to fix faulty code quickly and reliably. Followings are the two most important tasks of the pdp debugger −"
},
{
"code": null,
"e": 83764,
"s": 83706,
"text": "It allows us to check the values of variables at runtime."
},
{
"code": null,
"e": 83819,
"s": 83764,
"text": "We can step through the code and set breakpoints also."
},
{
"code": null,
"e": 83868,
"s": 83819,
"text": "We can work with pdb in the following two ways −"
},
{
"code": null,
"e": 83936,
"s": 83868,
"text": "Through the command-line; this is also called postmortem debugging."
},
{
"code": null,
"e": 83966,
"s": 83936,
"text": "By interactively running pdb."
},
{
"code": null,
"e": 84097,
"s": 83966,
"text": "For working with the Python debugger, we need to use the following code at the location where we want to break into the debugger −"
},
{
"code": null,
"e": 84125,
"s": 84097,
"text": "import pdb;\npdb.set_trace()"
},
{
"code": null,
"e": 84196,
"s": 84125,
"text": "Consider the following commands to work with pdb through command-line."
},
{
"code": null,
"e": 84204,
"s": 84196,
"text": "h(help)"
},
{
"code": null,
"e": 84212,
"s": 84204,
"text": "d(down)"
},
{
"code": null,
"e": 84218,
"s": 84212,
"text": "u(up)"
},
{
"code": null,
"e": 84227,
"s": 84218,
"text": "b(break)"
},
{
"code": null,
"e": 84237,
"s": 84227,
"text": "cl(clear)"
},
{
"code": null,
"e": 84246,
"s": 84237,
"text": "l(list))"
},
{
"code": null,
"e": 84255,
"s": 84246,
"text": "n(next))"
},
{
"code": null,
"e": 84267,
"s": 84255,
"text": "c(continue)"
},
{
"code": null,
"e": 84275,
"s": 84267,
"text": "s(step)"
},
{
"code": null,
"e": 84286,
"s": 84275,
"text": "r(return))"
},
{
"code": null,
"e": 84295,
"s": 84286,
"text": "b(break)"
},
{
"code": null,
"e": 84363,
"s": 84295,
"text": "Following is a demo of the h(help) command of the Python debugger −"
},
{
"code": null,
"e": 85114,
"s": 84363,
"text": "import pdb\n\npdb.set_trace()\n--Call--\n>d:\\programdata\\lib\\site-packages\\ipython\\core\\displayhook.py(247)__call__()\n-> def __call__(self, result = None):\n(Pdb) h\n\nDocumented commands (type help <topic>):\n========================================\nEOF c d h list q rv undisplay\na cl debug help ll quit s unt\nalias clear disable ignore longlist r source until\nargs commands display interact n restart step up\nb condition down j next return tbreak w\nbreak cont enable jump p retval u whatis\nbt continue exit l pp run unalias where\n\nMiscellaneous help topics:\n==========================\nexec pdb"
},
{
"code": null,
"e": 85230,
"s": 85114,
"text": "While working with Python debugger, we can set the breakpoint anywhere in the script by using the following lines −"
},
{
"code": null,
"e": 85258,
"s": 85230,
"text": "import pdb;\npdb.set_trace()"
},
{
"code": null,
"e": 85529,
"s": 85258,
"text": "After setting the breakpoint, we can run the script normally. The script will execute until a certain point; until where a line has been set. Consider the following example where we will run the script by using the above-mentioned lines at various places in the script −"
},
{
"code": null,
"e": 85619,
"s": 85529,
"text": "import pdb;\na = \"aaa\"\npdb.set_trace()\nb = \"bbb\"\nc = \"ccc\"\nfinal = a + b + c\nprint (final)"
},
{
"code": null,
"e": 85736,
"s": 85619,
"text": "When the above script is run, it will execute the program till a = “aaa”, we can check this in the following output."
},
{
"code": null,
"e": 85933,
"s": 85736,
"text": "--Return--\n> <ipython-input-7-8a7d1b5cc854>(3)<module>()->None\n-> pdb.set_trace()\n(Pdb) p a\n'aaa'\n(Pdb) p b\n*** NameError: name 'b' is not defined\n(Pdb) p c\n*** NameError: name 'c' is not defined\n"
},
{
"code": null,
"e": 86092,
"s": 85933,
"text": "After using the command ‘p(print)’ in pdb, this script is only printing ‘aaa’. This is followed by an error because we have set the breakpoint till a = \"aaa\"."
},
{
"code": null,
"e": 86192,
"s": 86092,
"text": "Similarly, we can run the script by changing the breakpoints and see the difference in the output −"
},
{
"code": null,
"e": 86282,
"s": 86192,
"text": "import pdb\na = \"aaa\"\nb = \"bbb\"\nc = \"ccc\"\npdb.set_trace()\nfinal = a + b + c\nprint (final)\n"
},
{
"code": null,
"e": 86481,
"s": 86282,
"text": "--Return--\n> <ipython-input-9-a59ef5caf723>(5)<module>()->None\n-> pdb.set_trace()\n(Pdb) p a\n'aaa'\n(Pdb) p b\n'bbb'\n(Pdb) p c\n'ccc'\n(Pdb) p final\n*** NameError: name 'final' is not defined\n(Pdb) exit\n"
},
{
"code": null,
"e": 86570,
"s": 86481,
"text": "In the following script, we are setting the breakpoint in the last line of the program −"
},
{
"code": null,
"e": 86659,
"s": 86570,
"text": "import pdb\na = \"aaa\"\nb = \"bbb\"\nc = \"ccc\"\nfinal = a + b + c\npdb.set_trace()\nprint (final)"
},
{
"code": null,
"e": 86686,
"s": 86659,
"text": "The output is as follows −"
},
{
"code": null,
"e": 86850,
"s": 86686,
"text": "--Return--\n> <ipython-input-11-8019b029997d>(6)<module>()->None\n-> pdb.set_trace()\n(Pdb) p a\n'aaa'\n(Pdb) p b\n'bbb'\n(Pdb) p c\n'ccc'\n(Pdb) p final\n'aaabbbccc'\n(Pdb)\n"
},
{
"code": null,
"e": 86951,
"s": 86850,
"text": "In this chapter, we will learn how benchmarking and profiling help in addressing performance issues."
},
{
"code": null,
"e": 87253,
"s": 86951,
"text": "Suppose we had written a code and it is giving the desired result too but what if we want to run this code a bit faster because the needs have changed. In this case, we need to find out what parts of our code are slowing down the entire program. In this case, benchmarking and profiling can be useful."
},
{
"code": null,
"e": 87609,
"s": 87253,
"text": "Benchmarking aims at evaluating something by comparison with a standard. However, the question that arises here is that what would be the benchmarking and why we need it in case of software programming. Benchmarking the code means how fast the code is executing and where the bottleneck is. One major reason for benchmarking is that it optimizes the code."
},
{
"code": null,
"e": 88029,
"s": 87609,
"text": "If we talk about the working of benchmarking, we need to start by benchmarking the whole program as one current state then we can combine micro benchmarks and then decompose a program into smaller programs. In order to find the bottlenecks within our program and optimize it. In other words, we can understand it as breaking the big and hard problem into series of smaller and a bit easier problems for optimizing them."
},
{
"code": null,
"e": 88229,
"s": 88029,
"text": "In Python, we have a by default module for benchmarking which is called timeit. With the help of the timeit module, we can measure the performance of small bit of Python code within our main program."
},
{
"code": null,
"e": 88388,
"s": 88229,
"text": "In the following Python script, we are importing the timeit module, which further measures the time taken to execute two functions – functionA and functionB −"
},
{
"code": null,
"e": 88814,
"s": 88388,
"text": "import timeit\nimport time\ndef functionA():\n print(\"Function A starts the execution:\")\n print(\"Function A completes the execution:\")\ndef functionB():\n print(\"Function B starts the execution\")\n print(\"Function B completes the execution\")\nstart_time = timeit.default_timer()\nfunctionA()\nprint(timeit.default_timer() - start_time)\nstart_time = timeit.default_timer()\nfunctionB()\nprint(timeit.default_timer() - start_time)"
},
{
"code": null,
"e": 88915,
"s": 88814,
"text": "After running the above script, we will get the execution time of both the functions as shown below."
},
{
"code": null,
"e": 89096,
"s": 88915,
"text": "Function A starts the execution:\nFunction A completes the execution:\n0.0014599495514175942\nFunction B starts the execution\nFunction B completes the execution\n0.0017024724827479076\n"
},
{
"code": null,
"e": 89282,
"s": 89096,
"text": "In Python, we can create our own timer, which will act just like the timeit module. It can be done with the help of the decorator function. Following is an example of the custom timer −"
},
{
"code": null,
"e": 89806,
"s": 89282,
"text": "import random\nimport time\n\ndef timer_func(func):\n\n def function_timer(*args, **kwargs):\n start = time.time()\n value = func(*args, **kwargs)\n end = time.time()\n runtime = end - start\n msg = \"{func} took {time} seconds to complete its execution.\"\n print(msg.format(func = func.__name__,time = runtime))\n return value\n return function_timer\n\n@timer_func\ndef Myfunction():\n for x in range(5):\n sleep_time = random.choice(range(1,3))\n time.sleep(sleep_time)\n\nif __name__ == '__main__':\n Myfunction()"
},
{
"code": null,
"e": 90246,
"s": 89806,
"text": "The above python script helps in importing random time modules. We have created the timer_func() decorator function. This has the function_timer() function inside it. Now, the nested function will grab the time before calling the passed in function. Then it waits for the function to return and grabs the end time. In this way, we can finally make python script print the execution time. The script will generate the output as shown below."
},
{
"code": null,
"e": 90316,
"s": 90246,
"text": "Myfunction took 8.000457763671875 seconds to complete its execution.\n"
},
{
"code": null,
"e": 90637,
"s": 90316,
"text": "Sometimes the programmer wants to measure some attributes like the use of memory, time complexity or usage of particular instructions about the programs to measure the real capability of that program. Such kind of measuring about program is called profiling. Profiling uses dynamic program analysis to do such measuring."
},
{
"code": null,
"e": 90729,
"s": 90637,
"text": "In the subsequent sections, we will learn about the different Python Modules for Profiling."
},
{
"code": null,
"e": 91102,
"s": 90729,
"text": "cProfile is a Python built-in module for profiling. The module is a C-extension with reasonable overhead that makes it suitable for profiling long-running programs. After running it, it logs all the functions and execution times. It is very powerful but sometimes a bit difficult to interpret and act on. In the following example, we are using cProfile on the code below −"
},
{
"code": null,
"e": 91614,
"s": 91102,
"text": "def increment_global():\n\n global x\n x += 1\n\ndef taskofThread(lock):\n\n for _ in range(50000):\n lock.acquire()\n increment_global()\n lock.release()\n\ndef main():\n global x\n x = 0\n\n lock = threading.Lock()\n\n t1 = threading.Thread(target=taskofThread, args=(lock,))\n t2 = threading.Thread(target= taskofThread, args=(lock,))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n\nif __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))"
},
{
"code": null,
"e": 91740,
"s": 91614,
"text": "The above code is saved in the thread_increment.py file. Now, execute the code with cProfile on the command line as follows −"
},
{
"code": null,
"e": 92350,
"s": 91740,
"text": "(base) D:\\ProgramData>python -m cProfile thread_increment.py\nx = 100000 after Iteration 0\nx = 100000 after Iteration 1\nx = 100000 after Iteration 2\nx = 100000 after Iteration 3\nx = 100000 after Iteration 4\n 3577 function calls (3522 primitive calls) in 1.688 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:103(release)\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:143(__init__)\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:147(__enter__)\n ... ... ... ..."
},
{
"code": null,
"e": 92562,
"s": 92350,
"text": "From the above output, it is clear that cProfile prints out all the 3577 functions called, with the time spent in each and the number of times they have been called. Followings are the columns we got in output −"
},
{
"code": null,
"e": 92603,
"s": 92562,
"text": "ncalls − It is the number of calls made."
},
{
"code": null,
"e": 92644,
"s": 92603,
"text": "ncalls − It is the number of calls made."
},
{
"code": null,
"e": 92704,
"s": 92644,
"text": "tottime − It is the total time spent in the given function."
},
{
"code": null,
"e": 92764,
"s": 92704,
"text": "tottime − It is the total time spent in the given function."
},
{
"code": null,
"e": 92830,
"s": 92764,
"text": "percall − It refers to the quotient of tottime divided by ncalls."
},
{
"code": null,
"e": 92896,
"s": 92830,
"text": "percall − It refers to the quotient of tottime divided by ncalls."
},
{
"code": null,
"e": 93013,
"s": 92896,
"text": "cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions."
},
{
"code": null,
"e": 93130,
"s": 93013,
"text": "cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions."
},
{
"code": null,
"e": 93198,
"s": 93130,
"text": "percall − It is the quotient of cumtime divided by primitive calls."
},
{
"code": null,
"e": 93266,
"s": 93198,
"text": "percall − It is the quotient of cumtime divided by primitive calls."
},
{
"code": null,
"e": 93354,
"s": 93266,
"text": "filename:lineno(function) − It basically provides the respective data of each function."
},
{
"code": null,
"e": 93442,
"s": 93354,
"text": "filename:lineno(function) − It basically provides the respective data of each function."
},
{
"code": null,
"e": 94070,
"s": 93442,
"text": "Suppose we had to create a large number of threads for our multithreaded tasks. It would be computationally most expensive as there can be many performance issues, due to too many threads. A major issue could be in the throughput getting limited. We can solve this problem by creating a pool of threads. A thread pool may be defined as the group of pre-instantiated and idle threads, which stand ready to be given work. Creating thread pool is preferred over instantiating new threads for every task when we need to do large number of tasks. A thread pool can manage concurrent execution of large number of threads as follows −"
},
{
"code": null,
"e": 94155,
"s": 94070,
"text": "If a thread in a thread pool completes its execution then that thread can be reused."
},
{
"code": null,
"e": 94240,
"s": 94155,
"text": "If a thread in a thread pool completes its execution then that thread can be reused."
},
{
"code": null,
"e": 94322,
"s": 94240,
"text": "If a thread is terminated, another thread will be created to replace that thread."
},
{
"code": null,
"e": 94404,
"s": 94322,
"text": "If a thread is terminated, another thread will be created to replace that thread."
},
{
"code": null,
"e": 94763,
"s": 94404,
"text": "Python standard library includes the concurrent.futures module. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes."
},
{
"code": null,
"e": 94867,
"s": 94763,
"text": "In our subsequent sections, we will learn about the different classes of the concurrent.futures module."
},
{
"code": null,
"e": 95026,
"s": 94867,
"text": "Executoris an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses −"
},
{
"code": null,
"e": 95045,
"s": 95026,
"text": "ThreadPoolExecutor"
},
{
"code": null,
"e": 95065,
"s": 95045,
"text": "ProcessPoolExecutor"
},
{
"code": null,
"e": 95289,
"s": 95065,
"text": "It is one of the concrete subclasses of the Executor class. The subclass uses multi-threading and we get a pool of thread for submitting the tasks. This pool assigns tasks to the available threads and schedules them to run."
},
{
"code": null,
"e": 95867,
"s": 95289,
"text": "With the help of concurrent.futures module and its concrete subclass Executor, we can easily create a pool of threads. For this, we need to construct a ThreadPoolExecutor with the number of threads we want in the pool. By default, the number is 5. Then we can submit a task to the thread pool. When we submit() a task, we get back a Future. The Future object has a method called done(), which tells if the future has resolved. With this, a value has been set for that particular future object. When a task finishes, the thread pool executor sets the value to the future object."
},
{
"code": null,
"e": 96207,
"s": 95867,
"text": "from concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\ndef task(message):\n sleep(2)\n return message\n\ndef main():\n executor = ThreadPoolExecutor(5)\n future = executor.submit(task, (\"Completed\"))\n print(future.done())\n sleep(2)\n print(future.done())\n print(future.result())\nif __name__ == '__main__':\nmain()"
},
{
"code": null,
"e": 96229,
"s": 96207,
"text": "False\nTrue\nCompleted\n"
},
{
"code": null,
"e": 96645,
"s": 96229,
"text": "In the above example, a ThreadPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the thread pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it."
},
{
"code": null,
"e": 96935,
"s": 96645,
"text": "Another way to instantiate ThreadPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code −"
},
{
"code": null,
"e": 96988,
"s": 96935,
"text": "with ThreadPoolExecutor(max_workers = 5) as executor"
},
{
"code": null,
"e": 97415,
"s": 96988,
"text": "The following example is borrowed from the Python docs. In this example, first of all the concurrent.futures module has to be imported. Then a function named load_url() is created which will load the requested url. The function then creates ThreadPoolExecutor\nwith the 5 threads in the pool. The ThreadPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it."
},
{
"code": null,
"e": 98169,
"s": 97415,
"text": "import concurrent.futures\nimport urllib.request\n\nURLS = ['http://www.foxnews.com/',\n 'http://www.cnn.com/',\n 'http://europe.wsj.com/',\n 'http://www.bbc.co.uk/',\n 'http://some-made-up-domain.com/']\n\ndef load_url(url, timeout):\n with urllib.request.urlopen(url, timeout = timeout) as conn:\n return conn.read()\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor:\n\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as exc:\n print('%r generated an exception: %s' % (url, exc))\n else:\n print('%r page is %d bytes' % (url, len(data)))"
},
{
"code": null,
"e": 98228,
"s": 98169,
"text": "Following would be the output of the above Python script −"
},
{
"code": null,
"e": 98517,
"s": 98228,
"text": "'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>\n'http://www.foxnews.com/' page is 229313 bytes\n'http://www.cnn.com/' page is 168933 bytes\n'http://www.bbc.co.uk/' page is 283893 bytes\n'http://europe.wsj.com/' page is 938109 bytes\n"
},
{
"code": null,
"e": 98878,
"s": 98517,
"text": "The Python map() function is widely used in a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to out ThreadPoolExecutor. Consider the following example of Python script to understand how the function works."
},
{
"code": null,
"e": 98993,
"s": 98878,
"text": "In this example below, the map function is used to apply the square() function to every value in the values array."
},
{
"code": null,
"e": 99331,
"s": 98993,
"text": "from concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import as_completed\nvalues = [2,3,4,5]\ndef square(n):\n return n * n\ndef main():\n with ThreadPoolExecutor(max_workers = 3) as executor:\n results = executor.map(square, values)\nfor result in results:\n print(result)\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 99388,
"s": 99331,
"text": "The above Python script generates the following output −"
},
{
"code": null,
"e": 99399,
"s": 99388,
"text": "4\n9\n16\n25\n"
},
{
"code": null,
"e": 99748,
"s": 99399,
"text": "Pool of process can be created and used in the same way as we have created and used the pool of threads. Process pool can be defined as the group of pre-instantiated and idle processes, which stand ready to be given work. Creating process pool is preferred over instantiating new processes for every task when we need to do a large number of tasks."
},
{
"code": null,
"e": 100111,
"s": 99748,
"text": "Python standard library has a module called the concurrent.futures. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes."
},
{
"code": null,
"e": 100214,
"s": 100111,
"text": "In our subsequent sections, we will look at the different subclasses of the concurrent.futures module."
},
{
"code": null,
"e": 100374,
"s": 100214,
"text": "Executor is an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses −"
},
{
"code": null,
"e": 100393,
"s": 100374,
"text": "ThreadPoolExecutor"
},
{
"code": null,
"e": 100413,
"s": 100393,
"text": "ProcessPoolExecutor"
},
{
"code": null,
"e": 100632,
"s": 100413,
"text": "It is one of the concrete subclasses of the Executor class. It uses multi-processing and we get a pool of processes for submitting the tasks. This pool assigns tasks to the available processes and schedule them to run."
},
{
"code": null,
"e": 100946,
"s": 100632,
"text": "With the help of the concurrent.futures module and its concrete subclass Executor, we can easily create a pool of process. For this, we need to construct a ProcessPoolExecutor with the number of processes we want in the pool. By default, the number is 5. This is followed by submitting a task to the process pool."
},
{
"code": null,
"e": 101124,
"s": 100946,
"text": "We will now consider the same example that we used while creating thread pool, the only difference being that now we will use ProcessPoolExecutor instead of ThreadPoolExecutor ."
},
{
"code": null,
"e": 101466,
"s": 101124,
"text": "from concurrent.futures import ProcessPoolExecutor\nfrom time import sleep\ndef task(message):\n sleep(2)\n return message\n\ndef main():\n executor = ProcessPoolExecutor(5)\n future = executor.submit(task, (\"Completed\"))\n print(future.done())\n sleep(2)\n print(future.done())\n print(future.result())\nif __name__ == '__main__':\nmain()"
},
{
"code": null,
"e": 101489,
"s": 101466,
"text": "False\nFalse\nCompleted\n"
},
{
"code": null,
"e": 101907,
"s": 101489,
"text": "In the above example, a ProcessPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the process pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it."
},
{
"code": null,
"e": 102198,
"s": 101907,
"text": "Another way to instantiate ProcessPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code −"
},
{
"code": null,
"e": 102253,
"s": 102198,
"text": "with ProcessPoolExecutor(max_workers = 5) as executor\n"
},
{
"code": null,
"e": 102721,
"s": 102253,
"text": "For better understanding, we are taking the same example as used while creating thread pool. In this example, we need to start by importing the concurrent.futures module. Then a function named load_url() is created which will load the requested url. The ProcessPoolExecutor is then created with the 5 number of threads in the pool. The ProcessPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it."
},
{
"code": null,
"e": 103607,
"s": 102721,
"text": "import concurrent.futures\nfrom concurrent.futures import ProcessPoolExecutor\nimport urllib.request\n\nURLS = ['http://www.foxnews.com/',\n 'http://www.cnn.com/',\n 'http://europe.wsj.com/',\n 'http://www.bbc.co.uk/',\n 'http://some-made-up-domain.com/']\n\ndef load_url(url, timeout):\n with urllib.request.urlopen(url, timeout = timeout) as conn:\n return conn.read()\n\ndef main():\n with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as exc:\n print('%r generated an exception: %s' % (url, exc))\n else:\n print('%r page is %d bytes' % (url, len(data)))\n\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 103668,
"s": 103607,
"text": "The above Python script will generate the following output −"
},
{
"code": null,
"e": 103957,
"s": 103668,
"text": "'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>\n'http://www.foxnews.com/' page is 229476 bytes\n'http://www.cnn.com/' page is 165323 bytes\n'http://www.bbc.co.uk/' page is 284981 bytes\n'http://europe.wsj.com/' page is 967575 bytes\n"
},
{
"code": null,
"e": 104309,
"s": 103957,
"text": "The Python map() function is widely used to perform a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to the ProcessPoolExecutor. Consider the following example of Python script to understand this."
},
{
"code": null,
"e": 104533,
"s": 104309,
"text": "We will consider the same example that we used while creating thread pool using the Executor.map() function. In the example givenbelow, the map function is used to apply square() function to every value in the values array."
},
{
"code": null,
"e": 104876,
"s": 104533,
"text": "from concurrent.futures import ProcessPoolExecutor\nfrom concurrent.futures import as_completed\nvalues = [2,3,4,5]\ndef square(n):\n return n * n\ndef main():\n with ProcessPoolExecutor(max_workers = 3) as executor:\n results = executor.map(square, values)\n for result in results:\n print(result)\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 104935,
"s": 104876,
"text": "The above Python script will generate the following output"
},
{
"code": null,
"e": 104946,
"s": 104935,
"text": "4\n9\n16\n25\n"
},
{
"code": null,
"e": 105217,
"s": 104946,
"text": "Now that we have studied about both the Executor classes – ThreadPoolExecutor and ProcessPoolExecutor, we need to know when to use which executor. We need to choose ProcessPoolExecutor in case of CPU-bound workloads and ThreadPoolExecutor in case of I/O-bound workloads."
},
{
"code": null,
"e": 105465,
"s": 105217,
"text": "If we use ProcessPoolExecutor, then we do not need to worry about GIL because it uses multiprocessing. Moreover, the execution time will be less when compared to ThreadPoolExecution. Consider the following Python script example to understand this."
},
{
"code": null,
"e": 105970,
"s": 105465,
"text": "import time\nimport concurrent.futures\n\nvalue = [8000000, 7000000]\n\ndef counting(n):\n start = time.time()\n while n > 0:\n n -= 1\n return time.time() - start\n\ndef main():\n start = time.time()\n with concurrent.futures.ProcessPoolExecutor() as executor:\n for number, time_taken in zip(value, executor.map(counting, value)):\n print('Start: {} Time taken: {}'.format(number, time_taken))\n print('Total time taken: {}'.format(time.time() - start))\n\nif __name__ == '__main__':\nmain()"
},
{
"code": null,
"e": 106656,
"s": 105970,
"text": "Start: 8000000 Time taken: 1.5509998798370361\nStart: 7000000 Time taken: 1.3259999752044678\nTotal time taken: 2.0840001106262207\n\nExample- Python script with ThreadPoolExecutor:\nimport time\nimport concurrent.futures\n\nvalue = [8000000, 7000000]\n\ndef counting(n):\n start = time.time()\n while n > 0:\n n -= 1\n return time.time() - start\n\ndef main():\n start = time.time()\n with concurrent.futures.ThreadPoolExecutor() as executor:\n for number, time_taken in zip(value, executor.map(counting, value)):\n print('Start: {} Time taken: {}'.format(number, time_taken))\n print('Total time taken: {}'.format(time.time() - start))\n\nif __name__ == '__main__':\nmain()\n"
},
{
"code": null,
"e": 106786,
"s": 106656,
"text": "Start: 8000000 Time taken: 3.8420000076293945\nStart: 7000000 Time taken: 3.6010000705718994\nTotal time taken: 3.8480000495910645\n"
},
{
"code": null,
"e": 106931,
"s": 106786,
"text": "From the outputs of both the programs above, we can see the difference of execution time while using ProcessPoolExecutor and ThreadPoolExecutor."
},
{
"code": null,
"e": 107029,
"s": 106931,
"text": "In this chapter, we will focus more on the comparison between multiprocessing and multithreading."
},
{
"code": null,
"e": 107242,
"s": 107029,
"text": "It is the use of two or more CPUs units within a single computer system. It is the best approach to get the full potential from our hardware by utilizing full number of CPU cores available in our computer system."
},
{
"code": null,
"e": 107454,
"s": 107242,
"text": "It is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads."
},
{
"code": null,
"e": 107529,
"s": 107454,
"text": "The following table shows some of the important differences between them −"
},
{
"code": null,
"e": 108069,
"s": 107529,
"text": "While working with concurrent applications, there is a limitation present in Python called the GIL (Global Interpreter Lock). GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. GIL is the mutex – mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first."
},
{
"code": null,
"e": 108159,
"s": 108069,
"text": "With the use of multiprocessing, we can effectively bypass the limitation caused by GIL −"
},
{
"code": null,
"e": 108297,
"s": 108159,
"text": "By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL."
},
{
"code": null,
"e": 108435,
"s": 108297,
"text": "By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL."
},
{
"code": null,
"e": 108549,
"s": 108435,
"text": "Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time."
},
{
"code": null,
"e": 108663,
"s": 108549,
"text": "Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time."
},
{
"code": null,
"e": 108768,
"s": 108663,
"text": "The following three methods can be used to start a process in Python within the multiprocessing module −"
},
{
"code": null,
"e": 108773,
"s": 108768,
"text": "Fork"
},
{
"code": null,
"e": 108779,
"s": 108773,
"text": "Spawn"
},
{
"code": null,
"e": 108790,
"s": 108779,
"text": "Forkserver"
},
{
"code": null,
"e": 109178,
"s": 108790,
"text": "Fork command is a standard command found in UNIX. It is used to create new processes called child processes. This child process runs concurrently with the process called the parent process. These child processes are also identical to their parent processes and inherit all of the resources available to the parent. The following system calls are used while creating a process with Fork −"
},
{
"code": null,
"e": 109286,
"s": 109178,
"text": "fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>"
},
{
"code": null,
"e": 109394,
"s": 109286,
"text": "fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>"
},
{
"code": null,
"e": 109474,
"s": 109394,
"text": "getpid() − This system call returns the process ID(PID) of the calling process."
},
{
"code": null,
"e": 109554,
"s": 109474,
"text": "getpid() − This system call returns the process ID(PID) of the calling process."
},
{
"code": null,
"e": 109698,
"s": 109554,
"text": "The following Python script example will help you understabd how to create a new child process and get the PIDs of child and parent processes −"
},
{
"code": null,
"e": 109885,
"s": 109698,
"text": "import os\n\ndef child():\n n = os.fork()\n \n if n > 0:\n print(\"PID of Parent process is : \", os.getpid())\n\n else:\n print(\"PID of Child process is : \", os.getpid())\nchild()"
},
{
"code": null,
"e": 109951,
"s": 109885,
"text": "PID of Parent process is : 25989\nPID of Child process is : 25990\n"
},
{
"code": null,
"e": 110225,
"s": 109951,
"text": "Spawn means to start something new. Hence, spawning a process means the creation of a new process by a parent process. The parent process continues its execution asynchronously or waits until the child process ends its execution. Follow these steps for spawning a process −"
},
{
"code": null,
"e": 110259,
"s": 110225,
"text": "Importing multiprocessing module."
},
{
"code": null,
"e": 110293,
"s": 110259,
"text": "Importing multiprocessing module."
},
{
"code": null,
"e": 110322,
"s": 110293,
"text": "Creating the object process."
},
{
"code": null,
"e": 110351,
"s": 110322,
"text": "Creating the object process."
},
{
"code": null,
"e": 110408,
"s": 110351,
"text": "Starting the process activity by calling start() method."
},
{
"code": null,
"e": 110465,
"s": 110408,
"text": "Starting the process activity by calling start() method."
},
{
"code": null,
"e": 110548,
"s": 110465,
"text": "Waiting until the process has finished its work and exit by calling join() method."
},
{
"code": null,
"e": 110631,
"s": 110548,
"text": "Waiting until the process has finished its work and exit by calling join() method."
},
{
"code": null,
"e": 110704,
"s": 110631,
"text": "The following example of Python script helps in spawning three processes"
},
{
"code": null,
"e": 110989,
"s": 110704,
"text": "import multiprocessing\n\ndef spawn_process(i):\n print ('This is process: %s' %i)\n return\n\nif __name__ == '__main__':\n Process_jobs = []\n for i in range(3):\n p = multiprocessing.Process(target = spawn_process, args = (i,))\n Process_jobs.append(p)\n p.start()\n p.join()"
},
{
"code": null,
"e": 111047,
"s": 110989,
"text": "This is process: 0\nThis is process: 1\nThis is process: 2\n"
},
{
"code": null,
"e": 111260,
"s": 111047,
"text": "Forkserver mechanism is only available on those selected UNIX platforms that support passing the file descriptors over Unix Pipes. Consider the following points to understand the working of Forkserver mechanism −"
},
{
"code": null,
"e": 111341,
"s": 111260,
"text": "A server is instantiated on using Forkserver mechanism for starting new process."
},
{
"code": null,
"e": 111422,
"s": 111341,
"text": "A server is instantiated on using Forkserver mechanism for starting new process."
},
{
"code": null,
"e": 111516,
"s": 111422,
"text": "The server then receives the command and handles all the requests for creating new processes."
},
{
"code": null,
"e": 111610,
"s": 111516,
"text": "The server then receives the command and handles all the requests for creating new processes."
},
{
"code": null,
"e": 111728,
"s": 111610,
"text": "For creating a new process, our python program will send a request to Forkserver and it will create a process for us."
},
{
"code": null,
"e": 111846,
"s": 111728,
"text": "For creating a new process, our python program will send a request to Forkserver and it will create a process for us."
},
{
"code": null,
"e": 111908,
"s": 111846,
"text": "At last, we can use this new created process in our programs."
},
{
"code": null,
"e": 111970,
"s": 111908,
"text": "At last, we can use this new created process in our programs."
},
{
"code": null,
"e": 112438,
"s": 111970,
"text": "Python multiprocessing module allows us to have daemon processes through its daemonic option. Daemon processes or the processes that are running in the background follow similar concept as the daemon threads. To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed."
},
{
"code": null,
"e": 112687,
"s": 112438,
"text": "Here, we are using the same example as used in the daemon threads. The only difference is the change of module from multithreading to multiprocessing and setting the daemonic flag to true. However, there would be a change in output as shown below −"
},
{
"code": null,
"e": 113183,
"s": 112687,
"text": "import multiprocessing\nimport time\n\ndef nondaemonProcess():\n print(\"starting my Process\")\n time.sleep(8)\n print(\"ending my Process\")\ndef daemonProcess():\n while True:\n print(\"Hello\")\n time.sleep(2)\nif __name__ == '__main__':\n nondaemonProcess = multiprocessing.Process(target = nondaemonProcess)\n daemonProcess = multiprocessing.Process(target = daemonProcess)\n daemonProcess.daemon = True\n nondaemonProcess.daemon = False\n daemonProcess.start()\n nondaemonProcess.start()"
},
{
"code": null,
"e": 113222,
"s": 113183,
"text": "starting my Process\nending my Process\n"
},
{
"code": null,
"e": 113476,
"s": 113222,
"text": "The output is different when compared to the one generated by daemon threads, because the process in no daemon mode have an output. Hence, the daemonic process ends automatically after the main programs end to avoid the persistence of running processes."
},
{
"code": null,
"e": 113707,
"s": 113476,
"text": "We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution."
},
{
"code": null,
"e": 114060,
"s": 113707,
"text": "import multiprocessing\nimport time\ndef Child_process():\n print ('Starting function')\n time.sleep(5)\n print ('Finished function')\nP = multiprocessing.Process(target = Child_process)\nP.start()\nprint(\"My Process has terminated, terminating main thread\")\nprint(\"Terminating Child Process\")\nP.terminate()\nprint(\"Child Process successfully terminated\")"
},
{
"code": null,
"e": 114176,
"s": 114060,
"text": "My Process has terminated, terminating main thread\nTerminating Child Process\nChild Process successfully terminated\n"
},
{
"code": null,
"e": 114398,
"s": 114176,
"text": "The output shows that the program terminates before the execution of child process that has been created with the help of the Child_process() function. This implies that the child process has been terminated successfully."
},
{
"code": null,
"e": 114572,
"s": 114398,
"text": "Every process in the operating system is having process identity known as PID. In Python, we can find out the PID of current process with the help of the following command −"
},
{
"code": null,
"e": 114640,
"s": 114572,
"text": "import multiprocessing\nprint(multiprocessing.current_process().pid)"
},
{
"code": null,
"e": 114752,
"s": 114640,
"text": "The following example of Python script helps find out the PID of main process as well as PID of child process −"
},
{
"code": null,
"e": 115045,
"s": 114752,
"text": "import multiprocessing\nimport time\ndef Child_process():\n print(\"PID of Child Process is: {}\".format(multiprocessing.current_process().pid))\nprint(\"PID of Main process is: {}\".format(multiprocessing.current_process().pid))\nP = multiprocessing.Process(target=Child_process)\nP.start()\nP.join()"
},
{
"code": null,
"e": 115105,
"s": 115045,
"text": "PID of Main process is: 9401\nPID of Child Process is: 9402\n"
},
{
"code": null,
"e": 115340,
"s": 115105,
"text": "We can create threads by sub-classing the threading.Thread class. In addition, we can also create processes by sub-classing the multiprocessing.Process class. For using a process in subclass, we need to consider the following points −"
},
{
"code": null,
"e": 115395,
"s": 115340,
"text": "We need to define a new subclass of the Process class."
},
{
"code": null,
"e": 115450,
"s": 115395,
"text": "We need to define a new subclass of the Process class."
},
{
"code": null,
"e": 115503,
"s": 115450,
"text": "We need to override the _init_(self [,args] ) class."
},
{
"code": null,
"e": 115556,
"s": 115503,
"text": "We need to override the _init_(self [,args] ) class."
},
{
"code": null,
"e": 115639,
"s": 115556,
"text": "We need to override the of the run(self [,args] ) method to implement what Process"
},
{
"code": null,
"e": 115722,
"s": 115639,
"text": "We need to override the of the run(self [,args] ) method to implement what Process"
},
{
"code": null,
"e": 115782,
"s": 115722,
"text": "We need to start the process by invoking thestart() method."
},
{
"code": null,
"e": 115842,
"s": 115782,
"text": "We need to start the process by invoking thestart() method."
},
{
"code": null,
"e": 116116,
"s": 115842,
"text": "import multiprocessing\nclass MyProcess(multiprocessing.Process):\n def run(self):\n print ('called run method in process: %s' %self.name)\n return\nif __name__ == '__main__':\n jobs = []\n for i in range(5):\n P = MyProcess()\n jobs.append(P)\n P.start()\n P.join()"
},
{
"code": null,
"e": 116327,
"s": 116116,
"text": "called run method in process: MyProcess-1\ncalled run method in process: MyProcess-2\ncalled run method in process: MyProcess-3\ncalled run method in process: MyProcess-4\ncalled run method in process: MyProcess-5\n"
},
{
"code": null,
"e": 116569,
"s": 116327,
"text": "If we talk about simple parallel processing tasks in our Python applications, then multiprocessing module provide us the Pool class. The following methods of Pool class can be used to spin up number of child processes within our main program"
},
{
"code": null,
"e": 116674,
"s": 116569,
"text": "This method is similar to the.submit()method of .ThreadPoolExecutor.It blocks until the result is ready."
},
{
"code": null,
"e": 116902,
"s": 116674,
"text": "When we need parallel execution of our tasks then we need to use theapply_async()method to submit tasks to the pool. It is an asynchronous operation that will not lock the main thread until all the child processes are executed."
},
{
"code": null,
"e": 117125,
"s": 116902,
"text": "Just like the apply() method, it also blocks until the result is ready. It is equivalent to the built-in map() function that splits the iterable data in a number of chunks and submits to the process pool as separate tasks."
},
{
"code": null,
"e": 117401,
"s": 117125,
"text": "It is a variant of the map() method as apply_async() is to the apply() method. It returns a result object. When the result becomes ready, a callable is applied to it. The callable must be completed immediately; otherwise, the thread that handles the results will get blocked."
},
{
"code": null,
"e": 117787,
"s": 117401,
"text": "The following example will help you implement a process pool for performing parallel execution. A simple calculation of square of number has been performed by applying the square() function through the multiprocessing.Pool method. Then pool.map() has been used to submit the 5, because input is a list of integers from 0 to 4. The result would be stored in p_outputs and it is printed."
},
{
"code": null,
"e": 118037,
"s": 117787,
"text": "def square(n):\n result = n*n\n return result\nif __name__ == '__main__':\n inputs = list(range(5))\n p = multiprocessing.Pool(processes = 4)\n p_outputs = pool.map(function_square, inputs)\n p.close()\n p.join()\n print ('Pool :', p_outputs)"
},
{
"code": null,
"e": 118062,
"s": 118037,
"text": "Pool : [0, 1, 4, 9, 16]\n"
},
{
"code": null,
"e": 118349,
"s": 118062,
"text": "Process intercommunication means the exchange of data between processes. It is necessary to exchange the data between processes for the development of parallel application. Following diagram shows the various communication mechanisms for synchronization between multiple sub processes −"
},
{
"code": null,
"e": 118461,
"s": 118349,
"text": "In this section, we will learn about the various communication mechanisms. The mechanisms are described below −"
},
{
"code": null,
"e": 118753,
"s": 118461,
"text": "Queues can be used with multi-process programs. The Queue class of multiprocessing module is similar to the Queue.Queue class. Hence, the same API can be used. Multiprocessing.Queue provides us a thread and process safe FIFO (first-in first-out) mechanism of communication between processes."
},
{
"code": null,
"e": 118895,
"s": 118753,
"text": "Following is a simple example taken from python official docs on multiprocessing to understand the concept of Queue class of multiprocessing."
},
{
"code": null,
"e": 119141,
"s": 118895,
"text": "from multiprocessing import Process, Queue\nimport queue\nimport random\ndef f(q):\n q.put([42, None, 'hello'])\ndef main():\n q = Queue()\n p = Process(target = f, args = (q,))\n p.start()\n print (q.get())\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 119162,
"s": 119141,
"text": "[42, None, 'hello']\n"
},
{
"code": null,
"e": 119409,
"s": 119162,
"text": "It is a data structure, which is used to communicate between processes in multi-process programs. The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex(two way). It works in the following manner −"
},
{
"code": null,
"e": 119486,
"s": 119409,
"text": "It returns a pair of connection objects that represent the two ends of pipe."
},
{
"code": null,
"e": 119563,
"s": 119486,
"text": "It returns a pair of connection objects that represent the two ends of pipe."
},
{
"code": null,
"e": 119648,
"s": 119563,
"text": "Every object has two methods – send() and recv(), to communicate between processes. "
},
{
"code": null,
"e": 119733,
"s": 119648,
"text": "Every object has two methods – send() and recv(), to communicate between processes. "
},
{
"code": null,
"e": 119879,
"s": 119733,
"text": "Following is a simple example taken from python official docs on multiprocessing to understand the concept of Pipe() function of multiprocessing."
},
{
"code": null,
"e": 120153,
"s": 119879,
"text": "from multiprocessing import Process, Pipe\n\ndef f(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target = f, args = (child_conn,))\n p.start()\n print (parent_conn.recv())\n p.join()"
},
{
"code": null,
"e": 120174,
"s": 120153,
"text": "[42, None, 'hello']\n"
},
{
"code": null,
"e": 120576,
"s": 120174,
"text": "Manager is a class of multiprocessing module that provides a way to coordinate shared information between all its users. A manager object controls a server process, which manages shared objects and allows other processes to manipulate them. In other words, managers provide a way to create data that can be shared between different processes. Following are the different properties of manager object −"
},
{
"code": null,
"e": 120671,
"s": 120576,
"text": "The main property of manager is to control a server process, which manages the shared objects."
},
{
"code": null,
"e": 120766,
"s": 120671,
"text": "The main property of manager is to control a server process, which manages the shared objects."
},
{
"code": null,
"e": 120859,
"s": 120766,
"text": "Another important property is to update all the shared objects when any process modifies it."
},
{
"code": null,
"e": 120952,
"s": 120859,
"text": "Another important property is to update all the shared objects when any process modifies it."
},
{
"code": null,
"e": 121094,
"s": 120952,
"text": "Following is an example which uses the manager object for creating a list record in server process and then adding a new record in that list."
},
{
"code": null,
"e": 121760,
"s": 121094,
"text": "import multiprocessing\n\ndef print_records(records):\n for record in records:\n print(\"Name: {0}\\nScore: {1}\\n\".format(record[0], record[1]))\n\ndef insert_record(record, records):\n records.append(record)\n print(\"A New record is added\\n\")\n\nif __name__ == '__main__':\n with multiprocessing.Manager() as manager:\n\n records = manager.list([('Computers', 1), ('Histoty', 5), ('Hindi',9)])\n new_record = ('English', 3)\n\n p1 = multiprocessing.Process(target = insert_record, args = (new_record, records))\n p2 = multiprocessing.Process(target = print_records, args = (records,))\n\t p1.start()\n p1.join()\n p2.start()\n p2.join()"
},
{
"code": null,
"e": 121879,
"s": 121760,
"text": "A New record is added\n\nName: Computers\nScore: 1\n\nName: Histoty\nScore: 5\n\nName: Hindi\nScore: 9\n\nName: English\nScore: 3\n"
},
{
"code": null,
"e": 122118,
"s": 121879,
"text": "Manager Class comes with the concept of namespaces, which is a quick way method for sharing several attributes across multiple processes. Namespaces do not feature any public method, which can be called, but they have writable attributes."
},
{
"code": null,
"e": 122239,
"s": 122118,
"text": "The following Python script example helps us utilize namespaces for sharing data across main process and child process −"
},
{
"code": null,
"e": 122618,
"s": 122239,
"text": "import multiprocessing\n\ndef Mng_NaSp(using_ns):\n\n using_ns.x +=5\n using_ns.y *= 10\n\nif __name__ == '__main__':\n manager = multiprocessing.Manager()\n using_ns = manager.Namespace()\n using_ns.x = 1\n using_ns.y = 1\n\n print ('before', using_ns)\n p = multiprocessing.Process(target = Mng_NaSp, args = (using_ns,))\n p.start()\n p.join()\n print ('after', using_ns)"
},
{
"code": null,
"e": 122681,
"s": 122618,
"text": "before Namespace(x = 1, y = 1)\nafter Namespace(x = 6, y = 10)\n"
},
{
"code": null,
"e": 122894,
"s": 122681,
"text": "Multiprocessing module provides Array and Value objects for storing the data in a shared memory map. Array is a ctypes array allocated from shared memory and Value is a ctypes object allocated from shared memory."
},
{
"code": null,
"e": 122960,
"s": 122894,
"text": "To being with, import Process, Value, Array from multiprocessing."
},
{
"code": null,
"e": 123096,
"s": 122960,
"text": "Following Python script is an example taken from python docs to utilize Ctypes Array and Value for sharing some data between processes."
},
{
"code": null,
"e": 123370,
"s": 123096,
"text": "def f(n, a):\n n.value = 3.1415927\n for i in range(len(a)):\n a[i] = -a[i]\n\nif __name__ == '__main__':\n num = Value('d', 0.0)\n arr = Array('i', range(10))\n\n p = Process(target = f, args = (num, arr))\n p.start()\n p.join()\n print (num.value)\n print (arr[:])"
},
{
"code": null,
"e": 123421,
"s": 123370,
"text": "3.1415927\n[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n"
},
{
"code": null,
"e": 123649,
"s": 123421,
"text": "CSP is used to illustrate the interaction of systems with other systems featuring concurrent models. CSP is a framework for writing concurrent or program via message passing and hence it is effective for describing concurrency."
},
{
"code": null,
"e": 123875,
"s": 123649,
"text": "For implementing core primitives found in CSP, Python has a library called PyCSP. It keeps the implementation very short and readable so that it can be understood very easily. Following is the basic process network of PyCSP −"
},
{
"code": null,
"e": 124057,
"s": 123875,
"text": "In the above PyCSP process network, there are two processes – Process1 and Process 2. These processes communicate by passing messages through two channels – channel 1 and channel 2."
},
{
"code": null,
"e": 124131,
"s": 124057,
"text": "With the help of following command, we can install Python library PyCSP −"
},
{
"code": null,
"e": 124149,
"s": 124131,
"text": "pip install PyCSP"
},
{
"code": null,
"e": 124302,
"s": 124149,
"text": "Following Python script is a simple example for running two processes in parallel to each other. It is done with the help of the PyCSP python libabary −"
},
{
"code": null,
"e": 124558,
"s": 124302,
"text": "from pycsp.parallel import *\nimport time\n@process\ndef P1():\n time.sleep(1)\n print('P1 exiting')\n@process\ndef P2():\n time.sleep(1)\n print('P2 exiting')\ndef main():\n Parallel(P1(), P2())\n print('Terminating')\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 124697,
"s": 124558,
"text": "In the above script, two functions namely P1 and P2 have been created and then decorated with @process for converting them into processes."
},
{
"code": null,
"e": 124732,
"s": 124697,
"text": "P2 exiting\nP1 exiting\nTerminating\n"
},
{
"code": null,
"e": 125307,
"s": 124732,
"text": "Event-driven programming focuses on events. Eventually, the flow of program depends upon events. Until now, we were dealing with either sequential or parallel execution model but the model having the concept of event-driven programming is called asynchronous model. Event-driven programming depends upon an event loop that is always listening for the new incoming events. The working of event-driven programming is dependent upon events. Once an event loops, then events decide what to execute and in what order. Following flowchart will help you understand how this works −"
},
{
"code": null,
"e": 125506,
"s": 125307,
"text": "Asyncio module was added in Python 3.4 and it provides infrastructure for writing single-threaded concurrent code using co-routines. Following are the different concepts used by the Asyncio module −"
},
{
"code": null,
"e": 125843,
"s": 125506,
"text": "Event-loop is a functionality to handle all the events in a computational code. It acts round the way during the execution of whole program and keeps track of the incoming and execution of events. The Asyncio module allows a single event loop per process. Followings are some methods provided by Asyncio module to manage an event loop −"
},
{
"code": null,
"e": 125934,
"s": 125843,
"text": "loop = get_event_loop() − This method will provide the event loop for the current context."
},
{
"code": null,
"e": 126025,
"s": 125934,
"text": "loop = get_event_loop() − This method will provide the event loop for the current context."
},
{
"code": null,
"e": 126168,
"s": 126025,
"text": "loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds."
},
{
"code": null,
"e": 126311,
"s": 126168,
"text": "loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds."
},
{
"code": null,
"e": 126522,
"s": 126311,
"text": "loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop."
},
{
"code": null,
"e": 126733,
"s": 126522,
"text": "loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop."
},
{
"code": null,
"e": 126840,
"s": 126733,
"text": "loop.time() − This method is used to return the current time according to the event loop’s internal clock."
},
{
"code": null,
"e": 126947,
"s": 126840,
"text": "loop.time() − This method is used to return the current time according to the event loop’s internal clock."
},
{
"code": null,
"e": 127047,
"s": 126947,
"text": "asyncio.set_event_loop() − This method will set the event loop for the current context to the loop."
},
{
"code": null,
"e": 127147,
"s": 127047,
"text": "asyncio.set_event_loop() − This method will set the event loop for the current context to the loop."
},
{
"code": null,
"e": 127234,
"s": 127147,
"text": "asyncio.new_event_loop() − This method will create and return a new event loop object."
},
{
"code": null,
"e": 127321,
"s": 127234,
"text": "asyncio.new_event_loop() − This method will create and return a new event loop object."
},
{
"code": null,
"e": 127394,
"s": 127321,
"text": "loop.run_forever() − This method will run until stop() method is called."
},
{
"code": null,
"e": 127467,
"s": 127394,
"text": "loop.run_forever() − This method will run until stop() method is called."
},
{
"code": null,
"e": 127624,
"s": 127467,
"text": "The following example of event loop helps in printing hello world by using the get_event_loop() method. This example is taken from the Python official docs."
},
{
"code": null,
"e": 127803,
"s": 127624,
"text": "import asyncio\n\ndef hello_world(loop):\n print('Hello World')\n loop.stop()\n\nloop = asyncio.get_event_loop()\n\nloop.call_soon(hello_world, loop)\n\nloop.run_forever()\nloop.close()"
},
{
"code": null,
"e": 127816,
"s": 127803,
"text": "Hello World\n"
},
{
"code": null,
"e": 128033,
"s": 127816,
"text": "This is compatible with the concurrent.futures.Future class that represents a computation that has not been accomplished. There are following differences between asyncio.futures.Future and concurrent.futures.Future −"
},
{
"code": null,
"e": 128152,
"s": 128033,
"text": "result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet."
},
{
"code": null,
"e": 128271,
"s": 128152,
"text": "result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet."
},
{
"code": null,
"e": 128369,
"s": 128271,
"text": "Callbacks registered with add_done_callback() are always called via the event loop’s call_soon()."
},
{
"code": null,
"e": 128467,
"s": 128369,
"text": "Callbacks registered with add_done_callback() are always called via the event loop’s call_soon()."
},
{
"code": null,
"e": 128594,
"s": 128467,
"text": "asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package."
},
{
"code": null,
"e": 128721,
"s": 128594,
"text": "asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package."
},
{
"code": null,
"e": 128820,
"s": 128721,
"text": "The following is an example that will help you understand how to use asyncio.futures.future class."
},
{
"code": null,
"e": 129127,
"s": 128820,
"text": "import asyncio\n\nasync def Myoperation(future):\n await asyncio.sleep(2)\n future.set_result('Future Completed')\n\nloop = asyncio.get_event_loop()\nfuture = asyncio.Future()\nasyncio.ensure_future(Myoperation(future))\ntry:\n loop.run_until_complete(future)\n print(future.result())\nfinally:\n loop.close()"
},
{
"code": null,
"e": 129145,
"s": 129127,
"text": "Future Completed\n"
},
{
"code": null,
"e": 129557,
"s": 129145,
"text": "The concept of coroutines in Asyncio is similar to the concept of standard Thread object under threading module. This is the generalization of the subroutine concept. A coroutine can be suspended during the execution so that it waits for the external processing and returns from the point at which it had stopped when the external processing was done. The following two ways help us in implementing coroutines −"
},
{
"code": null,
"e": 129673,
"s": 129557,
"text": "This is a method for implementation of coroutines under Asyncio module. Following is a Python script for the same −"
},
{
"code": null,
"e": 129848,
"s": 129673,
"text": "import asyncio\n\nasync def Myoperation():\n print(\"First Coroutine\")\n\nloop = asyncio.get_event_loop()\ntry:\n loop.run_until_complete(Myoperation())\n\nfinally:\n loop.close()"
},
{
"code": null,
"e": 129865,
"s": 129848,
"text": "First Coroutine\n"
},
{
"code": null,
"e": 130021,
"s": 129865,
"text": "Another method for implementation of coroutines is to utilize generators with the @asyncio.coroutine decorator. Following is a Python script for the same −"
},
{
"code": null,
"e": 130209,
"s": 130021,
"text": "import asyncio\n\n@asyncio.coroutine\ndef Myoperation():\n print(\"First Coroutine\")\n\nloop = asyncio.get_event_loop()\ntry:\n loop.run_until_complete(Myoperation())\n\nfinally:\n loop.close()"
},
{
"code": null,
"e": 130226,
"s": 130209,
"text": "First Coroutine\n"
},
{
"code": null,
"e": 130418,
"s": 130226,
"text": "This subclass of Asyncio module is responsible for execution of coroutines within an event loop in parallel manner. Following Python script is an example of processing some tasks in parallel."
},
{
"code": null,
"e": 130745,
"s": 130418,
"text": "import asyncio\nimport time\nasync def Task_ex(n):\n time.sleep(1)\n print(\"Processing {}\".format(n))\nasync def Generator_task():\n for i in range(10):\n asyncio.ensure_future(Task_ex(i))\n int(\"Tasks Completed\")\n asyncio.sleep(2)\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(Generator_task())\nloop.close()"
},
{
"code": null,
"e": 130892,
"s": 130745,
"text": "Tasks Completed\nProcessing 0\nProcessing 1\nProcessing 2\nProcessing 3\nProcessing 4\nProcessing 5\nProcessing 6\nProcessing 7\nProcessing 8\nProcessing 9\n"
},
{
"code": null,
"e": 131106,
"s": 130892,
"text": "Asyncio module provides transport classes for implementing various types of communication. These classes are not thread safe and always paired with a protocol instance after establishment of communication channel."
},
{
"code": null,
"e": 131184,
"s": 131106,
"text": "Following are distinct types of transports inherited from the BaseTransport −"
},
{
"code": null,
"e": 131248,
"s": 131184,
"text": "ReadTransport − This is an interface for read-only transports."
},
{
"code": null,
"e": 131312,
"s": 131248,
"text": "ReadTransport − This is an interface for read-only transports."
},
{
"code": null,
"e": 131378,
"s": 131312,
"text": "WriteTransport − This is an interface for write-only transports."
},
{
"code": null,
"e": 131444,
"s": 131378,
"text": "WriteTransport − This is an interface for write-only transports."
},
{
"code": null,
"e": 131508,
"s": 131444,
"text": "DatagramTransport − This is an interface for sending the data."
},
{
"code": null,
"e": 131572,
"s": 131508,
"text": "DatagramTransport − This is an interface for sending the data."
},
{
"code": null,
"e": 131630,
"s": 131572,
"text": "BaseSubprocessTransport − Similar to BaseTransport class."
},
{
"code": null,
"e": 131688,
"s": 131630,
"text": "BaseSubprocessTransport − Similar to BaseTransport class."
},
{
"code": null,
"e": 131814,
"s": 131688,
"text": "Followings are five distinct methods of BaseTransport class that are subsequently transient across the four transport types −"
},
{
"code": null,
"e": 131850,
"s": 131814,
"text": "close() − It closes the transport."
},
{
"code": null,
"e": 131886,
"s": 131850,
"text": "close() − It closes the transport."
},
{
"code": null,
"e": 131991,
"s": 131886,
"text": "is_closing() − This method will return true if the transport is closing or is already closed.transports."
},
{
"code": null,
"e": 132096,
"s": 131991,
"text": "is_closing() − This method will return true if the transport is closing or is already closed.transports."
},
{
"code": null,
"e": 132194,
"s": 132096,
"text": "get_extra_info(name, default = none) − This will give us some extra information about transport."
},
{
"code": null,
"e": 132292,
"s": 132194,
"text": "get_extra_info(name, default = none) − This will give us some extra information about transport."
},
{
"code": null,
"e": 132355,
"s": 132292,
"text": "get_protocol() − This method will return the current protocol."
},
{
"code": null,
"e": 132418,
"s": 132355,
"text": "get_protocol() − This method will return the current protocol."
},
{
"code": null,
"e": 132757,
"s": 132418,
"text": "Asyncio module provides base classes that you can subclass to implement your network protocols. Those classes are used in conjunction with transports; the protocol parses incoming data and asks for the writing of outgoing data, while the transport is responsible for the actual I/O and buffering. Following are three classes of Protocol −"
},
{
"code": null,
"e": 132866,
"s": 132757,
"text": "Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports."
},
{
"code": null,
"e": 132975,
"s": 132866,
"text": "Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports."
},
{
"code": null,
"e": 133083,
"s": 132975,
"text": "DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports.."
},
{
"code": null,
"e": 133191,
"s": 133083,
"text": "DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports.."
},
{
"code": null,
"e": 133336,
"s": 133191,
"text": "SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes."
},
{
"code": null,
"e": 133481,
"s": 133336,
"text": "SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes."
},
{
"code": null,
"e": 133970,
"s": 133481,
"text": "Reactive programming is a programming paradigm that deals with data flows and the propagation of change. It means that when a data flow is emitted by one component, the change will be propagated to other components by reactive programming library. The propagation of change will continue until it reaches the final receiver. The difference between event-driven and reactive programming is that event-driven programming revolves around events and reactive programming revolves around data."
},
{
"code": null,
"e": 134127,
"s": 133970,
"text": "ReactiveX or Raective Extension is the most famous implementation of reactive programming. The working of ReactiveX depends upon the following two classes −"
},
{
"code": null,
"e": 134326,
"s": 134127,
"text": "This class is the source of data stream or events and it packs the incoming data so that the data can be passed from one thread to another. It will not give data until some observer subscribe to it."
},
{
"code": null,
"e": 134573,
"s": 134326,
"text": "This class consumes the data stream emitted by observable. There can be multiple observers with observable and each observer will receive each data item that is emitted. The observer can receive three type of events by subscribing to observable −"
},
{
"code": null,
"e": 134643,
"s": 134573,
"text": "on_next() event − It implies there is an element in the data stream."
},
{
"code": null,
"e": 134713,
"s": 134643,
"text": "on_next() event − It implies there is an element in the data stream."
},
{
"code": null,
"e": 134793,
"s": 134713,
"text": "on_completed() event − It implies end of emission and no more items are coming."
},
{
"code": null,
"e": 134873,
"s": 134793,
"text": "on_completed() event − It implies end of emission and no more items are coming."
},
{
"code": null,
"e": 134975,
"s": 134873,
"text": "on_error() event − It also implies end of emission but in case when an error is thrown by observable."
},
{
"code": null,
"e": 135077,
"s": 134975,
"text": "on_error() event − It also implies end of emission but in case when an error is thrown by observable."
},
{
"code": null,
"e": 135256,
"s": 135077,
"text": "RxPY is a Python module which can be used for reactive programming. We need to ensure that the module is installed. The following command can be used to install the RxPY module −"
},
{
"code": null,
"e": 135274,
"s": 135256,
"text": "pip install RxPY\n"
},
{
"code": null,
"e": 135426,
"s": 135274,
"text": "Following is a Python script, which uses RxPY module and its classes Observable and Observe for reactive programming. There are basically two classes −"
},
{
"code": null,
"e": 135481,
"s": 135426,
"text": "get_strings() − for getting the strings from observer."
},
{
"code": null,
"e": 135536,
"s": 135481,
"text": "get_strings() − for getting the strings from observer."
},
{
"code": null,
"e": 135670,
"s": 135536,
"text": "PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class."
},
{
"code": null,
"e": 135804,
"s": 135670,
"text": "PrintObserver() − for printing the strings from observer. It uses all three events of observer class. It also uses subscribe() class."
},
{
"code": null,
"e": 136276,
"s": 135804,
"text": "from rx import Observable, Observer\ndef get_strings(observer):\n observer.on_next(\"Ram\")\n observer.on_next(\"Mohan\")\n observer.on_next(\"Shyam\")\n observer.on_completed()\nclass PrintObserver(Observer):\n def on_next(self, value):\n print(\"Received {0}\".format(value))\n def on_completed(self):\n print(\"Finished\")\n def on_error(self, error):\n print(\"Error: {0}\".format(error))\nsource = Observable.create(get_strings)\nsource.subscribe(PrintObserver())"
},
{
"code": null,
"e": 136329,
"s": 136276,
"text": "Received Ram\nReceived Mohan\nReceived Shyam\nFinished\n"
},
{
"code": null,
"e": 136591,
"s": 136329,
"text": "PyFunctionalis another Python library that can be used for reactive programming. It enables us to create functional programs using the Python programming language. It is useful because it allows us to create data pipelines by using chained functional operators."
},
{
"code": null,
"e": 136904,
"s": 136591,
"text": "Both the libraries are used for reactive programming and handle the stream in similar fashion but the main difference between both of them depends upon the handling of data. RxPY handles data and events in the system while PyFunctional is focused on transformation of data using functional programming paradigms."
},
{
"code": null,
"e": 137014,
"s": 136904,
"text": "We need to install this module before using it. It can be installed with the help of pip command as follows −"
},
{
"code": null,
"e": 137039,
"s": 137014,
"text": "pip install pyfunctional"
},
{
"code": null,
"e": 137394,
"s": 137039,
"text": "Following example uses the PyFunctional module and its seq class which act as the stream object with which we can iterate and manipulate. In this program, it maps the sequence by using the lamda function that doubles every value, then filters the value where x is greater than 4 and finally it reduces the sequence into a sum of all the remaining values."
},
{
"code": null,
"e": 137549,
"s": 137394,
"text": "from functional import seq\n\nresult = seq(1,2,3).map(lambda x: x*2).filter(lambda x: x > 4).reduce(lambda x, y: x + y)\n\nprint (\"Result: {}\".format(result))"
},
{
"code": null,
"e": 137560,
"s": 137549,
"text": "Result: 6\n"
},
{
"code": null,
"e": 137593,
"s": 137560,
"text": "\n 57 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 137608,
"s": 137593,
"text": " Denis Tishkov"
},
{
"code": null,
"e": 137615,
"s": 137608,
"text": " Print"
},
{
"code": null,
"e": 137626,
"s": 137615,
"text": " Add Notes"
}
] |
Why Multiple Dispatch Is My Favorite Way To Program | by Emmett Boudreau | Towards Data Science
|
The Julia language is an incredible technical feat that has been a work in progress since around 2008 and has really made ground in the past couple of years. The language is exciting, science-geared, and fun to use with its unique paradigm and programming style. To understand the Julia programming language, you need to understand multiple dispatch.
Multiple dispatch is a generic programming concept that is built on the grounds of parametric polymorphism. What is interesting about polymorphism, in general, is that it is typically a quality of declarative and functional programming, but the quality itself seems to be better described elsewhere in other programming paradigms. Multiple dispatch is the backbone of the Julia programming language, but that is most certainly not where the programming concept originated. The programming concept of multiple dispatch was actually originally introduced in 1973, 48 years ago! The first implementation was put into a little language called ML, which was fabricated by one Robert Milner and other associates at the University of Edinburgh.
The language is quite similar to a lot of high-level programming and scripting languages that we have today. The biggest difference between ML and a lot of the more declarative modern languages is that ML was also a very imperative language, which seems a bit odd when you consider that the language is also functional. A lot of languages from the mid-’70s and onward follow this tone actually, which I think is an interesting observation. We always credit C++ for really inventing the concept of generics, but there were so many multi-paradigm languages coming out in the 70’s that it is nearly impossible to keep track of them.
Multiple dispatch is a programming concept that allows a programmer to write a function multiple times to handle different types. A lot of programmers tend to stray far away from the functional programming paradigm for its global scope. This is understandable, having everything be global, especially with exports like in Julia, can be very problematic. This is primarily true because of naming. I actually wrote an article all about namespaces in the Julia language a long time ago, where I discussed why an implementation of namespaces similar to C++ might be able to mitigate this issue. I think it is an interesting read, and if you would like to check it out you may here:
towardsdatascience.com
This problem can be especially prevalent with functions. This is because Julia is not an object-oriented language, therefore there isn’t really a class scope that we can use to make functions private in order to work with specific types, we just write methods to take our types inside of the global scope. This means that a lot of times we might have methods that are under completely different names that do the exact same thing. Of course, that is not the case at all in Julia, and the reason that is not the case is because of multiple dispatch.
Multiple dispatch is a way that we can apply function calls as properties of types. In other words, we can redefine the same function over and over again, but just plan for different types to be passed through it in order to essentially recreate the method to handle a new type. Consider the following example.
x = [1, 2, 3, 4, 5]y = 5function add_5(x) x + 5end
The function above adds five to the argument passed as x. For this example, we would only be able to pass our y through this function. If we tried to pass x through this function, we would quickly realize that there is no method matching +(Array, Int64). This is of course because there is not really a way that we can add an integer to our array. We also wouldn’t want to get sloppy and write another function with an alternate name, like this:
function add_5_array(x) [x += 5 for x in array]end
That would be ridiculous. Luckily, multiple dispatch was created with the intention of solving this very problem. Using dispatch, we can cast a type to our arguments on both of these functions, and when that type is passed through the function only the function for that particular type is going to run.
function add_5(x::Array) [x += 5 for x in array]endfunction add_5(x::Int64) x + 5end
Now we can pass both our x and our y through there without any worries at all.
The Julian implementation of multiple is akin to typical multiple dispatch, but on steroids. Not only do we get the added benefit of being able to call multiple dispatch really fast and in one line almost as if we are writing lambda expressions in Python, we also have the choice to write functions in both ways interchangeably. Furthermore, Julia has even more tricks up its sleeve that make multiple dispatch even better.
The first thing that really adds to Julia’s dispatch beauty is the ability to create sub-types. In Julia, most types are part of something called a super-type hierarchy. A super-type hierarchy simply allows us to create inheritance across methods with types that are similar and can be handled the same way by these functions. For example, say we have a function that can take an irrational number, an integer, or a float. We could limit what part of the tree this goes to by simply dispatching the real type from our function.
add5(x::Real) = x + 5
We could also include the complex type in the use of this function by instead going up the tree and calling on all numbers:
add5(x::Number) = x + 5
This means that not only can we dispatch our types, but we can also have other types inherit those functions that we have dispatched to our abstract types. If you would like to learn more about this number hierarchy I just touched on, I actually have an entire article on it that you could read here:
towardsdatascience.com
Adding to the beauty of dispatch is Julia’s awesome inner constructors. Inner constructors allow you to create multiple inputs to achieve the same output. These are basically initialization functions that can take any number of arguments, and then construct the type they are applied to out of the arguments provided. What is really cool is that dispatch will take care of whether or not someone is calling the inner or the outer constructor, so you could still make the type with the normal arguments, but you can also create it with a new argument. Consider the following example:
mutable struct broken_array dim1 dim2end
Here we have a new type called broken_array. In order to construct this type out of a two-element array, we will need to populate the dim1 and dim2 data values. We could of course do this like so:
array = [5, 2]broken = broken_array(array[1], array[2])
However, that is some inconvenient calling for an end user to do. We could solve this with an inner constructor, like so:
mutable struct broken_array dim1::Int64 dim2::Int64 function broken_array(x::Array) new(x[1], x[2]) endend
The old call we did before will still be dispatched to create the type directly by calling the outer constructor, but now we have the extended functionality of calling the inner constructor with our array like this.
broken = broken_array(array)
Pretty cool, right?
Another great thing about this is that it also makes all of the types and methods in the language incredibly extendable. We can take any type or any method from any package, directly import it, and extend it to do whatever we want. The inner constructor for types does not even need to be within the constructor, as well, so we could really take advantage and write functions to create types that already exist from other packages and use them anywhere. Furthermore, we could even extend other methods with our own types. One really cool result of that is that all of the packages in Julia often end up using the same set of base methods that you might be used to for completely different types.
Of all the programming languages I have worked and dabbled in, Julia has easily become my favorite to program in. This is a direct result of multiple dispatch. The multiple dispatch concept in the Julia language allows for not only some pretty radical and expressive programming, but also the extension of essentially any method or type that is used in the language. Needless to say, that is quite a powerful concept. Furthermore, it is a great way to program scientifically, because often method calls and function definitions end up looking just as they do in the papers. Thank you very much for reading my article, and hopefully, it might have made you inclined to check out the wonderful gift that is multiple dispatch!
|
[
{
"code": null,
"e": 522,
"s": 171,
"text": "The Julia language is an incredible technical feat that has been a work in progress since around 2008 and has really made ground in the past couple of years. The language is exciting, science-geared, and fun to use with its unique paradigm and programming style. To understand the Julia programming language, you need to understand multiple dispatch."
},
{
"code": null,
"e": 1260,
"s": 522,
"text": "Multiple dispatch is a generic programming concept that is built on the grounds of parametric polymorphism. What is interesting about polymorphism, in general, is that it is typically a quality of declarative and functional programming, but the quality itself seems to be better described elsewhere in other programming paradigms. Multiple dispatch is the backbone of the Julia programming language, but that is most certainly not where the programming concept originated. The programming concept of multiple dispatch was actually originally introduced in 1973, 48 years ago! The first implementation was put into a little language called ML, which was fabricated by one Robert Milner and other associates at the University of Edinburgh."
},
{
"code": null,
"e": 1890,
"s": 1260,
"text": "The language is quite similar to a lot of high-level programming and scripting languages that we have today. The biggest difference between ML and a lot of the more declarative modern languages is that ML was also a very imperative language, which seems a bit odd when you consider that the language is also functional. A lot of languages from the mid-’70s and onward follow this tone actually, which I think is an interesting observation. We always credit C++ for really inventing the concept of generics, but there were so many multi-paradigm languages coming out in the 70’s that it is nearly impossible to keep track of them."
},
{
"code": null,
"e": 2568,
"s": 1890,
"text": "Multiple dispatch is a programming concept that allows a programmer to write a function multiple times to handle different types. A lot of programmers tend to stray far away from the functional programming paradigm for its global scope. This is understandable, having everything be global, especially with exports like in Julia, can be very problematic. This is primarily true because of naming. I actually wrote an article all about namespaces in the Julia language a long time ago, where I discussed why an implementation of namespaces similar to C++ might be able to mitigate this issue. I think it is an interesting read, and if you would like to check it out you may here:"
},
{
"code": null,
"e": 2591,
"s": 2568,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3140,
"s": 2591,
"text": "This problem can be especially prevalent with functions. This is because Julia is not an object-oriented language, therefore there isn’t really a class scope that we can use to make functions private in order to work with specific types, we just write methods to take our types inside of the global scope. This means that a lot of times we might have methods that are under completely different names that do the exact same thing. Of course, that is not the case at all in Julia, and the reason that is not the case is because of multiple dispatch."
},
{
"code": null,
"e": 3451,
"s": 3140,
"text": "Multiple dispatch is a way that we can apply function calls as properties of types. In other words, we can redefine the same function over and over again, but just plan for different types to be passed through it in order to essentially recreate the method to handle a new type. Consider the following example."
},
{
"code": null,
"e": 3505,
"s": 3451,
"text": "x = [1, 2, 3, 4, 5]y = 5function add_5(x) x + 5end"
},
{
"code": null,
"e": 3951,
"s": 3505,
"text": "The function above adds five to the argument passed as x. For this example, we would only be able to pass our y through this function. If we tried to pass x through this function, we would quickly realize that there is no method matching +(Array, Int64). This is of course because there is not really a way that we can add an integer to our array. We also wouldn’t want to get sloppy and write another function with an alternate name, like this:"
},
{
"code": null,
"e": 4006,
"s": 3951,
"text": "function add_5_array(x) [x += 5 for x in array]end"
},
{
"code": null,
"e": 4310,
"s": 4006,
"text": "That would be ridiculous. Luckily, multiple dispatch was created with the intention of solving this very problem. Using dispatch, we can cast a type to our arguments on both of these functions, and when that type is passed through the function only the function for that particular type is going to run."
},
{
"code": null,
"e": 4402,
"s": 4310,
"text": "function add_5(x::Array) [x += 5 for x in array]endfunction add_5(x::Int64) x + 5end"
},
{
"code": null,
"e": 4481,
"s": 4402,
"text": "Now we can pass both our x and our y through there without any worries at all."
},
{
"code": null,
"e": 4905,
"s": 4481,
"text": "The Julian implementation of multiple is akin to typical multiple dispatch, but on steroids. Not only do we get the added benefit of being able to call multiple dispatch really fast and in one line almost as if we are writing lambda expressions in Python, we also have the choice to write functions in both ways interchangeably. Furthermore, Julia has even more tricks up its sleeve that make multiple dispatch even better."
},
{
"code": null,
"e": 5433,
"s": 4905,
"text": "The first thing that really adds to Julia’s dispatch beauty is the ability to create sub-types. In Julia, most types are part of something called a super-type hierarchy. A super-type hierarchy simply allows us to create inheritance across methods with types that are similar and can be handled the same way by these functions. For example, say we have a function that can take an irrational number, an integer, or a float. We could limit what part of the tree this goes to by simply dispatching the real type from our function."
},
{
"code": null,
"e": 5455,
"s": 5433,
"text": "add5(x::Real) = x + 5"
},
{
"code": null,
"e": 5579,
"s": 5455,
"text": "We could also include the complex type in the use of this function by instead going up the tree and calling on all numbers:"
},
{
"code": null,
"e": 5603,
"s": 5579,
"text": "add5(x::Number) = x + 5"
},
{
"code": null,
"e": 5904,
"s": 5603,
"text": "This means that not only can we dispatch our types, but we can also have other types inherit those functions that we have dispatched to our abstract types. If you would like to learn more about this number hierarchy I just touched on, I actually have an entire article on it that you could read here:"
},
{
"code": null,
"e": 5927,
"s": 5904,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6510,
"s": 5927,
"text": "Adding to the beauty of dispatch is Julia’s awesome inner constructors. Inner constructors allow you to create multiple inputs to achieve the same output. These are basically initialization functions that can take any number of arguments, and then construct the type they are applied to out of the arguments provided. What is really cool is that dispatch will take care of whether or not someone is calling the inner or the outer constructor, so you could still make the type with the normal arguments, but you can also create it with a new argument. Consider the following example:"
},
{
"code": null,
"e": 6557,
"s": 6510,
"text": "mutable struct broken_array dim1 dim2end"
},
{
"code": null,
"e": 6754,
"s": 6557,
"text": "Here we have a new type called broken_array. In order to construct this type out of a two-element array, we will need to populate the dim1 and dim2 data values. We could of course do this like so:"
},
{
"code": null,
"e": 6810,
"s": 6754,
"text": "array = [5, 2]broken = broken_array(array[1], array[2])"
},
{
"code": null,
"e": 6932,
"s": 6810,
"text": "However, that is some inconvenient calling for an end user to do. We could solve this with an inner constructor, like so:"
},
{
"code": null,
"e": 7058,
"s": 6932,
"text": "mutable struct broken_array dim1::Int64 dim2::Int64 function broken_array(x::Array) new(x[1], x[2]) endend"
},
{
"code": null,
"e": 7274,
"s": 7058,
"text": "The old call we did before will still be dispatched to create the type directly by calling the outer constructor, but now we have the extended functionality of calling the inner constructor with our array like this."
},
{
"code": null,
"e": 7303,
"s": 7274,
"text": "broken = broken_array(array)"
},
{
"code": null,
"e": 7323,
"s": 7303,
"text": "Pretty cool, right?"
},
{
"code": null,
"e": 8019,
"s": 7323,
"text": "Another great thing about this is that it also makes all of the types and methods in the language incredibly extendable. We can take any type or any method from any package, directly import it, and extend it to do whatever we want. The inner constructor for types does not even need to be within the constructor, as well, so we could really take advantage and write functions to create types that already exist from other packages and use them anywhere. Furthermore, we could even extend other methods with our own types. One really cool result of that is that all of the packages in Julia often end up using the same set of base methods that you might be used to for completely different types."
}
] |
ReactJS | Calculator App ( Structure )
|
08 Oct, 2020
In our previous article, we have talked about a Calculator app we are going to develop and also have seen a glimpse of our final project. In this article, we will get our hands ready to start the development of our first application.
We have told this earlier also that every application we will develop in React will be made up of pieces called components. We can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI. So let’s now try to break down the UI of calculator App into smaller pieces. We will get the following elements after breaking the UI into small pieces:
Calculator Title: This is the title at the top of our application, “GeeksforGeeks Calculator”.
Output Screen: This will be our output screen, where all text will be shown. Like the input that the user will type and the answer calculated from the user input. So, we can again break down this into two smaller pieces as shown below:Question Output: This will be the input given by the user.Answer Output: This will be the result calculated from user input.
Question Output: This will be the input given by the user.
Answer Output: This will be the result calculated from user input.
Buttons: As you have seen in the image of our calculator app, we had used a lot of buttons for the input numbers from ‘0-9’, operators, to clear the screen, for backspace etc.
So, the above-shown elements are the smallest elements in which we can break our complete calculator app. So we will create Components for each of these elements. So, as we have seen the structure of our app let’s take the first step towards the developing it. We will do things in this project from the very beginning, i.e. by creating a react app, building individual components etc.
Let us now create our app using the create-react-app command. Open your terminal and type the below command:
create-react-app firstapp
Here firstapp, is the name of our react application. You can choose whatever name you want for your application but make sure that the name of your application should be in lowercase letters only. After successful execution of the above command, React will create a directory named ‘firstapp’. This directory will contain all of the files of our application. Below image shows the default files created by React for our application firstapp.
Now, as you can see in the above image that React had created a number of files for us. But we do not actually need all of them. We will create and work with our own files. So, open the src directory and delete all of the files and create two new files with the names ‘index.js’ and ‘index.css’. Also, go to the public directory and delete all pre-written code from the index.html file and add the below code to it.
Below is our /public/index.html file:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>GeeksforGeeks Calculator</title> </head> <body> <!-- This is the element where our entire app will be rendered --> <div id="root"></div> </body></html>
So, we are done setting our App, let us now start creating our Components. As we have discussed above. We will need a total of four components as shown below:
Calculator: This will be the parent component and will represent the entire Calculator application as a whole.CalculatorTitle: This component will be used to render the title at the top of our application, “GeeksforGeeks Calculator”.OutputScreen: This Component will be for all of the text shown on the screen.OutputScreenRow: This component will be for the type of output, i.e. input text and calculated result.Button: This component will be for all of the buttons that we have in our application.
Calculator: This will be the parent component and will represent the entire Calculator application as a whole.
CalculatorTitle: This component will be used to render the title at the top of our application, “GeeksforGeeks Calculator”.
OutputScreen: This Component will be for all of the text shown on the screen.
OutputScreenRow: This component will be for the type of output, i.e. input text and calculated result.
Button: This component will be for all of the buttons that we have in our application.
Let us now create a new folder named components inside our src folder and create four files inside this folder for the components mentioned above. The names of these files will be same as that of component’s name with the first letter as lowercase. Our project directory will look like as shown in the below image after creating all files:
So, we have so far created the basic structure of our Calculator application. But till now we have not written any piece of code or have not designed anything. In our next article, we will start writing codes for our components and will create the design of our Calculator application.
ReactJS | Calculator App ( Building UI )
react-js
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": "\n08 Oct, 2020"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "In our previous article, we have talked about a Calculator app we are going to develop and also have seen a glimpse of our final project. In this article, we will get our hands ready to start the development of our first application."
},
{
"code": null,
"e": 718,
"s": 262,
"text": "We have told this earlier also that every application we will develop in React will be made up of pieces called components. We can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI. So let’s now try to break down the UI of calculator App into smaller pieces. We will get the following elements after breaking the UI into small pieces:"
},
{
"code": null,
"e": 813,
"s": 718,
"text": "Calculator Title: This is the title at the top of our application, “GeeksforGeeks Calculator”."
},
{
"code": null,
"e": 1173,
"s": 813,
"text": "Output Screen: This will be our output screen, where all text will be shown. Like the input that the user will type and the answer calculated from the user input. So, we can again break down this into two smaller pieces as shown below:Question Output: This will be the input given by the user.Answer Output: This will be the result calculated from user input."
},
{
"code": null,
"e": 1232,
"s": 1173,
"text": "Question Output: This will be the input given by the user."
},
{
"code": null,
"e": 1299,
"s": 1232,
"text": "Answer Output: This will be the result calculated from user input."
},
{
"code": null,
"e": 1475,
"s": 1299,
"text": "Buttons: As you have seen in the image of our calculator app, we had used a lot of buttons for the input numbers from ‘0-9’, operators, to clear the screen, for backspace etc."
},
{
"code": null,
"e": 1861,
"s": 1475,
"text": "So, the above-shown elements are the smallest elements in which we can break our complete calculator app. So we will create Components for each of these elements. So, as we have seen the structure of our app let’s take the first step towards the developing it. We will do things in this project from the very beginning, i.e. by creating a react app, building individual components etc."
},
{
"code": null,
"e": 1970,
"s": 1861,
"text": "Let us now create our app using the create-react-app command. Open your terminal and type the below command:"
},
{
"code": null,
"e": 1997,
"s": 1970,
"text": "create-react-app firstapp\n"
},
{
"code": null,
"e": 2439,
"s": 1997,
"text": "Here firstapp, is the name of our react application. You can choose whatever name you want for your application but make sure that the name of your application should be in lowercase letters only. After successful execution of the above command, React will create a directory named ‘firstapp’. This directory will contain all of the files of our application. Below image shows the default files created by React for our application firstapp."
},
{
"code": null,
"e": 2855,
"s": 2439,
"text": "Now, as you can see in the above image that React had created a number of files for us. But we do not actually need all of them. We will create and work with our own files. So, open the src directory and delete all of the files and create two new files with the names ‘index.js’ and ‘index.css’. Also, go to the public directory and delete all pre-written code from the index.html file and add the below code to it."
},
{
"code": null,
"e": 2893,
"s": 2855,
"text": "Below is our /public/index.html file:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>GeeksforGeeks Calculator</title> </head> <body> <!-- This is the element where our entire app will be rendered --> <div id=\"root\"></div> </body></html>",
"e": 3255,
"s": 2893,
"text": null
},
{
"code": null,
"e": 3414,
"s": 3255,
"text": "So, we are done setting our App, let us now start creating our Components. As we have discussed above. We will need a total of four components as shown below:"
},
{
"code": null,
"e": 3913,
"s": 3414,
"text": "Calculator: This will be the parent component and will represent the entire Calculator application as a whole.CalculatorTitle: This component will be used to render the title at the top of our application, “GeeksforGeeks Calculator”.OutputScreen: This Component will be for all of the text shown on the screen.OutputScreenRow: This component will be for the type of output, i.e. input text and calculated result.Button: This component will be for all of the buttons that we have in our application."
},
{
"code": null,
"e": 4024,
"s": 3913,
"text": "Calculator: This will be the parent component and will represent the entire Calculator application as a whole."
},
{
"code": null,
"e": 4148,
"s": 4024,
"text": "CalculatorTitle: This component will be used to render the title at the top of our application, “GeeksforGeeks Calculator”."
},
{
"code": null,
"e": 4226,
"s": 4148,
"text": "OutputScreen: This Component will be for all of the text shown on the screen."
},
{
"code": null,
"e": 4329,
"s": 4226,
"text": "OutputScreenRow: This component will be for the type of output, i.e. input text and calculated result."
},
{
"code": null,
"e": 4416,
"s": 4329,
"text": "Button: This component will be for all of the buttons that we have in our application."
},
{
"code": null,
"e": 4756,
"s": 4416,
"text": "Let us now create a new folder named components inside our src folder and create four files inside this folder for the components mentioned above. The names of these files will be same as that of component’s name with the first letter as lowercase. Our project directory will look like as shown in the below image after creating all files:"
},
{
"code": null,
"e": 5042,
"s": 4756,
"text": "So, we have so far created the basic structure of our Calculator application. But till now we have not written any piece of code or have not designed anything. In our next article, we will start writing codes for our components and will create the design of our Calculator application."
},
{
"code": null,
"e": 5083,
"s": 5042,
"text": "ReactJS | Calculator App ( Building UI )"
},
{
"code": null,
"e": 5092,
"s": 5083,
"text": "react-js"
},
{
"code": null,
"e": 5109,
"s": 5092,
"text": "Web Technologies"
}
] |
Design Patterns in Java – Iterator Pattern
|
02 Aug, 2021
A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. Using design patterns you can make your code more flexible, reusable, and maintainable.
Types of design patterns: There are 3 types of Design Patterns in java that are depicted more clearly in a tabular format below.
Behavioral Design PatternCreational Design PatternStructural Design Pattern
Behavioral Design Pattern
Creational Design Pattern
Structural Design Pattern
Behavioural – Iterator Pattern
Here we will be discussing Iterator Pattern with an example.
The iterator pattern is a great pattern for providing navigation without exposing the structure of an object.
Traverse a container. In Java and most current programming languages, there’s the notion of a collection. List, Maps, Sets are all examples of a collection that we would want to traverse. Historically we use a loop of some sort and index into your collection to traverse it.
Doesn’t expose the underlying structure of the object we want to navigate. Navigating various structures may have different algorithms or approaches to cycle through the data.
Decouples the data from the algorithm used to traverse it
Design: Iterator Pattern
It is an interface-based design pattern. Whichever object you want to iterate over will provide a method to return an instance of an iterator from it.
Follows a factory-based method pattern in the way you get an instance of the iterator.
Each iterator is developed in such a way that it is independent of another.
Iterators also Fail Fast. Fail Fast means that iterators can’t modify the underlying object without an error being thrown.
The Collection interface is extended by the List Interface.
List Interface contains a factory method iterator(). This iterator factory method returns an instance of the Iterator Interface.
In the case of the list and its implementations, the underlying instances are ListIterator.
The ListIterator is an implementation of the Iterator interface that understands how to iterate over the various list objects in the Collection API. It declares the interface for objects in the composition.
There are some pitfalls of iterator which are as follows:
You don’t have access to an index of any sort. If you want to get an element of a certain position, there is no way to do that without just iterating though. In the case of sets and maps, there isn’t a method to grab an element at a certain index position
UniDirectional: It iterates objects in forwarding direction only.
Although iterator is the most efficient way to looping through objects of any sort. But in some cases, it may be slower than using an index and looping through it.
Example:
Java
// Java Program to Implement Behavioral>Iterator Pattern // importing required package to// implement Behavioral>Iterator Patternpackage com.demo.application; // Importing required libraries// Here Iterator Interface to// use it to iterate over the elementsimport java.util.Iterator; // Class 1 // Car Class Implementing Iterable Interface so// that we can implement the iterator method and// add our own implementation public class Car implements Iterable<String> { private String[] cars; private int index; // Default Constructor public Car() { cars = new String[10]; index = 0; } // Method 1 // Adding method to add Cars public void addCar(String car) { if (index == cars.length) { String[] largerCars = new String[cars.length + 5]; System.arraycopy(cars, 0, largerCars, 0, cars.length); cars = largerCars; largerCars = null; } cars[index] = car; index++; } // Method 2 // Implementing the iterator method and // adding your own implementation @Override public Iterator<String> iterator() { Iterator<String> it = new Iterator<String>() { private int currentIndex = 0; // Method 3 // Finding whether during iteration if // there is next element or not @Override public boolean hasNext() { return currentIndex < cars.length && cars[currentIndex] != null; } // Method 4 // Going to grab each car element by one by one // according to the index @Override public String next() { return cars[currentIndex++]; } // Method 5 @Override public void remove() { throw new UnsupportedOperationException(); } }; return it; } // Method 6 // Main driver method public static void main(String[] args) { // Instantiating Car object Car cars = new Car(); // Adding cars to the Array cars.addCar("Dodge"); cars.addCar("Ferrari"); cars.addCar("Sedan"); // Creating an Iterator and pointing the cursor // to the index just before the first element in cars Iterator<String> carIterator = cars.iterator(); // Checking whether the next element is available or not while (carIterator.hasNext()) { System.out.println(carIterator.next()); } }}
Conclusion:
An iterator is an efficient way to traverse an object.
Hides the algorithm from the client, so that simplicity for your client is contained within the algorithm that you have coated in the container you’re creating an iterator for
Helps us to simplify that client.
Helps us to take advantage of the for each syntax which definitely simplifies iterating over that object in a for each loop.
surinderdawra388
Java-Design-Patterns
Design Pattern
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": "\n02 Aug, 2021"
},
{
"code": null,
"e": 415,
"s": 28,
"text": "A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. Using design patterns you can make your code more flexible, reusable, and maintainable."
},
{
"code": null,
"e": 544,
"s": 415,
"text": "Types of design patterns: There are 3 types of Design Patterns in java that are depicted more clearly in a tabular format below."
},
{
"code": null,
"e": 620,
"s": 544,
"text": "Behavioral Design PatternCreational Design PatternStructural Design Pattern"
},
{
"code": null,
"e": 646,
"s": 620,
"text": "Behavioral Design Pattern"
},
{
"code": null,
"e": 672,
"s": 646,
"text": "Creational Design Pattern"
},
{
"code": null,
"e": 698,
"s": 672,
"text": "Structural Design Pattern"
},
{
"code": null,
"e": 729,
"s": 698,
"text": "Behavioural – Iterator Pattern"
},
{
"code": null,
"e": 790,
"s": 729,
"text": "Here we will be discussing Iterator Pattern with an example."
},
{
"code": null,
"e": 900,
"s": 790,
"text": "The iterator pattern is a great pattern for providing navigation without exposing the structure of an object."
},
{
"code": null,
"e": 1175,
"s": 900,
"text": "Traverse a container. In Java and most current programming languages, there’s the notion of a collection. List, Maps, Sets are all examples of a collection that we would want to traverse. Historically we use a loop of some sort and index into your collection to traverse it."
},
{
"code": null,
"e": 1351,
"s": 1175,
"text": "Doesn’t expose the underlying structure of the object we want to navigate. Navigating various structures may have different algorithms or approaches to cycle through the data."
},
{
"code": null,
"e": 1409,
"s": 1351,
"text": "Decouples the data from the algorithm used to traverse it"
},
{
"code": null,
"e": 1434,
"s": 1409,
"text": "Design: Iterator Pattern"
},
{
"code": null,
"e": 1585,
"s": 1434,
"text": "It is an interface-based design pattern. Whichever object you want to iterate over will provide a method to return an instance of an iterator from it."
},
{
"code": null,
"e": 1672,
"s": 1585,
"text": "Follows a factory-based method pattern in the way you get an instance of the iterator."
},
{
"code": null,
"e": 1748,
"s": 1672,
"text": "Each iterator is developed in such a way that it is independent of another."
},
{
"code": null,
"e": 1871,
"s": 1748,
"text": "Iterators also Fail Fast. Fail Fast means that iterators can’t modify the underlying object without an error being thrown."
},
{
"code": null,
"e": 1931,
"s": 1871,
"text": "The Collection interface is extended by the List Interface."
},
{
"code": null,
"e": 2060,
"s": 1931,
"text": "List Interface contains a factory method iterator(). This iterator factory method returns an instance of the Iterator Interface."
},
{
"code": null,
"e": 2152,
"s": 2060,
"text": "In the case of the list and its implementations, the underlying instances are ListIterator."
},
{
"code": null,
"e": 2359,
"s": 2152,
"text": "The ListIterator is an implementation of the Iterator interface that understands how to iterate over the various list objects in the Collection API. It declares the interface for objects in the composition."
},
{
"code": null,
"e": 2417,
"s": 2359,
"text": "There are some pitfalls of iterator which are as follows:"
},
{
"code": null,
"e": 2673,
"s": 2417,
"text": "You don’t have access to an index of any sort. If you want to get an element of a certain position, there is no way to do that without just iterating though. In the case of sets and maps, there isn’t a method to grab an element at a certain index position"
},
{
"code": null,
"e": 2739,
"s": 2673,
"text": "UniDirectional: It iterates objects in forwarding direction only."
},
{
"code": null,
"e": 2903,
"s": 2739,
"text": "Although iterator is the most efficient way to looping through objects of any sort. But in some cases, it may be slower than using an index and looping through it."
},
{
"code": null,
"e": 2912,
"s": 2903,
"text": "Example:"
},
{
"code": null,
"e": 2917,
"s": 2912,
"text": "Java"
},
{
"code": "// Java Program to Implement Behavioral>Iterator Pattern // importing required package to// implement Behavioral>Iterator Patternpackage com.demo.application; // Importing required libraries// Here Iterator Interface to// use it to iterate over the elementsimport java.util.Iterator; // Class 1 // Car Class Implementing Iterable Interface so// that we can implement the iterator method and// add our own implementation public class Car implements Iterable<String> { private String[] cars; private int index; // Default Constructor public Car() { cars = new String[10]; index = 0; } // Method 1 // Adding method to add Cars public void addCar(String car) { if (index == cars.length) { String[] largerCars = new String[cars.length + 5]; System.arraycopy(cars, 0, largerCars, 0, cars.length); cars = largerCars; largerCars = null; } cars[index] = car; index++; } // Method 2 // Implementing the iterator method and // adding your own implementation @Override public Iterator<String> iterator() { Iterator<String> it = new Iterator<String>() { private int currentIndex = 0; // Method 3 // Finding whether during iteration if // there is next element or not @Override public boolean hasNext() { return currentIndex < cars.length && cars[currentIndex] != null; } // Method 4 // Going to grab each car element by one by one // according to the index @Override public String next() { return cars[currentIndex++]; } // Method 5 @Override public void remove() { throw new UnsupportedOperationException(); } }; return it; } // Method 6 // Main driver method public static void main(String[] args) { // Instantiating Car object Car cars = new Car(); // Adding cars to the Array cars.addCar(\"Dodge\"); cars.addCar(\"Ferrari\"); cars.addCar(\"Sedan\"); // Creating an Iterator and pointing the cursor // to the index just before the first element in cars Iterator<String> carIterator = cars.iterator(); // Checking whether the next element is available or not while (carIterator.hasNext()) { System.out.println(carIterator.next()); } }}",
"e": 5163,
"s": 2917,
"text": null
},
{
"code": null,
"e": 5175,
"s": 5163,
"text": "Conclusion:"
},
{
"code": null,
"e": 5230,
"s": 5175,
"text": "An iterator is an efficient way to traverse an object."
},
{
"code": null,
"e": 5406,
"s": 5230,
"text": "Hides the algorithm from the client, so that simplicity for your client is contained within the algorithm that you have coated in the container you’re creating an iterator for"
},
{
"code": null,
"e": 5440,
"s": 5406,
"text": "Helps us to simplify that client."
},
{
"code": null,
"e": 5565,
"s": 5440,
"text": "Helps us to take advantage of the for each syntax which definitely simplifies iterating over that object in a for each loop."
},
{
"code": null,
"e": 5582,
"s": 5565,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5603,
"s": 5582,
"text": "Java-Design-Patterns"
},
{
"code": null,
"e": 5618,
"s": 5603,
"text": "Design Pattern"
},
{
"code": null,
"e": 5623,
"s": 5618,
"text": "Java"
},
{
"code": null,
"e": 5628,
"s": 5623,
"text": "Java"
}
] |
Stacking in Machine Learning
|
21 Dec, 2021
Stacking: Stacking is a way of ensembling classification or regression models it consists of two-layer estimators. The first layer consists of all the baseline models that are used to predict the outputs on the test datasets. The second layer consists of Meta-Classifier or Regressor which takes all the predictions of baseline models as an input and generate new predictions.Stacking Architecture:
Stacking Architecture
mlxtend: Mlxtend (machine learning extensions) is a Python library of useful tools for day-to-day data science tasks. It consists of lots of tools that are useful for data science and machine learning tasks for example:
Feature SelectionFeature ExtractionVisualizationEnsembling
Feature Selection
Feature Extraction
Visualization
Ensembling
and many more.This article explains how to implement Stacking Classifier on the classification dataset.Why Stacking? Most of the Machine-Learning and Data science competitions are won by using Stacked models. They can improve the existing accuracy that is shown by individual models. We can get most of the Stacked models by choosing diverse algorithms in the first layer of architecture as different algorithms capture different trends in training data by combining both of the models can give better and accurate results.Installation of libraries on the system:
pip install mlxtend pip install pandas pip install -U scikit-learn
Code: Import Required Libraries:
python3
import pandas as pdimport matplotlib.pyplot as pltfrom mlxtend.plotting import plot_confusion_matrixfrom mlxtend.classifier import StackingClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_score
Code: Loading the dataset
python3
df = pd.read_csv('heart.csv') # loading the datasetdf.head() # viewing top 5 rows of dataset
Output:
Code:
python3
# Creating X and y for trainingX = df.drop('target', axis = 1)y = df['target']
Code: Splitting Data into Train and Test
python3
# 20 % training dataset is considered for testingX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
Code: Standardizing Data
python3
# initializing sc objectsc = StandardScaler() # variables that needed to be transformedvar_transform = ['thalach', 'age', 'trestbps', 'oldpeak', 'chol']X_train[var_transform] = sc.fit_transform(X_train[var_transform]) # standardizing training dataX_test[var_transform] = sc.transform(X_test[var_transform]) # standardizing test dataprint(X_train.head())
Output:
Code: Building First Layer Estimators
python3
KNC = KNeighborsClassifier() # initialising KNeighbors ClassifierNB = GaussianNB() # initialising Naive Bayes
Let’s Train and evaluate with our first layer estimators to observe the difference in the performance of the stacked model and general modelCode: Training KNeighborsClassifier
python3
model_kNeighborsClassifier = KNC.fit(X_train, y_train) # fitting Training Setpred_knc = model_kNeighborsClassifier.predict(X_test) # Predicting on test dataset
Code: Evaluation of KNeighborsClassifier
python3
acc_knc = accuracy_score(y_test, pred_knc) # evaluating accuracy scoreprint('accuracy score of KNeighbors Classifier is:', acc_knc * 100)
Output:
Code: Training Naive Bayes Classifier
python3
model_NaiveBayes = NB.fit(X_train, y_train)pred_nb = model_NaiveBayes.predict(X_test)
Code: Evaluation of Naive Bayes Classifier
python3
acc_nb = accuracy_score(y_test, pred_nb)print('Accuracy of Naive Bayes Classifier:', acc_nb * 100)
Output:
Code: Implementing Stacking Classifier
python3
lr = LogisticRegression() # defining meta-classifierclf_stack = StackingClassifier(classifiers =[KNC, NB], meta_classifier = lr, use_probas = True, use_features_in_secondary = True)
use_probas=True indicates the Stacking Classifier uses the prediction probabilities as an input instead of using predictions classes.
use_features_in_secondary=True indicates Stacking Classifier not only take predictions as an input but also uses features in the dataset to predict on new data.
Code: Training Stacking Classifier
python3
model_stack = clf_stack.fit(X_train, y_train) # training of stacked modelpred_stack = model_stack.predict(X_test) # predictions on test data using stacked model
Code: Evaluating Stacking Classifier
python3
acc_stack = accuracy_score(y_test, pred_stack) # evaluating accuracyprint('accuracy score of Stacked model:', acc_stack * 100)
Output:
Our both individual models scores an accuracy of nearly 80% and our Stacked model got an accuracy of nearly 84%.By Combining two individual models we got a significant performance improvement.Code:
python3
model_stack = clf_stack.fit(X_train, y_train) # training of stacked modelpred_stack = model_stack.predict(X_test) # predictions on test data using stacked model
Code: Evaluating Stacking Classifier
python3
acc_stack = accuracy_score(y_test, pred_stack) # evaluating accuracyprint('accuracy score of Stacked model:', acc_stack * 100)
Output:
Our both individual models scores an accuracy of nearly 80% and our Stacked model got an accuracy of nearly 84%. By Combining two individual models we got a significant performance improvement.
sagar0719kumar
rkbhola5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 429,
"s": 28,
"text": "Stacking: Stacking is a way of ensembling classification or regression models it consists of two-layer estimators. The first layer consists of all the baseline models that are used to predict the outputs on the test datasets. The second layer consists of Meta-Classifier or Regressor which takes all the predictions of baseline models as an input and generate new predictions.Stacking Architecture: "
},
{
"code": null,
"e": 451,
"s": 429,
"text": "Stacking Architecture"
},
{
"code": null,
"e": 673,
"s": 451,
"text": "mlxtend: Mlxtend (machine learning extensions) is a Python library of useful tools for day-to-day data science tasks. It consists of lots of tools that are useful for data science and machine learning tasks for example: "
},
{
"code": null,
"e": 732,
"s": 673,
"text": "Feature SelectionFeature ExtractionVisualizationEnsembling"
},
{
"code": null,
"e": 750,
"s": 732,
"text": "Feature Selection"
},
{
"code": null,
"e": 769,
"s": 750,
"text": "Feature Extraction"
},
{
"code": null,
"e": 783,
"s": 769,
"text": "Visualization"
},
{
"code": null,
"e": 794,
"s": 783,
"text": "Ensembling"
},
{
"code": null,
"e": 1360,
"s": 794,
"text": "and many more.This article explains how to implement Stacking Classifier on the classification dataset.Why Stacking? Most of the Machine-Learning and Data science competitions are won by using Stacked models. They can improve the existing accuracy that is shown by individual models. We can get most of the Stacked models by choosing diverse algorithms in the first layer of architecture as different algorithms capture different trends in training data by combining both of the models can give better and accurate results.Installation of libraries on the system: "
},
{
"code": null,
"e": 1427,
"s": 1360,
"text": "pip install mlxtend pip install pandas pip install -U scikit-learn"
},
{
"code": null,
"e": 1462,
"s": 1427,
"text": "Code: Import Required Libraries: "
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltfrom mlxtend.plotting import plot_confusion_matrixfrom mlxtend.classifier import StackingClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_score",
"e": 1949,
"s": 1470,
"text": null
},
{
"code": null,
"e": 1977,
"s": 1949,
"text": "Code: Loading the dataset "
},
{
"code": null,
"e": 1985,
"s": 1977,
"text": "python3"
},
{
"code": "df = pd.read_csv('heart.csv') # loading the datasetdf.head() # viewing top 5 rows of dataset",
"e": 2104,
"s": 1985,
"text": null
},
{
"code": null,
"e": 2114,
"s": 2104,
"text": "Output: "
},
{
"code": null,
"e": 2122,
"s": 2114,
"text": "Code: "
},
{
"code": null,
"e": 2130,
"s": 2122,
"text": "python3"
},
{
"code": "# Creating X and y for trainingX = df.drop('target', axis = 1)y = df['target']",
"e": 2209,
"s": 2130,
"text": null
},
{
"code": null,
"e": 2252,
"s": 2209,
"text": "Code: Splitting Data into Train and Test "
},
{
"code": null,
"e": 2260,
"s": 2252,
"text": "python3"
},
{
"code": "# 20 % training dataset is considered for testingX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)",
"e": 2403,
"s": 2260,
"text": null
},
{
"code": null,
"e": 2430,
"s": 2403,
"text": "Code: Standardizing Data "
},
{
"code": null,
"e": 2438,
"s": 2430,
"text": "python3"
},
{
"code": "# initializing sc objectsc = StandardScaler() # variables that needed to be transformedvar_transform = ['thalach', 'age', 'trestbps', 'oldpeak', 'chol']X_train[var_transform] = sc.fit_transform(X_train[var_transform]) # standardizing training dataX_test[var_transform] = sc.transform(X_test[var_transform]) # standardizing test dataprint(X_train.head())",
"e": 2805,
"s": 2438,
"text": null
},
{
"code": null,
"e": 2815,
"s": 2805,
"text": "Output: "
},
{
"code": null,
"e": 2855,
"s": 2815,
"text": "Code: Building First Layer Estimators "
},
{
"code": null,
"e": 2863,
"s": 2855,
"text": "python3"
},
{
"code": "KNC = KNeighborsClassifier() # initialising KNeighbors ClassifierNB = GaussianNB() # initialising Naive Bayes",
"e": 2988,
"s": 2863,
"text": null
},
{
"code": null,
"e": 3166,
"s": 2988,
"text": "Let’s Train and evaluate with our first layer estimators to observe the difference in the performance of the stacked model and general modelCode: Training KNeighborsClassifier "
},
{
"code": null,
"e": 3174,
"s": 3166,
"text": "python3"
},
{
"code": "model_kNeighborsClassifier = KNC.fit(X_train, y_train) # fitting Training Setpred_knc = model_kNeighborsClassifier.predict(X_test) # Predicting on test dataset",
"e": 3338,
"s": 3174,
"text": null
},
{
"code": null,
"e": 3381,
"s": 3338,
"text": "Code: Evaluation of KNeighborsClassifier "
},
{
"code": null,
"e": 3389,
"s": 3381,
"text": "python3"
},
{
"code": "acc_knc = accuracy_score(y_test, pred_knc) # evaluating accuracy scoreprint('accuracy score of KNeighbors Classifier is:', acc_knc * 100)",
"e": 3528,
"s": 3389,
"text": null
},
{
"code": null,
"e": 3538,
"s": 3528,
"text": "Output: "
},
{
"code": null,
"e": 3578,
"s": 3538,
"text": "Code: Training Naive Bayes Classifier "
},
{
"code": null,
"e": 3586,
"s": 3578,
"text": "python3"
},
{
"code": "model_NaiveBayes = NB.fit(X_train, y_train)pred_nb = model_NaiveBayes.predict(X_test)",
"e": 3672,
"s": 3586,
"text": null
},
{
"code": null,
"e": 3717,
"s": 3672,
"text": "Code: Evaluation of Naive Bayes Classifier "
},
{
"code": null,
"e": 3725,
"s": 3717,
"text": "python3"
},
{
"code": "acc_nb = accuracy_score(y_test, pred_nb)print('Accuracy of Naive Bayes Classifier:', acc_nb * 100)",
"e": 3824,
"s": 3725,
"text": null
},
{
"code": null,
"e": 3834,
"s": 3824,
"text": "Output: "
},
{
"code": null,
"e": 3875,
"s": 3834,
"text": "Code: Implementing Stacking Classifier "
},
{
"code": null,
"e": 3883,
"s": 3875,
"text": "python3"
},
{
"code": "lr = LogisticRegression() # defining meta-classifierclf_stack = StackingClassifier(classifiers =[KNC, NB], meta_classifier = lr, use_probas = True, use_features_in_secondary = True)",
"e": 4066,
"s": 3883,
"text": null
},
{
"code": null,
"e": 4200,
"s": 4066,
"text": "use_probas=True indicates the Stacking Classifier uses the prediction probabilities as an input instead of using predictions classes."
},
{
"code": null,
"e": 4361,
"s": 4200,
"text": "use_features_in_secondary=True indicates Stacking Classifier not only take predictions as an input but also uses features in the dataset to predict on new data."
},
{
"code": null,
"e": 4398,
"s": 4361,
"text": "Code: Training Stacking Classifier "
},
{
"code": null,
"e": 4406,
"s": 4398,
"text": "python3"
},
{
"code": "model_stack = clf_stack.fit(X_train, y_train) # training of stacked modelpred_stack = model_stack.predict(X_test) # predictions on test data using stacked model",
"e": 4575,
"s": 4406,
"text": null
},
{
"code": null,
"e": 4614,
"s": 4575,
"text": "Code: Evaluating Stacking Classifier "
},
{
"code": null,
"e": 4622,
"s": 4614,
"text": "python3"
},
{
"code": "acc_stack = accuracy_score(y_test, pred_stack) # evaluating accuracyprint('accuracy score of Stacked model:', acc_stack * 100)",
"e": 4750,
"s": 4622,
"text": null
},
{
"code": null,
"e": 4760,
"s": 4750,
"text": "Output: "
},
{
"code": null,
"e": 4960,
"s": 4760,
"text": "Our both individual models scores an accuracy of nearly 80% and our Stacked model got an accuracy of nearly 84%.By Combining two individual models we got a significant performance improvement.Code: "
},
{
"code": null,
"e": 4968,
"s": 4960,
"text": "python3"
},
{
"code": "model_stack = clf_stack.fit(X_train, y_train) # training of stacked modelpred_stack = model_stack.predict(X_test) # predictions on test data using stacked model",
"e": 5137,
"s": 4968,
"text": null
},
{
"code": null,
"e": 5176,
"s": 5137,
"text": "Code: Evaluating Stacking Classifier "
},
{
"code": null,
"e": 5184,
"s": 5176,
"text": "python3"
},
{
"code": "acc_stack = accuracy_score(y_test, pred_stack) # evaluating accuracyprint('accuracy score of Stacked model:', acc_stack * 100)",
"e": 5312,
"s": 5184,
"text": null
},
{
"code": null,
"e": 5322,
"s": 5312,
"text": "Output: "
},
{
"code": null,
"e": 5517,
"s": 5322,
"text": "Our both individual models scores an accuracy of nearly 80% and our Stacked model got an accuracy of nearly 84%. By Combining two individual models we got a significant performance improvement. "
},
{
"code": null,
"e": 5532,
"s": 5517,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 5541,
"s": 5532,
"text": "rkbhola5"
},
{
"code": null,
"e": 5558,
"s": 5541,
"text": "Machine Learning"
},
{
"code": null,
"e": 5565,
"s": 5558,
"text": "Python"
},
{
"code": null,
"e": 5582,
"s": 5565,
"text": "Machine Learning"
}
] |
k-th distinct (or non-repeating) element among unique elements in an array.
|
11 Jul, 2022
Given an integer array, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th element among all unique elements. If k is more than number of distinct elements, print -1.Examples :
Input : arr[] = {1, 2, 1, 3, 4, 2},
k = 2
Output : 4
First non-repeating element is 3
Second non-repeating element is 4
Input : arr[] = {1, 2, 50, 10, 20, 2},
k = 3
Output : 10
Input : {2, 2, 2, 2},
k = 2
Output : -1
A simple solution is to use two nested loops where outer loop picks elements from left to right, and inner loop checks if the picked element is present somewhere else. If not present, then increment count of distinct elements. If count becomes k, return current element.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print k-th distinct// element in a given array#include <bits/stdc++.h>using namespace std; // Returns k-th distinct// element in arr.int printKDistinct(int arr[], int n, int k){ int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codeint main (){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); int k = 2; cout << printKDistinct(ar, n, k); return 0;}
// Java program to print k-th distinct// element in a given arrayclass GFG{ // Returns k-th distinct element in arr. static int printKDistinct(int arr[], int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } //Driver code public static void main (String[] args) { int ar[] = {1, 2, 1, 3, 4, 2}; int n = ar.length; int k = 2; System.out.print(printKDistinct(ar, n, k)); }} // This code is contributed by Anant Agarwal.
# Python3 program to print k-th distinct# element in a given array # Returns k-th distinct# element in arr.def printKDistinct(arr, n, k): dist_count = 0 for i in range(n): # Check if current element is # present somewhere else. j = 0 while j < n: if (i != j and arr[j] == arr[i]): break j += 1 # If element is unique if (j == n): dist_count += 1 if (dist_count == k): return arr[i] return -1 # Driver Codear = [1, 2, 1, 3, 4, 2]n = len(ar)k = 2print(printKDistinct(ar, n, k)) # This code is contributed by Mohit Kumar
// C# program to print k-th distinct// element in a given arrayusing System; class GFG{ // Returns k-th distinct element in arr static int printKDistinct(int []arr, int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } //Driver code public static void Main () { int []ar = {1, 2, 1, 3, 4, 2}; int n = ar.Length; int k = 2; Console.Write(printKDistinct(ar, n, k)); }} // This code is contributed by nitn mittal
<?php// PHP program to print k-th// distinct element in a// given array // Returns k-th distinct// element in arr.function printKDistinct($arr, $n, $k){ $dist_count = 0; for ($i = 0; $i < $n; $i++) { // Check if current element // is present somewhere else. $j; for ($j = 0; $j < $n; $j++) if ($i != $j && $arr[$j] == $arr[$i]) break; // If element is unique if ($j == $n) $dist_count++; if ($dist_count == $k) return $arr[$i]; } return -1;} // Driver Code$ar = array(1, 2, 1, 3, 4, 2);$n = sizeof($ar) / sizeof($ar[0]);$k = 2;echo printKDistinct($ar, $n, $k); // This code is contributed by nitin mittal.?>
<script>//Javascript program to print k-th distinct// element in a given array // Returns k-th distinct// element in arr.function printKDistinct(arr, n, k){ var dist_count = 0; for (var i = 0; i < n; i++) { // Check if current element is // present somewhere else. var j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1;} var ar = [1, 2, 1, 3, 4, 2]; var n = ar.length; var k = 2; document.write( printKDistinct(ar, n, k)); //This code is contributed by SoumikMondal</script>
4
Time Complexity: O(n^2)Auxiliary Space: O(1)
An efficient solution is to use Hashing to solve this in O(n) time on average.
reate an empty hash table. Traverse input array from left to right and store elements and their counts in the hash table. Traverse input array again from left to right. Keep counting elements with count as 1. If count becomes k, return current element.
reate an empty hash table.
Traverse input array from left to right and store elements and their counts in the hash table.
Traverse input array again from left to right. Keep counting elements with count as 1.
If count becomes k, return current element.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to print k-th// distinct element in a// given array#include <bits/stdc++.h>using namespace std; // Returns k-th distinct// element in arrint printKDistinct(int arr[], int n, int k){ // Traverse input array and // store counts if individual // elements. unordered_map<int, int> h; for (int i = 0; i < n; i++) h[arr[i]]++; // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codeint main (){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); cout << printKDistinct(ar, n, 2); return 0;}
// Java program to print k-th distinct// element in a given arrayimport java.util.*; class GfG{ // Returns k-th distinct// element in arr.static int printKDistinct(int arr[], int n, int k){ //int dist_count = 0; Map <Integer, Integer> h = new HashMap<Integer, Integer> (); for (int i = 0; i < n; i++) { if(h.containsKey(arr[i])) h.put(arr[i], h.get(arr[i]) + 1); else h.put(arr[i], 1); } // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h.get(arr[i]) == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codepublic static void main (String[] args){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = ar.length; System.out.println(printKDistinct(ar, n, 2));}} // This code is contributed by// Prerna Saini
# Python3 program to print k-th# distinct element in a given arraydef printKDistinct(arr, size, KthIndex): dict = {} vect = [] for i in range(size): if(arr[i] in dict): dict[arr[i]] = dict[arr[i]] + 1 else: dict[arr[i]] = 1 for i in range(size): if(dict[arr[i]] > 1): continue else: KthIndex = KthIndex - 1 if(KthIndex == 0): return arr[i] return -1 # Driver Codearr = [1, 2, 1, 3, 4, 2]size = len(arr)print(printKDistinct(arr, size, 2)) # This code is contributed# by Akhand Pratap Singh
// C# program to print k-th distinct// element in a given arrayusing System;using System.Collections.Generic; class GfG{ // Returns k-th distinct// element in arr.static int printKDistinct(int []arr, int n, int k){ Dictionary<int, int> h = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if(h.ContainsKey(arr[i])) { var val = h[arr[i]]; h.Remove(arr[i]); h.Add(arr[i], val + 1); } else h.Add(arr[i], 1); } // If size of hash is // less than k. if (h.Count < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codepublic static void Main (String[] args){ int []ar = {1, 2, 1, 3, 4, 2}; int n = ar.Length; Console.WriteLine(printKDistinct(ar, n, 2));}} // This code contributed by Rajput-Ji
<script>// Javascript program to print k-th distinct// element in a given array // Returns k-th distinct // element in arr. function printKDistinct(arr,n,k) { // int dist_count = 0; let h = new Map(); for (let i = 0; i < n; i++) { if(h.has(arr[i])) h.set(arr[i], h.get(arr[i]) + 1); else h.set(arr[i], 1); } // If size of hash is // less than k. if (h.length < k) return -1; // Traverse array again and // find k-th element with // count as 1. let dist_count = 0; for (let i = 0; i < n; i++) { if (h.get(arr[i]) == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code let ar=[1, 2, 1, 3, 4, 2]; let n = ar.length; document.write(printKDistinct(ar, n, 2)); // This code is contributed by unknown2108</script>
4
Time Complexity: O(n)Auxiliary Space: O(n)
This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
Akhand Pratap Singh 3
prerna saini
Rajput-Ji
mohit kumar 29
SoumikMondal
unknown2108
prophet1999
simmytarika5
hardikkoriintern
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 292,
"s": 52,
"text": "Given an integer array, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th element among all unique elements. If k is more than number of distinct elements, print -1.Examples : "
},
{
"code": null,
"e": 539,
"s": 292,
"text": "Input : arr[] = {1, 2, 1, 3, 4, 2}, \n k = 2\nOutput : 4\n\nFirst non-repeating element is 3\nSecond non-repeating element is 4\n\nInput : arr[] = {1, 2, 50, 10, 20, 2}, \n k = 3\nOutput : 10\n\nInput : {2, 2, 2, 2}, \n k = 2\nOutput : -1"
},
{
"code": null,
"e": 810,
"s": 539,
"text": "A simple solution is to use two nested loops where outer loop picks elements from left to right, and inner loop checks if the picked element is present somewhere else. If not present, then increment count of distinct elements. If count becomes k, return current element."
},
{
"code": null,
"e": 826,
"s": 810,
"text": "Implementation:"
},
{
"code": null,
"e": 830,
"s": 826,
"text": "C++"
},
{
"code": null,
"e": 835,
"s": 830,
"text": "Java"
},
{
"code": null,
"e": 843,
"s": 835,
"text": "Python3"
},
{
"code": null,
"e": 846,
"s": 843,
"text": "C#"
},
{
"code": null,
"e": 850,
"s": 846,
"text": "PHP"
},
{
"code": null,
"e": 861,
"s": 850,
"text": "Javascript"
},
{
"code": "// C++ program to print k-th distinct// element in a given array#include <bits/stdc++.h>using namespace std; // Returns k-th distinct// element in arr.int printKDistinct(int arr[], int n, int k){ int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codeint main (){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); int k = 2; cout << printKDistinct(ar, n, k); return 0;}",
"e": 1644,
"s": 861,
"text": null
},
{
"code": "// Java program to print k-th distinct// element in a given arrayclass GFG{ // Returns k-th distinct element in arr. static int printKDistinct(int arr[], int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } //Driver code public static void main (String[] args) { int ar[] = {1, 2, 1, 3, 4, 2}; int n = ar.length; int k = 2; System.out.print(printKDistinct(ar, n, k)); }} // This code is contributed by Anant Agarwal.",
"e": 2661,
"s": 1644,
"text": null
},
{
"code": "# Python3 program to print k-th distinct# element in a given array # Returns k-th distinct# element in arr.def printKDistinct(arr, n, k): dist_count = 0 for i in range(n): # Check if current element is # present somewhere else. j = 0 while j < n: if (i != j and arr[j] == arr[i]): break j += 1 # If element is unique if (j == n): dist_count += 1 if (dist_count == k): return arr[i] return -1 # Driver Codear = [1, 2, 1, 3, 4, 2]n = len(ar)k = 2print(printKDistinct(ar, n, k)) # This code is contributed by Mohit Kumar",
"e": 3308,
"s": 2661,
"text": null
},
{
"code": "// C# program to print k-th distinct// element in a given arrayusing System; class GFG{ // Returns k-th distinct element in arr static int printKDistinct(int []arr, int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } //Driver code public static void Main () { int []ar = {1, 2, 1, 3, 4, 2}; int n = ar.Length; int k = 2; Console.Write(printKDistinct(ar, n, k)); }} // This code is contributed by nitn mittal",
"e": 4326,
"s": 3308,
"text": null
},
{
"code": "<?php// PHP program to print k-th// distinct element in a// given array // Returns k-th distinct// element in arr.function printKDistinct($arr, $n, $k){ $dist_count = 0; for ($i = 0; $i < $n; $i++) { // Check if current element // is present somewhere else. $j; for ($j = 0; $j < $n; $j++) if ($i != $j && $arr[$j] == $arr[$i]) break; // If element is unique if ($j == $n) $dist_count++; if ($dist_count == $k) return $arr[$i]; } return -1;} // Driver Code$ar = array(1, 2, 1, 3, 4, 2);$n = sizeof($ar) / sizeof($ar[0]);$k = 2;echo printKDistinct($ar, $n, $k); // This code is contributed by nitin mittal.?>",
"e": 5100,
"s": 4326,
"text": null
},
{
"code": "<script>//Javascript program to print k-th distinct// element in a given array // Returns k-th distinct// element in arr.function printKDistinct(arr, n, k){ var dist_count = 0; for (var i = 0; i < n; i++) { // Check if current element is // present somewhere else. var j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1;} var ar = [1, 2, 1, 3, 4, 2]; var n = ar.length; var k = 2; document.write( printKDistinct(ar, n, k)); //This code is contributed by SoumikMondal</script>",
"e": 5814,
"s": 5100,
"text": null
},
{
"code": null,
"e": 5816,
"s": 5814,
"text": "4"
},
{
"code": null,
"e": 5861,
"s": 5816,
"text": "Time Complexity: O(n^2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5941,
"s": 5861,
"text": "An efficient solution is to use Hashing to solve this in O(n) time on average. "
},
{
"code": null,
"e": 6196,
"s": 5941,
"text": "reate an empty hash table. Traverse input array from left to right and store elements and their counts in the hash table. Traverse input array again from left to right. Keep counting elements with count as 1. If count becomes k, return current element. "
},
{
"code": null,
"e": 6224,
"s": 6196,
"text": "reate an empty hash table. "
},
{
"code": null,
"e": 6321,
"s": 6224,
"text": " Traverse input array from left to right and store elements and their counts in the hash table. "
},
{
"code": null,
"e": 6409,
"s": 6321,
"text": "Traverse input array again from left to right. Keep counting elements with count as 1. "
},
{
"code": null,
"e": 6454,
"s": 6409,
"text": "If count becomes k, return current element. "
},
{
"code": null,
"e": 6470,
"s": 6454,
"text": "Implementation:"
},
{
"code": null,
"e": 6474,
"s": 6470,
"text": "C++"
},
{
"code": null,
"e": 6479,
"s": 6474,
"text": "Java"
},
{
"code": null,
"e": 6487,
"s": 6479,
"text": "Python3"
},
{
"code": null,
"e": 6490,
"s": 6487,
"text": "C#"
},
{
"code": null,
"e": 6501,
"s": 6490,
"text": "Javascript"
},
{
"code": "// C++ program to print k-th// distinct element in a// given array#include <bits/stdc++.h>using namespace std; // Returns k-th distinct// element in arrint printKDistinct(int arr[], int n, int k){ // Traverse input array and // store counts if individual // elements. unordered_map<int, int> h; for (int i = 0; i < n; i++) h[arr[i]]++; // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codeint main (){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); cout << printKDistinct(ar, n, 2); return 0;}",
"e": 7377,
"s": 6501,
"text": null
},
{
"code": "// Java program to print k-th distinct// element in a given arrayimport java.util.*; class GfG{ // Returns k-th distinct// element in arr.static int printKDistinct(int arr[], int n, int k){ //int dist_count = 0; Map <Integer, Integer> h = new HashMap<Integer, Integer> (); for (int i = 0; i < n; i++) { if(h.containsKey(arr[i])) h.put(arr[i], h.get(arr[i]) + 1); else h.put(arr[i], 1); } // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h.get(arr[i]) == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codepublic static void main (String[] args){ int ar[] = {1, 2, 1, 3, 4, 2}; int n = ar.length; System.out.println(printKDistinct(ar, n, 2));}} // This code is contributed by// Prerna Saini",
"e": 8413,
"s": 7377,
"text": null
},
{
"code": "# Python3 program to print k-th# distinct element in a given arraydef printKDistinct(arr, size, KthIndex): dict = {} vect = [] for i in range(size): if(arr[i] in dict): dict[arr[i]] = dict[arr[i]] + 1 else: dict[arr[i]] = 1 for i in range(size): if(dict[arr[i]] > 1): continue else: KthIndex = KthIndex - 1 if(KthIndex == 0): return arr[i] return -1 # Driver Codearr = [1, 2, 1, 3, 4, 2]size = len(arr)print(printKDistinct(arr, size, 2)) # This code is contributed# by Akhand Pratap Singh",
"e": 9007,
"s": 8413,
"text": null
},
{
"code": "// C# program to print k-th distinct// element in a given arrayusing System;using System.Collections.Generic; class GfG{ // Returns k-th distinct// element in arr.static int printKDistinct(int []arr, int n, int k){ Dictionary<int, int> h = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if(h.ContainsKey(arr[i])) { var val = h[arr[i]]; h.Remove(arr[i]); h.Add(arr[i], val + 1); } else h.Add(arr[i], 1); } // If size of hash is // less than k. if (h.Count < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1;} // Driver Codepublic static void Main (String[] args){ int []ar = {1, 2, 1, 3, 4, 2}; int n = ar.Length; Console.WriteLine(printKDistinct(ar, n, 2));}} // This code contributed by Rajput-Ji",
"e": 10097,
"s": 9007,
"text": null
},
{
"code": "<script>// Javascript program to print k-th distinct// element in a given array // Returns k-th distinct // element in arr. function printKDistinct(arr,n,k) { // int dist_count = 0; let h = new Map(); for (let i = 0; i < n; i++) { if(h.has(arr[i])) h.set(arr[i], h.get(arr[i]) + 1); else h.set(arr[i], 1); } // If size of hash is // less than k. if (h.length < k) return -1; // Traverse array again and // find k-th element with // count as 1. let dist_count = 0; for (let i = 0; i < n; i++) { if (h.get(arr[i]) == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code let ar=[1, 2, 1, 3, 4, 2]; let n = ar.length; document.write(printKDistinct(ar, n, 2)); // This code is contributed by unknown2108</script>",
"e": 11020,
"s": 10097,
"text": null
},
{
"code": null,
"e": 11022,
"s": 11020,
"text": "4"
},
{
"code": null,
"e": 11065,
"s": 11022,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 11361,
"s": 11065,
"text": "This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11374,
"s": 11361,
"text": "nitin mittal"
},
{
"code": null,
"e": 11396,
"s": 11374,
"text": "Akhand Pratap Singh 3"
},
{
"code": null,
"e": 11409,
"s": 11396,
"text": "prerna saini"
},
{
"code": null,
"e": 11419,
"s": 11409,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11434,
"s": 11419,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11447,
"s": 11434,
"text": "SoumikMondal"
},
{
"code": null,
"e": 11459,
"s": 11447,
"text": "unknown2108"
},
{
"code": null,
"e": 11471,
"s": 11459,
"text": "prophet1999"
},
{
"code": null,
"e": 11484,
"s": 11471,
"text": "simmytarika5"
},
{
"code": null,
"e": 11501,
"s": 11484,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 11508,
"s": 11501,
"text": "Arrays"
},
{
"code": null,
"e": 11513,
"s": 11508,
"text": "Hash"
},
{
"code": null,
"e": 11520,
"s": 11513,
"text": "Arrays"
},
{
"code": null,
"e": 11525,
"s": 11520,
"text": "Hash"
}
] |
LinkedList removeFirst() Method in Java
|
10 Dec, 2018
The Java.util.LinkedList.removeFirst() method is used to remove the first element from a linked list. This function also returns the first element after removing it.
Syntax:
LinkedList.removeFirst();
Parameters: This function does not take any parameters.
Return Value: The method returns the first element or the element present at the head of the list.
Below program illustrate the Java.util.LinkedList.removeFirst() method:
// Java code to illustrate removeFirst() methodimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the list System.out.println("LinkedList:" + list); // Remove the head using removeFirst() method System.out.println("The first element is: " + list.removeFirst()); // Displaying the final list System.out.println("Final LinkedList:" + list); }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The first element is: Geeks
Final LinkedList:[for, Geeks, 10, 20]
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "The Java.util.LinkedList.removeFirst() method is used to remove the first element from a linked list. This function also returns the first element after removing it."
},
{
"code": null,
"e": 202,
"s": 194,
"text": "Syntax:"
},
{
"code": null,
"e": 229,
"s": 202,
"text": "LinkedList.removeFirst();\n"
},
{
"code": null,
"e": 285,
"s": 229,
"text": "Parameters: This function does not take any parameters."
},
{
"code": null,
"e": 384,
"s": 285,
"text": "Return Value: The method returns the first element or the element present at the head of the list."
},
{
"code": null,
"e": 456,
"s": 384,
"text": "Below program illustrate the Java.util.LinkedList.removeFirst() method:"
},
{
"code": "// Java code to illustrate removeFirst() methodimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the list System.out.println(\"LinkedList:\" + list); // Remove the head using removeFirst() method System.out.println(\"The first element is: \" + list.removeFirst()); // Displaying the final list System.out.println(\"Final LinkedList:\" + list); }}",
"e": 1215,
"s": 456,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1215,
"text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nThe first element is: Geeks\nFinal LinkedList:[for, Geeks, 10, 20]\n"
},
{
"code": null,
"e": 1341,
"s": 1321,
"text": "Java - util package"
},
{
"code": null,
"e": 1358,
"s": 1341,
"text": "Java-Collections"
},
{
"code": null,
"e": 1373,
"s": 1358,
"text": "Java-Functions"
},
{
"code": null,
"e": 1389,
"s": 1373,
"text": "java-LinkedList"
},
{
"code": null,
"e": 1394,
"s": 1389,
"text": "Java"
},
{
"code": null,
"e": 1399,
"s": 1394,
"text": "Java"
},
{
"code": null,
"e": 1416,
"s": 1399,
"text": "Java-Collections"
}
] |
Collection contains() method in Java with Examples
|
29 Nov, 2018
The contains(Object element) of java.util.Collection interface is used to check whether the element ‘element’ exists in this collection. This method returns a boolean value depicting the presence of the element. If the element is present, it returns true, else it returns false.
Syntax:
Collection.contains(Object element)
Parameters: This method accepts a mandatory parameter element of type Object which is to be checked in this collection.
Return Value: This method returns a boolean value depicting the presence of the element. If the element is added, it returns true, else it returns false.
Exceptions: This method throws following exceptions:
ClassCastException: if the class of the specified element prevents it from being added to this collection
NullPointerException: if the specified element is null and this collection does not permit null elements
Below examples illustrate the Collection contains() method:
Example 1: Using LinkedList Class
// Java code to illustrate boolean contains() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Output the present list System.out.println("The list is: " + list); // Checking the presence of Geeks // using contains() method boolean result = list.contains("Geeks"); // printing the result System.out.println("Is Geeks present in the List: " + result); }}
The list is: [Geeks, for, Geeks]
Is Geeks present in the List: true
Example 2: Using ArrayDeque Class
// Java code to illustrate contains() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Checking the presence of Geeks // using contains() method boolean result = de_que.contains("Geeks"); // printing the result System.out.println("Is Geeks present in the ArrayDeque: " + result); }}
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Is Geeks present in the ArrayDeque: true
Example 3: Using ArrayList Class
// Java code to illustrate contains() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // Output the present list System.out.println("ArrayList: " + arrlist); // Checking the presence of 20 // using contains() method boolean result = arrlist.contains(20); // printing the result System.out.println("Is 20 present in the ArrayList: " + result); }}
ArrayList: [15, 20, 25]
Is 20 present in the ArrayList: true
Example 4: To demonstrate NullPointer Exception
// Java code to illustrate boolean contains() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // Displaying the list System.out.println("The ArrayList is: " + list); try { // Checking presence of null list.contains(null); } catch (Exception e) { System.out.println("Exception: " + e); } }}
The ArrayList is: []
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#contains-java.lang.Object-
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
HashSet in Java
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "The contains(Object element) of java.util.Collection interface is used to check whether the element ‘element’ exists in this collection. This method returns a boolean value depicting the presence of the element. If the element is present, it returns true, else it returns false."
},
{
"code": null,
"e": 315,
"s": 307,
"text": "Syntax:"
},
{
"code": null,
"e": 352,
"s": 315,
"text": "Collection.contains(Object element)\n"
},
{
"code": null,
"e": 472,
"s": 352,
"text": "Parameters: This method accepts a mandatory parameter element of type Object which is to be checked in this collection."
},
{
"code": null,
"e": 626,
"s": 472,
"text": "Return Value: This method returns a boolean value depicting the presence of the element. If the element is added, it returns true, else it returns false."
},
{
"code": null,
"e": 679,
"s": 626,
"text": "Exceptions: This method throws following exceptions:"
},
{
"code": null,
"e": 785,
"s": 679,
"text": "ClassCastException: if the class of the specified element prevents it from being added to this collection"
},
{
"code": null,
"e": 890,
"s": 785,
"text": "NullPointerException: if the specified element is null and this collection does not permit null elements"
},
{
"code": null,
"e": 950,
"s": 890,
"text": "Below examples illustrate the Collection contains() method:"
},
{
"code": null,
"e": 984,
"s": 950,
"text": "Example 1: Using LinkedList Class"
},
{
"code": "// Java code to illustrate boolean contains() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Output the present list System.out.println(\"The list is: \" + list); // Checking the presence of Geeks // using contains() method boolean result = list.contains(\"Geeks\"); // printing the result System.out.println(\"Is Geeks present in the List: \" + result); }}",
"e": 1721,
"s": 984,
"text": null
},
{
"code": null,
"e": 1790,
"s": 1721,
"text": "The list is: [Geeks, for, Geeks]\nIs Geeks present in the List: true\n"
},
{
"code": null,
"e": 1824,
"s": 1790,
"text": "Example 2: Using ArrayDeque Class"
},
{
"code": "// Java code to illustrate contains() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Checking the presence of Geeks // using contains() method boolean result = de_que.contains(\"Geeks\"); // printing the result System.out.println(\"Is Geeks present in the ArrayDeque: \" + result); }}",
"e": 2620,
"s": 1824,
"text": null
},
{
"code": null,
"e": 2705,
"s": 2620,
"text": "ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nIs Geeks present in the ArrayDeque: true\n"
},
{
"code": null,
"e": 2738,
"s": 2705,
"text": "Example 3: Using ArrayList Class"
},
{
"code": "// Java code to illustrate contains() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // Output the present list System.out.println(\"ArrayList: \" + arrlist); // Checking the presence of 20 // using contains() method boolean result = arrlist.contains(20); // printing the result System.out.println(\"Is 20 present in the ArrayList: \" + result); }}",
"e": 3499,
"s": 2738,
"text": null
},
{
"code": null,
"e": 3561,
"s": 3499,
"text": "ArrayList: [15, 20, 25]\nIs 20 present in the ArrayList: true\n"
},
{
"code": null,
"e": 3609,
"s": 3561,
"text": "Example 4: To demonstrate NullPointer Exception"
},
{
"code": "// Java code to illustrate boolean contains() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // Displaying the list System.out.println(\"The ArrayList is: \" + list); try { // Checking presence of null list.contains(null); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 4141,
"s": 3609,
"text": null
},
{
"code": null,
"e": 4163,
"s": 4141,
"text": "The ArrayList is: []\n"
},
{
"code": null,
"e": 4269,
"s": 4163,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#contains-java.lang.Object-"
},
{
"code": null,
"e": 4289,
"s": 4269,
"text": "Java - util package"
},
{
"code": null,
"e": 4306,
"s": 4289,
"text": "Java-Collections"
},
{
"code": null,
"e": 4321,
"s": 4306,
"text": "Java-Functions"
},
{
"code": null,
"e": 4326,
"s": 4321,
"text": "Java"
},
{
"code": null,
"e": 4331,
"s": 4326,
"text": "Java"
},
{
"code": null,
"e": 4348,
"s": 4331,
"text": "Java-Collections"
},
{
"code": null,
"e": 4446,
"s": 4348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4461,
"s": 4446,
"text": "Stream In Java"
},
{
"code": null,
"e": 4482,
"s": 4461,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4503,
"s": 4482,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4522,
"s": 4503,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4539,
"s": 4522,
"text": "Generics in Java"
},
{
"code": null,
"e": 4569,
"s": 4539,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4585,
"s": 4569,
"text": "Strings in Java"
},
{
"code": null,
"e": 4611,
"s": 4585,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4627,
"s": 4611,
"text": "HashSet in Java"
}
] |
Synchronization in Java
|
25 Jun, 2022
Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results.
So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point in time. Java provides a way of creating threads and synchronizing their tasks using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
Following is the general form of a synchronized block:
// Only one thread can execute at a time.
// sync_object is a reference to an object
// whose lock associates with the monitor.
// The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
Following is an example of multi-threading with synchronized.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Java
// A Java program to demonstrate working of// synchronized. import java.io.*;import java.util.*; // A Class used to send a messageclass Sender{ public void send(String msg) { System.out.println("Sending\t" + msg ); try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Thread interrupted."); } System.out.println("\n" + msg + "Sent"); }} // Class for send a message using Threadsclass ThreadedSend extends Thread{ private String msg; Sender sender; // Receives a message object and a string // message to be sent ThreadedSend(String m, Sender obj) { msg = m; sender = obj; } public void run() { // Only one thread can send a message // at a time. synchronized(sender) { // synchronizing the send object sender.send(msg); } }} // Driver classclass SyncDemo{ public static void main(String args[]) { Sender send = new Sender(); ThreadedSend S1 = new ThreadedSend( " Hi " , send ); ThreadedSend S2 = new ThreadedSend( " Bye " , send ); // Start two threads of ThreadedSend type S1.start(); S2.start(); // wait for threads to end try { S1.join(); S2.join(); } catch(Exception e) { System.out.println("Interrupted"); } }}
Sending Hi
Hi Sent
Sending Bye
Bye Sent
The output is the same every time we run the program.
In the above example, we choose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the whole send() block as synchronized, producing the same result. Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class.
// An alternate implementation to demonstrate
// that we can use synchronized with method also.
class Sender {
public synchronized void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
We do not always have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods make this possible.
// One more alternate implementation to demonstrate
// that synchronized can be used with only a part of
// method
class Sender
{
public void send(String msg)
{
synchronized(this)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
}
This article is contributed by Souradeep Barua. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
DeepakMathuria
saurabh1990aror
sooda367
nishkarshgandhi
surinderdawra388
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Initialize an ArrayList in Java
Generics in Java
Java Programming Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 219,
"s": 54,
"text": "Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. "
},
{
"code": null,
"e": 827,
"s": 219,
"text": "So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point in time. Java provides a way of creating threads and synchronizing their tasks using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block."
},
{
"code": null,
"e": 883,
"s": 827,
"text": "Following is the general form of a synchronized block: "
},
{
"code": null,
"e": 1170,
"s": 883,
"text": "// Only one thread can execute at a time. \n// sync_object is a reference to an object\n// whose lock associates with the monitor. \n// The code is said to be synchronized on\n// the monitor object\nsynchronized(sync_object)\n{\n // Access shared variables and other\n // shared resources\n}"
},
{
"code": null,
"e": 1485,
"s": 1170,
"text": "This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor."
},
{
"code": null,
"e": 1547,
"s": 1485,
"text": "Following is an example of multi-threading with synchronized."
},
{
"code": null,
"e": 1556,
"s": 1547,
"text": "Chapters"
},
{
"code": null,
"e": 1583,
"s": 1556,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1633,
"s": 1583,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1656,
"s": 1633,
"text": "captions off, selected"
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "English"
},
{
"code": null,
"e": 1688,
"s": 1664,
"text": "This is a modal window."
},
{
"code": null,
"e": 1757,
"s": 1688,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1779,
"s": 1757,
"text": "End of dialog window."
},
{
"code": null,
"e": 1784,
"s": 1779,
"text": "Java"
},
{
"code": "// A Java program to demonstrate working of// synchronized. import java.io.*;import java.util.*; // A Class used to send a messageclass Sender{ public void send(String msg) { System.out.println(\"Sending\\t\" + msg ); try { Thread.sleep(1000); } catch (Exception e) { System.out.println(\"Thread interrupted.\"); } System.out.println(\"\\n\" + msg + \"Sent\"); }} // Class for send a message using Threadsclass ThreadedSend extends Thread{ private String msg; Sender sender; // Receives a message object and a string // message to be sent ThreadedSend(String m, Sender obj) { msg = m; sender = obj; } public void run() { // Only one thread can send a message // at a time. synchronized(sender) { // synchronizing the send object sender.send(msg); } }} // Driver classclass SyncDemo{ public static void main(String args[]) { Sender send = new Sender(); ThreadedSend S1 = new ThreadedSend( \" Hi \" , send ); ThreadedSend S2 = new ThreadedSend( \" Bye \" , send ); // Start two threads of ThreadedSend type S1.start(); S2.start(); // wait for threads to end try { S1.join(); S2.join(); } catch(Exception e) { System.out.println(\"Interrupted\"); } }}",
"e": 3276,
"s": 1784,
"text": null
},
{
"code": null,
"e": 3333,
"s": 3279,
"text": "Sending Hi \n\n Hi Sent\nSending Bye \n\n Bye Sent"
},
{
"code": null,
"e": 3389,
"s": 3335,
"text": "The output is the same every time we run the program."
},
{
"code": null,
"e": 3704,
"s": 3391,
"text": "In the above example, we choose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the whole send() block as synchronized, producing the same result. Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class. "
},
{
"code": null,
"e": 4114,
"s": 3706,
"text": "// An alternate implementation to demonstrate\n// that we can use synchronized with method also.\n\nclass Sender {\n public synchronized void send(String msg)\n {\n System.out.println(\"Sending\\t\" + msg);\n try {\n Thread.sleep(1000);\n }\n catch (Exception e) {\n System.out.println(\"Thread interrupted.\");\n }\n System.out.println(\"\\n\" + msg + \"Sent\");\n }\n}"
},
{
"code": null,
"e": 4292,
"s": 4114,
"text": "We do not always have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods make this possible."
},
{
"code": null,
"e": 4817,
"s": 4294,
"text": "// One more alternate implementation to demonstrate\n// that synchronized can be used with only a part of \n// method\n\nclass Sender \n{\n public void send(String msg)\n {\n synchronized(this)\n {\n System.out.println(\"Sending\\t\" + msg );\n try \n {\n Thread.sleep(1000);\n } \n catch (Exception e) \n {\n System.out.println(\"Thread interrupted.\");\n }\n System.out.println(\"\\n\" + msg + \"Sent\");\n }\n }\n}"
},
{
"code": null,
"e": 4993,
"s": 4821,
"text": "This article is contributed by Souradeep Barua. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 5010,
"s": 4995,
"text": "DeepakMathuria"
},
{
"code": null,
"e": 5026,
"s": 5010,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5035,
"s": 5026,
"text": "sooda367"
},
{
"code": null,
"e": 5051,
"s": 5035,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 5068,
"s": 5051,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5088,
"s": 5068,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 5093,
"s": 5088,
"text": "Java"
},
{
"code": null,
"e": 5098,
"s": 5093,
"text": "Java"
},
{
"code": null,
"e": 5196,
"s": 5098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5240,
"s": 5196,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 5276,
"s": 5240,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5301,
"s": 5276,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5332,
"s": 5301,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5347,
"s": 5332,
"text": "Stream In Java"
},
{
"code": null,
"e": 5371,
"s": 5347,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5399,
"s": 5371,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 5431,
"s": 5399,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 5448,
"s": 5431,
"text": "Generics in Java"
}
] |
Python | Number of values greater than K in list
|
25 Nov, 2018
One of the problem that is basically a subproblem for many complex problem, finding numbers greater than certain number in list in python, is commonly encountered and this particular article discusses possible solutions to this particular problem.
Method 1 : Naive methodThe most common way this problem can be solved is using loop and just counting the occurrences of elements that are greater than the given number K.
# Python 3 code to demonstrate # find number of elements > k# using naive method # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print ("The list : " + str(test_list)) # using naive method # to get numbers > kcount = 0for i in test_list : if i > k : count = count + 1 # printing the intersection print ("The numbers greater than 4 : " + str(count))
Output :
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Method 2 : Using list comprehensionThis method achieves this task in similar way, but in more concise manner. List comprehension always lower the lines of codes in the program even though runs a similar approach in background.
# Python 3 code to demonstrate # find number of elements > k# using list comprehension # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print ("The list : " + str(test_list)) # using list comprehension# to get numbers > kcount = len([i for i in test_list if i > k]) # printing the intersection print ("The numbers greater than 4 : " + str(count))
Output :
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Method 3 : Using sum()The sum() can also help us achieving this task. We can return 1 when the number greater than k is found and then compute the summation of is using sum()
# Python 3 code to demonstrate # find number of elements > k# using sum() # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print ("The list : " + str(test_list)) # using sum()# to get numbers > kcount = sum(i > k for i in test_list) # printing the intersection print ("The numbers greater than 4 : " + str(count))
Output :
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Method 4 : Using functools.reduce()By using reduce(), we can also perform the summation of all the collected numbers for the function and then accumulate them to return the result i.e the count of numbers greater than K.
# Python 3 code to demonstrate # find number of elements > k# using reduce()from functools import reduce # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print ("The list : " + str(test_list)) # using reduce()# to get numbers > kcount = reduce(lambda sum, j: sum + (1 if j > k else 0), test_list, 0) # printing the intersection print ("The numbers greater than 4 : " + str(count))
Output :
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Method 5 : Using bisect() + sort()The combination of sort() and bisect(), can actually perform the task of binary search, and hence getting the index and subtracting the size of list can actually help us get elements that are greater than particular element in the list.
# Python 3 code to demonstrate # find number of elements > k# using bisect() + sort()from bisect import bisect # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print ("The list : " + str(test_list)) # using bisect() + sort()# to get numbers > ktest_list.sort()count = len(test_list) - bisect(test_list, k) # printing the intersection print ("The numbers greater than 4 : " + str(count))
Output :
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2018"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "One of the problem that is basically a subproblem for many complex problem, finding numbers greater than certain number in list in python, is commonly encountered and this particular article discusses possible solutions to this particular problem."
},
{
"code": null,
"e": 448,
"s": 276,
"text": "Method 1 : Naive methodThe most common way this problem can be solved is using loop and just counting the occurrences of elements that are greater than the given number K."
},
{
"code": "# Python 3 code to demonstrate # find number of elements > k# using naive method # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print (\"The list : \" + str(test_list)) # using naive method # to get numbers > kcount = 0for i in test_list : if i > k : count = count + 1 # printing the intersection print (\"The numbers greater than 4 : \" + str(count))",
"e": 853,
"s": 448,
"text": null
},
{
"code": null,
"e": 862,
"s": 853,
"text": "Output :"
},
{
"code": null,
"e": 924,
"s": 862,
"text": "The list : [1, 7, 5, 6, 3, 8]\nThe numbers greater than 4 : 4\n"
},
{
"code": null,
"e": 1151,
"s": 924,
"text": "Method 2 : Using list comprehensionThis method achieves this task in similar way, but in more concise manner. List comprehension always lower the lines of codes in the program even though runs a similar approach in background."
},
{
"code": "# Python 3 code to demonstrate # find number of elements > k# using list comprehension # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print (\"The list : \" + str(test_list)) # using list comprehension# to get numbers > kcount = len([i for i in test_list if i > k]) # printing the intersection print (\"The numbers greater than 4 : \" + str(count))",
"e": 1542,
"s": 1151,
"text": null
},
{
"code": null,
"e": 1551,
"s": 1542,
"text": "Output :"
},
{
"code": null,
"e": 1613,
"s": 1551,
"text": "The list : [1, 7, 5, 6, 3, 8]\nThe numbers greater than 4 : 4\n"
},
{
"code": null,
"e": 1788,
"s": 1613,
"text": "Method 3 : Using sum()The sum() can also help us achieving this task. We can return 1 when the number greater than k is found and then compute the summation of is using sum()"
},
{
"code": "# Python 3 code to demonstrate # find number of elements > k# using sum() # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print (\"The list : \" + str(test_list)) # using sum()# to get numbers > kcount = sum(i > k for i in test_list) # printing the intersection print (\"The numbers greater than 4 : \" + str(count))",
"e": 2146,
"s": 1788,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2146,
"text": "Output :"
},
{
"code": null,
"e": 2217,
"s": 2155,
"text": "The list : [1, 7, 5, 6, 3, 8]\nThe numbers greater than 4 : 4\n"
},
{
"code": null,
"e": 2438,
"s": 2217,
"text": "Method 4 : Using functools.reduce()By using reduce(), we can also perform the summation of all the collected numbers for the function and then accumulate them to return the result i.e the count of numbers greater than K."
},
{
"code": "# Python 3 code to demonstrate # find number of elements > k# using reduce()from functools import reduce # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print (\"The list : \" + str(test_list)) # using reduce()# to get numbers > kcount = reduce(lambda sum, j: sum + (1 if j > k else 0), test_list, 0) # printing the intersection print (\"The numbers greater than 4 : \" + str(count))",
"e": 2864,
"s": 2438,
"text": null
},
{
"code": null,
"e": 2873,
"s": 2864,
"text": "Output :"
},
{
"code": null,
"e": 2935,
"s": 2873,
"text": "The list : [1, 7, 5, 6, 3, 8]\nThe numbers greater than 4 : 4\n"
},
{
"code": null,
"e": 3206,
"s": 2935,
"text": "Method 5 : Using bisect() + sort()The combination of sort() and bisect(), can actually perform the task of binary search, and hence getting the index and subtracting the size of list can actually help us get elements that are greater than particular element in the list."
},
{
"code": "# Python 3 code to demonstrate # find number of elements > k# using bisect() + sort()from bisect import bisect # initializing listtest_list = [1, 7, 5, 6, 3, 8] # initializing kk = 4 # printing list print (\"The list : \" + str(test_list)) # using bisect() + sort()# to get numbers > ktest_list.sort()count = len(test_list) - bisect(test_list, k) # printing the intersection print (\"The numbers greater than 4 : \" + str(count))",
"e": 3637,
"s": 3206,
"text": null
},
{
"code": null,
"e": 3646,
"s": 3637,
"text": "Output :"
},
{
"code": null,
"e": 3708,
"s": 3646,
"text": "The list : [1, 7, 5, 6, 3, 8]\nThe numbers greater than 4 : 4\n"
},
{
"code": null,
"e": 3729,
"s": 3708,
"text": "Python list-programs"
},
{
"code": null,
"e": 3741,
"s": 3729,
"text": "python-list"
},
{
"code": null,
"e": 3748,
"s": 3741,
"text": "Python"
},
{
"code": null,
"e": 3760,
"s": 3748,
"text": "python-list"
},
{
"code": null,
"e": 3858,
"s": 3760,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3876,
"s": 3858,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3918,
"s": 3876,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3953,
"s": 3918,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3985,
"s": 3953,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4011,
"s": 3985,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4040,
"s": 4011,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4067,
"s": 4040,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4088,
"s": 4067,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4111,
"s": 4088,
"text": "Introduction To PYTHON"
}
] |
Back to Basics — Linear Regression in R | by Jason Chong | Towards Data Science
|
It’s been a while since my last article on here and that’s because I have been busy preparing for my actuarial exam that is coming up in just two months. In the process of studying these past couple of weeks, I ran into a good old friend from way back in my first ever statistics class, linear regression.
As I started to learn more complex machine learning algorithms, I sometimes get caught up with building the fanciest model to solve a problem when in reality, a simple linear model could have easily gotten the job done. It wasn’t until I started refreshing my knowledge around linear regression that I gained a newfound appreciation for its simplicity and ease of use.
So, I thought it’d be a good idea to use this article to not only reinforce my understanding of linear regression but also take this opportunity to share this fundamental topic in statistics with others.
To keep this article as concise as possible, I will not be covering every small detail of linear regression but instead, offer just enough for you to gain a good understanding of how to perform and interpret it in R. I will also briefly touch upon the topic of ANOVA, that is the analysis of variance as well as the coefficient of determination or more commonly known as R-squared.
With that said, here we go!
Linear regression is a linear model which plots the relationship between a response variable and a single explanatory variable (simple linear regression) or multiple explanatory variables (multiple linear regression).
Since we were talking about my actuarial exam, let’s just use that as an example.
Suppose I would like to study the relationship between the hours someone spends studying and their corresponding examination score. I will first need to collect data points for my study. Then, I will proceed to plot these data points on a graph where the x-axis represents the hours someone spent studying and the y-axis represents their final examination score.
Note that the final examination score in this example represents our response variable as it is the variable that we’re investigating. On the other hand, the hours spent studying is called an explanatory variable as it is the variable that will influence and “explain” the outcome of the response variable.
But hold on, so far we have only discussed the data points that go onto the graph. How does the regression line actually come about?
If we try to draw a line through all the data points, chances are, not all of them will fit directly on that line. So how do we know how to best position the line? This is where the concept of line of best fit comes in.
The idea is to fit a line through all the data points such that the line minimises the cumulative distances or in regression terms, the residuals, between the observed values and the fitted values. This process is called fitting a line of best fit.
I highly encourage checking out the video below for a more visual explanation of this particular concept.
As a result, we should expect to see a linear line that is trending upwards or in other words, has a positive slope and that is because the more hours someone spends studying for an exam, quite naturally, the better the person performs in that exam.
Now that we got all the basics out of the way, let us now see how we can perform a simple linear regression in R.
Suppose we have a 6x2 dataframe which measures the estimated baby weights at different time periods during a pregnancy.
First, let’s store this dataframe into a variable called baby.
# Load datababy = read.table("baby weights.txt", header = T)# Show datababy
We can then plot these 6 data points on a graph using a scatterplot.
# Plot dataplot(baby, main = "Estimated baby weights during pregnancy", xlab = "Gestation period (weeks)", ylab = "Weight (kg)")
Main, xlab and ylab are simply arguments within the plot function in R which specifies the main title, x-axis label and y-axis label of the plot respectively. The following is the result of that plot.
It does look like there is a positive relationship between our explanatory variable, gestation period and the response variable, weight. In other words, the longer the baby stays in the womb, the heavier it gets. Sounds logical.
We can examine the correlation between the two variables by using the cor function in R and further test if it is statistically significant.
Also, we can attach the baby dataframe so that we can access its content without repeatedly calling the variable, just to make our analysis easier.
# Attach dataattach(baby)# Compute correlation between gestation period and baby weightcor(gestation, weight)# Test whether correlation coefficient is zerocor.test(gestation, weight)
There is a very strong positive correlation between the two variables. The output also clearly indicates that this is a significant result. Thus, we can now proceed to fit a linear line through those data points.
Fitting a linear regression model in R is extremely easy and straightforward. The function to pay attention to here is lm, which stands for linear model.
Here, we are going to fit a linear model which regresses the baby weight on the y-axis against gestation period on the x-axis. The order here is important and worth remembering, the response variable always comes before the explanatory variables.
We will store the linear model in a variable called model so that we can access the output at a later stage.
# Fit linear modelmodel = lm(weight ~ gestation)# Examine modelmodelsummary(model)
There are a number of ways we can examine the linear model but the most comprehensive one is using the summary function.
As we can see, there are a few sections in this particular output but don’t worry, we will go through each section and discuss exactly what they mean later. For now, let’s go ahead and add this linear model to our scatterplot from earlier on by using the abline function.
# Add regression lineabline(model, col = "red", lty = "dashed")
Fitted values share the same x values as the observed data, except they lie precisely on the regression line.
In this section, we will look at how we can obtain these fitted values as well as how to add them to our existing regression line. Again, there are a few ways we can go about this and they all give the same result.
# Obtain fitted values model$fitted.valuesfitted(model)predict(model)# Add fitted values to regression line points(gestation, fitted(model), col = "blue", pch = 16)
Variance is a statistical measurement of the spread between the numbers in a dataset. More specifically, how far each data point is away from the mean. Analysis of variance is, therefore, the study of variance.
By dividing total variance into two components, we can assess the amount of variance that is accounted for by our regression line and those that are not accounted for, called residuals.
R-squared is the percentage of the response variable variation that a linear model explains. The higher the R-squared values, the smaller the differences between the observed values and the fitted values.
However, R-squared alone is not a sufficient indicator of whether or not a regression line provides a good fit. We have to also take into consideration the context of the study as well as the statistical significance of each explanatory variable in the regression model.
# ANOVAanova(model)
The p-value of 0.0003661 from the F-test confirms that there is a linear relationship between gestation and weight. This result is consistent with our correlation test from earlier on.
We can also see that the regression sum of squares is 2.92129 and the residual sum of squares is 0.09371, which gives a total sum of squares of 3.015.
There are two ways we can work out the sum of squares. One is by first principles and the other is by using the output from the anova function.
x = gestation; y = weight# Total sum of squares(SStot = sum((y - mean(y))^2)sum(anova(model)[,2])# Residual sum of squares(SSres = sum((y-fitted(model))^2))anova(model)[2,2]# Regression sum of squares(SSreg = sum((fitted(model)-mean(y))^2))anova(model)[1,2]
Similarly, there are three ways to calculate the coefficient of determination or R-squared and all three of them give the same result of 0.9689173.
From the summary outputSquare of correlationDividing regression sum of squares by total sum of squares
From the summary output
Square of correlation
Dividing regression sum of squares by total sum of squares
# Method 1summary(model)$r.squared# Method 2cor(gestation, weight)^2# Method 3SSreg / SStot
Since we only have one explanatory variable in this particular study, we have two coefficients in total, one for the intercept and the one for the slope.
Recall the output from the summary function.
We can see that the slope parameter has a p-value of 0.000366 which signifies that it is statistically significant or in other words, non-zero.
To take this a step further, we can also produce a confidence interval for the intercept and the slope parameter.
# Confidence interval for intercept and regression coefficient confint(model, level = 0.99)
The goal of fitting a linear model is to make predictions that are of reasonable accuracy.
In this section, we will look at two different ways we can make predictions using a simple linear model.
By first principlesUsing the predict function
By first principles
Using the predict function
In addition, we can also produce confidence intervals and prediction intervals on these predictions to evaluate their accuracy.
Suppose we would like to predict a baby’s weight at week 33, here is how we can do it via two separate methods.
# First principlescoef(model)[1] + coef(model)[2] * 33# Using predict functionnewdata = data.frame(gestation = 33)predict(model, newdata)# Confidence interval predict(model, newdata, interval = "confidence", level = 0.9)# Prediction intervalpredict(model, newdata, interval = "predict", level = 0.9)
Both methods should give the same prediction value of 2.141429.
Recall that residuals are the differences between the observed values and the fitted values in a regression. There is an underlying assumption in regression and that is that residuals ought to follow a normal distribution.
In addition to checking the normality assumption, by examining the trends of the residuals, we can also evaluate how well our regression line fits the data points i.e. observe if there is any particular section of where the model is overestimating or underestimating the true data points.
In this section, we will discuss how to obtain the residual values as well as how to use various plots to analyse the patterns that are present in these residuals.
There are two ways to obtain the residuals:
Using the resid functionSubtract the fitted values from the observed values
Using the resid function
Subtract the fitted values from the observed values
# Method 1resid(model)[1]# Method 2weight - fitted(model)
Next, we will look at how to visualise the trends in the residuals. There are different plots that we can use here and each plot can provide us with different information about the behaviour of the residuals.
# Plot residuals vs fittedplot(model, 1)
Residuals are hovering around the value 0 which is a good indicator that the linear model is a good fit. Point 2 does look like an outlier but it is difficult to tell with only a few values.
Another plot that we can use is called the QQ plot which is a scatterplot that plots two sets of quantiles against one another. In our case, we are interested to see if the residuals follow a normal distribution and therefore we will plot the quantiles of the residuals against those of a normal distribution.
If our residuals are indeed normally distributed, we should expect to see a plot that is diagonal from the bottom left to the top right.
# QQ plotplot(model, 2)
The diagonal line appears very close to the majority of the data points except point 2. This might suggest that it is worth dropping point 2 from the dataset to allow for a more accurate linear model.
Well done for making it all the way through this article. I hope you have learned a little bit more about the concept of linear regression as well as how to perform and interpret it in R.
To recap, in this article, we have covered:
What a linear model is
How to fit a line of best fit
Analysis of variance and R-squared
Significance of the intercept and regression coefficient
How to make predictions using a linear model
Residuals
Do check out my other articles if you are interested in learning about data science and machine learning.
|
[
{
"code": null,
"e": 478,
"s": 172,
"text": "It’s been a while since my last article on here and that’s because I have been busy preparing for my actuarial exam that is coming up in just two months. In the process of studying these past couple of weeks, I ran into a good old friend from way back in my first ever statistics class, linear regression."
},
{
"code": null,
"e": 847,
"s": 478,
"text": "As I started to learn more complex machine learning algorithms, I sometimes get caught up with building the fanciest model to solve a problem when in reality, a simple linear model could have easily gotten the job done. It wasn’t until I started refreshing my knowledge around linear regression that I gained a newfound appreciation for its simplicity and ease of use."
},
{
"code": null,
"e": 1051,
"s": 847,
"text": "So, I thought it’d be a good idea to use this article to not only reinforce my understanding of linear regression but also take this opportunity to share this fundamental topic in statistics with others."
},
{
"code": null,
"e": 1433,
"s": 1051,
"text": "To keep this article as concise as possible, I will not be covering every small detail of linear regression but instead, offer just enough for you to gain a good understanding of how to perform and interpret it in R. I will also briefly touch upon the topic of ANOVA, that is the analysis of variance as well as the coefficient of determination or more commonly known as R-squared."
},
{
"code": null,
"e": 1461,
"s": 1433,
"text": "With that said, here we go!"
},
{
"code": null,
"e": 1679,
"s": 1461,
"text": "Linear regression is a linear model which plots the relationship between a response variable and a single explanatory variable (simple linear regression) or multiple explanatory variables (multiple linear regression)."
},
{
"code": null,
"e": 1761,
"s": 1679,
"text": "Since we were talking about my actuarial exam, let’s just use that as an example."
},
{
"code": null,
"e": 2124,
"s": 1761,
"text": "Suppose I would like to study the relationship between the hours someone spends studying and their corresponding examination score. I will first need to collect data points for my study. Then, I will proceed to plot these data points on a graph where the x-axis represents the hours someone spent studying and the y-axis represents their final examination score."
},
{
"code": null,
"e": 2431,
"s": 2124,
"text": "Note that the final examination score in this example represents our response variable as it is the variable that we’re investigating. On the other hand, the hours spent studying is called an explanatory variable as it is the variable that will influence and “explain” the outcome of the response variable."
},
{
"code": null,
"e": 2564,
"s": 2431,
"text": "But hold on, so far we have only discussed the data points that go onto the graph. How does the regression line actually come about?"
},
{
"code": null,
"e": 2784,
"s": 2564,
"text": "If we try to draw a line through all the data points, chances are, not all of them will fit directly on that line. So how do we know how to best position the line? This is where the concept of line of best fit comes in."
},
{
"code": null,
"e": 3033,
"s": 2784,
"text": "The idea is to fit a line through all the data points such that the line minimises the cumulative distances or in regression terms, the residuals, between the observed values and the fitted values. This process is called fitting a line of best fit."
},
{
"code": null,
"e": 3139,
"s": 3033,
"text": "I highly encourage checking out the video below for a more visual explanation of this particular concept."
},
{
"code": null,
"e": 3389,
"s": 3139,
"text": "As a result, we should expect to see a linear line that is trending upwards or in other words, has a positive slope and that is because the more hours someone spends studying for an exam, quite naturally, the better the person performs in that exam."
},
{
"code": null,
"e": 3503,
"s": 3389,
"text": "Now that we got all the basics out of the way, let us now see how we can perform a simple linear regression in R."
},
{
"code": null,
"e": 3623,
"s": 3503,
"text": "Suppose we have a 6x2 dataframe which measures the estimated baby weights at different time periods during a pregnancy."
},
{
"code": null,
"e": 3686,
"s": 3623,
"text": "First, let’s store this dataframe into a variable called baby."
},
{
"code": null,
"e": 3762,
"s": 3686,
"text": "# Load datababy = read.table(\"baby weights.txt\", header = T)# Show datababy"
},
{
"code": null,
"e": 3831,
"s": 3762,
"text": "We can then plot these 6 data points on a graph using a scatterplot."
},
{
"code": null,
"e": 3960,
"s": 3831,
"text": "# Plot dataplot(baby, main = \"Estimated baby weights during pregnancy\", xlab = \"Gestation period (weeks)\", ylab = \"Weight (kg)\")"
},
{
"code": null,
"e": 4161,
"s": 3960,
"text": "Main, xlab and ylab are simply arguments within the plot function in R which specifies the main title, x-axis label and y-axis label of the plot respectively. The following is the result of that plot."
},
{
"code": null,
"e": 4390,
"s": 4161,
"text": "It does look like there is a positive relationship between our explanatory variable, gestation period and the response variable, weight. In other words, the longer the baby stays in the womb, the heavier it gets. Sounds logical."
},
{
"code": null,
"e": 4531,
"s": 4390,
"text": "We can examine the correlation between the two variables by using the cor function in R and further test if it is statistically significant."
},
{
"code": null,
"e": 4679,
"s": 4531,
"text": "Also, we can attach the baby dataframe so that we can access its content without repeatedly calling the variable, just to make our analysis easier."
},
{
"code": null,
"e": 4862,
"s": 4679,
"text": "# Attach dataattach(baby)# Compute correlation between gestation period and baby weightcor(gestation, weight)# Test whether correlation coefficient is zerocor.test(gestation, weight)"
},
{
"code": null,
"e": 5075,
"s": 4862,
"text": "There is a very strong positive correlation between the two variables. The output also clearly indicates that this is a significant result. Thus, we can now proceed to fit a linear line through those data points."
},
{
"code": null,
"e": 5229,
"s": 5075,
"text": "Fitting a linear regression model in R is extremely easy and straightforward. The function to pay attention to here is lm, which stands for linear model."
},
{
"code": null,
"e": 5476,
"s": 5229,
"text": "Here, we are going to fit a linear model which regresses the baby weight on the y-axis against gestation period on the x-axis. The order here is important and worth remembering, the response variable always comes before the explanatory variables."
},
{
"code": null,
"e": 5585,
"s": 5476,
"text": "We will store the linear model in a variable called model so that we can access the output at a later stage."
},
{
"code": null,
"e": 5668,
"s": 5585,
"text": "# Fit linear modelmodel = lm(weight ~ gestation)# Examine modelmodelsummary(model)"
},
{
"code": null,
"e": 5789,
"s": 5668,
"text": "There are a number of ways we can examine the linear model but the most comprehensive one is using the summary function."
},
{
"code": null,
"e": 6061,
"s": 5789,
"text": "As we can see, there are a few sections in this particular output but don’t worry, we will go through each section and discuss exactly what they mean later. For now, let’s go ahead and add this linear model to our scatterplot from earlier on by using the abline function."
},
{
"code": null,
"e": 6125,
"s": 6061,
"text": "# Add regression lineabline(model, col = \"red\", lty = \"dashed\")"
},
{
"code": null,
"e": 6235,
"s": 6125,
"text": "Fitted values share the same x values as the observed data, except they lie precisely on the regression line."
},
{
"code": null,
"e": 6450,
"s": 6235,
"text": "In this section, we will look at how we can obtain these fitted values as well as how to add them to our existing regression line. Again, there are a few ways we can go about this and they all give the same result."
},
{
"code": null,
"e": 6615,
"s": 6450,
"text": "# Obtain fitted values model$fitted.valuesfitted(model)predict(model)# Add fitted values to regression line points(gestation, fitted(model), col = \"blue\", pch = 16)"
},
{
"code": null,
"e": 6826,
"s": 6615,
"text": "Variance is a statistical measurement of the spread between the numbers in a dataset. More specifically, how far each data point is away from the mean. Analysis of variance is, therefore, the study of variance."
},
{
"code": null,
"e": 7012,
"s": 6826,
"text": "By dividing total variance into two components, we can assess the amount of variance that is accounted for by our regression line and those that are not accounted for, called residuals."
},
{
"code": null,
"e": 7217,
"s": 7012,
"text": "R-squared is the percentage of the response variable variation that a linear model explains. The higher the R-squared values, the smaller the differences between the observed values and the fitted values."
},
{
"code": null,
"e": 7488,
"s": 7217,
"text": "However, R-squared alone is not a sufficient indicator of whether or not a regression line provides a good fit. We have to also take into consideration the context of the study as well as the statistical significance of each explanatory variable in the regression model."
},
{
"code": null,
"e": 7508,
"s": 7488,
"text": "# ANOVAanova(model)"
},
{
"code": null,
"e": 7693,
"s": 7508,
"text": "The p-value of 0.0003661 from the F-test confirms that there is a linear relationship between gestation and weight. This result is consistent with our correlation test from earlier on."
},
{
"code": null,
"e": 7844,
"s": 7693,
"text": "We can also see that the regression sum of squares is 2.92129 and the residual sum of squares is 0.09371, which gives a total sum of squares of 3.015."
},
{
"code": null,
"e": 7988,
"s": 7844,
"text": "There are two ways we can work out the sum of squares. One is by first principles and the other is by using the output from the anova function."
},
{
"code": null,
"e": 8246,
"s": 7988,
"text": "x = gestation; y = weight# Total sum of squares(SStot = sum((y - mean(y))^2)sum(anova(model)[,2])# Residual sum of squares(SSres = sum((y-fitted(model))^2))anova(model)[2,2]# Regression sum of squares(SSreg = sum((fitted(model)-mean(y))^2))anova(model)[1,2]"
},
{
"code": null,
"e": 8394,
"s": 8246,
"text": "Similarly, there are three ways to calculate the coefficient of determination or R-squared and all three of them give the same result of 0.9689173."
},
{
"code": null,
"e": 8497,
"s": 8394,
"text": "From the summary outputSquare of correlationDividing regression sum of squares by total sum of squares"
},
{
"code": null,
"e": 8521,
"s": 8497,
"text": "From the summary output"
},
{
"code": null,
"e": 8543,
"s": 8521,
"text": "Square of correlation"
},
{
"code": null,
"e": 8602,
"s": 8543,
"text": "Dividing regression sum of squares by total sum of squares"
},
{
"code": null,
"e": 8695,
"s": 8602,
"text": "# Method 1summary(model)$r.squared# Method 2cor(gestation, weight)^2# Method 3SSreg / SStot "
},
{
"code": null,
"e": 8849,
"s": 8695,
"text": "Since we only have one explanatory variable in this particular study, we have two coefficients in total, one for the intercept and the one for the slope."
},
{
"code": null,
"e": 8894,
"s": 8849,
"text": "Recall the output from the summary function."
},
{
"code": null,
"e": 9038,
"s": 8894,
"text": "We can see that the slope parameter has a p-value of 0.000366 which signifies that it is statistically significant or in other words, non-zero."
},
{
"code": null,
"e": 9152,
"s": 9038,
"text": "To take this a step further, we can also produce a confidence interval for the intercept and the slope parameter."
},
{
"code": null,
"e": 9244,
"s": 9152,
"text": "# Confidence interval for intercept and regression coefficient confint(model, level = 0.99)"
},
{
"code": null,
"e": 9335,
"s": 9244,
"text": "The goal of fitting a linear model is to make predictions that are of reasonable accuracy."
},
{
"code": null,
"e": 9440,
"s": 9335,
"text": "In this section, we will look at two different ways we can make predictions using a simple linear model."
},
{
"code": null,
"e": 9486,
"s": 9440,
"text": "By first principlesUsing the predict function"
},
{
"code": null,
"e": 9506,
"s": 9486,
"text": "By first principles"
},
{
"code": null,
"e": 9533,
"s": 9506,
"text": "Using the predict function"
},
{
"code": null,
"e": 9661,
"s": 9533,
"text": "In addition, we can also produce confidence intervals and prediction intervals on these predictions to evaluate their accuracy."
},
{
"code": null,
"e": 9773,
"s": 9661,
"text": "Suppose we would like to predict a baby’s weight at week 33, here is how we can do it via two separate methods."
},
{
"code": null,
"e": 10073,
"s": 9773,
"text": "# First principlescoef(model)[1] + coef(model)[2] * 33# Using predict functionnewdata = data.frame(gestation = 33)predict(model, newdata)# Confidence interval predict(model, newdata, interval = \"confidence\", level = 0.9)# Prediction intervalpredict(model, newdata, interval = \"predict\", level = 0.9)"
},
{
"code": null,
"e": 10137,
"s": 10073,
"text": "Both methods should give the same prediction value of 2.141429."
},
{
"code": null,
"e": 10360,
"s": 10137,
"text": "Recall that residuals are the differences between the observed values and the fitted values in a regression. There is an underlying assumption in regression and that is that residuals ought to follow a normal distribution."
},
{
"code": null,
"e": 10649,
"s": 10360,
"text": "In addition to checking the normality assumption, by examining the trends of the residuals, we can also evaluate how well our regression line fits the data points i.e. observe if there is any particular section of where the model is overestimating or underestimating the true data points."
},
{
"code": null,
"e": 10813,
"s": 10649,
"text": "In this section, we will discuss how to obtain the residual values as well as how to use various plots to analyse the patterns that are present in these residuals."
},
{
"code": null,
"e": 10857,
"s": 10813,
"text": "There are two ways to obtain the residuals:"
},
{
"code": null,
"e": 10933,
"s": 10857,
"text": "Using the resid functionSubtract the fitted values from the observed values"
},
{
"code": null,
"e": 10958,
"s": 10933,
"text": "Using the resid function"
},
{
"code": null,
"e": 11010,
"s": 10958,
"text": "Subtract the fitted values from the observed values"
},
{
"code": null,
"e": 11068,
"s": 11010,
"text": "# Method 1resid(model)[1]# Method 2weight - fitted(model)"
},
{
"code": null,
"e": 11277,
"s": 11068,
"text": "Next, we will look at how to visualise the trends in the residuals. There are different plots that we can use here and each plot can provide us with different information about the behaviour of the residuals."
},
{
"code": null,
"e": 11318,
"s": 11277,
"text": "# Plot residuals vs fittedplot(model, 1)"
},
{
"code": null,
"e": 11509,
"s": 11318,
"text": "Residuals are hovering around the value 0 which is a good indicator that the linear model is a good fit. Point 2 does look like an outlier but it is difficult to tell with only a few values."
},
{
"code": null,
"e": 11819,
"s": 11509,
"text": "Another plot that we can use is called the QQ plot which is a scatterplot that plots two sets of quantiles against one another. In our case, we are interested to see if the residuals follow a normal distribution and therefore we will plot the quantiles of the residuals against those of a normal distribution."
},
{
"code": null,
"e": 11956,
"s": 11819,
"text": "If our residuals are indeed normally distributed, we should expect to see a plot that is diagonal from the bottom left to the top right."
},
{
"code": null,
"e": 11980,
"s": 11956,
"text": "# QQ plotplot(model, 2)"
},
{
"code": null,
"e": 12181,
"s": 11980,
"text": "The diagonal line appears very close to the majority of the data points except point 2. This might suggest that it is worth dropping point 2 from the dataset to allow for a more accurate linear model."
},
{
"code": null,
"e": 12369,
"s": 12181,
"text": "Well done for making it all the way through this article. I hope you have learned a little bit more about the concept of linear regression as well as how to perform and interpret it in R."
},
{
"code": null,
"e": 12413,
"s": 12369,
"text": "To recap, in this article, we have covered:"
},
{
"code": null,
"e": 12436,
"s": 12413,
"text": "What a linear model is"
},
{
"code": null,
"e": 12466,
"s": 12436,
"text": "How to fit a line of best fit"
},
{
"code": null,
"e": 12501,
"s": 12466,
"text": "Analysis of variance and R-squared"
},
{
"code": null,
"e": 12558,
"s": 12501,
"text": "Significance of the intercept and regression coefficient"
},
{
"code": null,
"e": 12603,
"s": 12558,
"text": "How to make predictions using a linear model"
},
{
"code": null,
"e": 12613,
"s": 12603,
"text": "Residuals"
}
] |
map count( ) function in C++
|
In this article we will be discussing the working, syntax and examples of map::empty() function in C++ STL.
Maps are the associative container, which facilitates to store the elements formed by a combination on key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in map container is accessed by its unique keys.
The map::count( ) is a function which comes under <map> header file. This function counts the elements with specific key, it returns 1 if the element with key is present, It returns the 0 if the element with key is not present in container.
map_name.count(key n);
This function accepts the parameter N which specifies Key in container.
This function returns the Boolean Number 1 if the key is present in the container and returns 0 if the key is not present in the container.
Input (key, Element)
(2,70), (3,30), (4,90), (5,100)
Output
Key 5 is present.
Key 6 is not present.
2,11
3,26
1,66
4,81
Key 2 is present.
Key 8 is not present.
First initialize the container.
First initialize the container.
Then insert the element with their keys.
Then insert the element with their keys.
Then we check the desired key is present in the container.
Then we check the desired key is present in the container.
By using the above approach, we can check the key is present in the container, there is another approach which can be followed as −
Firstly, we initialize the container.
Firstly, we initialize the container.
Then we insert the element with their keys.
Then we insert the element with their keys.
Then we create the loop from first element to last element.
Then we create the loop from first element to last element.
In this loop, we check the the desired key is present or not.
In this loop, we check the the desired key is present or not.
Above approach is generally used for alphabetically stored element. In this approach code print that the element is present in element or not in Output.
/ / C++ code to demonstrate the working of map count( ) function
#incude<iostream.h>
#include<map.h>
Using namespace std;
int main( ){
map<int, int> mp;
mp.insert({1, 40});
mp.insert({3, 20});
mp.insert({2, 30});
mp.insert({5, 10});
mp.insert({4, 50});
if (mp.count(1))
cout<< ” The Key 1 is present\n”;
else
cout<< ” The Key 1 is not present\n”;
if(mp.count(7))
cout<< “ The Key 7 is Present \n”;
else
cout<< “ The Key 7 is not Present\n”;
return 0;
}
If we run the above code it will generate following output
The Key 1 is present
The Key 7 is not present
#include<iostream.h>
#include<map.h>
Using namespace std;
int main ( ){
map<char, int> mp;
int I;
mp[‘a’] = 2;
mp[‘c’] = 3;
mp[‘e’] = 1;
for ( i = ’a’ ; i < ’f’ ; i++){
cout<< i;
if (mp.count(i)>0)
cout<< “ is an element of mp.\n”;
else
cout<< “ is not an element of mp.\n”;
}
return 0;
}
If we run the above code it will generate the following output
a is an element of mp.
b is not an element of mp.
c is an element of mp.
d is not an element of mp.
e is an element of mp.
f is not an element of mp.
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of map::empty() function in C++ STL."
},
{
"code": null,
"e": 1475,
"s": 1170,
"text": "Maps are the associative container, which facilitates to store the elements formed by a combination on key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in map container is accessed by its unique keys."
},
{
"code": null,
"e": 1716,
"s": 1475,
"text": "The map::count( ) is a function which comes under <map> header file. This function counts the elements with specific key, it returns 1 if the element with key is present, It returns the 0 if the element with key is not present in container."
},
{
"code": null,
"e": 1739,
"s": 1716,
"text": "map_name.count(key n);"
},
{
"code": null,
"e": 1811,
"s": 1739,
"text": "This function accepts the parameter N which specifies Key in container."
},
{
"code": null,
"e": 1951,
"s": 1811,
"text": "This function returns the Boolean Number 1 if the key is present in the container and returns 0 if the key is not present in the container."
},
{
"code": null,
"e": 1973,
"s": 1951,
"text": "Input (key, Element) "
},
{
"code": null,
"e": 2005,
"s": 1973,
"text": "(2,70), (3,30), (4,90), (5,100)"
},
{
"code": null,
"e": 2013,
"s": 2005,
"text": "Output "
},
{
"code": null,
"e": 2113,
"s": 2013,
"text": "Key 5 is present.\nKey 6 is not present.\n2,11\n3,26\n1,66\n4,81\nKey 2 is present.\nKey 8 is not present."
},
{
"code": null,
"e": 2145,
"s": 2113,
"text": "First initialize the container."
},
{
"code": null,
"e": 2177,
"s": 2145,
"text": "First initialize the container."
},
{
"code": null,
"e": 2218,
"s": 2177,
"text": "Then insert the element with their keys."
},
{
"code": null,
"e": 2259,
"s": 2218,
"text": "Then insert the element with their keys."
},
{
"code": null,
"e": 2318,
"s": 2259,
"text": "Then we check the desired key is present in the container."
},
{
"code": null,
"e": 2377,
"s": 2318,
"text": "Then we check the desired key is present in the container."
},
{
"code": null,
"e": 2509,
"s": 2377,
"text": "By using the above approach, we can check the key is present in the container, there is another approach which can be followed as −"
},
{
"code": null,
"e": 2547,
"s": 2509,
"text": "Firstly, we initialize the container."
},
{
"code": null,
"e": 2585,
"s": 2547,
"text": "Firstly, we initialize the container."
},
{
"code": null,
"e": 2629,
"s": 2585,
"text": "Then we insert the element with their keys."
},
{
"code": null,
"e": 2673,
"s": 2629,
"text": "Then we insert the element with their keys."
},
{
"code": null,
"e": 2733,
"s": 2673,
"text": "Then we create the loop from first element to last element."
},
{
"code": null,
"e": 2793,
"s": 2733,
"text": "Then we create the loop from first element to last element."
},
{
"code": null,
"e": 2855,
"s": 2793,
"text": "In this loop, we check the the desired key is present or not."
},
{
"code": null,
"e": 2917,
"s": 2855,
"text": "In this loop, we check the the desired key is present or not."
},
{
"code": null,
"e": 3070,
"s": 2917,
"text": "Above approach is generally used for alphabetically stored element. In this approach code print that the element is present in element or not in Output."
},
{
"code": null,
"e": 3580,
"s": 3070,
"text": "/ / C++ code to demonstrate the working of map count( ) function\n#incude<iostream.h>\n#include<map.h>\nUsing namespace std;\nint main( ){\n map<int, int> mp;\n mp.insert({1, 40});\n mp.insert({3, 20});\n mp.insert({2, 30});\n mp.insert({5, 10});\n mp.insert({4, 50});\n if (mp.count(1))\n cout<< ” The Key 1 is present\\n”;\n else\n cout<< ” The Key 1 is not present\\n”;\n if(mp.count(7))\n cout<< “ The Key 7 is Present \\n”;\n else\n cout<< “ The Key 7 is not Present\\n”;\n return 0;\n}"
},
{
"code": null,
"e": 3639,
"s": 3580,
"text": "If we run the above code it will generate following output"
},
{
"code": null,
"e": 3685,
"s": 3639,
"text": "The Key 1 is present\nThe Key 7 is not present"
},
{
"code": null,
"e": 4034,
"s": 3685,
"text": "#include<iostream.h>\n#include<map.h>\nUsing namespace std;\nint main ( ){\n map<char, int> mp;\n int I;\n mp[‘a’] = 2;\n mp[‘c’] = 3;\n mp[‘e’] = 1;\n for ( i = ’a’ ; i < ’f’ ; i++){\n cout<< i;\n if (mp.count(i)>0)\n cout<< “ is an element of mp.\\n”;\n else\n cout<< “ is not an element of mp.\\n”;\n }\n return 0;\n}"
},
{
"code": null,
"e": 4097,
"s": 4034,
"text": "If we run the above code it will generate the following output"
},
{
"code": null,
"e": 4247,
"s": 4097,
"text": "a is an element of mp.\nb is not an element of mp.\nc is an element of mp.\nd is not an element of mp.\ne is an element of mp.\nf is not an element of mp."
}
] |
Volumetric Medical Image Segmentation with Vox2Vox | by Enoch Kan | Towards Data Science
|
If you are familiar with generative adversarial networks (GANs) and their popular variants, the term Pix2Pix should not be an unfamiliar at all. Pix2Pix is a type of conditional GAN (cGAN) that performs image-to-image translation. In the medical field, they are typically used to perform modality translation and in some cases organ segmentation.
Similar to most GANs, Pix2Pix consists of a single generator network and a single discriminator network. The generator network is nothing but a U-Net, which is a type of deep convolutional neural network originally proposed to perform biomedical image segmentation. U-Net has the following architecture:
The U-Net contains three major components: the Encoder, the Bottleneck and the Decoder. Technical details including numbers of input/ output channels, kernel sizes, strides and paddings of Pix2Pix’s generator U-Net can be found in its original paper. In short, the Encoder provides a contracting path which convolves and reduces the dimensionality of a given 2D image. The Bottleneck blocks contain convolutional blocks with skip connections, and finally the Decoder provides an expansion path to upscale the encoded representation. Encoder and decoder layers that share the same size are concatenated along their channels. If you are interested in learning more about the U-Net specifically and how it performs image segmentation, Heet Sankesara has a great article about it.
The discriminator of Pix2Pix is nothing but a standard convolutional network which ‘discriminates’ whether a given image is real (original training data) or fake (generated by the U-Net generator). The training objective of Pix2Pix is a simple minmax formulation of L2/ MSE loss (adversarial loss) and L1 loss (reconstruction loss) between the generated and real images.
One of the earliest applications of Pix2Pix was to generate cat pictures from drawings (for all you cool cats and kittens). However, it has also been extended to the medical imaging field to perform domain transfer between magnetic resonance (MR), positron emission tomography (PET) and computed tomography (CT) images.
One of the major criticisms of Pix2Pix is its inability to perform image-to-image translation on the 3D level. This is a huge roadblock for many medical AI researchers since medical images are usually volumetric of nature. With advancements in graphical processing units (GPUs) and deep neural network designs, researchers have made tremendous breakthroughs in recent years which allow them to perform volumetric segmentation. V-Nets (a simple 3D extension of U-Nets) and Dense V-Nets are common architectures to perform 3D single-/ multi-organ segmentation. M. Cirillo, D. Abramian and A. Eklund from Linkoping University of Sweden have proposed a variant of Pix2Pix, in which they call the Vox2Vox network to perform segmentation in an adversarial fashion. Here is the link to the paper.
Since there are currently no open-sourced PyTorch implementations of Vox2Vox at the time of this blog post, I decided to take a stab at it. The full network implementation can be found at my github repo. It is also linked to PapersWithCode in order to gain more exposure and feedbacks. Please feel free to fork, modify my code and even submit bug fixes as long as you give me credit.
For this project, you are going to need the following dependencies:
Python 3.7
PyTorch>=0.4.0
Torchvision
Matplotlib
Numpy, Scipy
Pillow
Scikit-image
Pyvista
h5py
After cloning the repo, you can install all the required libraries by running:
pip install -r requirements.txt
The implementation of the U-Net generator can be a bit tricky, mainly because the authors of the paper did not specify how the convolutional blocks are concatenated. It took me quite a few hours just to get the volume dimensions right.
Nevertheless, below are the three major building blocks of the volumetric U-Net generator. Each block contains a convolutional layer, a normalization layer and an activation layer. The three blocks: encoder blocks, bottleneck blocks and decoder blocks are implemented as follows:
Both the bottleneck and decoder blocks use concatenation. However, the bottleneck blocks are concatenate a little differently from the decoder blocks. As illustrated in the paper, input to a typical bottleneck block is the concatenation of the input and output of its previous block. The output dimensions of the bottleneck blocks should remain constant (8x8x8x512) despite constant concatenation of inputs and outputs. On the other hand, outputs of the decoder blocks are concatenated to outputs of their respective encoder blocks.
With the model architecture description at hand, it is quite straightforward to implement the U-Net generator with the three basic blocks we have previously created:
The implementation of the discriminator is pretty straightforward as it contains the same volumetric encoder blocks as the generator. In fact, you will be able to train with any discriminator architecture you want. Just make sure you pay attention to the balance between the generator and the discriminator during training. By tuning the initial learning rates and setting an accuracy threshold for the discriminator, you can easily balance the two networks through trial-and-error. The authors of 3DGAN have provided many useful advice on balancing and stabilizing training of volumetric GANs in their original 3DGAN paper.
Another important piece of Vox2Vox’s implementation is its loss function. Similar to Pix2Pix, Vox2Vox’s loss can be broken down into adversarial loss (MSE loss) and reconstruction loss (generalized dice loss). In PyTorch, a criterion is analogous to a loss function. Hence, criterion_GAN represents the adversarial loss and criterion_voxelwise represents the reconstruction loss. Calculation of generator loss contains a tunable parameter lambda, which controls the ratio between adversarial and reconstruction losses. Below is the implementation for the loss function during generator and discriminator training:
In medical image segmentation, a commonly used loss function is the generalized dice loss. Sørensen–Dice coefficient is typically used to evaluate the similarity between two samples, and it has the following formula:
TP stands for True Positive, FP stands for False Positive and FN stands for False Negatives. Dice coefficients usually range from 0 to 1, with 1 representing a perfect match between two given samples. Generalized dice loss is a simple modification of dice score to provide a loss function for minimization during deep learning training. Below is my PyTorch implementation of the generalized dice loss:
Although it is possible for me to go through the rest of my code line-by-line, I’m going to leave it to you to read through and understand my implementation. It is definitely helpful to read through the original paper. I have nothing but respect for the authors for creating Vox2Vox, so please give them credits as well if you decide to implement Vox2Vox on your own. Comment below if you have any questions and tell me what you’d like to see on my next blog post! Stay safe and stay curious :)
|
[
{
"code": null,
"e": 519,
"s": 172,
"text": "If you are familiar with generative adversarial networks (GANs) and their popular variants, the term Pix2Pix should not be an unfamiliar at all. Pix2Pix is a type of conditional GAN (cGAN) that performs image-to-image translation. In the medical field, they are typically used to perform modality translation and in some cases organ segmentation."
},
{
"code": null,
"e": 823,
"s": 519,
"text": "Similar to most GANs, Pix2Pix consists of a single generator network and a single discriminator network. The generator network is nothing but a U-Net, which is a type of deep convolutional neural network originally proposed to perform biomedical image segmentation. U-Net has the following architecture:"
},
{
"code": null,
"e": 1600,
"s": 823,
"text": "The U-Net contains three major components: the Encoder, the Bottleneck and the Decoder. Technical details including numbers of input/ output channels, kernel sizes, strides and paddings of Pix2Pix’s generator U-Net can be found in its original paper. In short, the Encoder provides a contracting path which convolves and reduces the dimensionality of a given 2D image. The Bottleneck blocks contain convolutional blocks with skip connections, and finally the Decoder provides an expansion path to upscale the encoded representation. Encoder and decoder layers that share the same size are concatenated along their channels. If you are interested in learning more about the U-Net specifically and how it performs image segmentation, Heet Sankesara has a great article about it."
},
{
"code": null,
"e": 1971,
"s": 1600,
"text": "The discriminator of Pix2Pix is nothing but a standard convolutional network which ‘discriminates’ whether a given image is real (original training data) or fake (generated by the U-Net generator). The training objective of Pix2Pix is a simple minmax formulation of L2/ MSE loss (adversarial loss) and L1 loss (reconstruction loss) between the generated and real images."
},
{
"code": null,
"e": 2291,
"s": 1971,
"text": "One of the earliest applications of Pix2Pix was to generate cat pictures from drawings (for all you cool cats and kittens). However, it has also been extended to the medical imaging field to perform domain transfer between magnetic resonance (MR), positron emission tomography (PET) and computed tomography (CT) images."
},
{
"code": null,
"e": 3081,
"s": 2291,
"text": "One of the major criticisms of Pix2Pix is its inability to perform image-to-image translation on the 3D level. This is a huge roadblock for many medical AI researchers since medical images are usually volumetric of nature. With advancements in graphical processing units (GPUs) and deep neural network designs, researchers have made tremendous breakthroughs in recent years which allow them to perform volumetric segmentation. V-Nets (a simple 3D extension of U-Nets) and Dense V-Nets are common architectures to perform 3D single-/ multi-organ segmentation. M. Cirillo, D. Abramian and A. Eklund from Linkoping University of Sweden have proposed a variant of Pix2Pix, in which they call the Vox2Vox network to perform segmentation in an adversarial fashion. Here is the link to the paper."
},
{
"code": null,
"e": 3465,
"s": 3081,
"text": "Since there are currently no open-sourced PyTorch implementations of Vox2Vox at the time of this blog post, I decided to take a stab at it. The full network implementation can be found at my github repo. It is also linked to PapersWithCode in order to gain more exposure and feedbacks. Please feel free to fork, modify my code and even submit bug fixes as long as you give me credit."
},
{
"code": null,
"e": 3533,
"s": 3465,
"text": "For this project, you are going to need the following dependencies:"
},
{
"code": null,
"e": 3544,
"s": 3533,
"text": "Python 3.7"
},
{
"code": null,
"e": 3559,
"s": 3544,
"text": "PyTorch>=0.4.0"
},
{
"code": null,
"e": 3571,
"s": 3559,
"text": "Torchvision"
},
{
"code": null,
"e": 3582,
"s": 3571,
"text": "Matplotlib"
},
{
"code": null,
"e": 3595,
"s": 3582,
"text": "Numpy, Scipy"
},
{
"code": null,
"e": 3602,
"s": 3595,
"text": "Pillow"
},
{
"code": null,
"e": 3615,
"s": 3602,
"text": "Scikit-image"
},
{
"code": null,
"e": 3623,
"s": 3615,
"text": "Pyvista"
},
{
"code": null,
"e": 3628,
"s": 3623,
"text": "h5py"
},
{
"code": null,
"e": 3707,
"s": 3628,
"text": "After cloning the repo, you can install all the required libraries by running:"
},
{
"code": null,
"e": 3739,
"s": 3707,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 3975,
"s": 3739,
"text": "The implementation of the U-Net generator can be a bit tricky, mainly because the authors of the paper did not specify how the convolutional blocks are concatenated. It took me quite a few hours just to get the volume dimensions right."
},
{
"code": null,
"e": 4255,
"s": 3975,
"text": "Nevertheless, below are the three major building blocks of the volumetric U-Net generator. Each block contains a convolutional layer, a normalization layer and an activation layer. The three blocks: encoder blocks, bottleneck blocks and decoder blocks are implemented as follows:"
},
{
"code": null,
"e": 4788,
"s": 4255,
"text": "Both the bottleneck and decoder blocks use concatenation. However, the bottleneck blocks are concatenate a little differently from the decoder blocks. As illustrated in the paper, input to a typical bottleneck block is the concatenation of the input and output of its previous block. The output dimensions of the bottleneck blocks should remain constant (8x8x8x512) despite constant concatenation of inputs and outputs. On the other hand, outputs of the decoder blocks are concatenated to outputs of their respective encoder blocks."
},
{
"code": null,
"e": 4954,
"s": 4788,
"text": "With the model architecture description at hand, it is quite straightforward to implement the U-Net generator with the three basic blocks we have previously created:"
},
{
"code": null,
"e": 5579,
"s": 4954,
"text": "The implementation of the discriminator is pretty straightforward as it contains the same volumetric encoder blocks as the generator. In fact, you will be able to train with any discriminator architecture you want. Just make sure you pay attention to the balance between the generator and the discriminator during training. By tuning the initial learning rates and setting an accuracy threshold for the discriminator, you can easily balance the two networks through trial-and-error. The authors of 3DGAN have provided many useful advice on balancing and stabilizing training of volumetric GANs in their original 3DGAN paper."
},
{
"code": null,
"e": 6193,
"s": 5579,
"text": "Another important piece of Vox2Vox’s implementation is its loss function. Similar to Pix2Pix, Vox2Vox’s loss can be broken down into adversarial loss (MSE loss) and reconstruction loss (generalized dice loss). In PyTorch, a criterion is analogous to a loss function. Hence, criterion_GAN represents the adversarial loss and criterion_voxelwise represents the reconstruction loss. Calculation of generator loss contains a tunable parameter lambda, which controls the ratio between adversarial and reconstruction losses. Below is the implementation for the loss function during generator and discriminator training:"
},
{
"code": null,
"e": 6410,
"s": 6193,
"text": "In medical image segmentation, a commonly used loss function is the generalized dice loss. Sørensen–Dice coefficient is typically used to evaluate the similarity between two samples, and it has the following formula:"
},
{
"code": null,
"e": 6812,
"s": 6410,
"text": "TP stands for True Positive, FP stands for False Positive and FN stands for False Negatives. Dice coefficients usually range from 0 to 1, with 1 representing a perfect match between two given samples. Generalized dice loss is a simple modification of dice score to provide a loss function for minimization during deep learning training. Below is my PyTorch implementation of the generalized dice loss:"
}
] |
Program to convert Degree to Radian - GeeksforGeeks
|
26 Feb, 2021
Given the angle in degree, the task is to convert this into radians.Examples:
Input: degree = 45
Output: radian = 0.785398
Input: degree = 58
Output: radian = 1.01229
Approach: Radian: The Radian is the SI unit for measuring angles, used mainly in trigonometry. A radian is defined by an arc of a circle. A full circle is just over 6 radians (Roughly 6.28). One radian is just under 57.3 degrees.Degree: A degree, usually denoted by ° (the degree symbol), is a measurement of a plane angle, defined so that a full rotation is 360 degrees. Because a full rotation equals 2*pi radians, one degree is equivalent to pi/180 radians. The formula to convert radian to degree is:
radian = degree * (pi/180)
where pi = 22/7
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to convert degree to radian #include <iostream>#include <math.h>using namespace std; // Function for conversiondouble Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codeint main(){ double degree = 30; double radian = Convert(degree); cout << radian; return 0;}
// Java program to convert degree to radianimport java.io.*;import java.util.*; class GFG { // Function for conversionstatic double Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codepublic static void main(String[] args){ double degree = 30; double radian = Convert(degree); System.out.printf("%.6f", radian);}} // This code is contributed by coder001
# Python3 program to convert degree to radian # Function for conversiondef Convert(degree): pi = 3.14159265359; return (degree * (pi / 180)); # Driver codedegree = 30;radian = Convert(degree);print(radian); # This code is contributed by Code_Mech
// C# program to convert degree to radianusing System; class GFG{ // Function for conversionstatic double Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codepublic static void Main(){ double degree = 30; double radian = Convert(degree); Console.Write("{0:F6}", radian);}} // This code is contributed by Code_Mech
<script> // Javascript program to convert degree to radian // Function for conversionfunction Convert(degree){ let pi = 3.14159265359; return (degree * (pi / 180));} // Driver code let degree = 30; let radian = Convert(degree); document.write(radian); // This code is contributed Mayank Tyagi </script>
0.523599
coder001
Code_Mech
mayanktyagi1709
Mathematical
School Programming
Write From Home
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
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": 24690,
"s": 24662,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 24770,
"s": 24690,
"text": "Given the angle in degree, the task is to convert this into radians.Examples: "
},
{
"code": null,
"e": 24861,
"s": 24770,
"text": "Input: degree = 45 \nOutput: radian = 0.785398\n\nInput: degree = 58\nOutput: radian = 1.01229"
},
{
"code": null,
"e": 25370,
"s": 24863,
"text": "Approach: Radian: The Radian is the SI unit for measuring angles, used mainly in trigonometry. A radian is defined by an arc of a circle. A full circle is just over 6 radians (Roughly 6.28). One radian is just under 57.3 degrees.Degree: A degree, usually denoted by ° (the degree symbol), is a measurement of a plane angle, defined so that a full rotation is 360 degrees. Because a full rotation equals 2*pi radians, one degree is equivalent to pi/180 radians. The formula to convert radian to degree is: "
},
{
"code": null,
"e": 25414,
"s": 25370,
"text": "radian = degree * (pi/180) \nwhere pi = 22/7"
},
{
"code": null,
"e": 25467,
"s": 25414,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25471,
"s": 25467,
"text": "C++"
},
{
"code": null,
"e": 25476,
"s": 25471,
"text": "Java"
},
{
"code": null,
"e": 25484,
"s": 25476,
"text": "Python3"
},
{
"code": null,
"e": 25487,
"s": 25484,
"text": "C#"
},
{
"code": null,
"e": 25498,
"s": 25487,
"text": "Javascript"
},
{
"code": "// C++ program to convert degree to radian #include <iostream>#include <math.h>using namespace std; // Function for conversiondouble Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codeint main(){ double degree = 30; double radian = Convert(degree); cout << radian; return 0;}",
"e": 25837,
"s": 25498,
"text": null
},
{
"code": "// Java program to convert degree to radianimport java.io.*;import java.util.*; class GFG { // Function for conversionstatic double Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codepublic static void main(String[] args){ double degree = 30; double radian = Convert(degree); System.out.printf(\"%.6f\", radian);}} // This code is contributed by coder001 ",
"e": 26267,
"s": 25837,
"text": null
},
{
"code": "# Python3 program to convert degree to radian # Function for conversiondef Convert(degree): pi = 3.14159265359; return (degree * (pi / 180)); # Driver codedegree = 30;radian = Convert(degree);print(radian); # This code is contributed by Code_Mech",
"e": 26521,
"s": 26267,
"text": null
},
{
"code": "// C# program to convert degree to radianusing System; class GFG{ // Function for conversionstatic double Convert(double degree){ double pi = 3.14159265359; return (degree * (pi / 180));} // Driver codepublic static void Main(){ double degree = 30; double radian = Convert(degree); Console.Write(\"{0:F6}\", radian);}} // This code is contributed by Code_Mech",
"e": 26908,
"s": 26521,
"text": null
},
{
"code": "<script> // Javascript program to convert degree to radian // Function for conversionfunction Convert(degree){ let pi = 3.14159265359; return (degree * (pi / 180));} // Driver code let degree = 30; let radian = Convert(degree); document.write(radian); // This code is contributed Mayank Tyagi </script>",
"e": 27228,
"s": 26908,
"text": null
},
{
"code": null,
"e": 27237,
"s": 27228,
"text": "0.523599"
},
{
"code": null,
"e": 27248,
"s": 27239,
"text": "coder001"
},
{
"code": null,
"e": 27258,
"s": 27248,
"text": "Code_Mech"
},
{
"code": null,
"e": 27274,
"s": 27258,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 27287,
"s": 27274,
"text": "Mathematical"
},
{
"code": null,
"e": 27306,
"s": 27287,
"text": "School Programming"
},
{
"code": null,
"e": 27322,
"s": 27306,
"text": "Write From Home"
},
{
"code": null,
"e": 27335,
"s": 27322,
"text": "Mathematical"
},
{
"code": null,
"e": 27433,
"s": 27335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27442,
"s": 27433,
"text": "Comments"
},
{
"code": null,
"e": 27455,
"s": 27442,
"text": "Old Comments"
},
{
"code": null,
"e": 27497,
"s": 27455,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 27521,
"s": 27497,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 27564,
"s": 27521,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 27578,
"s": 27564,
"text": "Prime Numbers"
},
{
"code": null,
"e": 27627,
"s": 27578,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 27645,
"s": 27627,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27661,
"s": 27645,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27680,
"s": 27661,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27705,
"s": 27680,
"text": "Reverse a string in Java"
}
] |
jQuery Mobile Popup create Event - GeeksforGeeks
|
07 Jan, 2022
jQuery Mobile is a set of HTML5 based user interface systems developed to create responsive content for mobiles, tabs, and desktops. It is built on top of jQuery. In this article, we will be using the jQuery Mobile Popup create event which triggers when the popup is created.
Callback Parameters: The callback function accepts an event parameter of type event and a UI Object. The UI object is empty, it is included for consistency with other events across the jQuery Mobile library.
Syntax:
Initialize the popup with the create callback specified.$(".selector").popup({
create: function( event, ui ) {
// Your code here
}
});
Initialize the popup with the create callback specified.
$(".selector").popup({
create: function( event, ui ) {
// Your code here
}
});
Bind an event listener to the popupcreate event.$(".selector").on( "popupcreate", function( event, ui ) {} );
Bind an event listener to the popupcreate event.
$(".selector").on( "popupcreate", function( event, ui ) {} );
Parameters: It accepts a callback function that holds two parameters.
event: It accepts event type value.
ui: It accepts Object type value. The ui object can be empty but used for consistency with other events.
CDN Links:
<link rel=”stylesheet” href=”https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css” /><script src=”https://code.jquery.com/jquery-2.1.3.js”></script><script src=”https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js”></script>
Example: The below example demonstrates the use of Popup create event.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Popup - create Event</title> <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /> <script src= "https://code.jquery.com/jquery-2.1.3.js"> </script> <script src= "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"> </script> </head> <body> <div data-role="page"> <center> <h2 style="color:green">GeeksforGeeks</h2> <h3>jQuery Mobile Popup create Event</h3> <p id="target">Popup will open here</p> <div data-role="popup" id="popup1"> <p>Welcome to GeeksforGeeks</p> </div> <button style="width: 450px;" onclick="openPopup()"> Open Popup </button> </center> </div> <script> // Popup create event. $("#popup1").popup({ create: function (event, ui) { alert("Popup create Event triggered"); } }); // A function to open the popup. function openPopup() { $("#popup1").popup("open", { positionTo: "#target" }); } </script></body> </html>
Output:
Reference: https://api.jquerymobile.com/popup/#event-create
jQuery-Mobile
jQuery-Mobile-Popup
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27064,
"s": 27036,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 27340,
"s": 27064,
"text": "jQuery Mobile is a set of HTML5 based user interface systems developed to create responsive content for mobiles, tabs, and desktops. It is built on top of jQuery. In this article, we will be using the jQuery Mobile Popup create event which triggers when the popup is created."
},
{
"code": null,
"e": 27548,
"s": 27340,
"text": "Callback Parameters: The callback function accepts an event parameter of type event and a UI Object. The UI object is empty, it is included for consistency with other events across the jQuery Mobile library."
},
{
"code": null,
"e": 27556,
"s": 27548,
"text": "Syntax:"
},
{
"code": null,
"e": 27702,
"s": 27556,
"text": "Initialize the popup with the create callback specified.$(\".selector\").popup({\n create: function( event, ui ) {\n // Your code here\n }\n});"
},
{
"code": null,
"e": 27759,
"s": 27702,
"text": "Initialize the popup with the create callback specified."
},
{
"code": null,
"e": 27849,
"s": 27759,
"text": "$(\".selector\").popup({\n create: function( event, ui ) {\n // Your code here\n }\n});"
},
{
"code": null,
"e": 27959,
"s": 27849,
"text": "Bind an event listener to the popupcreate event.$(\".selector\").on( \"popupcreate\", function( event, ui ) {} );"
},
{
"code": null,
"e": 28008,
"s": 27959,
"text": "Bind an event listener to the popupcreate event."
},
{
"code": null,
"e": 28070,
"s": 28008,
"text": "$(\".selector\").on( \"popupcreate\", function( event, ui ) {} );"
},
{
"code": null,
"e": 28140,
"s": 28070,
"text": "Parameters: It accepts a callback function that holds two parameters."
},
{
"code": null,
"e": 28176,
"s": 28140,
"text": "event: It accepts event type value."
},
{
"code": null,
"e": 28281,
"s": 28176,
"text": "ui: It accepts Object type value. The ui object can be empty but used for consistency with other events."
},
{
"code": null,
"e": 28292,
"s": 28281,
"text": "CDN Links:"
},
{
"code": null,
"e": 28536,
"s": 28292,
"text": "<link rel=”stylesheet” href=”https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css” /><script src=”https://code.jquery.com/jquery-2.1.3.js”></script><script src=”https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js”></script>"
},
{
"code": null,
"e": 28607,
"s": 28536,
"text": "Example: The below example demonstrates the use of Popup create event."
},
{
"code": null,
"e": 28612,
"s": 28607,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Popup - create Event</title> <link rel=\"stylesheet\" href=\"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\" /> <script src= \"https://code.jquery.com/jquery-2.1.3.js\"> </script> <script src= \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js\"> </script> </head> <body> <div data-role=\"page\"> <center> <h2 style=\"color:green\">GeeksforGeeks</h2> <h3>jQuery Mobile Popup create Event</h3> <p id=\"target\">Popup will open here</p> <div data-role=\"popup\" id=\"popup1\"> <p>Welcome to GeeksforGeeks</p> </div> <button style=\"width: 450px;\" onclick=\"openPopup()\"> Open Popup </button> </center> </div> <script> // Popup create event. $(\"#popup1\").popup({ create: function (event, ui) { alert(\"Popup create Event triggered\"); } }); // A function to open the popup. function openPopup() { $(\"#popup1\").popup(\"open\", { positionTo: \"#target\" }); } </script></body> </html>",
"e": 29978,
"s": 28612,
"text": null
},
{
"code": null,
"e": 29986,
"s": 29978,
"text": "Output:"
},
{
"code": null,
"e": 30046,
"s": 29986,
"text": "Reference: https://api.jquerymobile.com/popup/#event-create"
},
{
"code": null,
"e": 30060,
"s": 30046,
"text": "jQuery-Mobile"
},
{
"code": null,
"e": 30080,
"s": 30060,
"text": "jQuery-Mobile-Popup"
},
{
"code": null,
"e": 30087,
"s": 30080,
"text": "Picked"
},
{
"code": null,
"e": 30094,
"s": 30087,
"text": "JQuery"
},
{
"code": null,
"e": 30111,
"s": 30094,
"text": "Web Technologies"
},
{
"code": null,
"e": 30209,
"s": 30111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30264,
"s": 30209,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30337,
"s": 30264,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30360,
"s": 30337,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 30396,
"s": 30360,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 30453,
"s": 30396,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 30493,
"s": 30453,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30526,
"s": 30493,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30571,
"s": 30526,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30614,
"s": 30571,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Bootstrap panel-title class
|
Add panel title in Bootstrap to add a title to the panel using the .panel-title class.
You can try to run the following code to implement the .panel-title class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "panel panel-default">
<div class = "panel-heading">
<h3 class = "panel-title">
Panel with title
</h3>
</div>
<div class = "panel-body">
Panel content
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Add panel title in Bootstrap to add a title to the panel using the .panel-title class."
},
{
"code": null,
"e": 1223,
"s": 1149,
"text": "You can try to run the following code to implement the .panel-title class"
},
{
"code": null,
"e": 1233,
"s": 1223,
"text": "Live Demo"
},
{
"code": null,
"e": 1814,
"s": 1233,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"panel panel-default\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">\n Panel with title\n </h3>\n </div>\n <div class = \"panel-body\">\n Panel content\n </div>\n </div>\n </body>\n</html>"
}
] |
Maximum money | Practice | GeeksforGeeks
|
Given a street of N houses (a row of houses), each house having K amount of money kept inside; now there is a thief who is going to steal this money but he has a constraint/rule that he cannot steal/rob two adjacent houses. Find the maximum money he can rob.
Example 1:
Input:
N = 5 , K = 10
Output:
30
Explanation:
The Robber can rob from the first, third
and fifth houses which will result in 30.
Example 2:
Input:
N = 2 , K = 12
Output:
12
Explanation:
The Robber can only rob from the first
or second which will result in 12.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maximizeMoney() which takes 2 Integers N and K as input and returns the answer.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N,K <= 103
0
devkumar6699432 weeks ago
python
time = 0.07
import math
class Solution: def maximizeMoney(self, N , K): # code here return ((math.ceil(N/2))*K)
0
pranavchandore20004 weeks ago
class Solution {
public:
int maximizeMoney(int N , int K) {
// code here
int p=0;
for(int i=0;i<N;i+=2){
p +=K;
}
return p;
}
};
0
akashmarkad22101 month ago
static int maximizeMoney(int N , int K) { // code here int count = 0; for(int i=0;i<N;i += 2) { count++; } return K*count; }
+1
kartikeyashokgautam1 month ago
Simple JAVA Solution :-
static int maximizeMoney(int N , int K) { int count =0; for(int i=1;i<=N;i++) { if(i%2!=0) { count++; } } return count*K; }
0
kaushaloff2 months ago
FASTEST AND SHORTEST PYTHON SOLUTION:
return K*int((N/2)+0.5)
0
codewithshoaib192 months ago
if(N%2==0){ return (N/2)*K; } return ((N/2)+1)*K;
0
codewithaddy2 months ago
SIMPLE C++ SOLUTION
int maximizeMoney(int N , int K) {
return K*((N+1)/2);
}
0
towfiq1845tasin
This comment was deleted.
0
saurabhjejurkar193 months ago
Java Solution
class Solution {
static int maximizeMoney(int N , int K) {
// code here
int ans=0;
if(N%2==0){
ans=(N/2)*K;
}else{
ans=((N/2)+1)*K;
}
return ans;
}
};
0
ll9nutbz963cw2rm9l7ssmmpcjfnohfquzp5i0uc3 months ago
def maximizeMoney(self, N , K): div, mod = divmod(N,2) return (div+mod)*K
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": 498,
"s": 238,
"text": "Given a street of N houses (a row of houses), each house having K amount of money kept inside; now there is a thief who is going to steal this money but he has a constraint/rule that he cannot steal/rob two adjacent houses. Find the maximum money he can rob. "
},
{
"code": null,
"e": 509,
"s": 498,
"text": "Example 1:"
},
{
"code": null,
"e": 638,
"s": 509,
"text": "Input:\nN = 5 , K = 10\nOutput:\n30\nExplanation:\nThe Robber can rob from the first, third\nand fifth houses which will result in 30."
},
{
"code": null,
"e": 649,
"s": 638,
"text": "Example 2:"
},
{
"code": null,
"e": 770,
"s": 649,
"text": "Input:\nN = 2 , K = 12\nOutput:\n12\nExplanation:\nThe Robber can only rob from the first\nor second which will result in 12.\n"
},
{
"code": null,
"e": 947,
"s": 770,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maximizeMoney() which takes 2 Integers N and K as input and returns the answer."
},
{
"code": null,
"e": 1009,
"s": 947,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1038,
"s": 1009,
"text": "Constraints:\n1 <= N,K <= 103"
},
{
"code": null,
"e": 1040,
"s": 1038,
"text": "0"
},
{
"code": null,
"e": 1066,
"s": 1040,
"text": "devkumar6699432 weeks ago"
},
{
"code": null,
"e": 1074,
"s": 1066,
"text": "python "
},
{
"code": null,
"e": 1086,
"s": 1074,
"text": "time = 0.07"
},
{
"code": null,
"e": 1100,
"s": 1088,
"text": "import math"
},
{
"code": null,
"e": 1203,
"s": 1100,
"text": "class Solution: def maximizeMoney(self, N , K): # code here return ((math.ceil(N/2))*K)"
},
{
"code": null,
"e": 1205,
"s": 1203,
"text": "0"
},
{
"code": null,
"e": 1235,
"s": 1205,
"text": "pranavchandore20004 weeks ago"
},
{
"code": null,
"e": 1427,
"s": 1235,
"text": "class Solution {\n public:\n int maximizeMoney(int N , int K) {\n // code here\n int p=0;\n for(int i=0;i<N;i+=2){\n p +=K;\n }\n return p;\n }\n};\n"
},
{
"code": null,
"e": 1429,
"s": 1427,
"text": "0"
},
{
"code": null,
"e": 1456,
"s": 1429,
"text": "akashmarkad22101 month ago"
},
{
"code": null,
"e": 1650,
"s": 1456,
"text": "static int maximizeMoney(int N , int K) { // code here int count = 0; for(int i=0;i<N;i += 2) { count++; } return K*count; }"
},
{
"code": null,
"e": 1653,
"s": 1650,
"text": "+1"
},
{
"code": null,
"e": 1684,
"s": 1653,
"text": "kartikeyashokgautam1 month ago"
},
{
"code": null,
"e": 1709,
"s": 1684,
"text": "Simple JAVA Solution :- "
},
{
"code": null,
"e": 1922,
"s": 1711,
"text": " static int maximizeMoney(int N , int K) { int count =0; for(int i=1;i<=N;i++) { if(i%2!=0) { count++; } } return count*K; }"
},
{
"code": null,
"e": 1924,
"s": 1922,
"text": "0"
},
{
"code": null,
"e": 1947,
"s": 1924,
"text": "kaushaloff2 months ago"
},
{
"code": null,
"e": 1985,
"s": 1947,
"text": "FASTEST AND SHORTEST PYTHON SOLUTION:"
},
{
"code": null,
"e": 2011,
"s": 1987,
"text": "return K*int((N/2)+0.5)"
},
{
"code": null,
"e": 2013,
"s": 2011,
"text": "0"
},
{
"code": null,
"e": 2042,
"s": 2013,
"text": "codewithshoaib192 months ago"
},
{
"code": null,
"e": 2115,
"s": 2042,
"text": " if(N%2==0){ return (N/2)*K; } return ((N/2)+1)*K;"
},
{
"code": null,
"e": 2117,
"s": 2115,
"text": "0"
},
{
"code": null,
"e": 2142,
"s": 2117,
"text": "codewithaddy2 months ago"
},
{
"code": null,
"e": 2162,
"s": 2142,
"text": "SIMPLE C++ SOLUTION"
},
{
"code": null,
"e": 2234,
"s": 2162,
"text": "int maximizeMoney(int N , int K) {\n return K*((N+1)/2);\n }"
},
{
"code": null,
"e": 2236,
"s": 2234,
"text": "0"
},
{
"code": null,
"e": 2252,
"s": 2236,
"text": "towfiq1845tasin"
},
{
"code": null,
"e": 2278,
"s": 2252,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2280,
"s": 2278,
"text": "0"
},
{
"code": null,
"e": 2310,
"s": 2280,
"text": "saurabhjejurkar193 months ago"
},
{
"code": null,
"e": 2324,
"s": 2310,
"text": "Java Solution"
},
{
"code": null,
"e": 2573,
"s": 2324,
"text": "class Solution {\n static int maximizeMoney(int N , int K) {\n // code here\n int ans=0;\n \n if(N%2==0){\n ans=(N/2)*K;\n }else{\n ans=((N/2)+1)*K;\n }\n \n return ans;\n }\n};"
},
{
"code": null,
"e": 2575,
"s": 2573,
"text": "0"
},
{
"code": null,
"e": 2628,
"s": 2575,
"text": "ll9nutbz963cw2rm9l7ssmmpcjfnohfquzp5i0uc3 months ago"
},
{
"code": null,
"e": 2714,
"s": 2628,
"text": "def maximizeMoney(self, N , K): div, mod = divmod(N,2) return (div+mod)*K"
},
{
"code": null,
"e": 2860,
"s": 2714,
"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": 2896,
"s": 2860,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2906,
"s": 2896,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2916,
"s": 2906,
"text": "\nContest\n"
},
{
"code": null,
"e": 2979,
"s": 2916,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3127,
"s": 2979,
"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": 3335,
"s": 3127,
"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": 3441,
"s": 3335,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Private Variables in C#
|
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
Create a private variable −
private double length;
Let us see an example. Here, if we will try to access the length variable which is set private, then the following error would generate.
BoxApplication.Box.length' is inaccessible due to its protection level
Let us see the complete example now −
using System;
namespace BoxApplication {
class Box {
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len ) {
length = len;
}
public void setBreadth( double bre ) {
breadth = bre;
}
public void setHeight( double hei ) {
height = hei;
}
public double getVolume() {
return length * breadth * height;
}
}
class Boxtester {
static void Main(string[] args) {
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// ACcessing private variables outside the class gives an error.
// Box1.length = 10;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
|
[
{
"code": null,
"e": 1314,
"s": 1062,
"text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members."
},
{
"code": null,
"e": 1342,
"s": 1314,
"text": "Create a private variable −"
},
{
"code": null,
"e": 1365,
"s": 1342,
"text": "private double length;"
},
{
"code": null,
"e": 1502,
"s": 1365,
"text": "Let us see an example. Here, if we will try to access the length variable which is set private, then the following error would generate."
},
{
"code": null,
"e": 1573,
"s": 1502,
"text": "BoxApplication.Box.length' is inaccessible due to its protection level"
},
{
"code": null,
"e": 1611,
"s": 1573,
"text": "Let us see the complete example now −"
},
{
"code": null,
"e": 2929,
"s": 1611,
"text": "using System;\n\nnamespace BoxApplication {\n class Box {\n private double length; // Length of a box\n private double breadth; // Breadth of a box\n private double height; // Height of a box\n\n public void setLength( double len ) {\n length = len;\n }\n\n public void setBreadth( double bre ) {\n breadth = bre;\n }\n\n public void setHeight( double hei ) {\n height = hei;\n }\n\n public double getVolume() {\n return length * breadth * height;\n }\n }\n\n class Boxtester {\n static void Main(string[] args) {\n Box Box1 = new Box(); // Declare Box1 of type Box\n Box Box2 = new Box();\n double volume;\n\n // ACcessing private variables outside the class gives an error.\n // Box1.length = 10;\n\n Box1.setLength(6.0);\n Box1.setBreadth(7.0);\n Box1.setHeight(5.0);\n\n // box 2 specification\n Box2.setLength(12.0);\n Box2.setBreadth(13.0);\n Box2.setHeight(10.0);\n\n // volume of box 1\n volume = Box1.getVolume();\n Console.WriteLine(\"Volume of Box1 : {0}\" ,volume);\n\n // volume of box 2\n volume = Box2.getVolume();\n Console.WriteLine(\"Volume of Box2 : {0}\", volume);\n\n Console.ReadKey();\n }\n }\n}"
}
] |
How to add a class to DOM element in JavaScript?
|
To add a class to a DOM element, you first need to find it using a querySelector like querySelector, getElementById, etc. Then you need to add the class. For example, if you have the following HTML −
<!DOCTYPE html>
<html>
<head></head>
<body>
<p id="para">This is some text</p>
</body>
</html>
You can find the element using either of the following 2 ways −
let myPara = querySelector('#para')[0];
let myPara = getElementById('para');
Then you can add a class to this element using −
let myPara = getElementById('para');
myPara.classList.add('myClass');
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "To add a class to a DOM element, you first need to find it using a querySelector like querySelector, getElementById, etc. Then you need to add the class. For example, if you have the following HTML −"
},
{
"code": null,
"e": 1372,
"s": 1262,
"text": "<!DOCTYPE html>\n<html>\n <head></head>\n <body>\n <p id=\"para\">This is some text</p>\n </body>\n</html>"
},
{
"code": null,
"e": 1436,
"s": 1372,
"text": "You can find the element using either of the following 2 ways −"
},
{
"code": null,
"e": 1476,
"s": 1436,
"text": "let myPara = querySelector('#para')[0];"
},
{
"code": null,
"e": 1513,
"s": 1476,
"text": "let myPara = getElementById('para');"
},
{
"code": null,
"e": 1562,
"s": 1513,
"text": "Then you can add a class to this element using −"
},
{
"code": null,
"e": 1632,
"s": 1562,
"text": "let myPara = getElementById('para');\nmyPara.classList.add('myClass');"
}
] |
Select text after last slash in MySQL?
|
You need to use substring_index() function from MySQL to select text.
The syntax is as follows
SELECT substring_index(yourColumnName,'/',-1) AS anyAliasName FROM yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows
mysql> create table selectTextAfterLastSlashDemo
- > (
- > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > UserPathDirectory varchar(200)
- > );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)
values('C:/MyFolder1/MyEntityFramework');
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)
values('D:/MySpringFrameworkDemo');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)
values('E:/Java/MyRootFolder/Source/AllHibernateDemo');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory) values('C:/Program
Files/MySQL/Server 8.0');
Query OK, 1 row affected (0.20 sec)
mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)
values('C:/John/Folder1/Folder2');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from selectTextAfterLastSlashDemo;
The following is the output displaying path in of the columns
+--------+----------------------------------------------+
| UserId | UserPathDirectory |
+--------+----------------------------------------------+
| 1 | C:/MyFolder1/MyEntityFramework |
| 2 | D:/MySpringFrameworkDemo |
| 3 | E:/Java/MyRootFolder/Source/AllHibernateDemo |
| 4 | C:/Program Files/MySQL/Server 8.0 |
| 5 | C:/John/Folder1/Folder2 |
+--------+----------------------------------------------+
5 rows in set (0.00 sec)
Here is the query to get text after last slash
mysql> select substring_index(UserPathDirectory,'/',-1) as TextAfterLastSlash from
selectTextAfterLastSlashDemo;
The following is the output displaying the text after last slash
+-----------------------+
| TextAfterLastSlash |
+-----------------------+
| MyEntityFramework |
| MySpringFrameworkDemo |
| AllHibernateDemo |
| Server 8.0 |
| Folder2 |
+-----------------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "You need to use substring_index() function from MySQL to select text."
},
{
"code": null,
"e": 1157,
"s": 1132,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1239,
"s": 1157,
"text": "SELECT substring_index(yourColumnName,'/',-1) AS anyAliasName FROM yourTableName;"
},
{
"code": null,
"e": 1337,
"s": 1239,
"text": "To understand the above concept, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1535,
"s": 1337,
"text": "mysql> create table selectTextAfterLastSlashDemo\n - > (\n - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > UserPathDirectory varchar(200)\n - > );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1590,
"s": 1535,
"text": "Insert some records in the table using insert command."
},
{
"code": null,
"e": 1614,
"s": 1590,
"text": "The query is as follows"
},
{
"code": null,
"e": 2343,
"s": 1614,
"text": "mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)\nvalues('C:/MyFolder1/MyEntityFramework');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)\nvalues('D:/MySpringFrameworkDemo');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)\nvalues('E:/Java/MyRootFolder/Source/AllHibernateDemo');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory) values('C:/Program\nFiles/MySQL/Server 8.0');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory)\nvalues('C:/John/Folder1/Folder2');\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 2402,
"s": 2343,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2426,
"s": 2402,
"text": "The query is as follows"
},
{
"code": null,
"e": 2476,
"s": 2426,
"text": "mysql> select *from selectTextAfterLastSlashDemo;"
},
{
"code": null,
"e": 2538,
"s": 2476,
"text": "The following is the output displaying path in of the columns"
},
{
"code": null,
"e": 3085,
"s": 2538,
"text": "+--------+----------------------------------------------+\n| UserId | UserPathDirectory |\n+--------+----------------------------------------------+\n| 1 | C:/MyFolder1/MyEntityFramework |\n| 2 | D:/MySpringFrameworkDemo |\n| 3 | E:/Java/MyRootFolder/Source/AllHibernateDemo |\n| 4 | C:/Program Files/MySQL/Server 8.0 |\n| 5 | C:/John/Folder1/Folder2 |\n+--------+----------------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3132,
"s": 3085,
"text": "Here is the query to get text after last slash"
},
{
"code": null,
"e": 3245,
"s": 3132,
"text": "mysql> select substring_index(UserPathDirectory,'/',-1) as TextAfterLastSlash from\nselectTextAfterLastSlashDemo;"
},
{
"code": null,
"e": 3310,
"s": 3245,
"text": "The following is the output displaying the text after last slash"
},
{
"code": null,
"e": 3569,
"s": 3310,
"text": "+-----------------------+\n| TextAfterLastSlash |\n+-----------------------+\n| MyEntityFramework |\n| MySpringFrameworkDemo |\n| AllHibernateDemo |\n| Server 8.0 |\n| Folder2 |\n+-----------------------+\n5 rows in set (0.00 sec)"
}
] |
How to create DefaultTableModel which is an implementation of TableModel
|
Let us create DefaultTableModel −
DefaultTableModel tableModel = new DefaultTableModel();
Now, set the model to JTable −
JTable table = new JTable(tableModel);
Add a column −
tableModel.addColumn("Languages");
Now, we will add rows to our table −
tableModel.insertRow(0, new Object[] { "CSS" });
tableModel.insertRow(0, new Object[] { "HTML5" });
The following is an example to create DefaultTableModel −
package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
public static void main(String[] argv) throws Exception {
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
tableModel.addColumn("Languages");
tableModel.insertRow(0, new Object[] { "CSS" });
tableModel.insertRow(0, new Object[] { "HTML5" });
tableModel.insertRow(0, new Object[] { "JavaScript" });
tableModel.insertRow(0, new Object[] { "jQuery" });
tableModel.insertRow(0, new Object[] { "AngularJS" });
tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS" });
JFrame f = new JFrame();
f.setSize(550, 350);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1096,
"s": 1062,
"text": "Let us create DefaultTableModel −"
},
{
"code": null,
"e": 1152,
"s": 1096,
"text": "DefaultTableModel tableModel = new DefaultTableModel();"
},
{
"code": null,
"e": 1183,
"s": 1152,
"text": "Now, set the model to JTable −"
},
{
"code": null,
"e": 1222,
"s": 1183,
"text": "JTable table = new JTable(tableModel);"
},
{
"code": null,
"e": 1237,
"s": 1222,
"text": "Add a column −"
},
{
"code": null,
"e": 1272,
"s": 1237,
"text": "tableModel.addColumn(\"Languages\");"
},
{
"code": null,
"e": 1309,
"s": 1272,
"text": "Now, we will add rows to our table −"
},
{
"code": null,
"e": 1409,
"s": 1309,
"text": "tableModel.insertRow(0, new Object[] { \"CSS\" });\ntableModel.insertRow(0, new Object[] { \"HTML5\" });"
},
{
"code": null,
"e": 1467,
"s": 1409,
"text": "The following is an example to create DefaultTableModel −"
},
{
"code": null,
"e": 2348,
"s": 1467,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Languages\");\n tableModel.insertRow(0, new Object[] { \"CSS\" });\n tableModel.insertRow(0, new Object[] { \"HTML5\" });\n tableModel.insertRow(0, new Object[] { \"JavaScript\" });\n tableModel.insertRow(0, new Object[] { \"jQuery\" });\n tableModel.insertRow(0, new Object[] { \"AngularJS\" });\n tableModel.insertRow(tableModel.getRowCount(), new Object[] { \"ExpressJS\" });\n JFrame f = new JFrame();\n f.setSize(550, 350);\n f.add(new JScrollPane(table));\n f.setVisible(true);\n }\n}"
}
] |
PyQt5 - QCalendarWidget - GeeksforGeeks
|
09 Aug, 2021
QCalendarWidget is the class that provides a monthly based calendar widget allowing the user to select a date, this class belongs to the QWidgets class. A calendar is a system of organizing days for social, religious, commercial, or administrative purposes. This is done by giving names to periods of time, typically days, weeks, months and years. A date is the designation of a single, specific day within such a system. Below is how QCalendarWidget looks like.
Example : A window having a QCalendarWidget and user can see the various months and can select any dateBelow is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(50, 50, 400, 250) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23851,
"s": 23823,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 24315,
"s": 23851,
"text": "QCalendarWidget is the class that provides a monthly based calendar widget allowing the user to select a date, this class belongs to the QWidgets class. A calendar is a system of organizing days for social, religious, commercial, or administrative purposes. This is done by giving names to periods of time, typically days, weeks, months and years. A date is the designation of a single, specific day within such a system. Below is how QCalendarWidget looks like. "
},
{
"code": null,
"e": 24448,
"s": 24315,
"text": "Example : A window having a QCalendarWidget and user can see the various months and can select any dateBelow is the implementation "
},
{
"code": null,
"e": 24456,
"s": 24448,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(50, 50, 400, 250) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 25297,
"s": 24456,
"text": null
},
{
"code": null,
"e": 25306,
"s": 25297,
"text": "Output :"
},
{
"code": null,
"e": 25316,
"s": 25308,
"text": "clintra"
},
{
"code": null,
"e": 25344,
"s": 25316,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 25355,
"s": 25344,
"text": "Python-gui"
},
{
"code": null,
"e": 25367,
"s": 25355,
"text": "Python-PyQt"
},
{
"code": null,
"e": 25374,
"s": 25367,
"text": "Python"
},
{
"code": null,
"e": 25472,
"s": 25374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25481,
"s": 25472,
"text": "Comments"
},
{
"code": null,
"e": 25494,
"s": 25481,
"text": "Old Comments"
},
{
"code": null,
"e": 25512,
"s": 25494,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25547,
"s": 25512,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25569,
"s": 25547,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25601,
"s": 25569,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25631,
"s": 25601,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25673,
"s": 25631,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25699,
"s": 25673,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25742,
"s": 25699,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25786,
"s": 25742,
"text": "Reading and Writing to text files in Python"
}
] |
JSTL - fn:contains() Function
|
The fn:contains() function determines whether an input string contains a specified substring.
The fn:contains() function has the following syntax −
boolean contains(java.lang.String, java.lang.String)
Following example explains the functionality of fn:contains() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var = "theString" value = "I am a test String"/>
<c:if test = "${fn:contains(theString, 'test')}">
<p>Found test string<p>
</c:if>
<c:if test = "${fn:contains(theString, 'TEST')}">
<p>Found TEST string<p>
</c:if>
</body>
</html>
You will receive the following result −
Found test string
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2333,
"s": 2239,
"text": "The fn:contains() function determines whether an input string contains a specified substring."
},
{
"code": null,
"e": 2387,
"s": 2333,
"text": "The fn:contains() function has the following syntax −"
},
{
"code": null,
"e": 2441,
"s": 2387,
"text": "boolean contains(java.lang.String, java.lang.String)\n"
},
{
"code": null,
"e": 2514,
"s": 2441,
"text": "Following example explains the functionality of fn:contains() function −"
},
{
"code": null,
"e": 3030,
"s": 2514,
"text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"theString\" value = \"I am a test String\"/>\n\n <c:if test = \"${fn:contains(theString, 'test')}\">\n <p>Found test string<p>\n </c:if>\n\n <c:if test = \"${fn:contains(theString, 'TEST')}\">\n <p>Found TEST string<p>\n </c:if>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3070,
"s": 3030,
"text": "You will receive the following result −"
},
{
"code": null,
"e": 3089,
"s": 3070,
"text": "Found test string\n"
},
{
"code": null,
"e": 3124,
"s": 3089,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3139,
"s": 3124,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3174,
"s": 3139,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3189,
"s": 3174,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3224,
"s": 3189,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3238,
"s": 3224,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3273,
"s": 3238,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3273,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3322,
"s": 3289,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3338,
"s": 3322,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3372,
"s": 3338,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3380,
"s": 3372,
"text": " Uplatz"
},
{
"code": null,
"e": 3387,
"s": 3380,
"text": " Print"
},
{
"code": null,
"e": 3398,
"s": 3387,
"text": " Add Notes"
}
] |
Activation maps for deep learning models in a few lines of code | by Tirthajyoti Sarkar | Towards Data Science
|
Update: This story received a silver badge from KDNuggets as the most shared story of October.
Deep Learning (DL) models are revolutionizing the business and technology world with jaw-dropping performances in one application area after another — image classification, object detection, object tracking, pose recognition, video analytics, synthetic picture generation — just to name a few.
However, they are like anything but classical Machine Learning (ML) algorithms/techniques. DL models use millions of parameters and create extremely complex and highly nonlinear internal representations of the images or datasets that are fed to these models.
They are, therefore, often called the perfect black-box ML techniques. We can get highly accurate predictions from them after we train them with large datasets, but we have little hope of understanding the internal features and representations of the data that a model uses to classify a particular image into a category.
Black-box problem of deep learning — predictive power without an intuitive and easy-to-follow explanation.
This does not bode well because we, humans, are visual creatures. Millions of years of evolution have gifted us an amazingly complex pair of eyes and an even more complex visual cortex, and we use those organs for making sense of the world.
The scientific process starts with observation, and that is almost always synonymous with vision. In business, only what we can observe and measure, we can control and manage effectively.
Seeing/observing is how we start to make mental models of worldly phenomena, classify objects around us, separate a friend from a foe, love, work, and play.
Visualization helps a lot. Especially, for deep learning.
Therefore, a ‘black box’ DL model, where we cannot visualize the inner workings, often draws some criticism.
Among various deep learning architectures, perhaps the most prominent one is the so-called Convolutional Neural Network (CNN). It has emerged as the workhorse for analyzing high-dimensional, unstructured data — image, text, or audio — which has traditionally posed severe challenges for classical ML (non-deep-learning) or hand-crafted (non-ML) algorithms.
Several approaches for understanding and visualizing CNN have been developed in the literature, partly as a response to the common criticism that the learned internal features in a CNN are not interpretable.
The most straight-forward visualization technique is to show the activations of the network during the forward pass.
So, what are activation anyway?
At a simple level, activation functions help decide whether a neuron should be activated. This helps determine whether the information that the neuron is receiving is relevant for the input. The activation function is a non-linear transformation that happens over an input signal, and the transformed output is sent to the next neuron.
If you want to understand what precisely, these activations mean, and why are they placed in the neural net architecture in the first place, check out this article,
www.analyticsvidhya.com
Below is a fantastic video by the renowned data scientist Brandon Rohrer about the basic mechanism of a CNN i.e. how a given input (say a two-dimensional image) is processed layer by layer. At each layer, the output is generated by passing the transformed input through an activation function.
Activation maps are just a visual representation of these activation numbers at various layers of the network as a given image progresses through as a result of various linear algebraic operations.
For ReLU activation based networks, the activations usually start out looking relatively blobby and dense, but as the training progresses the activations usually become more sparse and localized. One design pitfall that can be easily caught with this visualization is that some activation maps may be all zero for many different inputs, which can indicate dead filters and can be a symptom of high learning rates.
Activation maps are just a visual representation of these activation numbers at various layers of the network.
Sounds good. But visualizing these activation maps is a non-trivial task, even after you have trained your neural net well and are making predictions out of it.
How do you easily visualize and show these activation maps for a reasonably complicated CNN with just a few lines of code?
The whole Jupyter notebook is here. Feel free to fork and expand (and leave a star for the repository if you like it).
I showed previously in an article, how to write a single compact function for obtaining a fully trained CNN model by reading image files one by one automatically from your disk, by utilizing some amazing utility methods and classes offered by Keras library.
Do check out this article, because, without it, you cannot train arbitrary models with arbitrary image datasets in a compact manner, as described in this article.
towardsdatascience.com
Next, we use this function along with a nice little library called Keract, which makes the visualization of activation maps super easy. It is a high-level accessory library to Keras library to show useful heatmaps and activation maps on various layers of a neural network.
Therefore, for this code, we need to use a couple of utility functions from my utils.DL_utils module - train_CNN_keras and preprocess_image to make a random RGB image compatible for generating the activation maps (these were described in the article mentioned above).
Here is the Python module — DL_utils.py. You can store in your local drive and import the functions as usual.
For training, we are using the famous Caltech-101 dataset from http://www.vision.caltech.edu/Image_Datasets/Caltech101/. This dataset was somewhat a precursor to the ImageNet database, which is the current gold standard for image classification data repository.
It is an image dataset of diverse types of objects belonging to 101 categories. There are about 40 to 800 images per category. Most categories have about 50 images. The size of each image is roughly 300 x 200 pixels.
However, we are training only with 5 categories of images — crab, cup, brain, camera, and chair.
This is just a random choice for this demo, feel free to choose your own categories.
Training is done in a few lines of code only.
For generating the activations, we download a random image of a human brain from the internet.
Then, another couple of lines of code to generate the activation.
We get back a dictionary with layer names as the keys and Numpy arrays as the values corresponding to the activations. Below an illustration is shown where the activation arrays are shown to have varying lengths corresponding to the size of the filter maps of that particular convolutional layer.
Again, a single line of code,
display_activations(activations, save=False)
We get to see activation maps layer by layer. Here is the first convolutional layer (16 images corresponding to the 16 filters)
And, here is layer number 2 (32 images corresponding to the 32filters)
We have 5 convolutional layers (followed by Max pooling layers) in this model, and therefore, we get back 10 sets of images. For brevity, I am not showing the rest but you can see them all in my Github repo here.
You can also show the activations as heatmaps.
display_heatmaps(activations, x, save=False)
After writing this article last week, I found out about another beautiful library for activation visualization called Quiver. However, this one is built on the Python microserver framework Flask and displays the activation maps on a browser port rather than inside your Jupyter Notebook.
They also need a trained Keras model as input. So, you can easily use the compact function described in this article (from my DL_uitls module) and try this library for interactive visualization of activation maps.
That’s it, for now.
The whole Jupyter notebook is here.
We showed, how using only a few lines of code (utilizing compact functions from a special module and a nice little accessory library to Keras) we can train a CNN, generate activation maps, and display them layer by layer — from scratch.
This gives you the ability to train CNN models (simple to complex) from any image dataset (as long as you can arrange it in a simple format) and look inside their guts for any test image you want.
For more of such hands-on tutorials, check my Deep-Learning-with-Python Github repo.
If you have any questions or ideas to share, please contact the author at tirthajyoti[AT]gmail.com. Also, you can check the author’s GitHub repositories for other fun code snippets in Python, R, and machine learning resources. If you are, like me, passionate about machine learning/data science, please feel free to add me on LinkedIn or follow me on Twitter.
|
[
{
"code": null,
"e": 267,
"s": 172,
"text": "Update: This story received a silver badge from KDNuggets as the most shared story of October."
},
{
"code": null,
"e": 561,
"s": 267,
"text": "Deep Learning (DL) models are revolutionizing the business and technology world with jaw-dropping performances in one application area after another — image classification, object detection, object tracking, pose recognition, video analytics, synthetic picture generation — just to name a few."
},
{
"code": null,
"e": 820,
"s": 561,
"text": "However, they are like anything but classical Machine Learning (ML) algorithms/techniques. DL models use millions of parameters and create extremely complex and highly nonlinear internal representations of the images or datasets that are fed to these models."
},
{
"code": null,
"e": 1142,
"s": 820,
"text": "They are, therefore, often called the perfect black-box ML techniques. We can get highly accurate predictions from them after we train them with large datasets, but we have little hope of understanding the internal features and representations of the data that a model uses to classify a particular image into a category."
},
{
"code": null,
"e": 1249,
"s": 1142,
"text": "Black-box problem of deep learning — predictive power without an intuitive and easy-to-follow explanation."
},
{
"code": null,
"e": 1490,
"s": 1249,
"text": "This does not bode well because we, humans, are visual creatures. Millions of years of evolution have gifted us an amazingly complex pair of eyes and an even more complex visual cortex, and we use those organs for making sense of the world."
},
{
"code": null,
"e": 1678,
"s": 1490,
"text": "The scientific process starts with observation, and that is almost always synonymous with vision. In business, only what we can observe and measure, we can control and manage effectively."
},
{
"code": null,
"e": 1835,
"s": 1678,
"text": "Seeing/observing is how we start to make mental models of worldly phenomena, classify objects around us, separate a friend from a foe, love, work, and play."
},
{
"code": null,
"e": 1893,
"s": 1835,
"text": "Visualization helps a lot. Especially, for deep learning."
},
{
"code": null,
"e": 2002,
"s": 1893,
"text": "Therefore, a ‘black box’ DL model, where we cannot visualize the inner workings, often draws some criticism."
},
{
"code": null,
"e": 2359,
"s": 2002,
"text": "Among various deep learning architectures, perhaps the most prominent one is the so-called Convolutional Neural Network (CNN). It has emerged as the workhorse for analyzing high-dimensional, unstructured data — image, text, or audio — which has traditionally posed severe challenges for classical ML (non-deep-learning) or hand-crafted (non-ML) algorithms."
},
{
"code": null,
"e": 2567,
"s": 2359,
"text": "Several approaches for understanding and visualizing CNN have been developed in the literature, partly as a response to the common criticism that the learned internal features in a CNN are not interpretable."
},
{
"code": null,
"e": 2684,
"s": 2567,
"text": "The most straight-forward visualization technique is to show the activations of the network during the forward pass."
},
{
"code": null,
"e": 2716,
"s": 2684,
"text": "So, what are activation anyway?"
},
{
"code": null,
"e": 3052,
"s": 2716,
"text": "At a simple level, activation functions help decide whether a neuron should be activated. This helps determine whether the information that the neuron is receiving is relevant for the input. The activation function is a non-linear transformation that happens over an input signal, and the transformed output is sent to the next neuron."
},
{
"code": null,
"e": 3217,
"s": 3052,
"text": "If you want to understand what precisely, these activations mean, and why are they placed in the neural net architecture in the first place, check out this article,"
},
{
"code": null,
"e": 3241,
"s": 3217,
"text": "www.analyticsvidhya.com"
},
{
"code": null,
"e": 3535,
"s": 3241,
"text": "Below is a fantastic video by the renowned data scientist Brandon Rohrer about the basic mechanism of a CNN i.e. how a given input (say a two-dimensional image) is processed layer by layer. At each layer, the output is generated by passing the transformed input through an activation function."
},
{
"code": null,
"e": 3733,
"s": 3535,
"text": "Activation maps are just a visual representation of these activation numbers at various layers of the network as a given image progresses through as a result of various linear algebraic operations."
},
{
"code": null,
"e": 4147,
"s": 3733,
"text": "For ReLU activation based networks, the activations usually start out looking relatively blobby and dense, but as the training progresses the activations usually become more sparse and localized. One design pitfall that can be easily caught with this visualization is that some activation maps may be all zero for many different inputs, which can indicate dead filters and can be a symptom of high learning rates."
},
{
"code": null,
"e": 4258,
"s": 4147,
"text": "Activation maps are just a visual representation of these activation numbers at various layers of the network."
},
{
"code": null,
"e": 4419,
"s": 4258,
"text": "Sounds good. But visualizing these activation maps is a non-trivial task, even after you have trained your neural net well and are making predictions out of it."
},
{
"code": null,
"e": 4542,
"s": 4419,
"text": "How do you easily visualize and show these activation maps for a reasonably complicated CNN with just a few lines of code?"
},
{
"code": null,
"e": 4661,
"s": 4542,
"text": "The whole Jupyter notebook is here. Feel free to fork and expand (and leave a star for the repository if you like it)."
},
{
"code": null,
"e": 4919,
"s": 4661,
"text": "I showed previously in an article, how to write a single compact function for obtaining a fully trained CNN model by reading image files one by one automatically from your disk, by utilizing some amazing utility methods and classes offered by Keras library."
},
{
"code": null,
"e": 5082,
"s": 4919,
"text": "Do check out this article, because, without it, you cannot train arbitrary models with arbitrary image datasets in a compact manner, as described in this article."
},
{
"code": null,
"e": 5105,
"s": 5082,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5378,
"s": 5105,
"text": "Next, we use this function along with a nice little library called Keract, which makes the visualization of activation maps super easy. It is a high-level accessory library to Keras library to show useful heatmaps and activation maps on various layers of a neural network."
},
{
"code": null,
"e": 5646,
"s": 5378,
"text": "Therefore, for this code, we need to use a couple of utility functions from my utils.DL_utils module - train_CNN_keras and preprocess_image to make a random RGB image compatible for generating the activation maps (these were described in the article mentioned above)."
},
{
"code": null,
"e": 5756,
"s": 5646,
"text": "Here is the Python module — DL_utils.py. You can store in your local drive and import the functions as usual."
},
{
"code": null,
"e": 6018,
"s": 5756,
"text": "For training, we are using the famous Caltech-101 dataset from http://www.vision.caltech.edu/Image_Datasets/Caltech101/. This dataset was somewhat a precursor to the ImageNet database, which is the current gold standard for image classification data repository."
},
{
"code": null,
"e": 6235,
"s": 6018,
"text": "It is an image dataset of diverse types of objects belonging to 101 categories. There are about 40 to 800 images per category. Most categories have about 50 images. The size of each image is roughly 300 x 200 pixels."
},
{
"code": null,
"e": 6332,
"s": 6235,
"text": "However, we are training only with 5 categories of images — crab, cup, brain, camera, and chair."
},
{
"code": null,
"e": 6417,
"s": 6332,
"text": "This is just a random choice for this demo, feel free to choose your own categories."
},
{
"code": null,
"e": 6463,
"s": 6417,
"text": "Training is done in a few lines of code only."
},
{
"code": null,
"e": 6558,
"s": 6463,
"text": "For generating the activations, we download a random image of a human brain from the internet."
},
{
"code": null,
"e": 6624,
"s": 6558,
"text": "Then, another couple of lines of code to generate the activation."
},
{
"code": null,
"e": 6921,
"s": 6624,
"text": "We get back a dictionary with layer names as the keys and Numpy arrays as the values corresponding to the activations. Below an illustration is shown where the activation arrays are shown to have varying lengths corresponding to the size of the filter maps of that particular convolutional layer."
},
{
"code": null,
"e": 6951,
"s": 6921,
"text": "Again, a single line of code,"
},
{
"code": null,
"e": 6996,
"s": 6951,
"text": "display_activations(activations, save=False)"
},
{
"code": null,
"e": 7124,
"s": 6996,
"text": "We get to see activation maps layer by layer. Here is the first convolutional layer (16 images corresponding to the 16 filters)"
},
{
"code": null,
"e": 7195,
"s": 7124,
"text": "And, here is layer number 2 (32 images corresponding to the 32filters)"
},
{
"code": null,
"e": 7408,
"s": 7195,
"text": "We have 5 convolutional layers (followed by Max pooling layers) in this model, and therefore, we get back 10 sets of images. For brevity, I am not showing the rest but you can see them all in my Github repo here."
},
{
"code": null,
"e": 7455,
"s": 7408,
"text": "You can also show the activations as heatmaps."
},
{
"code": null,
"e": 7500,
"s": 7455,
"text": "display_heatmaps(activations, x, save=False)"
},
{
"code": null,
"e": 7788,
"s": 7500,
"text": "After writing this article last week, I found out about another beautiful library for activation visualization called Quiver. However, this one is built on the Python microserver framework Flask and displays the activation maps on a browser port rather than inside your Jupyter Notebook."
},
{
"code": null,
"e": 8002,
"s": 7788,
"text": "They also need a trained Keras model as input. So, you can easily use the compact function described in this article (from my DL_uitls module) and try this library for interactive visualization of activation maps."
},
{
"code": null,
"e": 8022,
"s": 8002,
"text": "That’s it, for now."
},
{
"code": null,
"e": 8058,
"s": 8022,
"text": "The whole Jupyter notebook is here."
},
{
"code": null,
"e": 8295,
"s": 8058,
"text": "We showed, how using only a few lines of code (utilizing compact functions from a special module and a nice little accessory library to Keras) we can train a CNN, generate activation maps, and display them layer by layer — from scratch."
},
{
"code": null,
"e": 8492,
"s": 8295,
"text": "This gives you the ability to train CNN models (simple to complex) from any image dataset (as long as you can arrange it in a simple format) and look inside their guts for any test image you want."
},
{
"code": null,
"e": 8577,
"s": 8492,
"text": "For more of such hands-on tutorials, check my Deep-Learning-with-Python Github repo."
}
] |
Get Your Conda Environment to Show in Jupyter Notebooks — the “Easy Way” | by Ben Bogart | Towards Data Science
|
When I first started using Jupyter Notebooks it took me longer than I’d like to admit to figure out how to get my conda environment kernels to show in the kernels list. When I succeeded I wasn’t satisfied, because I wanted it to be automatic. Like most things, both are simple once you know how.
I’ll show three methods below, each of which is best for a specific scenario.
This is my preferred method because it is simple. New environments appear automatically (as long as they have ipykernel installed.)
As of the time of this writing, nb_conda_kernels does not yet support Python 3.9. This only affects our base environment which we aren’t going to use for any of our work anyway, right? :). Your other environments can use any Python version including 3.9.
Initially your kernel list (under Change kernel) will only show your current environment.
To get your other environment kernels to show automatically:
1. First, install nb_conda_kernels in your base environment. Once this is installed any notebook running from the base environment will automatically show the kernel from any other environment which has ipykernel installed.
(base)$ conda install nb_conda_kernels
2. Next, create a new environment. I will call mine new-env. If you already have an environment you are trying to get to show on Jupyter Notebook, skip this step.
(base)$ conda create --name new-env
3. Activate the environment you want to use in your notebook and install iypkernel. My environment is called new-env. If you already have an environment substitute your environment nane for new-env
(base)$ conda activate new-env(new-env)$ conda install ipykernel
4. Restart Jupyter Notebooks from your base environment and done. You can see here that all of my environments with ipykernel installed including new-env are showing. I can now switch between them at will. Bliss.
It is not that much harder to individually register each environment you want to show in your kernels list. If you have many environments this might be preferable because it allows you to register and un-register your environment kernels which could help keep that list tidy.
In your new environment install ipykernel
In your new environment install ipykernel
(new-env)$ conda install ipykernel
2. Register the kernel spec with Jupyter using the following command. The--name= argument will set the name you see in Jupyter Notebooks for this environment’s kernel (so you can call it whatever you want but using the environment’s name might be wise).
(new-env)$ipython kernel install --user --name=new-env
3. Now new-env will be displayed in your list of kernels (no need to restart Jupyter Notebook — just reload the page in your browser).
4. When you want to un-register that kernel spec (remove the environment’s kernel from the list of available kernels) use the following command:
$jupyter kernelspec uninstall new-env
This method doesn’t actually get your environment to show in Jupyter Notebooks, but it is worth noting. If you install jupyter in any environment and run jupyter notebook from that environment the notebook will use the kernel from the active environment. The kernel will show with the default name Python 3 but we can verify this works by doing the following.
Activate your environment, install jupyter, and run jupyer notebook.
Activate your environment, install jupyter, and run jupyer notebook.
(base)$ conda activate new-env(new_env)$ conda install jupyter(new_env)$ jupyter notebook
2. Run the following code in your notebook to confirm that you are using the correct kernel
import osprint (os.environ['CONDA_DEFAULT_ENV'])
In the end, how you choose to interact with your kernels in Jupyter Notebook should be based on your particular needs, and not on lack of information about your choices. I hope this article helps to eliminate the later.
Go do good.
I think this stack overflow answer is not rated high enough (go over and upvote it to show some love for lumbric who posted the answer in response to his own question). It was the basis for my initial understanding on this subject.
|
[
{
"code": null,
"e": 468,
"s": 172,
"text": "When I first started using Jupyter Notebooks it took me longer than I’d like to admit to figure out how to get my conda environment kernels to show in the kernels list. When I succeeded I wasn’t satisfied, because I wanted it to be automatic. Like most things, both are simple once you know how."
},
{
"code": null,
"e": 546,
"s": 468,
"text": "I’ll show three methods below, each of which is best for a specific scenario."
},
{
"code": null,
"e": 678,
"s": 546,
"text": "This is my preferred method because it is simple. New environments appear automatically (as long as they have ipykernel installed.)"
},
{
"code": null,
"e": 933,
"s": 678,
"text": "As of the time of this writing, nb_conda_kernels does not yet support Python 3.9. This only affects our base environment which we aren’t going to use for any of our work anyway, right? :). Your other environments can use any Python version including 3.9."
},
{
"code": null,
"e": 1023,
"s": 933,
"text": "Initially your kernel list (under Change kernel) will only show your current environment."
},
{
"code": null,
"e": 1084,
"s": 1023,
"text": "To get your other environment kernels to show automatically:"
},
{
"code": null,
"e": 1308,
"s": 1084,
"text": "1. First, install nb_conda_kernels in your base environment. Once this is installed any notebook running from the base environment will automatically show the kernel from any other environment which has ipykernel installed."
},
{
"code": null,
"e": 1347,
"s": 1308,
"text": "(base)$ conda install nb_conda_kernels"
},
{
"code": null,
"e": 1510,
"s": 1347,
"text": "2. Next, create a new environment. I will call mine new-env. If you already have an environment you are trying to get to show on Jupyter Notebook, skip this step."
},
{
"code": null,
"e": 1546,
"s": 1510,
"text": "(base)$ conda create --name new-env"
},
{
"code": null,
"e": 1744,
"s": 1546,
"text": "3. Activate the environment you want to use in your notebook and install iypkernel. My environment is called new-env. If you already have an environment substitute your environment nane for new-env"
},
{
"code": null,
"e": 1809,
"s": 1744,
"text": "(base)$ conda activate new-env(new-env)$ conda install ipykernel"
},
{
"code": null,
"e": 2022,
"s": 1809,
"text": "4. Restart Jupyter Notebooks from your base environment and done. You can see here that all of my environments with ipykernel installed including new-env are showing. I can now switch between them at will. Bliss."
},
{
"code": null,
"e": 2298,
"s": 2022,
"text": "It is not that much harder to individually register each environment you want to show in your kernels list. If you have many environments this might be preferable because it allows you to register and un-register your environment kernels which could help keep that list tidy."
},
{
"code": null,
"e": 2340,
"s": 2298,
"text": "In your new environment install ipykernel"
},
{
"code": null,
"e": 2382,
"s": 2340,
"text": "In your new environment install ipykernel"
},
{
"code": null,
"e": 2417,
"s": 2382,
"text": "(new-env)$ conda install ipykernel"
},
{
"code": null,
"e": 2671,
"s": 2417,
"text": "2. Register the kernel spec with Jupyter using the following command. The--name= argument will set the name you see in Jupyter Notebooks for this environment’s kernel (so you can call it whatever you want but using the environment’s name might be wise)."
},
{
"code": null,
"e": 2726,
"s": 2671,
"text": "(new-env)$ipython kernel install --user --name=new-env"
},
{
"code": null,
"e": 2861,
"s": 2726,
"text": "3. Now new-env will be displayed in your list of kernels (no need to restart Jupyter Notebook — just reload the page in your browser)."
},
{
"code": null,
"e": 3006,
"s": 2861,
"text": "4. When you want to un-register that kernel spec (remove the environment’s kernel from the list of available kernels) use the following command:"
},
{
"code": null,
"e": 3044,
"s": 3006,
"text": "$jupyter kernelspec uninstall new-env"
},
{
"code": null,
"e": 3404,
"s": 3044,
"text": "This method doesn’t actually get your environment to show in Jupyter Notebooks, but it is worth noting. If you install jupyter in any environment and run jupyter notebook from that environment the notebook will use the kernel from the active environment. The kernel will show with the default name Python 3 but we can verify this works by doing the following."
},
{
"code": null,
"e": 3473,
"s": 3404,
"text": "Activate your environment, install jupyter, and run jupyer notebook."
},
{
"code": null,
"e": 3542,
"s": 3473,
"text": "Activate your environment, install jupyter, and run jupyer notebook."
},
{
"code": null,
"e": 3632,
"s": 3542,
"text": "(base)$ conda activate new-env(new_env)$ conda install jupyter(new_env)$ jupyter notebook"
},
{
"code": null,
"e": 3724,
"s": 3632,
"text": "2. Run the following code in your notebook to confirm that you are using the correct kernel"
},
{
"code": null,
"e": 3773,
"s": 3724,
"text": "import osprint (os.environ['CONDA_DEFAULT_ENV'])"
},
{
"code": null,
"e": 3993,
"s": 3773,
"text": "In the end, how you choose to interact with your kernels in Jupyter Notebook should be based on your particular needs, and not on lack of information about your choices. I hope this article helps to eliminate the later."
},
{
"code": null,
"e": 4005,
"s": 3993,
"text": "Go do good."
}
] |
Bootstrap table-responsive class
|
Wrapping any .table in .table-responsive class, you will make the table scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.
To make a responsive table, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Table</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "table-responsive">
<table class = "table">
<thead>
<tr>
<th>Subject</th>
<th>Marks</th>
<th>Student</th>
</tr>
</thead>
<tbody>
<tr class = "success">
<td>Programming</td>
<td>90</td>
<td>Amit</td>
</tr>
<tr class = "active">
<td>Web Dev</td>
<td>92</td>
<td>Yuvraj</td>
</tr>
<tr class = "warning">
<td>Science</td>
<td>95</td>
<td>Sachin</td>
</tr>
<tr class = "danger">
<td>Economics</td>
<td>80</td>
<td>Tony</td>
</tr>
</tbody>
</table>
</body>
</html>
|
[
{
"code": null,
"e": 1287,
"s": 1062,
"text": "Wrapping any .table in .table-responsive class, you will make the table scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables."
},
{
"code": null,
"e": 1355,
"s": 1287,
"text": "To make a responsive table, you can try to run the following code −"
},
{
"code": null,
"e": 1365,
"s": 1355,
"text": "Live Demo"
},
{
"code": null,
"e": 2544,
"s": 1365,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"table-responsive\">\n <table class = \"table\">\n <thead>\n <tr>\n <th>Subject</th>\n <th>Marks</th>\n <th>Student</th>\n </tr>\n </thead>\n <tbody>\n <tr class = \"success\">\n <td>Programming</td>\n <td>90</td>\n <td>Amit</td>\n </tr>\n <tr class = \"active\">\n <td>Web Dev</td>\n <td>92</td>\n <td>Yuvraj</td>\n </tr>\n <tr class = \"warning\">\n <td>Science</td>\n <td>95</td>\n <td>Sachin</td>\n </tr>\n <tr class = \"danger\">\n <td>Economics</td>\n <td>80</td>\n <td>Tony</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>"
}
] |
Convert list of strings and characters to list of characters in Python
|
While dalign with lists, we may come across a situation where we have to process a string and get its individual characters for further processing. In this article we will see various ways to do that.
We design a for loop to go through each element of the list and another loop inside this to pick each character from the element which is a string.
Live Demo
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = [i for ele in listA for i in ele]
# Result
print("List of characters: \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']
The itertools module of python gives us the chain function. Using it we fetch each character from the strings of the list and put it into a new list.
Live Demo
from itertools import chain
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = list(chain.from_iterable(listA))
# Result
print("List of characters: \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']
The join method can be used to combine all the elements into a single string and then apply the list function which will store each character as a separate string.
Live Demo
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = list(''.join(listA))
# Result
print("List of characters: \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'd', 'ay']
List of characters:
['M', 'o', 'n', 'd', 'a', 'y']
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "While dalign with lists, we may come across a situation where we have to process a string and get its individual characters for further processing. In this article we will see various ways to do that."
},
{
"code": null,
"e": 1411,
"s": 1263,
"text": "We design a for loop to go through each element of the list and another loop inside this to pick each character from the element which is a string."
},
{
"code": null,
"e": 1422,
"s": 1411,
"text": " Live Demo"
},
{
"code": null,
"e": 1595,
"s": 1422,
"text": "listA = ['Mon','d','ay']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Get characters\nres = [i for ele in listA for i in ele]\n# Result\nprint(\"List of characters: \\n\",res)"
},
{
"code": null,
"e": 1650,
"s": 1595,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1733,
"s": 1650,
"text": "Given list :\n['Mon', 'd', 'ay']\nList of characters:\n['M', 'o', 'n', 'd', 'a', 'y']"
},
{
"code": null,
"e": 1883,
"s": 1733,
"text": "The itertools module of python gives us the chain function. Using it we fetch each character from the strings of the list and put it into a new list."
},
{
"code": null,
"e": 1894,
"s": 1883,
"text": " Live Demo"
},
{
"code": null,
"e": 2094,
"s": 1894,
"text": "from itertools import chain\nlistA = ['Mon','d','ay']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Get characters\nres = list(chain.from_iterable(listA))\n# Result\nprint(\"List of characters: \\n\",res)"
},
{
"code": null,
"e": 2149,
"s": 2094,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2232,
"s": 2149,
"text": "Given list :\n['Mon', 'd', 'ay']\nList of characters:\n['M', 'o', 'n', 'd', 'a', 'y']"
},
{
"code": null,
"e": 2396,
"s": 2232,
"text": "The join method can be used to combine all the elements into a single string and then apply the list function which will store each character as a separate string."
},
{
"code": null,
"e": 2407,
"s": 2396,
"text": " Live Demo"
},
{
"code": null,
"e": 2567,
"s": 2407,
"text": "listA = ['Mon','d','ay']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Convert to int\nres = list(''.join(listA))\n# Result\nprint(\"List of characters: \\n\",res)"
},
{
"code": null,
"e": 2622,
"s": 2567,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2705,
"s": 2622,
"text": "Given list :\n['Mon', 'd', 'ay']\nList of characters:\n['M', 'o', 'n', 'd', 'a', 'y']"
}
] |
Apache Kafka - Installation Steps
|
Following are the steps for installing Java on your machine.
Hopefully you have already installed java on your machine right now, so you just verify it using the following command.
$ java -version
If java is successfully installed on your machine, you could see the version of the installed Java.
If Java is not downloaded, please download the latest version of JDK by visiting the following link and download latest version.
Now the latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Please download the file on your machine.
Generally, files being downloaded are stored in the downloads folder, verify it and extract the tar setup using the following commands.
$ cd /go/to/download/path
$ tar -zxf jdk-8u60-linux-x64.gz
To make java available to all users, move the extracted java content to usr/local/java/ folder.
$ su
password: (type password of root user)
$ mkdir /opt/jdk
$ mv jdk-1.8.0_60 /opt/jdk/
To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file.
export JAVA_HOME =/usr/jdk/jdk-1.8.0_60
export PATH=$PATH:$JAVA_HOME/bin
Now apply all the changes into current running system.
$ source ~/.bashrc
Use the following command to change Java Alternatives.
update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100
Step 1.6 − Now verify java using verification command (java -version) explained in Step 1.
To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper.
As of now, latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz).
Extract tar file using the following command
$ cd opt/
$ tar -zxf zookeeper-3.4.6.tar.gz
$ cd zookeeper-3.4.6
$ mkdir data
Open Configuration File named conf/zoo.cfg using the command vi “conf/zoo.cfg” and all the following parameters to set as starting point.
$ vi conf/zoo.cfg
tickTime=2000
dataDir=/path/to/zookeeper/data
clientPort=2181
initLimit=5
syncLimit=2
Once the configuration file has been saved successfully and return to terminal again, you can start the zookeeper server.
$ bin/zkServer.sh start
After executing this command, you will get a response as shown below −
$ JMX enabled by default
$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg
$ Starting zookeeper ... STARTED
$ bin/zkCli.sh
After typing the above command, you will be connected to the zookeeper server and will get the below response.
Connecting to localhost:2181
................
................
................
Welcome to ZooKeeper!
................
................
WATCHER::
WatchedEvent state:SyncConnected type: None path:null
[zk: localhost:2181(CONNECTED) 0]
After connecting the server and performing all the operations, you can stop the zookeeper server with the following command −
$ bin/zkServer.sh stop
Now you have successfully installed Java and ZooKeeper on your machine. Let us see the steps to install Apache Kafka.
Let us continue with the following steps to install Kafka on your machine.
To install Kafka on your machine, click on the below link −
Now the latest version i.e., – kafka_2.11_0.9.0.0.tgz will be downloaded onto your machine.
Extract the tar file using the following command −
$ cd opt/
$ tar -zxf kafka_2.11.0.9.0.0 tar.gz
$ cd kafka_2.11.0.9.0.0
Now you have downloaded the latest version of Kafka on your machine.
You can start the server by giving the following command −
$ bin/kafka-server-start.sh config/server.properties
After the server starts, you would see the below response on your screen −
$ bin/kafka-server-start.sh config/server.properties
[2016-01-02 15:37:30,410] INFO KafkaConfig values:
request.timeout.ms = 30000
log.roll.hours = 168
inter.broker.protocol.version = 0.9.0.X
log.preallocate = false
security.inter.broker.protocol = PLAINTEXT
....................................................
....................................................
After performing all the operations, you can stop the server using the following command −
$ bin/kafka-server-stop.sh config/server.properties
Now that we have already discussed the Kafka installation, we can learn how to perform basic operations on Kafka in the next chapter.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2028,
"s": 1967,
"text": "Following are the steps for installing Java on your machine."
},
{
"code": null,
"e": 2148,
"s": 2028,
"text": "Hopefully you have already installed java on your machine right now, so you just verify it using the following command."
},
{
"code": null,
"e": 2165,
"s": 2148,
"text": "$ java -version\n"
},
{
"code": null,
"e": 2265,
"s": 2165,
"text": "If java is successfully installed on your machine, you could see the version of the installed Java."
},
{
"code": null,
"e": 2394,
"s": 2265,
"text": "If Java is not downloaded, please download the latest version of JDK by visiting the following link and download latest version."
},
{
"code": null,
"e": 2517,
"s": 2394,
"text": "Now the latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Please download the file on your machine."
},
{
"code": null,
"e": 2653,
"s": 2517,
"text": "Generally, files being downloaded are stored in the downloads folder, verify it and extract the tar setup using the following commands."
},
{
"code": null,
"e": 2713,
"s": 2653,
"text": "$ cd /go/to/download/path\n$ tar -zxf jdk-8u60-linux-x64.gz\n"
},
{
"code": null,
"e": 2809,
"s": 2713,
"text": "To make java available to all users, move the extracted java content to usr/local/java/ folder."
},
{
"code": null,
"e": 2899,
"s": 2809,
"text": "$ su\npassword: (type password of root user)\n$ mkdir /opt/jdk\n$ mv jdk-1.8.0_60 /opt/jdk/\n"
},
{
"code": null,
"e": 2982,
"s": 2899,
"text": "To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file."
},
{
"code": null,
"e": 3056,
"s": 2982,
"text": "export JAVA_HOME =/usr/jdk/jdk-1.8.0_60\nexport PATH=$PATH:$JAVA_HOME/bin\n"
},
{
"code": null,
"e": 3111,
"s": 3056,
"text": "Now apply all the changes into current running system."
},
{
"code": null,
"e": 3131,
"s": 3111,
"text": "$ source ~/.bashrc\n"
},
{
"code": null,
"e": 3186,
"s": 3131,
"text": "Use the following command to change Java Alternatives."
},
{
"code": null,
"e": 3270,
"s": 3186,
"text": "update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100\n"
},
{
"code": null,
"e": 3361,
"s": 3270,
"text": "Step 1.6 − Now verify java using verification command (java -version) explained in Step 1."
},
{
"code": null,
"e": 3480,
"s": 3361,
"text": "To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper."
},
{
"code": null,
"e": 3554,
"s": 3480,
"text": "As of now, latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz)."
},
{
"code": null,
"e": 3599,
"s": 3554,
"text": "Extract tar file using the following command"
},
{
"code": null,
"e": 3678,
"s": 3599,
"text": "$ cd opt/\n$ tar -zxf zookeeper-3.4.6.tar.gz\n$ cd zookeeper-3.4.6\n$ mkdir data\n"
},
{
"code": null,
"e": 3816,
"s": 3678,
"text": "Open Configuration File named conf/zoo.cfg using the command vi “conf/zoo.cfg” and all the following parameters to set as starting point."
},
{
"code": null,
"e": 3921,
"s": 3816,
"text": "$ vi conf/zoo.cfg\ntickTime=2000\ndataDir=/path/to/zookeeper/data\nclientPort=2181\ninitLimit=5\nsyncLimit=2\n"
},
{
"code": null,
"e": 4043,
"s": 3921,
"text": "Once the configuration file has been saved successfully and return to terminal again, you can start the zookeeper server."
},
{
"code": null,
"e": 4068,
"s": 4043,
"text": "$ bin/zkServer.sh start\n"
},
{
"code": null,
"e": 4139,
"s": 4068,
"text": "After executing this command, you will get a response as shown below −"
},
{
"code": null,
"e": 4260,
"s": 4139,
"text": "$ JMX enabled by default\n$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg\n$ Starting zookeeper ... STARTED\n"
},
{
"code": null,
"e": 4276,
"s": 4260,
"text": "$ bin/zkCli.sh\n"
},
{
"code": null,
"e": 4387,
"s": 4276,
"text": "After typing the above command, you will be connected to the zookeeper server and will get the below response."
},
{
"code": null,
"e": 4622,
"s": 4387,
"text": "Connecting to localhost:2181\n................\n................\n................\nWelcome to ZooKeeper!\n................\n................\nWATCHER::\nWatchedEvent state:SyncConnected type: None path:null\n[zk: localhost:2181(CONNECTED) 0]\n"
},
{
"code": null,
"e": 4748,
"s": 4622,
"text": "After connecting the server and performing all the operations, you can stop the zookeeper server with the following command −"
},
{
"code": null,
"e": 4772,
"s": 4748,
"text": "$ bin/zkServer.sh stop\n"
},
{
"code": null,
"e": 4890,
"s": 4772,
"text": "Now you have successfully installed Java and ZooKeeper on your machine. Let us see the steps to install Apache Kafka."
},
{
"code": null,
"e": 4965,
"s": 4890,
"text": "Let us continue with the following steps to install Kafka on your machine."
},
{
"code": null,
"e": 5025,
"s": 4965,
"text": "To install Kafka on your machine, click on the below link −"
},
{
"code": null,
"e": 5117,
"s": 5025,
"text": "Now the latest version i.e., – kafka_2.11_0.9.0.0.tgz will be downloaded onto your machine."
},
{
"code": null,
"e": 5168,
"s": 5117,
"text": "Extract the tar file using the following command −"
},
{
"code": null,
"e": 5240,
"s": 5168,
"text": "$ cd opt/\n$ tar -zxf kafka_2.11.0.9.0.0 tar.gz\n$ cd kafka_2.11.0.9.0.0\n"
},
{
"code": null,
"e": 5309,
"s": 5240,
"text": "Now you have downloaded the latest version of Kafka on your machine."
},
{
"code": null,
"e": 5368,
"s": 5309,
"text": "You can start the server by giving the following command −"
},
{
"code": null,
"e": 5422,
"s": 5368,
"text": "$ bin/kafka-server-start.sh config/server.properties\n"
},
{
"code": null,
"e": 5497,
"s": 5422,
"text": "After the server starts, you would see the below response on your screen −"
},
{
"code": null,
"e": 5863,
"s": 5497,
"text": "$ bin/kafka-server-start.sh config/server.properties\n[2016-01-02 15:37:30,410] INFO KafkaConfig values:\nrequest.timeout.ms = 30000\nlog.roll.hours = 168\ninter.broker.protocol.version = 0.9.0.X\nlog.preallocate = false\nsecurity.inter.broker.protocol = PLAINTEXT\n....................................................\n....................................................\n"
},
{
"code": null,
"e": 5954,
"s": 5863,
"text": "After performing all the operations, you can stop the server using the following command −"
},
{
"code": null,
"e": 6007,
"s": 5954,
"text": "$ bin/kafka-server-stop.sh config/server.properties\n"
},
{
"code": null,
"e": 6141,
"s": 6007,
"text": "Now that we have already discussed the Kafka installation, we can learn how to perform basic operations on Kafka in the next chapter."
},
{
"code": null,
"e": 6176,
"s": 6141,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6195,
"s": 6176,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6230,
"s": 6195,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6251,
"s": 6230,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6284,
"s": 6251,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6297,
"s": 6284,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6332,
"s": 6297,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6350,
"s": 6332,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6383,
"s": 6350,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6401,
"s": 6383,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6434,
"s": 6401,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6452,
"s": 6434,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6459,
"s": 6452,
"text": " Print"
},
{
"code": null,
"e": 6470,
"s": 6459,
"text": " Add Notes"
}
] |
How can we read data from an excel sheet in Selenium Webdriver?
|
We can read data from an excel sheet in Selenium webdriver in Python.
An excel workbook consists of multiple sheets and each sheet consists of cells and columns.
To work with excel in Python(with extension .xlsx, .xlsm, and so on) we have to utilize the OpenPyXL library. To install this package, we have to run the command: pip install openpyxl. Also, we have to add the statement import openpyxl in our code.
To open an excel workbook, the method is load_workbook and pass the path of the excel file as a parameter to this method. To identify the active sheet, we have to use the active method on the workbook object.
To read a cell, the method cell is applied on the active sheet and the row and column numbers are passed as parameters to this method. Then the value method is applied on a particular cell to read values within it.
Let us read the value at the third row and second column having the value D as shown below in an excel workbook of name Data.xlsx −
import openpyxl
#configure workbook path
b = openpyxl.load_workbook("C:\\Data.xlsx")
#get active sheet
sht = b.active
#get cell address within active sheet
cl = sht.cell (row = 3, column = 2)
#read value with cell
print("Reading value from row-3, col-2: ")
print (cl.value)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "We can read data from an excel sheet in Selenium webdriver in Python."
},
{
"code": null,
"e": 1224,
"s": 1132,
"text": "An excel workbook consists of multiple sheets and each sheet consists of cells and columns."
},
{
"code": null,
"e": 1473,
"s": 1224,
"text": "To work with excel in Python(with extension .xlsx, .xlsm, and so on) we have to utilize the OpenPyXL library. To install this package, we have to run the command: pip install openpyxl. Also, we have to add the statement import openpyxl in our code."
},
{
"code": null,
"e": 1682,
"s": 1473,
"text": "To open an excel workbook, the method is load_workbook and pass the path of the excel file as a parameter to this method. To identify the active sheet, we have to use the active method on the workbook object."
},
{
"code": null,
"e": 1897,
"s": 1682,
"text": "To read a cell, the method cell is applied on the active sheet and the row and column numbers are passed as parameters to this method. Then the value method is applied on a particular cell to read values within it."
},
{
"code": null,
"e": 2029,
"s": 1897,
"text": "Let us read the value at the third row and second column having the value D as shown below in an excel workbook of name Data.xlsx −"
},
{
"code": null,
"e": 2303,
"s": 2029,
"text": "import openpyxl\n#configure workbook path\nb = openpyxl.load_workbook(\"C:\\\\Data.xlsx\")\n#get active sheet\nsht = b.active\n#get cell address within active sheet\ncl = sht.cell (row = 3, column = 2)\n#read value with cell\nprint(\"Reading value from row-3, col-2: \")\nprint (cl.value)"
}
] |
A LightGBM Autoregressor — Using Sktime | by Satya Pattnaik | Towards Data Science
|
I came across a new and promising Python Library for Time Series — Sktime. It provides a plethora of Time Series Functionalities like Transformations, Forecasting algorithms, the Composition of Forecasters, Model Validation, Pipelining the entire flow, and many more. In this article, we explore some features the library provides, the most important one being how to make a Machine Learning model — a Light GBM fit for time series forecasting.
When it comes to Time Series Forecasting, ARIMA and its variants dominate the domain(simple yet powerful methods). However, having a strong personal liking for Ensemble Tree Models it is always tempting to use them for forecasting too! We explore ways in which we can formulate a Time Series forecasting problem into a Supervised Learning Task and solve it using Sktime.
We take the previous k time-step values as our regressors and output the k+1 value. This is a One-Step Ahead forecaster, which can be better understood from the below diagram. In the diagram, we auto-regress on the previous four values and forecast the fifth one at each point in time. If you are familiar with Sklearn APIs, we can fit our regression model by using fit(X,y), where X and y are as shown below.
Assuming we use a GBM Regressor, the below diagram fits well to illustrate the concept!
But the real-world problems involve forecasting the future multiple steps ahead. How do we tackle that?
There are multiple ways to do that, for further reading, please refer to Reference[1]. We explore one of the strategies, namely the Recursive variant.
We achieve this by iterating over multiple-steps(which is known as Forecasting Horizon) and using the forecasted value as input for forecasting the next value. This is known as Recursive Strategy and despite some of its limitations(error sensitivity), it works well in real-world settings. The below diagram illustrates the idea.
A pseudo-code for the same:
for each_time_step in forecasting_horizon: Use forecast from (each_time_step - 1) step in the Input. forecast()
Let’s start by installing Sktime and importing the libraries!
! pip install sktime==0.4.3import pandas as pdimport numpy as npimport seaborn as snsimport warningsimport itertoolsimport numpy as npimport matplotlib.pyplot as pltimport lightgbm as lgbfrom pylab import rcParamsrcParams['figure.figsize'] = 18, 8warnings.filterwarnings("ignore")from statsmodels.tsa.seasonal import seasonal_decompose#-----------------------Imports from Sktime-------------------------from sktime.forecasting.base import ForecastingHorizonfrom sktime.transformers.single_series.detrend import Deseasonalizer, Detrenderfrom sktime.forecasting.trend import PolynomialTrendForecasterfrom sktime.forecasting.model_selection import ( temporal_train_test_split,)from sktime.utils.plotting import plot_seriesfrom sktime.forecasting.compose import ( TransformedTargetForecaster, ReducedRegressionForecaster)
The Sales data that we will work on can be found on Kaggle. Assuming the data is in the project root, we load the data.
#------------------------Reading Data from CSV----------------------df = pd.read_csv("train.csv",parse_dates=['date'])df.head()
For our implementation and demonstration, we select the Data from “store 1” and aggregate the data at a monthly level.
#--------------------------Data Preparation-------------------------#For the sake of demonstration, we will train our model on monthly aggregated Sales data of a particular store# Select sales for Store 1 Only.store1_agg = df.loc[df['store']==1].groupby(['date'])['sales'].sum()store1_agg.index = pd.to_datetime(store1_agg.index)#Aggregate the Data on a Monthly basis.store1_agg_monthly = store1_agg.resample('M').sum()#--------------------Visulaize Data on a Time Plot------------------sns.lineplot( data=store1_agg_monthly, )plt.title("Store-1 Sales Data aggreagted at Month Level")plt.show()
The above plot gives us the idea that the time series is seasonal and heteroskedastic(the variations increase with time for a Season). We need to use a Multiplicative Decomposition in such a case, to examine its Seasonal, Trend components and the residuals. The Seasonality is Annual, so we decompose with a Seasonality hyper-parameter set to 12. We notice a Linear(approximately) Trend and infer the Seasonal Element from the plot below. The maximum sales occur during the Mid-Year.
#----------------------Time Series Decomposition--------------------seasonal_decompose(store1_agg_monthly,model="multiplicative",period=12).plot()plt.show()
We go for a train-test split next using Sktime’s specialized function — temporal_train_test_split(20% of the data is set for validation). This function is tailored for Sequential Data Splitting as it maintains the ordering of the data without shuffling across time.
#--------------------Time Series Train-Test split-------------------store1_agg_monthly.index = store1_agg_monthly.index.to_period('M') y_train, y_test = temporal_train_test_split(store1_agg_monthly, test_size=0.2)
What if we just want to forecast the Trend for analysis purposes or in order to use it as one of the steps in Composition Forecasting?
Sktime provides PolynomialTrendForecaster for this purpose, which can be used to fit a polynomial trend. The forecast it generates can be in turn combined with forecasts from other components to generate a final forecast. To illustrate its effects, we can use Sktime’s Detrender which takes the Polynomial forecaster as input in order to detrend the Time Series. It returns the residuals after removing the trend generated by the Trend Forecaster. The trend generated can be seen in the yellow line in the below plot. As we see the residuals consist mostly of the Seasonal component.
#--------------------------Detrender-----------------------------#degree=1 for Linearforecaster = PolynomialTrendForecaster(degree=1) transformer = Detrender(forecaster=forecaster)#Get the residuals after fitting a linear trendy_resid = transformer.fit_transform(y_train)# Internally, the Detrender uses the in-sample predictions# of the PolynomialTrendForecasterforecaster = PolynomialTrendForecaster(degree=1)fh_ins = -np.arange(len(y_train)) # in-sample forecasting horizony_pred = forecaster.fit(y_train).predict(fh=fh_ins)plot_series(y_train, y_pred, y_resid, labels=["y_train", "fitted linear trend", "residuals"]);
Similarly, in order to extract the seasonal component from the time series, we can use Sktime’s Deseasonalizer. This removes the seasonal component leaving behind the trend and other cyclic components in the time series.We extract the Annual Seasonality in this step(period=12).
#--------------------------Deseasonalizer---------------------------#Multiplicative Deseasonalizer, period = 12(for Monthly Data)deseasonalizer = Deseasonalizer(model="multiplicative", sp=12)plot_series(deseasonalizer.fit_transform(y_train))seasonal = deseasonalizer.fit_transform(y_train)
To implement a recursive strategy(as discussed above) needs to take care of various boundary conditions and the implementation might not be a robust one. This implementation is abstracted by Sktime’s RecursiveRegressionForecaster or a more generalized ReducedRegressionForecaster, which takes a Sklearn API compatible Regressor and reduces it into a Multi-Step Ahead Forecaster based on Recursive strategy. Here we auto-regress on the previous four historic values.
Some important hyperparameters for ReducedRegressionForecaster:
window_length: The number of (immediate)previous historic values to consider as regressors.
strategy: Multi-Step Forecast strategy, in this case, its “recursive”.
regressor = lgb.LGBMRegressor()forecaster = ReducedRegressionForecaster( regressor=regressor, window_length=4, strategy="recursive" #hyper-paramter to set recursive strategy)
Finally, we can use a Meta-Forecaster which can combine the effects of multiple forecasters to produce the final forecast. To exemplify its use, we take the following case. We use three different forecasters and combine them:
Seasonality Forecaster(Using Deseasonalizer)
Trend Forecaster(Using Detrender)
AutoRegressor, based on immediate previous values(Using LightGBM and ReducedRegressionForecaster)
We use Sktime’s TransformedTargetForecaster for this purpose which abstracts the meta forecasting techniques. Internally it not only fits multiple forecasters as a pipeline but also generates the forecasts and combines them(the seasonal, the trend, and the autoregressive components) into a final one. The pipeline can be found in the below code snippet. All the sequential steps conveniently pipelined using TransformedTargetForecaster.
#----------------------------Create Pipeline--------------------def get_transformed_target_forecaster(alpha,params): #Initialize Light GBM Regressor regressor = lgb.LGBMRegressor(alpha = alpha,**params)#-----------------------Forecaster Pipeline----------------- #1.Separate the Seasonal Component. #2.Fit a forecaster for the trend. #3.Fit a Autoregressor to the resdiual(autoregressing on four historic values). forecaster = TransformedTargetForecaster( [ ("deseasonalise", Deseasonalizer(model="multiplicative", sp=12)), ("detrend", Detrender(forecaster=PolynomialTrendForecaster(degree=1))), ( # Recursive strategy for Multi-Step Ahead Forecast. # Auto Regress on four previous values "forecast", ReducedRegressionForecaster( regressor=regressor, window_length=4, strategy="recursive", ), ), ] ) return forecaster
Real-life forecasts involve uncertainty estimations mostly in the form of Confidence/Prediction Intervals. We use LightGBM’s quantile loss to get regressed values based on quantiles(10th, median, and 90th being popular ones). A blog on the same can be found here.
#-------------------Fitting an Auto Regressive Light-GBM------------#Setting Quantile Regression Hyper-parameter.params = { 'objective':'quantile'}#A 10 percent and 90 percent prediction interval(0.1,0.9 respectively).quantiles = [.1, .5, .9] #Hyper-parameter "alpha" in Light GBM#Capture forecasts for 10th/median/90th quantile, respectively.forecasts = []#Iterate for each quantile.for alpha in quantiles: forecaster = get_transformed_target_forecaster(alpha,params) #Initialize ForecastingHorizon class to specify the horizon of forecast fh = ForecastingHorizon(y_test.index, is_relative=False) #Fit on Training data. forecaster.fit(y_train) #Forecast the values. y_pred = forecaster.predict(fh) #List of forecasts made for each quantile. y_pred.index.name="date" y_pred.name=f"predicted_sales_q_{alpha}" forecasts.append(y_pred) #Append the actual data for plotting.store1_agg_monthly.index.name = "date"store1_agg_monthly.name = "original"forecasts.append(store1_agg_monthly)
Finally, we plot the results-
#-------------------Final Plotting of Forecasts------------------plot_data = pd.melt(pd.concat(forecasts,axis=1).reset_index(), id_vars=['date'],\ value_vars=['predicted_sales_q_0.1', 'predicted_sales_q_0.5', 'predicted_sales_q_0.9','original'])plot_data['date'] = pd.to_datetime(plot_data['date'].astype(str).to_numpy())plot_data['if_original'] = plot_data['variable'].apply( lambda r:'original' if r=='original' else 'predicted' )sns.lineplot(data = plot_data, x='date', y='value', hue='if_original', style="if_original", markers=['o','o'],)plt.title("Final Forecast")plt.show()
The library seems to be under active development so it's good to use the latest releases(and the corresponding functions/modules). Overall, this seems to be a very promising Time Series package and worthwhile to explore. To download the notebook please refer to this Kaggle Kernel. Thanks for the read!
Bontempi, Gianluca & Ben Taieb, Souhaib & Le Borgne, Yann-Aël. ( 2013). Machine Learning Strategies for Time Series Forecasting — https://www.researchgate.net/publication/236941795_Machine_Learning_Strategies_for_Time_Series_Forecasting.Markus Löning, Anthony Bagnall, Sajaysurya Ganesh, Viktor Kazakov, Jason Lines, Franz Király (2019): “sktime: A Unified Interface for Machine Learning with Time Series”LightGBM-Quantile loss — https://towardsdatascience.com/lightgbm-for-quantile-regression-4288d0bb23fd
Bontempi, Gianluca & Ben Taieb, Souhaib & Le Borgne, Yann-Aël. ( 2013). Machine Learning Strategies for Time Series Forecasting — https://www.researchgate.net/publication/236941795_Machine_Learning_Strategies_for_Time_Series_Forecasting.
Markus Löning, Anthony Bagnall, Sajaysurya Ganesh, Viktor Kazakov, Jason Lines, Franz Király (2019): “sktime: A Unified Interface for Machine Learning with Time Series”
LightGBM-Quantile loss — https://towardsdatascience.com/lightgbm-for-quantile-regression-4288d0bb23fd
|
[
{
"code": null,
"e": 617,
"s": 172,
"text": "I came across a new and promising Python Library for Time Series — Sktime. It provides a plethora of Time Series Functionalities like Transformations, Forecasting algorithms, the Composition of Forecasters, Model Validation, Pipelining the entire flow, and many more. In this article, we explore some features the library provides, the most important one being how to make a Machine Learning model — a Light GBM fit for time series forecasting."
},
{
"code": null,
"e": 988,
"s": 617,
"text": "When it comes to Time Series Forecasting, ARIMA and its variants dominate the domain(simple yet powerful methods). However, having a strong personal liking for Ensemble Tree Models it is always tempting to use them for forecasting too! We explore ways in which we can formulate a Time Series forecasting problem into a Supervised Learning Task and solve it using Sktime."
},
{
"code": null,
"e": 1398,
"s": 988,
"text": "We take the previous k time-step values as our regressors and output the k+1 value. This is a One-Step Ahead forecaster, which can be better understood from the below diagram. In the diagram, we auto-regress on the previous four values and forecast the fifth one at each point in time. If you are familiar with Sklearn APIs, we can fit our regression model by using fit(X,y), where X and y are as shown below."
},
{
"code": null,
"e": 1486,
"s": 1398,
"text": "Assuming we use a GBM Regressor, the below diagram fits well to illustrate the concept!"
},
{
"code": null,
"e": 1590,
"s": 1486,
"text": "But the real-world problems involve forecasting the future multiple steps ahead. How do we tackle that?"
},
{
"code": null,
"e": 1741,
"s": 1590,
"text": "There are multiple ways to do that, for further reading, please refer to Reference[1]. We explore one of the strategies, namely the Recursive variant."
},
{
"code": null,
"e": 2071,
"s": 1741,
"text": "We achieve this by iterating over multiple-steps(which is known as Forecasting Horizon) and using the forecasted value as input for forecasting the next value. This is known as Recursive Strategy and despite some of its limitations(error sensitivity), it works well in real-world settings. The below diagram illustrates the idea."
},
{
"code": null,
"e": 2099,
"s": 2071,
"text": "A pseudo-code for the same:"
},
{
"code": null,
"e": 2217,
"s": 2099,
"text": "for each_time_step in forecasting_horizon: Use forecast from (each_time_step - 1) step in the Input. forecast()"
},
{
"code": null,
"e": 2279,
"s": 2217,
"text": "Let’s start by installing Sktime and importing the libraries!"
},
{
"code": null,
"e": 3106,
"s": 2279,
"text": "! pip install sktime==0.4.3import pandas as pdimport numpy as npimport seaborn as snsimport warningsimport itertoolsimport numpy as npimport matplotlib.pyplot as pltimport lightgbm as lgbfrom pylab import rcParamsrcParams['figure.figsize'] = 18, 8warnings.filterwarnings(\"ignore\")from statsmodels.tsa.seasonal import seasonal_decompose#-----------------------Imports from Sktime-------------------------from sktime.forecasting.base import ForecastingHorizonfrom sktime.transformers.single_series.detrend import Deseasonalizer, Detrenderfrom sktime.forecasting.trend import PolynomialTrendForecasterfrom sktime.forecasting.model_selection import ( temporal_train_test_split,)from sktime.utils.plotting import plot_seriesfrom sktime.forecasting.compose import ( TransformedTargetForecaster, ReducedRegressionForecaster)"
},
{
"code": null,
"e": 3226,
"s": 3106,
"text": "The Sales data that we will work on can be found on Kaggle. Assuming the data is in the project root, we load the data."
},
{
"code": null,
"e": 3354,
"s": 3226,
"text": "#------------------------Reading Data from CSV----------------------df = pd.read_csv(\"train.csv\",parse_dates=['date'])df.head()"
},
{
"code": null,
"e": 3473,
"s": 3354,
"text": "For our implementation and demonstration, we select the Data from “store 1” and aggregate the data at a monthly level."
},
{
"code": null,
"e": 4071,
"s": 3473,
"text": "#--------------------------Data Preparation-------------------------#For the sake of demonstration, we will train our model on monthly aggregated Sales data of a particular store# Select sales for Store 1 Only.store1_agg = df.loc[df['store']==1].groupby(['date'])['sales'].sum()store1_agg.index = pd.to_datetime(store1_agg.index)#Aggregate the Data on a Monthly basis.store1_agg_monthly = store1_agg.resample('M').sum()#--------------------Visulaize Data on a Time Plot------------------sns.lineplot( data=store1_agg_monthly, )plt.title(\"Store-1 Sales Data aggreagted at Month Level\")plt.show()"
},
{
"code": null,
"e": 4555,
"s": 4071,
"text": "The above plot gives us the idea that the time series is seasonal and heteroskedastic(the variations increase with time for a Season). We need to use a Multiplicative Decomposition in such a case, to examine its Seasonal, Trend components and the residuals. The Seasonality is Annual, so we decompose with a Seasonality hyper-parameter set to 12. We notice a Linear(approximately) Trend and infer the Seasonal Element from the plot below. The maximum sales occur during the Mid-Year."
},
{
"code": null,
"e": 4712,
"s": 4555,
"text": "#----------------------Time Series Decomposition--------------------seasonal_decompose(store1_agg_monthly,model=\"multiplicative\",period=12).plot()plt.show()"
},
{
"code": null,
"e": 4978,
"s": 4712,
"text": "We go for a train-test split next using Sktime’s specialized function — temporal_train_test_split(20% of the data is set for validation). This function is tailored for Sequential Data Splitting as it maintains the ordering of the data without shuffling across time."
},
{
"code": null,
"e": 5192,
"s": 4978,
"text": "#--------------------Time Series Train-Test split-------------------store1_agg_monthly.index = store1_agg_monthly.index.to_period('M') y_train, y_test = temporal_train_test_split(store1_agg_monthly, test_size=0.2)"
},
{
"code": null,
"e": 5327,
"s": 5192,
"text": "What if we just want to forecast the Trend for analysis purposes or in order to use it as one of the steps in Composition Forecasting?"
},
{
"code": null,
"e": 5911,
"s": 5327,
"text": "Sktime provides PolynomialTrendForecaster for this purpose, which can be used to fit a polynomial trend. The forecast it generates can be in turn combined with forecasts from other components to generate a final forecast. To illustrate its effects, we can use Sktime’s Detrender which takes the Polynomial forecaster as input in order to detrend the Time Series. It returns the residuals after removing the trend generated by the Trend Forecaster. The trend generated can be seen in the yellow line in the below plot. As we see the residuals consist mostly of the Seasonal component."
},
{
"code": null,
"e": 6534,
"s": 5911,
"text": "#--------------------------Detrender-----------------------------#degree=1 for Linearforecaster = PolynomialTrendForecaster(degree=1) transformer = Detrender(forecaster=forecaster)#Get the residuals after fitting a linear trendy_resid = transformer.fit_transform(y_train)# Internally, the Detrender uses the in-sample predictions# of the PolynomialTrendForecasterforecaster = PolynomialTrendForecaster(degree=1)fh_ins = -np.arange(len(y_train)) # in-sample forecasting horizony_pred = forecaster.fit(y_train).predict(fh=fh_ins)plot_series(y_train, y_pred, y_resid, labels=[\"y_train\", \"fitted linear trend\", \"residuals\"]);"
},
{
"code": null,
"e": 6813,
"s": 6534,
"text": "Similarly, in order to extract the seasonal component from the time series, we can use Sktime’s Deseasonalizer. This removes the seasonal component leaving behind the trend and other cyclic components in the time series.We extract the Annual Seasonality in this step(period=12)."
},
{
"code": null,
"e": 7103,
"s": 6813,
"text": "#--------------------------Deseasonalizer---------------------------#Multiplicative Deseasonalizer, period = 12(for Monthly Data)deseasonalizer = Deseasonalizer(model=\"multiplicative\", sp=12)plot_series(deseasonalizer.fit_transform(y_train))seasonal = deseasonalizer.fit_transform(y_train)"
},
{
"code": null,
"e": 7569,
"s": 7103,
"text": "To implement a recursive strategy(as discussed above) needs to take care of various boundary conditions and the implementation might not be a robust one. This implementation is abstracted by Sktime’s RecursiveRegressionForecaster or a more generalized ReducedRegressionForecaster, which takes a Sklearn API compatible Regressor and reduces it into a Multi-Step Ahead Forecaster based on Recursive strategy. Here we auto-regress on the previous four historic values."
},
{
"code": null,
"e": 7633,
"s": 7569,
"text": "Some important hyperparameters for ReducedRegressionForecaster:"
},
{
"code": null,
"e": 7725,
"s": 7633,
"text": "window_length: The number of (immediate)previous historic values to consider as regressors."
},
{
"code": null,
"e": 7796,
"s": 7725,
"text": "strategy: Multi-Step Forecast strategy, in this case, its “recursive”."
},
{
"code": null,
"e": 8020,
"s": 7796,
"text": "regressor = lgb.LGBMRegressor()forecaster = ReducedRegressionForecaster( regressor=regressor, window_length=4, strategy=\"recursive\" #hyper-paramter to set recursive strategy)"
},
{
"code": null,
"e": 8246,
"s": 8020,
"text": "Finally, we can use a Meta-Forecaster which can combine the effects of multiple forecasters to produce the final forecast. To exemplify its use, we take the following case. We use three different forecasters and combine them:"
},
{
"code": null,
"e": 8291,
"s": 8246,
"text": "Seasonality Forecaster(Using Deseasonalizer)"
},
{
"code": null,
"e": 8325,
"s": 8291,
"text": "Trend Forecaster(Using Detrender)"
},
{
"code": null,
"e": 8423,
"s": 8325,
"text": "AutoRegressor, based on immediate previous values(Using LightGBM and ReducedRegressionForecaster)"
},
{
"code": null,
"e": 8861,
"s": 8423,
"text": "We use Sktime’s TransformedTargetForecaster for this purpose which abstracts the meta forecasting techniques. Internally it not only fits multiple forecasters as a pipeline but also generates the forecasts and combines them(the seasonal, the trend, and the autoregressive components) into a final one. The pipeline can be found in the below code snippet. All the sequential steps conveniently pipelined using TransformedTargetForecaster."
},
{
"code": null,
"e": 9872,
"s": 8861,
"text": "#----------------------------Create Pipeline--------------------def get_transformed_target_forecaster(alpha,params): #Initialize Light GBM Regressor regressor = lgb.LGBMRegressor(alpha = alpha,**params)#-----------------------Forecaster Pipeline----------------- #1.Separate the Seasonal Component. #2.Fit a forecaster for the trend. #3.Fit a Autoregressor to the resdiual(autoregressing on four historic values). forecaster = TransformedTargetForecaster( [ (\"deseasonalise\", Deseasonalizer(model=\"multiplicative\", sp=12)), (\"detrend\", Detrender(forecaster=PolynomialTrendForecaster(degree=1))), ( # Recursive strategy for Multi-Step Ahead Forecast. # Auto Regress on four previous values \"forecast\", ReducedRegressionForecaster( regressor=regressor, window_length=4, strategy=\"recursive\", ), ), ] ) return forecaster"
},
{
"code": null,
"e": 10136,
"s": 9872,
"text": "Real-life forecasts involve uncertainty estimations mostly in the form of Confidence/Prediction Intervals. We use LightGBM’s quantile loss to get regressed values based on quantiles(10th, median, and 90th being popular ones). A blog on the same can be found here."
},
{
"code": null,
"e": 11176,
"s": 10136,
"text": "#-------------------Fitting an Auto Regressive Light-GBM------------#Setting Quantile Regression Hyper-parameter.params = { 'objective':'quantile'}#A 10 percent and 90 percent prediction interval(0.1,0.9 respectively).quantiles = [.1, .5, .9] #Hyper-parameter \"alpha\" in Light GBM#Capture forecasts for 10th/median/90th quantile, respectively.forecasts = []#Iterate for each quantile.for alpha in quantiles: forecaster = get_transformed_target_forecaster(alpha,params) #Initialize ForecastingHorizon class to specify the horizon of forecast fh = ForecastingHorizon(y_test.index, is_relative=False) #Fit on Training data. forecaster.fit(y_train) #Forecast the values. y_pred = forecaster.predict(fh) #List of forecasts made for each quantile. y_pred.index.name=\"date\" y_pred.name=f\"predicted_sales_q_{alpha}\" forecasts.append(y_pred) #Append the actual data for plotting.store1_agg_monthly.index.name = \"date\"store1_agg_monthly.name = \"original\"forecasts.append(store1_agg_monthly)"
},
{
"code": null,
"e": 11206,
"s": 11176,
"text": "Finally, we plot the results-"
},
{
"code": null,
"e": 11855,
"s": 11206,
"text": "#-------------------Final Plotting of Forecasts------------------plot_data = pd.melt(pd.concat(forecasts,axis=1).reset_index(), id_vars=['date'],\\ value_vars=['predicted_sales_q_0.1', 'predicted_sales_q_0.5', 'predicted_sales_q_0.9','original'])plot_data['date'] = pd.to_datetime(plot_data['date'].astype(str).to_numpy())plot_data['if_original'] = plot_data['variable'].apply( lambda r:'original' if r=='original' else 'predicted' )sns.lineplot(data = plot_data, x='date', y='value', hue='if_original', style=\"if_original\", markers=['o','o'],)plt.title(\"Final Forecast\")plt.show()"
},
{
"code": null,
"e": 12158,
"s": 11855,
"text": "The library seems to be under active development so it's good to use the latest releases(and the corresponding functions/modules). Overall, this seems to be a very promising Time Series package and worthwhile to explore. To download the notebook please refer to this Kaggle Kernel. Thanks for the read!"
},
{
"code": null,
"e": 12668,
"s": 12158,
"text": "Bontempi, Gianluca & Ben Taieb, Souhaib & Le Borgne, Yann-Aël. ( 2013). Machine Learning Strategies for Time Series Forecasting — https://www.researchgate.net/publication/236941795_Machine_Learning_Strategies_for_Time_Series_Forecasting.Markus Löning, Anthony Bagnall, Sajaysurya Ganesh, Viktor Kazakov, Jason Lines, Franz Király (2019): “sktime: A Unified Interface for Machine Learning with Time Series”LightGBM-Quantile loss — https://towardsdatascience.com/lightgbm-for-quantile-regression-4288d0bb23fd"
},
{
"code": null,
"e": 12907,
"s": 12668,
"text": "Bontempi, Gianluca & Ben Taieb, Souhaib & Le Borgne, Yann-Aël. ( 2013). Machine Learning Strategies for Time Series Forecasting — https://www.researchgate.net/publication/236941795_Machine_Learning_Strategies_for_Time_Series_Forecasting."
},
{
"code": null,
"e": 13078,
"s": 12907,
"text": "Markus Löning, Anthony Bagnall, Sajaysurya Ganesh, Viktor Kazakov, Jason Lines, Franz Király (2019): “sktime: A Unified Interface for Machine Learning with Time Series”"
}
] |
DAX Text - RIGHT function
|
Returns the last characters in a text string, based on the number of characters you specify.
RIGHT (<text>, [<num_times>])
text
The text string that contains the characters you want to extract, or a reference to a column that contains text.
If the referenced column does not contain text, it will be implicitly cast to text.
num_times
Optional.
The number of characters you want RIGHT to extract. If omitted, default is 1.
You can also use a reference to a column that contains numbers.
A text string or a calculated column of text strings.
RIGHT always counts each character, whether single byte or double byte, as 1, no matter what the default language setting is.
If num_chars = 0, BLANK is returned.
If num_chars < 0, #ERROR value is returned.
= RIGHT([Product],2) returns the right two characters of the values in the Product column.
= RIGHT([Product]) returns Blank values.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2094,
"s": 2001,
"text": "Returns the last characters in a text string, based on the number of characters you specify."
},
{
"code": null,
"e": 2126,
"s": 2094,
"text": "RIGHT (<text>, [<num_times>]) \n"
},
{
"code": null,
"e": 2131,
"s": 2126,
"text": "text"
},
{
"code": null,
"e": 2244,
"s": 2131,
"text": "The text string that contains the characters you want to extract, or a reference to a column that contains text."
},
{
"code": null,
"e": 2328,
"s": 2244,
"text": "If the referenced column does not contain text, it will be implicitly cast to text."
},
{
"code": null,
"e": 2338,
"s": 2328,
"text": "num_times"
},
{
"code": null,
"e": 2348,
"s": 2338,
"text": "Optional."
},
{
"code": null,
"e": 2426,
"s": 2348,
"text": "The number of characters you want RIGHT to extract. If omitted, default is 1."
},
{
"code": null,
"e": 2490,
"s": 2426,
"text": "You can also use a reference to a column that contains numbers."
},
{
"code": null,
"e": 2544,
"s": 2490,
"text": "A text string or a calculated column of text strings."
},
{
"code": null,
"e": 2670,
"s": 2544,
"text": "RIGHT always counts each character, whether single byte or double byte, as 1, no matter what the default language setting is."
},
{
"code": null,
"e": 2707,
"s": 2670,
"text": "If num_chars = 0, BLANK is returned."
},
{
"code": null,
"e": 2751,
"s": 2707,
"text": "If num_chars < 0, #ERROR value is returned."
},
{
"code": null,
"e": 2884,
"s": 2751,
"text": "= RIGHT([Product],2) returns the right two characters of the values in the Product column.\n= RIGHT([Product]) returns Blank values. "
},
{
"code": null,
"e": 2919,
"s": 2884,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2933,
"s": 2919,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2966,
"s": 2933,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2980,
"s": 2966,
"text": " Randy Minder"
},
{
"code": null,
"e": 3015,
"s": 2980,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3029,
"s": 3015,
"text": " Randy Minder"
},
{
"code": null,
"e": 3036,
"s": 3029,
"text": " Print"
},
{
"code": null,
"e": 3047,
"s": 3036,
"text": " Add Notes"
}
] |
“volatile” qualifier in C
|
Here we will see what is the meaning of volatile qualifier in C++. The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time. These are some properties of volatile.
The volatile keyword cannot remove the memory assignment
It cannot cache the variables in register.
The value cannot change in order of assignment.
Let us see, how we can use the volatile keyword.
volatile int a;
int volatile a;
Here these two declarations are correct. Like other datatypes, we can use volatile pointers, structures, unions etc. The volatile structures and unions can be volatile itself, and their member variables can also be of type volatile.
The volatile is used in different places. For memory mapped peripheral registers, some global variables, that are accessed by some other functions or interrupt service routines, or in some multi-threaded applications, the volatile can be used.
int main (){
int value;
value++;
}i
nt main (){
volatile int value;
value++;
}
There are two blocks of code. In the first block the volatile keyword is not present. So for the first case, the variable will be copied from memory to CPU register, then the operations are performed. In the second case the volatile is present. So in this case the variable will not be copied from memory to registers.
|
[
{
"code": null,
"e": 1308,
"s": 1062,
"text": "Here we will see what is the meaning of volatile qualifier in C++. The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time. These are some properties of volatile."
},
{
"code": null,
"e": 1365,
"s": 1308,
"text": "The volatile keyword cannot remove the memory assignment"
},
{
"code": null,
"e": 1408,
"s": 1365,
"text": "It cannot cache the variables in register."
},
{
"code": null,
"e": 1456,
"s": 1408,
"text": "The value cannot change in order of assignment."
},
{
"code": null,
"e": 1505,
"s": 1456,
"text": "Let us see, how we can use the volatile keyword."
},
{
"code": null,
"e": 1537,
"s": 1505,
"text": "volatile int a;\nint volatile a;"
},
{
"code": null,
"e": 1770,
"s": 1537,
"text": "Here these two declarations are correct. Like other datatypes, we can use volatile pointers, structures, unions etc. The volatile structures and unions can be volatile itself, and their member variables can also be of type volatile."
},
{
"code": null,
"e": 2014,
"s": 1770,
"text": "The volatile is used in different places. For memory mapped peripheral registers, some global variables, that are accessed by some other functions or interrupt service routines, or in some multi-threaded applications, the volatile can be used."
},
{
"code": null,
"e": 2105,
"s": 2014,
"text": "int main (){\n int value;\n value++;\n}i\nnt main (){\n volatile int value;\n value++;\n}"
},
{
"code": null,
"e": 2424,
"s": 2105,
"text": "There are two blocks of code. In the first block the volatile keyword is not present. So for the first case, the variable will be copied from memory to CPU register, then the operations are performed. In the second case the volatile is present. So in this case the variable will not be copied from memory to registers."
}
] |
How to add a variable in HTML?
|
Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.
You can try to run the following code to add a variable in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML var Tag</title>
</head>
<body>
<p>The equations: <var>2x</var> - <var>4z</var> = <var>2y</var> + 3 and
<var>x</var> + <var>5z</var> = <var>3y</var> + 6</p>
</body>
</html>
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression."
},
{
"code": null,
"e": 1286,
"s": 1220,
"text": "You can try to run the following code to add a variable in HTML −"
},
{
"code": null,
"e": 1533,
"s": 1286,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML var Tag</title>\n </head>\n <body>\n <p>The equations: <var>2x</var> - <var>4z</var> = <var>2y</var> + 3 and\n <var>x</var> + <var>5z</var> = <var>3y</var> + 6</p>\n </body>\n</html>"
}
] |
C# - Reading from and Writing to Text Files
|
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class −
public override void Close()
It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
public override int Peek()
Returns the next available character but does not consume it.
public override int Read()
Reads the next character from the input stream and advances the character position by one.
The following example demonstrates reading a text file named Jamaica.txt. The file reads −
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/jamaica.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
Guess what it displays when you compile and run the program!
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table describes the most commonly used methods of this class −
public override void Close()
Closes the current StreamWriter object and the underlying stream.
public override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
public virtual void Write(bool value)
Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
public override void Write(char value)
Writes a character to the stream.
public virtual void Write(decimal value)
Writes the text representation of a decimal value to the text string or stream.
public virtual void Write(double value)
Writes the text representation of an 8-byte floating-point value to the text string or stream.
public virtual void Write(int value)
Writes the text representation of a 4-byte signed integer to the text string or stream.
public override void Write(string value)
Writes a string to the stream.
public virtual void WriteLine()
Writes a line terminator to the text string or stream.
For a complete list of methods, please visit Microsoft's C# documentation.
The following example demonstrates writing text data into a file using the StreamWriter class −
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
string[] names = new string[] {"Zara Ali", "Nuha Ali"};
using (StreamWriter sw = new StreamWriter("names.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Zara Ali
Nuha Ali
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2490,
"s": 2270,
"text": "The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream."
},
{
"code": null,
"e": 2718,
"s": 2490,
"text": "The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class −"
},
{
"code": null,
"e": 2747,
"s": 2718,
"text": "public override void Close()"
},
{
"code": null,
"e": 2870,
"s": 2747,
"text": "It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader."
},
{
"code": null,
"e": 2897,
"s": 2870,
"text": "public override int Peek()"
},
{
"code": null,
"e": 2959,
"s": 2897,
"text": "Returns the next available character but does not consume it."
},
{
"code": null,
"e": 2986,
"s": 2959,
"text": "public override int Read()"
},
{
"code": null,
"e": 3077,
"s": 2986,
"text": "Reads the next character from the input stream and advances the character position by one."
},
{
"code": null,
"e": 3168,
"s": 3077,
"text": "The following example demonstrates reading a text file named Jamaica.txt. The file reads −"
},
{
"code": null,
"e": 3325,
"s": 3168,
"text": "Down the way where the nights are gay\nAnd the sun shines daily on the mountain top\nI took a trip on a sailing ship\nAnd when I reached Jamaica\nI made a stop\n"
},
{
"code": null,
"e": 4183,
"s": 3325,
"text": "using System;\nusing System.IO;\n\nnamespace FileApplication {\n class Program {\n static void Main(string[] args) {\n try {\n // Create an instance of StreamReader to read from a file.\n // The using statement also closes the StreamReader.\n using (StreamReader sr = new StreamReader(\"c:/jamaica.txt\")) {\n string line;\n\n // Read and display lines from the file until \n // the end of the file is reached. \n while ((line = sr.ReadLine()) != null) {\n Console.WriteLine(line);\n }\n }\n } catch (Exception e) {\n // Let the user know what went wrong.\n Console.WriteLine(\"The file could not be read:\");\n Console.WriteLine(e.Message);\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4244,
"s": 4183,
"text": "Guess what it displays when you compile and run the program!"
},
{
"code": null,
"e": 4376,
"s": 4244,
"text": "The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character."
},
{
"code": null,
"e": 4453,
"s": 4376,
"text": "The following table describes the most commonly used methods of this class −"
},
{
"code": null,
"e": 4482,
"s": 4453,
"text": "public override void Close()"
},
{
"code": null,
"e": 4548,
"s": 4482,
"text": "Closes the current StreamWriter object and the underlying stream."
},
{
"code": null,
"e": 4577,
"s": 4548,
"text": "public override void Flush()"
},
{
"code": null,
"e": 4688,
"s": 4577,
"text": "Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream."
},
{
"code": null,
"e": 4726,
"s": 4688,
"text": "public virtual void Write(bool value)"
},
{
"code": null,
"e": 4835,
"s": 4726,
"text": "Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)"
},
{
"code": null,
"e": 4874,
"s": 4835,
"text": "public override void Write(char value)"
},
{
"code": null,
"e": 4908,
"s": 4874,
"text": "Writes a character to the stream."
},
{
"code": null,
"e": 4949,
"s": 4908,
"text": "public virtual void Write(decimal value)"
},
{
"code": null,
"e": 5029,
"s": 4949,
"text": "Writes the text representation of a decimal value to the text string or stream."
},
{
"code": null,
"e": 5069,
"s": 5029,
"text": "public virtual void Write(double value)"
},
{
"code": null,
"e": 5164,
"s": 5069,
"text": "Writes the text representation of an 8-byte floating-point value to the text string or stream."
},
{
"code": null,
"e": 5201,
"s": 5164,
"text": "public virtual void Write(int value)"
},
{
"code": null,
"e": 5289,
"s": 5201,
"text": "Writes the text representation of a 4-byte signed integer to the text string or stream."
},
{
"code": null,
"e": 5330,
"s": 5289,
"text": "public override void Write(string value)"
},
{
"code": null,
"e": 5361,
"s": 5330,
"text": "Writes a string to the stream."
},
{
"code": null,
"e": 5393,
"s": 5361,
"text": "public virtual void WriteLine()"
},
{
"code": null,
"e": 5448,
"s": 5393,
"text": "Writes a line terminator to the text string or stream."
},
{
"code": null,
"e": 5523,
"s": 5448,
"text": "For a complete list of methods, please visit Microsoft's C# documentation."
},
{
"code": null,
"e": 5619,
"s": 5523,
"text": "The following example demonstrates writing text data into a file using the StreamWriter class −"
},
{
"code": null,
"e": 6296,
"s": 5619,
"text": "using System;\nusing System.IO;\n\nnamespace FileApplication {\n class Program {\n static void Main(string[] args) {\n string[] names = new string[] {\"Zara Ali\", \"Nuha Ali\"};\n \n using (StreamWriter sw = new StreamWriter(\"names.txt\")) {\n\n foreach (string s in names) {\n sw.WriteLine(s);\n }\n }\n \n // Read and show each line from the file.\n string line = \"\";\n using (StreamReader sr = new StreamReader(\"names.txt\")) {\n while ((line = sr.ReadLine()) != null) {\n Console.WriteLine(line);\n }\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 6377,
"s": 6296,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6396,
"s": 6377,
"text": "Zara Ali\nNuha Ali\n"
},
{
"code": null,
"e": 6433,
"s": 6396,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 6446,
"s": 6433,
"text": " Raja Biswas"
},
{
"code": null,
"e": 6480,
"s": 6446,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6498,
"s": 6480,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6531,
"s": 6498,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6545,
"s": 6531,
"text": " Peter Jepson"
},
{
"code": null,
"e": 6582,
"s": 6545,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 6597,
"s": 6582,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 6632,
"s": 6597,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6647,
"s": 6632,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6682,
"s": 6647,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6694,
"s": 6682,
"text": " Eric Frick"
},
{
"code": null,
"e": 6701,
"s": 6694,
"text": " Print"
},
{
"code": null,
"e": 6712,
"s": 6701,
"text": " Add Notes"
}
] |
Elasticsearch - Index APIs
|
These APIs are responsible for managing all the aspects of the index like settings, aliases, mappings, index templates.
This API helps you to create an index. An index can be created automatically when a user is passing JSON objects to any index or it can be created before that. To create an index, you just need to send a PUT request with settings, mappings and aliases or just a simple request without body.
PUT colleges
On running the above code, we get the output as shown below −
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "colleges"
}
We can also add some settings to the above command −
PUT colleges
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}
}
On running the above code, we get the output as shown below −
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "colleges"
}
This API helps you to delete any index. You just need to pass a delete request with the name of that particular Index.
DELETE /colleges
You can delete all indices by just using _all or *.
This API can be called by just sending get request to one or more than one indices. This returns the information about index.
GET colleges
On running the above code, we get the output as shown below −
{
"colleges" : {
"aliases" : {
"alias_1" : { },
"alias_2" : {
"filter" : {
"term" : {
"user" : "pkay"
}
},
"index_routing" : "pkay",
"search_routing" : "pkay"
}
},
"mappings" : { },
"settings" : {
"index" : {
"creation_date" : "1556245406616",
"number_of_shards" : "1",
"number_of_replicas" : "1",
"uuid" : "3ExJbdl2R1qDLssIkwDAug",
"version" : {
"created" : "7000099"
},
"provided_name" : "colleges"
}
}
}
}
You can get the information of all the indices by using _all or *.
Existence of an index can be determined by just sending a get request to that index. If the HTTP response is 200, it exists; if it is 404, it does not exist.
HEAD colleges
On running the above code, we get the output as shown below −
200-OK
You can get the index settings by just appending _settings keyword at the end of URL.
GET /colleges/_settings
On running the above code, we get the output as shown below −
{
"colleges" : {
"settings" : {
"index" : {
"creation_date" : "1556245406616",
"number_of_shards" : "1",
"number_of_replicas" : "1",
"uuid" : "3ExJbdl2R1qDLssIkwDAug",
"version" : {
"created" : "7000099"
},
"provided_name" : "colleges"
}
}
}
}
This API helps you to extract statistics about a particular index. You just need to send a get request with the index URL and _stats keyword at the end.
GET /_stats
On running the above code, we get the output as shown below −
......................................................
},
"request_cache" : {
"memory_size_in_bytes" : 849,
"evictions" : 0,
"hit_count" : 1171,
"miss_count" : 4
},
"recovery" : {
"current_as_source" : 0,
"current_as_target" : 0,
"throttle_time_in_millis" : 0
}
} ......................................................
The flush process of an index makes sure that any data that is currently only persisted in the transaction log is also permanently persisted in Lucene. This reduces recovery times as that data does not need to be reindexed from the transaction logs after the Lucene indexed is opened.
POST colleges/_flush
On running the above code, we get the output as shown below −
{
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
}
}
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2701,
"s": 2581,
"text": "These APIs are responsible for managing all the aspects of the index like settings, aliases, mappings, index templates."
},
{
"code": null,
"e": 2992,
"s": 2701,
"text": "This API helps you to create an index. An index can be created automatically when a user is passing JSON objects to any index or it can be created before that. To create an index, you just need to send a PUT request with settings, mappings and aliases or just a simple request without body."
},
{
"code": null,
"e": 3006,
"s": 2992,
"text": "PUT colleges\n"
},
{
"code": null,
"e": 3068,
"s": 3006,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 3156,
"s": 3068,
"text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"colleges\"\n}\n"
},
{
"code": null,
"e": 3209,
"s": 3156,
"text": "We can also add some settings to the above command −"
},
{
"code": null,
"e": 3342,
"s": 3209,
"text": "PUT colleges\n{\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n }\n}\n"
},
{
"code": null,
"e": 3404,
"s": 3342,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 3492,
"s": 3404,
"text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"colleges\"\n}\n"
},
{
"code": null,
"e": 3611,
"s": 3492,
"text": "This API helps you to delete any index. You just need to pass a delete request with the name of that particular Index."
},
{
"code": null,
"e": 3629,
"s": 3611,
"text": "DELETE /colleges\n"
},
{
"code": null,
"e": 3681,
"s": 3629,
"text": "You can delete all indices by just using _all or *."
},
{
"code": null,
"e": 3807,
"s": 3681,
"text": "This API can be called by just sending get request to one or more than one indices. This returns the information about index."
},
{
"code": null,
"e": 3821,
"s": 3807,
"text": "GET colleges\n"
},
{
"code": null,
"e": 3883,
"s": 3821,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 4569,
"s": 3883,
"text": "{\n \"colleges\" : {\n \"aliases\" : {\n \"alias_1\" : { },\n \"alias_2\" : {\n \"filter\" : {\n \"term\" : {\n \"user\" : \"pkay\"\n }\n },\n \"index_routing\" : \"pkay\",\n \"search_routing\" : \"pkay\"\n }\n },\n \"mappings\" : { },\n \"settings\" : {\n \"index\" : {\n \"creation_date\" : \"1556245406616\",\n \"number_of_shards\" : \"1\",\n \"number_of_replicas\" : \"1\",\n \"uuid\" : \"3ExJbdl2R1qDLssIkwDAug\",\n \"version\" : {\n \"created\" : \"7000099\"\n },\n \"provided_name\" : \"colleges\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 4636,
"s": 4569,
"text": "You can get the information of all the indices by using _all or *."
},
{
"code": null,
"e": 4794,
"s": 4636,
"text": "Existence of an index can be determined by just sending a get request to that index. If the HTTP response is 200, it exists; if it is 404, it does not exist."
},
{
"code": null,
"e": 4809,
"s": 4794,
"text": "HEAD colleges\n"
},
{
"code": null,
"e": 4871,
"s": 4809,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 4879,
"s": 4871,
"text": "200-OK\n"
},
{
"code": null,
"e": 4965,
"s": 4879,
"text": "You can get the index settings by just appending _settings keyword at the end of URL."
},
{
"code": null,
"e": 4990,
"s": 4965,
"text": "GET /colleges/_settings\n"
},
{
"code": null,
"e": 5052,
"s": 4990,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 5432,
"s": 5052,
"text": "{\n \"colleges\" : {\n \"settings\" : {\n \"index\" : {\n \"creation_date\" : \"1556245406616\",\n \"number_of_shards\" : \"1\",\n \"number_of_replicas\" : \"1\",\n \"uuid\" : \"3ExJbdl2R1qDLssIkwDAug\",\n \"version\" : {\n \"created\" : \"7000099\"\n },\n \"provided_name\" : \"colleges\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 5585,
"s": 5432,
"text": "This API helps you to extract statistics about a particular index. You just need to send a get request with the index URL and _stats keyword at the end."
},
{
"code": null,
"e": 5598,
"s": 5585,
"text": "GET /_stats\n"
},
{
"code": null,
"e": 5660,
"s": 5598,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 6034,
"s": 5660,
"text": "......................................................\n},\n \"request_cache\" : {\n \"memory_size_in_bytes\" : 849,\n \"evictions\" : 0,\n \"hit_count\" : 1171,\n \"miss_count\" : 4\n },\n \"recovery\" : {\n \"current_as_source\" : 0,\n \"current_as_target\" : 0,\n \"throttle_time_in_millis\" : 0\n }\n} ......................................................\n"
},
{
"code": null,
"e": 6319,
"s": 6034,
"text": "The flush process of an index makes sure that any data that is currently only persisted in the transaction log is also permanently persisted in Lucene. This reduces recovery times as that data does not need to be reindexed from the transaction logs after the Lucene indexed is opened."
},
{
"code": null,
"e": 6341,
"s": 6319,
"text": "POST colleges/_flush\n"
},
{
"code": null,
"e": 6403,
"s": 6341,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 6493,
"s": 6403,
"text": "{\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n } \n}\n"
},
{
"code": null,
"e": 6526,
"s": 6493,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6542,
"s": 6526,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 6575,
"s": 6542,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6590,
"s": 6575,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 6597,
"s": 6590,
"text": " Print"
},
{
"code": null,
"e": 6608,
"s": 6597,
"text": " Add Notes"
}
] |
How to deal with Internet Explorer and addEventListener problem "Object doesn't support this property or method" in JavaScript?
|
To deal with “Object doesn’t support this property or method” issue in JavaScript, while using events and Internet Explorer, update your code with this −
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" />
</head>
<body>
...
</body>
</html>
You can also use attachEvent in IE to solve this issue like this −
if (ev.addEventListener) {
ev.addEventListener('click', myText, false);
}
else if (ev.attachEvent) {
ev.attachEvent('onclick', myText);
}
|
[
{
"code": null,
"e": 1216,
"s": 1062,
"text": "To deal with “Object doesn’t support this property or method” issue in JavaScript, while using events and Internet Explorer, update your code with this −"
},
{
"code": null,
"e": 1343,
"s": 1216,
"text": "<html>\n <head>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge;\" />\n </head>\n <body>\n ...\n </body>\n</html>"
},
{
"code": null,
"e": 1410,
"s": 1343,
"text": "You can also use attachEvent in IE to solve this issue like this −"
},
{
"code": null,
"e": 1555,
"s": 1410,
"text": "if (ev.addEventListener) {\n ev.addEventListener('click', myText, false);\n}\nelse if (ev.attachEvent) {\n ev.attachEvent('onclick', myText);\n}"
}
] |
Convert Class in C#
|
The Convert Class has methods to convert a base data type to another base data type. Let us see some examples −
The Convert.ToBoolean() method in C# is used to convert a specified value to an equivalent Boolean value.
Following is the syntax −
public static bool ToBoolean (string val, IFormatProvider provider);
Above, Val is a string that contains the value of either TrueString or FalseString, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToBoolean() method −
Live Demo
using System;
using System.Globalization;
public class Demo {
public static void Main(){
CultureInfo cultures = new CultureInfo("en-US");
String str = "true";
Console.WriteLine("Converted bool value...");
bool res = Convert.ToBoolean(str, cultures);
Console.Write("{0}", res);
}
}
This will produce the following output −
Converted bool value...
True
The Convert.ToDouble() method in C# converts the specified string representation of a number to an equivalent double-precision floating-point number, using the specified culture-specific formatting information.
Following is the syntax −
public static double ToDouble (string val, IFormatProvider provider);
Above, the value is a string that contains the number to convert, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToDouble() method −
Live Demo
using System;
using System.Globalization;
public class Demo {
public static void Main(){
String val = "876876, 878";
NumberFormatInfo formatProvider = new NumberFormatInfo();
formatProvider.NumberDecimalSeparator = ", ";
formatProvider.NumberGroupSeparator = ".";
formatProvider.NumberGroupSizes = new int[] { 2 };
Console.WriteLine("Converted Decimal value...");
double res = Convert.ToDouble(val, formatProvider);
Console.Write("{0}", res);
}
}
This will produce the following output −
Converted Decimal value...
876876.878
The Convert.ToDecimal() method in C# converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.
Following is the syntax −
public static decimal ToDecimal (string val, IFormatProvider provider);
Above, Val is a string that contains a number to convert, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToDecimal() method −
Live Demo
using System;
using System.Globalization;
public class Demo {
public static void Main(){
CultureInfo cultures = new CultureInfo("en-US");
String val = "8787";
Console.WriteLine("Converted Decimal value...");
decimal res = Convert.ToDecimal(val, cultures);
Console.Write("{0}", res);
}
}
This will produce the following output −
Converted Decimal value...
8787
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "The Convert Class has methods to convert a base data type to another base data type. Let us see some examples −"
},
{
"code": null,
"e": 1280,
"s": 1174,
"text": "The Convert.ToBoolean() method in C# is used to convert a specified value to an equivalent Boolean value."
},
{
"code": null,
"e": 1306,
"s": 1280,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1375,
"s": 1306,
"text": "public static bool ToBoolean (string val, IFormatProvider provider);"
},
{
"code": null,
"e": 1548,
"s": 1375,
"text": "Above, Val is a string that contains the value of either TrueString or FalseString, whereas the provider is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 1620,
"s": 1548,
"text": "Let us now see an example to implement the Convert.ToBoolean() method −"
},
{
"code": null,
"e": 1631,
"s": 1620,
"text": " Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1631,
"text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(){\n CultureInfo cultures = new CultureInfo(\"en-US\");\n String str = \"true\";\n Console.WriteLine(\"Converted bool value...\");\n bool res = Convert.ToBoolean(str, cultures);\n Console.Write(\"{0}\", res);\n }\n}"
},
{
"code": null,
"e": 1989,
"s": 1948,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2018,
"s": 1989,
"text": "Converted bool value...\nTrue"
},
{
"code": null,
"e": 2229,
"s": 2018,
"text": "The Convert.ToDouble() method in C# converts the specified string representation of a number to an equivalent double-precision floating-point number, using the specified culture-specific formatting information."
},
{
"code": null,
"e": 2255,
"s": 2229,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 2325,
"s": 2255,
"text": "public static double ToDouble (string val, IFormatProvider provider);"
},
{
"code": null,
"e": 2480,
"s": 2325,
"text": "Above, the value is a string that contains the number to convert, whereas the provider is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 2551,
"s": 2480,
"text": "Let us now see an example to implement the Convert.ToDouble() method −"
},
{
"code": null,
"e": 2562,
"s": 2551,
"text": " Live Demo"
},
{
"code": null,
"e": 3063,
"s": 2562,
"text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(){\n String val = \"876876, 878\";\n NumberFormatInfo formatProvider = new NumberFormatInfo();\n formatProvider.NumberDecimalSeparator = \", \";\n formatProvider.NumberGroupSeparator = \".\";\n formatProvider.NumberGroupSizes = new int[] { 2 };\n Console.WriteLine(\"Converted Decimal value...\");\n double res = Convert.ToDouble(val, formatProvider);\n Console.Write(\"{0}\", res);\n }\n}"
},
{
"code": null,
"e": 3104,
"s": 3063,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3142,
"s": 3104,
"text": "Converted Decimal value...\n876876.878"
},
{
"code": null,
"e": 3330,
"s": 3142,
"text": "The Convert.ToDecimal() method in C# converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information."
},
{
"code": null,
"e": 3356,
"s": 3330,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 3428,
"s": 3356,
"text": "public static decimal ToDecimal (string val, IFormatProvider provider);"
},
{
"code": null,
"e": 3575,
"s": 3428,
"text": "Above, Val is a string that contains a number to convert, whereas the provider is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 3647,
"s": 3575,
"text": "Let us now see an example to implement the Convert.ToDecimal() method −"
},
{
"code": null,
"e": 3658,
"s": 3647,
"text": " Live Demo"
},
{
"code": null,
"e": 3981,
"s": 3658,
"text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(){\n CultureInfo cultures = new CultureInfo(\"en-US\");\n String val = \"8787\";\n Console.WriteLine(\"Converted Decimal value...\");\n decimal res = Convert.ToDecimal(val, cultures);\n Console.Write(\"{0}\", res);\n }\n}"
},
{
"code": null,
"e": 4022,
"s": 3981,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4054,
"s": 4022,
"text": "Converted Decimal value...\n8787"
}
] |
Extract Health Data From Your Samsung Device | by Anuradha Wickramarachchi | Towards Data Science
|
Health data is collected every time you have your phone in your pocket. Apple or Android, the phones are equipped with a pedometer that counts your steps. Hence, health data is recorded. This data could be your one free data mart for a simple Machine Learning or some other project related to Health data. It’s yours and free to use!. Let’s see how we can export data from the Samsung S-Health App.
The data download feature is available in your Samsung health app.
Open health app
Open the left side panel — click on the settings wheel
Find “Download personal data” button
Follow instructions (you’ll need to login) and click Download
You’ll be shown with the location to find your health data
This probably is the easiest thing to do. However, understanding the data is a bit complicated. Let’s go through each of the file and its content to understand how Samsung health app stores data.
You will see the following set of files with data. In place of T you’ll see the export timestamp. In the files folder, you’ll see the profile picture image. In the folder named jsons, you can find the JSON objects for data referred in the CSV files (I’ll not talk about JSONS in this article). Please note that the data columns of CSV files will also contain the package extension com.samsung.health. However, for the simplicity of the text, I will ignore when I explain the content of the CSV files.
com.samsung.health.device_profile.T.csv com.samsung.shealth.preferences.T.csv com.samsung.health.floors_climbed.T.csv com.samsung.shealth.report.T.csv com.samsung.health.food_info.T.csv com.samsung.shealth.rewards.T.csv com.samsung.health.height.T.csv com.samsung.shealth.sleep.T.csv com.samsung.health.sleep_stage.T.csv com.samsung.shealth.social.leaderboard.T.csv com.samsung.health.user_profile.T.csv com.samsung.shealth.social.public_challenge.T.csv com.samsung.health.water_intake.T.csv com.samsung.shealth.social.public_challenge.detail.T.csv com.samsung.health.weight.T.csv com.samsung.shealth.social.public_challenge.extra.T.csv com.samsung.shealth.activity.day_summary.T.csv com.samsung.shealth.social.public_challenge.history.T.csv com.samsung.shealth.activity.goal.T.csv com.samsung.shealth.social.public_challenge.leaderboard.T.csv com.samsung.shealth.activity_level.T.csv com.samsung.shealth.social.service_status.T.csv com.samsung.shealth.best_records.T.csv com.samsung.shealth.stand_day_summary.T.csv com.samsung.shealth.breathing.T.csv com.samsung.shealth.step_daily_trend.T.csv com.samsung.shealth.caloric_balance_goal.T.csv com.samsung.shealth.stress.T.csv com.samsung.shealth.calories_burned.details.T.csv com.samsung.shealth.stress.histogram.T.csv com.samsung.shealth.exercise.T.csv com.samsung.shealth.tracker.heart_rate.T.csv com.samsung.shealth.exercise.weather.T.csv com.samsung.shealth.tracker.pedometer_day_summary.T.csv com.samsung.shealth.food_frequent.T.csv com.samsung.shealth.tracker.pedometer_event.T.csv com.samsung.shealth.food_goal.T.csv com.samsung.shealth.tracker.pedometer_recommendation.T.csv com.samsung.shealth.goal.T.csv com.samsung.shealth.tracker.pedometer_step_count.T.csv com.samsung.shealth.goal_history.T.csv com.samsung.shealth.insight.milestones.T.csv com.samsung.shealth.permission.T.csv jsonsfiles
These are the files that contain data from the sensors including heart rate data and steps from the Galaxy Watch and the Phone itself. Step counts are collected from pedometer and accelerometer sensors. Heart rate is measured through the PPG (Photoplethysmogram) sensor in your watch. For these data, you have to look into the following files.
Heart rate data are included in the following file.
com.samsung.shealth.tracker.heart_rate.T.csv
The important information in this file is the update_time and heart_rate columns. You will also find the min and max values along with end_time, which shows the end of the recording.
Out of curiosity, I plotted a histogram of my heart rates to see how my heart behaves. It seems I have a heart rate in the range 65–80bps. Googling resulted in “A normal resting heart rate for adults ranges from 60 to 100 beats per minute”. I guess the histogram makes sense. One of the main concerns, when I bought the watch, was to keep a note of my heart rate. Because, usually at the doctors, I have an above-average heart rate with a panicked person’s blood pressure. Read here if you want to know more about that scenario at Doctors.
Step tracker data are available in the following files;
com.samsung.shealth.step_daily_trend.202008162231.csvcom.samsung.shealth.tracker.pedometer_step_count.202008162231.csvcom.samsung.shealth.tracker.pedometer_day_summary.202008162231.csv
In the step_daily_trend you will see the daily values with step count, calories burnt, distance walked and the speed. However, in the pedometer_step_count you will find all the step information including running steps, walking steps. Basically this file contains the pedometer tracking information. In the last file (pedometer_day_summary), you can find the daily step summaries. Which might be enough for most of the tasks.
Let’s try to do some simple analysis of these data.
The above observation sort of aligns with the seasonal changes here in Australia. During the time June to December, we have cold temperatures. From December to June, we have much better running weather. However, COVID-19 came into play here in Canberra during the April and May, hence the low activity. However, in June my wife and I walked and tried to get back on the shape so we can eat out a lot during our anniversary period.
Step count isn’t quite a generic measure of activity. One might workout in a gym without any step count yet burning a lot of fat. Such activities are usually measured by calories using the heart rate sensor. However, as you can see below, my calorie counts are somewhat correlated with the step counts (There is a slight deviation of the X-axis, but they are close). This is because the only workout I prefer is running or jogging.
Something interesting is visible. On days I have run, I haven’t made many steps. In contrast, on walking days I have made it over 10000 steps. I wonder, whether I get tired on days I walk or the running steps aren’t counted for daily step count. Something I shall investigate in another article though.
There is more information including, weight and carb intakes. For that, you’ll have to have them recorded manually. However, there are some insightful data in the following file.
com.samsung.shealth.exercise.weather.T.csv
However, in order to use this file, you’ll have to combine this with the exercise file. That is for another article!
I hope this article would make a useful outcome of the data that you most often get rid of. Happy reading!
|
[
{
"code": null,
"e": 571,
"s": 172,
"text": "Health data is collected every time you have your phone in your pocket. Apple or Android, the phones are equipped with a pedometer that counts your steps. Hence, health data is recorded. This data could be your one free data mart for a simple Machine Learning or some other project related to Health data. It’s yours and free to use!. Let’s see how we can export data from the Samsung S-Health App."
},
{
"code": null,
"e": 638,
"s": 571,
"text": "The data download feature is available in your Samsung health app."
},
{
"code": null,
"e": 654,
"s": 638,
"text": "Open health app"
},
{
"code": null,
"e": 709,
"s": 654,
"text": "Open the left side panel — click on the settings wheel"
},
{
"code": null,
"e": 746,
"s": 709,
"text": "Find “Download personal data” button"
},
{
"code": null,
"e": 808,
"s": 746,
"text": "Follow instructions (you’ll need to login) and click Download"
},
{
"code": null,
"e": 867,
"s": 808,
"text": "You’ll be shown with the location to find your health data"
},
{
"code": null,
"e": 1063,
"s": 867,
"text": "This probably is the easiest thing to do. However, understanding the data is a bit complicated. Let’s go through each of the file and its content to understand how Samsung health app stores data."
},
{
"code": null,
"e": 1564,
"s": 1063,
"text": "You will see the following set of files with data. In place of T you’ll see the export timestamp. In the files folder, you’ll see the profile picture image. In the folder named jsons, you can find the JSON objects for data referred in the CSV files (I’ll not talk about JSONS in this article). Please note that the data columns of CSV files will also contain the package extension com.samsung.health. However, for the simplicity of the text, I will ignore when I explain the content of the CSV files."
},
{
"code": null,
"e": 3457,
"s": 1564,
"text": "com.samsung.health.device_profile.T.csv com.samsung.shealth.preferences.T.csv com.samsung.health.floors_climbed.T.csv com.samsung.shealth.report.T.csv com.samsung.health.food_info.T.csv com.samsung.shealth.rewards.T.csv com.samsung.health.height.T.csv com.samsung.shealth.sleep.T.csv com.samsung.health.sleep_stage.T.csv com.samsung.shealth.social.leaderboard.T.csv com.samsung.health.user_profile.T.csv com.samsung.shealth.social.public_challenge.T.csv com.samsung.health.water_intake.T.csv com.samsung.shealth.social.public_challenge.detail.T.csv com.samsung.health.weight.T.csv com.samsung.shealth.social.public_challenge.extra.T.csv com.samsung.shealth.activity.day_summary.T.csv com.samsung.shealth.social.public_challenge.history.T.csv com.samsung.shealth.activity.goal.T.csv com.samsung.shealth.social.public_challenge.leaderboard.T.csv com.samsung.shealth.activity_level.T.csv com.samsung.shealth.social.service_status.T.csv com.samsung.shealth.best_records.T.csv com.samsung.shealth.stand_day_summary.T.csv com.samsung.shealth.breathing.T.csv com.samsung.shealth.step_daily_trend.T.csv com.samsung.shealth.caloric_balance_goal.T.csv com.samsung.shealth.stress.T.csv com.samsung.shealth.calories_burned.details.T.csv com.samsung.shealth.stress.histogram.T.csv com.samsung.shealth.exercise.T.csv com.samsung.shealth.tracker.heart_rate.T.csv com.samsung.shealth.exercise.weather.T.csv com.samsung.shealth.tracker.pedometer_day_summary.T.csv com.samsung.shealth.food_frequent.T.csv com.samsung.shealth.tracker.pedometer_event.T.csv com.samsung.shealth.food_goal.T.csv com.samsung.shealth.tracker.pedometer_recommendation.T.csv com.samsung.shealth.goal.T.csv com.samsung.shealth.tracker.pedometer_step_count.T.csv com.samsung.shealth.goal_history.T.csv com.samsung.shealth.insight.milestones.T.csv com.samsung.shealth.permission.T.csv jsonsfiles"
},
{
"code": null,
"e": 3801,
"s": 3457,
"text": "These are the files that contain data from the sensors including heart rate data and steps from the Galaxy Watch and the Phone itself. Step counts are collected from pedometer and accelerometer sensors. Heart rate is measured through the PPG (Photoplethysmogram) sensor in your watch. For these data, you have to look into the following files."
},
{
"code": null,
"e": 3853,
"s": 3801,
"text": "Heart rate data are included in the following file."
},
{
"code": null,
"e": 3898,
"s": 3853,
"text": "com.samsung.shealth.tracker.heart_rate.T.csv"
},
{
"code": null,
"e": 4081,
"s": 3898,
"text": "The important information in this file is the update_time and heart_rate columns. You will also find the min and max values along with end_time, which shows the end of the recording."
},
{
"code": null,
"e": 4621,
"s": 4081,
"text": "Out of curiosity, I plotted a histogram of my heart rates to see how my heart behaves. It seems I have a heart rate in the range 65–80bps. Googling resulted in “A normal resting heart rate for adults ranges from 60 to 100 beats per minute”. I guess the histogram makes sense. One of the main concerns, when I bought the watch, was to keep a note of my heart rate. Because, usually at the doctors, I have an above-average heart rate with a panicked person’s blood pressure. Read here if you want to know more about that scenario at Doctors."
},
{
"code": null,
"e": 4677,
"s": 4621,
"text": "Step tracker data are available in the following files;"
},
{
"code": null,
"e": 4862,
"s": 4677,
"text": "com.samsung.shealth.step_daily_trend.202008162231.csvcom.samsung.shealth.tracker.pedometer_step_count.202008162231.csvcom.samsung.shealth.tracker.pedometer_day_summary.202008162231.csv"
},
{
"code": null,
"e": 5287,
"s": 4862,
"text": "In the step_daily_trend you will see the daily values with step count, calories burnt, distance walked and the speed. However, in the pedometer_step_count you will find all the step information including running steps, walking steps. Basically this file contains the pedometer tracking information. In the last file (pedometer_day_summary), you can find the daily step summaries. Which might be enough for most of the tasks."
},
{
"code": null,
"e": 5339,
"s": 5287,
"text": "Let’s try to do some simple analysis of these data."
},
{
"code": null,
"e": 5770,
"s": 5339,
"text": "The above observation sort of aligns with the seasonal changes here in Australia. During the time June to December, we have cold temperatures. From December to June, we have much better running weather. However, COVID-19 came into play here in Canberra during the April and May, hence the low activity. However, in June my wife and I walked and tried to get back on the shape so we can eat out a lot during our anniversary period."
},
{
"code": null,
"e": 6202,
"s": 5770,
"text": "Step count isn’t quite a generic measure of activity. One might workout in a gym without any step count yet burning a lot of fat. Such activities are usually measured by calories using the heart rate sensor. However, as you can see below, my calorie counts are somewhat correlated with the step counts (There is a slight deviation of the X-axis, but they are close). This is because the only workout I prefer is running or jogging."
},
{
"code": null,
"e": 6505,
"s": 6202,
"text": "Something interesting is visible. On days I have run, I haven’t made many steps. In contrast, on walking days I have made it over 10000 steps. I wonder, whether I get tired on days I walk or the running steps aren’t counted for daily step count. Something I shall investigate in another article though."
},
{
"code": null,
"e": 6684,
"s": 6505,
"text": "There is more information including, weight and carb intakes. For that, you’ll have to have them recorded manually. However, there are some insightful data in the following file."
},
{
"code": null,
"e": 6727,
"s": 6684,
"text": "com.samsung.shealth.exercise.weather.T.csv"
},
{
"code": null,
"e": 6844,
"s": 6727,
"text": "However, in order to use this file, you’ll have to combine this with the exercise file. That is for another article!"
}
] |
CSS Web Fonts
|
Web fonts allow Web designers to use fonts that are not installed on the user's computer.
When you have found/bought the font you wish to use, just include the font
file on your web server, and it will be automatically downloaded to the user when needed.
Your "own" fonts are defined within the CSS @font-face rule.
TrueType Fonts (TTF)
TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft
Windows operating systems.
OpenType Fonts (OTF)
OpenType is a format for scalable computer fonts. It was built on TrueType,
and is a registered trademark of
Microsoft. OpenType fonts are used commonly today on the major
computer platforms.
The Web Open Font Format (WOFF)
WOFF is a font format for use in web pages. It was developed in 2009, and is
now a W3C Recommendation. WOFF is essentially OpenType or TrueType with
compression and additional metadata. The goal is to support font distribution
from a server to a client over a network with bandwidth constraints.
The Web Open Font Format (WOFF 2.0)
TrueType/OpenType font that provides better compression than WOFF 1.0.
SVG Fonts/Shapes
SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1
specification define a font module that allows the creation of fonts within an
SVG document. You can also apply CSS to SVG documents, and the @font-face rule
can be applied to text in SVG documents.
Embedded OpenType Fonts (EOT)
EOT fonts are a compact form of OpenType fonts designed by Microsoft for use
as embedded fonts on web pages.
The numbers in the table specifies the first browser version that fully supports the
font format.
*IE: The font format only works when set to be "installable".
In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.
Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE.
To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:
You must add another @font-face rule containing descriptors for bold text:
The file "sansation_bold.woff" is another font file, that contains the bold characters for the Sansation font.
Browsers will use this whenever a piece of text with the font-family "myFirstFont" should render as bold.
This way you can have many @font-face rules for the same font.
Add a web font with the name "sansation" and the URL "sansation_light.woff".
<style>
{
font-family: ;
: ;
}
body {
font-family: sansation;
}
</style>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</body>
Start the Exercise
The following table lists all the font descriptors that can be defined inside the @font-face rule:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 90,
"s": 0,
"text": "Web fonts allow Web designers to use fonts that are not installed on the user's computer."
},
{
"code": null,
"e": 256,
"s": 90,
"text": "When you have found/bought the font you wish to use, just include the font \nfile on your web server, and it will be automatically downloaded to the user when needed."
},
{
"code": null,
"e": 317,
"s": 256,
"text": "Your \"own\" fonts are defined within the CSS @font-face rule."
},
{
"code": null,
"e": 338,
"s": 317,
"text": "TrueType Fonts (TTF)"
},
{
"code": null,
"e": 521,
"s": 338,
"text": "TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft \nWindows operating systems."
},
{
"code": null,
"e": 542,
"s": 521,
"text": "OpenType Fonts (OTF)"
},
{
"code": null,
"e": 737,
"s": 542,
"text": "OpenType is a format for scalable computer fonts. It was built on TrueType, \nand is a registered trademark of \nMicrosoft. OpenType fonts are used commonly today on the major \ncomputer platforms."
},
{
"code": null,
"e": 769,
"s": 737,
"text": "The Web Open Font Format (WOFF)"
},
{
"code": null,
"e": 1068,
"s": 769,
"text": "WOFF is a font format for use in web pages. It was developed in 2009, and is \nnow a W3C Recommendation. WOFF is essentially OpenType or TrueType with \ncompression and additional metadata. The goal is to support font distribution \nfrom a server to a client over a network with bandwidth constraints."
},
{
"code": null,
"e": 1104,
"s": 1068,
"text": "The Web Open Font Format (WOFF 2.0)"
},
{
"code": null,
"e": 1175,
"s": 1104,
"text": "TrueType/OpenType font that provides better compression than WOFF 1.0."
},
{
"code": null,
"e": 1192,
"s": 1175,
"text": "SVG Fonts/Shapes"
},
{
"code": null,
"e": 1469,
"s": 1192,
"text": "SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1 \nspecification define a font module that allows the creation of fonts within an \nSVG document. You can also apply CSS to SVG documents, and the @font-face rule \ncan be applied to text in SVG documents."
},
{
"code": null,
"e": 1499,
"s": 1469,
"text": "Embedded OpenType Fonts (EOT)"
},
{
"code": null,
"e": 1609,
"s": 1499,
"text": "EOT fonts are a compact form of OpenType fonts designed by Microsoft for use \nas embedded fonts on web pages."
},
{
"code": null,
"e": 1708,
"s": 1609,
"text": "The numbers in the table specifies the first browser version that fully supports the \nfont format."
},
{
"code": null,
"e": 1770,
"s": 1708,
"text": "*IE: The font format only works when set to be \"installable\"."
},
{
"code": null,
"e": 1879,
"s": 1770,
"text": "In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file."
},
{
"code": null,
"e": 1984,
"s": 1879,
"text": "Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE."
},
{
"code": null,
"e": 2099,
"s": 1984,
"text": "To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:"
},
{
"code": null,
"e": 2174,
"s": 2099,
"text": "You must add another @font-face rule containing descriptors for bold text:"
},
{
"code": null,
"e": 2285,
"s": 2174,
"text": "The file \"sansation_bold.woff\" is another font file, that contains the bold characters for the Sansation font."
},
{
"code": null,
"e": 2391,
"s": 2285,
"text": "Browsers will use this whenever a piece of text with the font-family \"myFirstFont\" should render as bold."
},
{
"code": null,
"e": 2454,
"s": 2391,
"text": "This way you can have many @font-face rules for the same font."
},
{
"code": null,
"e": 2531,
"s": 2454,
"text": "Add a web font with the name \"sansation\" and the URL \"sansation_light.woff\"."
},
{
"code": null,
"e": 2716,
"s": 2531,
"text": "<style>\n {\n font-family: ;\n : ;\n}\n\nbody {\n font-family: sansation;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n"
},
{
"code": null,
"e": 2735,
"s": 2716,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2834,
"s": 2735,
"text": "The following table lists all the font descriptors that can be defined inside the @font-face rule:"
},
{
"code": null,
"e": 2867,
"s": 2834,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2909,
"s": 2867,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3016,
"s": 2909,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3035,
"s": 3016,
"text": "help@w3schools.com"
}
] |
How to Filter DataFrame Rows Based on the Date in Pandas? - GeeksforGeeks
|
11 Dec, 2020
Different regions follow different date conventions (YYYY-MM-DD, YYYY-DD-MM, DD/MM/YY, etc.). It is difficult to work with such strings in the data. Pandas to_datetime() function allows converting the date and time in string format to datetime64. This datatype helps extract features of date and time ranging from ‘year’ to ‘microseconds’.
To filter rows based on dates, first format the dates in the DataFrame to datetime64 type. Then use the DataFrame.loc[] and DataFrame.query[] function from the Pandas package to specify a filter condition. As a result, acquire the subset of data, that is, the filtered DataFrame. Let’s see some examples of the same.
We will use a sample DataFrame consisting of the number of posts on a specific day. Convert the date in the sample data to datetime64 type as follows.
Python
# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date' : ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Display dataframedf
Example 1:
Filter data based on dates using DataFrame.loc[] function, the loc[] function is used to access a group of rows and columns of a DataFrame through labels or a boolean array. In this example, the conditional statement in loc[] returns a boolean array with True value if row satisfies condition (date is in between 1st and 15th September) and False value otherwise. Then the loc[] function returns only those rows having True values.
Python3
# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.loc[(df['date'] >= '2020-09-01') & (df['date'] < '2020-09-15')]# Displayfiltered_df
Output:
Example 2:
Use the DateTimeIndex(dt) to access separate date time attributes such as year, month, day, weekday, hours, minutes, seconds, microseconds etc. as a condition in loc[] function as follows.
Note: The date values should be in datetime64 format.
Python3
# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.loc[(df['date'] >= '2020-09-01') & (df['date'] < '2020-09-15')] # Displayprint("\nPosts in December:")print(filtered_df) # Filter data for specific weekday (tuesday)filtered_df = df.loc[df['date'].dt.weekday == 2] # Displayprint("\nPosts on all Tuesdays:")print(filtered_df)
Output:
Example 3:
Filter data based on dates using DataFrame.query() function, The query() function filters a Pandas DataFrame and selects rows by specifying a condition within quotes. As shown below, the condition inside query() is to select the data with dates in the month of August (range of dates is specified). The columns of the DataFrame are placed in the query namespace by default so the date column can be accessed without indexing (simply specify column name).
Python3
# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.query("date >= '2020-08-01' \ and date < '2020-09-01'") # Displayfiltered_df
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24633,
"s": 24292,
"text": "Different regions follow different date conventions (YYYY-MM-DD, YYYY-DD-MM, DD/MM/YY, etc.). It is difficult to work with such strings in the data. Pandas to_datetime() function allows converting the date and time in string format to datetime64. This datatype helps extract features of date and time ranging from ‘year’ to ‘microseconds’."
},
{
"code": null,
"e": 24950,
"s": 24633,
"text": "To filter rows based on dates, first format the dates in the DataFrame to datetime64 type. Then use the DataFrame.loc[] and DataFrame.query[] function from the Pandas package to specify a filter condition. As a result, acquire the subset of data, that is, the filtered DataFrame. Let’s see some examples of the same."
},
{
"code": null,
"e": 25101,
"s": 24950,
"text": "We will use a sample DataFrame consisting of the number of posts on a specific day. Convert the date in the sample data to datetime64 type as follows."
},
{
"code": null,
"e": 25108,
"s": 25101,
"text": "Python"
},
{
"code": "# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date' : ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Display dataframedf",
"e": 25613,
"s": 25108,
"text": null
},
{
"code": null,
"e": 25625,
"s": 25613,
"text": "Example 1: "
},
{
"code": null,
"e": 26058,
"s": 25625,
"text": "Filter data based on dates using DataFrame.loc[] function, the loc[] function is used to access a group of rows and columns of a DataFrame through labels or a boolean array. In this example, the conditional statement in loc[] returns a boolean array with True value if row satisfies condition (date is in between 1st and 15th September) and False value otherwise. Then the loc[] function returns only those rows having True values. "
},
{
"code": null,
"e": 26066,
"s": 26058,
"text": "Python3"
},
{
"code": "# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.loc[(df['date'] >= '2020-09-01') & (df['date'] < '2020-09-15')]# Displayfiltered_df",
"e": 26727,
"s": 26066,
"text": null
},
{
"code": null,
"e": 26735,
"s": 26727,
"text": "Output:"
},
{
"code": null,
"e": 26746,
"s": 26735,
"text": "Example 2:"
},
{
"code": null,
"e": 26936,
"s": 26746,
"text": "Use the DateTimeIndex(dt) to access separate date time attributes such as year, month, day, weekday, hours, minutes, seconds, microseconds etc. as a condition in loc[] function as follows. "
},
{
"code": null,
"e": 26990,
"s": 26936,
"text": "Note: The date values should be in datetime64 format."
},
{
"code": null,
"e": 26998,
"s": 26990,
"text": "Python3"
},
{
"code": "# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.loc[(df['date'] >= '2020-09-01') & (df['date'] < '2020-09-15')] # Displayprint(\"\\nPosts in December:\")print(filtered_df) # Filter data for specific weekday (tuesday)filtered_df = df.loc[df['date'].dt.weekday == 2] # Displayprint(\"\\nPosts on all Tuesdays:\")print(filtered_df)",
"e": 27850,
"s": 26998,
"text": null
},
{
"code": null,
"e": 27858,
"s": 27850,
"text": "Output:"
},
{
"code": null,
"e": 27870,
"s": 27858,
"text": "Example 3: "
},
{
"code": null,
"e": 28325,
"s": 27870,
"text": "Filter data based on dates using DataFrame.query() function, The query() function filters a Pandas DataFrame and selects rows by specifying a condition within quotes. As shown below, the condition inside query() is to select the data with dates in the month of August (range of dates is specified). The columns of the DataFrame are placed in the query namespace by default so the date column can be accessed without indexing (simply specify column name)."
},
{
"code": null,
"e": 28333,
"s": 28325,
"text": "Python3"
},
{
"code": "# Import Pandas packageimport pandas as pd # Create a sample dataframedf = pd.DataFrame({'num_posts': [4, 6, 3, 9, 1, 14, 2, 5, 7, 2], 'date': ['2020-08-09', '2020-08-25', '2020-09-05', '2020-09-12', '2020-09-29', '2020-10-15', '2020-11-21', '2020-12-02', '2020-12-10', '2020-12-18']}) # Convert the date to datetime64df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # Filter data between two datesfiltered_df = df.query(\"date >= '2020-08-01' \\ and date < '2020-09-01'\") # Displayfiltered_df",
"e": 28987,
"s": 28333,
"text": null
},
{
"code": null,
"e": 28995,
"s": 28987,
"text": "Output:"
},
{
"code": null,
"e": 29019,
"s": 28995,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 29042,
"s": 29019,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 29056,
"s": 29042,
"text": "Python-pandas"
},
{
"code": null,
"e": 29063,
"s": 29056,
"text": "Python"
},
{
"code": null,
"e": 29161,
"s": 29063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29193,
"s": 29161,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29249,
"s": 29193,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29291,
"s": 29249,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29333,
"s": 29291,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29355,
"s": 29333,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29394,
"s": 29355,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29425,
"s": 29394,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29480,
"s": 29425,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29509,
"s": 29480,
"text": "Create a directory in Python"
}
] |
Ultimate Guide to Lists, Tuples, Arrays and Dictionaries For Beginners. | by Susan Maina | Towards Data Science
|
Python uses data structures to store and organize other objects. The most commonly used data structures are lists and dictionaries. In this article we also talk about tuples and arrays. Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly. Another common data structure is a Set which only stores unique values and is therefore useful for removing duplicates from lists.
These are mutable sequences of objects enclosed by square brackets [].
Mutable means that you can manipulate the list by adding to it, removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. The objects may be any object type in python, from other lists to functions to custom objects. Square brackets enclose the list values .
Creating a list using list=[values]
list_1 = ['head', 'ears', 3, 'legs', 5.8]
Adding elements to a list we use list.append(a)
list_1.append('hair')print(list_1)### Results['head', 'ears', 3, 'legs', 5.8, 'hair']
Removing/deleting elements from a list using list.remove(a)
list_1.remove('head')list_1### Results['ears', 3, 'legs', 5.8, 'hair']
Updating list elements using list[index]=new_value
list_2 = ['beef', 'chicken', 'pork']list_2[2] = 'mutton'print(list_2)### Results['beef', 'chicken', 'mutton']
Retrieving elements from a list using list[index]
list_1 = ['ears', 3, 'legs', 5.8, 'hair']print(list_1[0]) #first elementprint(list_1[:]) #all the elementsprint(list_1[2:4]) # from 3rd element to but not including 5thprint(list_1[-1]) #last elementprint(list_1[1:-1]) #2nd element to but not including last### Resultsears['ears', 3, 'legs', 5.8, 'hair']['legs', 5.8]hair[3, 'legs', 5.8]
Adding lists together using list+list
list_1 + list_2### Results['ears', 3, 'legs', 5.8, 'hair', 'beef', 'chicken', 'mutton']
Repeating a list many times using list*number
a = [1,2,3]print(a * 3)### Results[1, 2, 3, 1, 2, 3, 1, 2, 3]
Checking if a value is a member of a list using ‘value in list’
print('beef' in list_2)### ResultsTrue
Check the number of elements/ length of a list using len(list)
print(len(list_1))### Results5
Getting the minimum and maximum values of a list using max(list) and min(list). Note that a TypeError will be thrown if the list has mixed objects such as Int and Strings.
a = [1,2,3]b = [‘a’, ‘ba’, ‘ca’, ‘za’, ‘ze’]print(min(a))print(max(b))### Result1 ze
These are immutable sequences of objects enclosed by parentheses () — normal brackets.
Immutable means that once a tuple is created, you cannot manipulate its contents, for example removing, updating or adding elements. Similar to lists above, the elements are in an ordered and indexed Sequence and can contain any python Objects. However, the tuple is created using parentheses, which are just normal brackets().
Tuples and Lists enjoy a lot of similar operations. For example you can create a tuple from elements of only one object type, or mixed types. Create a tuple using tuple = (values)
tuple_1 = (3, 'bags', 'belt', 2020, 7.9)tuple_2 = (1,4,6,2)
You can also retrieve tuple elements by index, slice the tuple to retrieve a subset of the values, get the length of the tuple, as well as the maximum and minimum values just like we did with lists above.
print(tuple_1[0])print(tuple_1[2:-1])print('backpack' in tuple_1)print(len(tuple_1))print(max(tuple_2))### Results3('belt', 2020)False56
Side tip: Unpacking lists and tuples.
This is a cool and convenient way to re-assign elements of lists and tuples into individual variables. This is by assigning the list to variables as in var_a,var_b=list. Note that if you try to unpack to less or more variables than the elements in the list, a ValueError is thrown.
t_1 = (1,2,3,4,5)a,b,c,d,e = t_1print(c)### Results3
Python has a separate module for handling arrays called array. Unlike lists, Tuples, Sets and Dictionaries which are inbuilt into the python library, you have to import the array module before using it in your code.
An array is a mutable sequence of similar type objects stored at contiguous/adjacent memory locations.
Mutable means that you can manipulate an array by adding or removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. However, unlike lists, arrays can only contains items of the same data type such as Ints, Floats, or Characters.
To initialize an array, you call the array method of the array module and pass the data type code, and the items enclosed in square brackets. For example array_name = array.array(type code,[array items]). The type code is a single character like ‘i’, ‘f’ or ‘u’ representing Integers, Floats or Unicode Characters respectively. Check out this documentation for a table of all type codes.
import array as arrarr_ints = arr.array('i', [1,2,3])arr_floats = arr.array('f', [2.5, 5.5, 3.0])arr_chars = arr.array('u', ['a','b','c'])
Retrieve the value at a certain index from an array using Array[index]. You can also get the location(index) of a value using Array.index(value).
arr_floats = arr.array('f', [2.5, 5.5, 3.0])print(arr_floats[1])print(arr_floats.index(3.0))### Results5.52
Inserting elements from an array use Array.insert(index,value). The index is the intended location of the new value. Note that the two arguments must be provided to the insert method or a TypeError will be thrown. You can also use Array.append(value) to add a value at the end position.
arr_chars = arr.array('u', ['a','b','c'])arr_chars.insert(2, 'g')print(arr_chars)### Resultsarray('u', 'abgc')
Remove a value from an array using Array.remove(value).
arr_floats = arr.array('f', [2.5, 5.5, 3.0])arr_floats.remove(2.5)print(arr_floats)### Resultsarray('f', [5.5, 3.0])
Similar to the list and tuple, you can also get the length using len(Array), and Maximum and minimum values using max(Array) and min(Array) respectively. Array.count(value) displays the number of times of a value occurs in the array.
A dictionary is an unordered collection of key-value pairs enclosed by curly braces {}. Dictionaries are useful for storing information in pairs of ‘keys’ and ‘values’.
Unordered means that they cannot be indexed. Key-value pairs means each element has a key which stores the value, and you can access an element’s value by its key.
We refer to a key-value pair as an item. A key represents the name of the value, and the value is any python object you need to store such as lists, functions, integers and so on. You can create a python dictionary using Dict={key: value}
dict_2 = {'fruits': ['apple','grape'], 10: 'number of fruits', 'carrier': 'bag'}print(dict_2)### Results{'fruits': ['apple', 'grape'], 10: 'number of fruits', 'carrier': 'bag'}
You can access values by their keys using Dict[key]
print(dict_2['fruits'])print(dict_2[10])### Results['apple', 'grape']number of fruits
You can update the values of a key using Dict[existing_key]=new_value
dict_2['carrier'] = 'basket'dict_2['fruits'].append('banana')print(dict_2)### Results{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket'}
You can create a new element with its own key-value pair, by using a key that does not exist in the current dictionary. Use Dict[new_key]=new_value
dict_2['status'] = 'not enough'print(dict_2)### Results{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket', 'status': 'not enough'}
Dictionaries have some convenient functions for accessing either the keys, the values or all the items. These are useful when iterating through the dictionary. You can access the keys using Dict.keys().
dict_2.keys()### Resultsdict_keys(['fruits', 10, 'carrier', 'status'])
Accessing the values using Dict.values()
dict_2.values()### Resultsdict_values([['apple', 'grape', 'banana'], 'number of fruits', 'basket', 'not enough'])
Accessing the items using Dict.items()
dict_2.items()### Resultsdict_items([('fruits', ['apple', 'grape', 'banana']), (10, 'number of fruits'), ('carrier', 'basket'), ('status', 'not enough')])
We cannot talk about python data structures without mentioning Sets, which we will not get into much details in this article.
Sets are unordered collections of unique objects enclosed by curly braces{} — not to be confused with dictionaries which are also enclosed with curly braces.
Unordered means the elements are not ordered therefore cannot be indexed. Unique means that a set cannot store duplicate values and are therefore very handy for removing duplicates from lists. You can store any python objects in a set. A set is created using Set={values}. You can convert a list into a set using Set(list).
Sets have their own unique operations for merging two sets. These are union() function or | operator, intersection() function or & operator, and the difference() function or — operator.
That’s it for now. This was a reference starter guide for using lists, tuples and dictionaries. There is so much more you can do with these data structures and I encourage you to practice and experiment as much as you can using the extensive information online. Best of luck!
|
[
{
"code": null,
"e": 683,
"s": 171,
"text": "Python uses data structures to store and organize other objects. The most commonly used data structures are lists and dictionaries. In this article we also talk about tuples and arrays. Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly. Another common data structure is a Set which only stores unique values and is therefore useful for removing duplicates from lists."
},
{
"code": null,
"e": 754,
"s": 683,
"text": "These are mutable sequences of objects enclosed by square brackets []."
},
{
"code": null,
"e": 1094,
"s": 754,
"text": "Mutable means that you can manipulate the list by adding to it, removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. The objects may be any object type in python, from other lists to functions to custom objects. Square brackets enclose the list values ."
},
{
"code": null,
"e": 1130,
"s": 1094,
"text": "Creating a list using list=[values]"
},
{
"code": null,
"e": 1172,
"s": 1130,
"text": "list_1 = ['head', 'ears', 3, 'legs', 5.8]"
},
{
"code": null,
"e": 1220,
"s": 1172,
"text": "Adding elements to a list we use list.append(a)"
},
{
"code": null,
"e": 1306,
"s": 1220,
"text": "list_1.append('hair')print(list_1)### Results['head', 'ears', 3, 'legs', 5.8, 'hair']"
},
{
"code": null,
"e": 1366,
"s": 1306,
"text": "Removing/deleting elements from a list using list.remove(a)"
},
{
"code": null,
"e": 1437,
"s": 1366,
"text": "list_1.remove('head')list_1### Results['ears', 3, 'legs', 5.8, 'hair']"
},
{
"code": null,
"e": 1488,
"s": 1437,
"text": "Updating list elements using list[index]=new_value"
},
{
"code": null,
"e": 1598,
"s": 1488,
"text": "list_2 = ['beef', 'chicken', 'pork']list_2[2] = 'mutton'print(list_2)### Results['beef', 'chicken', 'mutton']"
},
{
"code": null,
"e": 1648,
"s": 1598,
"text": "Retrieving elements from a list using list[index]"
},
{
"code": null,
"e": 1986,
"s": 1648,
"text": "list_1 = ['ears', 3, 'legs', 5.8, 'hair']print(list_1[0]) #first elementprint(list_1[:]) #all the elementsprint(list_1[2:4]) # from 3rd element to but not including 5thprint(list_1[-1]) #last elementprint(list_1[1:-1]) #2nd element to but not including last### Resultsears['ears', 3, 'legs', 5.8, 'hair']['legs', 5.8]hair[3, 'legs', 5.8]"
},
{
"code": null,
"e": 2024,
"s": 1986,
"text": "Adding lists together using list+list"
},
{
"code": null,
"e": 2112,
"s": 2024,
"text": "list_1 + list_2### Results['ears', 3, 'legs', 5.8, 'hair', 'beef', 'chicken', 'mutton']"
},
{
"code": null,
"e": 2158,
"s": 2112,
"text": "Repeating a list many times using list*number"
},
{
"code": null,
"e": 2220,
"s": 2158,
"text": "a = [1,2,3]print(a * 3)### Results[1, 2, 3, 1, 2, 3, 1, 2, 3]"
},
{
"code": null,
"e": 2284,
"s": 2220,
"text": "Checking if a value is a member of a list using ‘value in list’"
},
{
"code": null,
"e": 2323,
"s": 2284,
"text": "print('beef' in list_2)### ResultsTrue"
},
{
"code": null,
"e": 2386,
"s": 2323,
"text": "Check the number of elements/ length of a list using len(list)"
},
{
"code": null,
"e": 2417,
"s": 2386,
"text": "print(len(list_1))### Results5"
},
{
"code": null,
"e": 2589,
"s": 2417,
"text": "Getting the minimum and maximum values of a list using max(list) and min(list). Note that a TypeError will be thrown if the list has mixed objects such as Int and Strings."
},
{
"code": null,
"e": 2674,
"s": 2589,
"text": "a = [1,2,3]b = [‘a’, ‘ba’, ‘ca’, ‘za’, ‘ze’]print(min(a))print(max(b))### Result1 ze"
},
{
"code": null,
"e": 2761,
"s": 2674,
"text": "These are immutable sequences of objects enclosed by parentheses () — normal brackets."
},
{
"code": null,
"e": 3089,
"s": 2761,
"text": "Immutable means that once a tuple is created, you cannot manipulate its contents, for example removing, updating or adding elements. Similar to lists above, the elements are in an ordered and indexed Sequence and can contain any python Objects. However, the tuple is created using parentheses, which are just normal brackets()."
},
{
"code": null,
"e": 3269,
"s": 3089,
"text": "Tuples and Lists enjoy a lot of similar operations. For example you can create a tuple from elements of only one object type, or mixed types. Create a tuple using tuple = (values)"
},
{
"code": null,
"e": 3329,
"s": 3269,
"text": "tuple_1 = (3, 'bags', 'belt', 2020, 7.9)tuple_2 = (1,4,6,2)"
},
{
"code": null,
"e": 3534,
"s": 3329,
"text": "You can also retrieve tuple elements by index, slice the tuple to retrieve a subset of the values, get the length of the tuple, as well as the maximum and minimum values just like we did with lists above."
},
{
"code": null,
"e": 3671,
"s": 3534,
"text": "print(tuple_1[0])print(tuple_1[2:-1])print('backpack' in tuple_1)print(len(tuple_1))print(max(tuple_2))### Results3('belt', 2020)False56"
},
{
"code": null,
"e": 3709,
"s": 3671,
"text": "Side tip: Unpacking lists and tuples."
},
{
"code": null,
"e": 3991,
"s": 3709,
"text": "This is a cool and convenient way to re-assign elements of lists and tuples into individual variables. This is by assigning the list to variables as in var_a,var_b=list. Note that if you try to unpack to less or more variables than the elements in the list, a ValueError is thrown."
},
{
"code": null,
"e": 4044,
"s": 3991,
"text": "t_1 = (1,2,3,4,5)a,b,c,d,e = t_1print(c)### Results3"
},
{
"code": null,
"e": 4260,
"s": 4044,
"text": "Python has a separate module for handling arrays called array. Unlike lists, Tuples, Sets and Dictionaries which are inbuilt into the python library, you have to import the array module before using it in your code."
},
{
"code": null,
"e": 4363,
"s": 4260,
"text": "An array is a mutable sequence of similar type objects stored at contiguous/adjacent memory locations."
},
{
"code": null,
"e": 4675,
"s": 4363,
"text": "Mutable means that you can manipulate an array by adding or removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. However, unlike lists, arrays can only contains items of the same data type such as Ints, Floats, or Characters."
},
{
"code": null,
"e": 5063,
"s": 4675,
"text": "To initialize an array, you call the array method of the array module and pass the data type code, and the items enclosed in square brackets. For example array_name = array.array(type code,[array items]). The type code is a single character like ‘i’, ‘f’ or ‘u’ representing Integers, Floats or Unicode Characters respectively. Check out this documentation for a table of all type codes."
},
{
"code": null,
"e": 5202,
"s": 5063,
"text": "import array as arrarr_ints = arr.array('i', [1,2,3])arr_floats = arr.array('f', [2.5, 5.5, 3.0])arr_chars = arr.array('u', ['a','b','c'])"
},
{
"code": null,
"e": 5348,
"s": 5202,
"text": "Retrieve the value at a certain index from an array using Array[index]. You can also get the location(index) of a value using Array.index(value)."
},
{
"code": null,
"e": 5456,
"s": 5348,
"text": "arr_floats = arr.array('f', [2.5, 5.5, 3.0])print(arr_floats[1])print(arr_floats.index(3.0))### Results5.52"
},
{
"code": null,
"e": 5743,
"s": 5456,
"text": "Inserting elements from an array use Array.insert(index,value). The index is the intended location of the new value. Note that the two arguments must be provided to the insert method or a TypeError will be thrown. You can also use Array.append(value) to add a value at the end position."
},
{
"code": null,
"e": 5854,
"s": 5743,
"text": "arr_chars = arr.array('u', ['a','b','c'])arr_chars.insert(2, 'g')print(arr_chars)### Resultsarray('u', 'abgc')"
},
{
"code": null,
"e": 5910,
"s": 5854,
"text": "Remove a value from an array using Array.remove(value)."
},
{
"code": null,
"e": 6027,
"s": 5910,
"text": "arr_floats = arr.array('f', [2.5, 5.5, 3.0])arr_floats.remove(2.5)print(arr_floats)### Resultsarray('f', [5.5, 3.0])"
},
{
"code": null,
"e": 6261,
"s": 6027,
"text": "Similar to the list and tuple, you can also get the length using len(Array), and Maximum and minimum values using max(Array) and min(Array) respectively. Array.count(value) displays the number of times of a value occurs in the array."
},
{
"code": null,
"e": 6430,
"s": 6261,
"text": "A dictionary is an unordered collection of key-value pairs enclosed by curly braces {}. Dictionaries are useful for storing information in pairs of ‘keys’ and ‘values’."
},
{
"code": null,
"e": 6594,
"s": 6430,
"text": "Unordered means that they cannot be indexed. Key-value pairs means each element has a key which stores the value, and you can access an element’s value by its key."
},
{
"code": null,
"e": 6833,
"s": 6594,
"text": "We refer to a key-value pair as an item. A key represents the name of the value, and the value is any python object you need to store such as lists, functions, integers and so on. You can create a python dictionary using Dict={key: value}"
},
{
"code": null,
"e": 7026,
"s": 6833,
"text": "dict_2 = {'fruits': ['apple','grape'], 10: 'number of fruits', 'carrier': 'bag'}print(dict_2)### Results{'fruits': ['apple', 'grape'], 10: 'number of fruits', 'carrier': 'bag'}"
},
{
"code": null,
"e": 7078,
"s": 7026,
"text": "You can access values by their keys using Dict[key]"
},
{
"code": null,
"e": 7164,
"s": 7078,
"text": "print(dict_2['fruits'])print(dict_2[10])### Results['apple', 'grape']number of fruits"
},
{
"code": null,
"e": 7234,
"s": 7164,
"text": "You can update the values of a key using Dict[existing_key]=new_value"
},
{
"code": null,
"e": 7405,
"s": 7234,
"text": "dict_2['carrier'] = 'basket'dict_2['fruits'].append('banana')print(dict_2)### Results{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket'}"
},
{
"code": null,
"e": 7553,
"s": 7405,
"text": "You can create a new element with its own key-value pair, by using a key that does not exist in the current dictionary. Use Dict[new_key]=new_value"
},
{
"code": null,
"e": 7718,
"s": 7553,
"text": "dict_2['status'] = 'not enough'print(dict_2)### Results{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket', 'status': 'not enough'}"
},
{
"code": null,
"e": 7921,
"s": 7718,
"text": "Dictionaries have some convenient functions for accessing either the keys, the values or all the items. These are useful when iterating through the dictionary. You can access the keys using Dict.keys()."
},
{
"code": null,
"e": 7992,
"s": 7921,
"text": "dict_2.keys()### Resultsdict_keys(['fruits', 10, 'carrier', 'status'])"
},
{
"code": null,
"e": 8033,
"s": 7992,
"text": "Accessing the values using Dict.values()"
},
{
"code": null,
"e": 8147,
"s": 8033,
"text": "dict_2.values()### Resultsdict_values([['apple', 'grape', 'banana'], 'number of fruits', 'basket', 'not enough'])"
},
{
"code": null,
"e": 8186,
"s": 8147,
"text": "Accessing the items using Dict.items()"
},
{
"code": null,
"e": 8341,
"s": 8186,
"text": "dict_2.items()### Resultsdict_items([('fruits', ['apple', 'grape', 'banana']), (10, 'number of fruits'), ('carrier', 'basket'), ('status', 'not enough')])"
},
{
"code": null,
"e": 8467,
"s": 8341,
"text": "We cannot talk about python data structures without mentioning Sets, which we will not get into much details in this article."
},
{
"code": null,
"e": 8625,
"s": 8467,
"text": "Sets are unordered collections of unique objects enclosed by curly braces{} — not to be confused with dictionaries which are also enclosed with curly braces."
},
{
"code": null,
"e": 8949,
"s": 8625,
"text": "Unordered means the elements are not ordered therefore cannot be indexed. Unique means that a set cannot store duplicate values and are therefore very handy for removing duplicates from lists. You can store any python objects in a set. A set is created using Set={values}. You can convert a list into a set using Set(list)."
},
{
"code": null,
"e": 9135,
"s": 8949,
"text": "Sets have their own unique operations for merging two sets. These are union() function or | operator, intersection() function or & operator, and the difference() function or — operator."
}
] |
Mouse Position in Python Tkinter
|
Events are very useful to perform and manage multiple tasks in a large-scale application. We can bind a particular event with the keyboard buttons or mouse buttons using the bind(‘handler’, ‘callback’) method. Generally, the mouse pointer and its motion are tracked for the purpose of building a screensaver, 2D or 3D games. In order to print the coordinates of the pointer, we have to bind the Motion with a callback function that gets the position of the pointer in x and y variables.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
def callback(e):
x= e.x
y= e.y
print("Pointer is currently at %d, %d" %(x,y))
win.bind('<Motion>',callback)
win.mainloop()
Running the above code will print the actual position of the pointer whenever we hover on the window.
On the console, you will get to see the actual position of the mouse pointer as you hover the mouse on the screen.
Pointer is currently at 452, 225
Pointer is currently at 426, 200
Pointer is currently at 409, 187
Pointer is currently at 392, 174
Pointer is currently at 382, 168
Pointer is currently at 378, 163
Pointer is currently at 376, 159
Pointer is currently at 369, 150
Pointer is currently at 366, 141
Pointer is currently at 362, 130
|
[
{
"code": null,
"e": 1549,
"s": 1062,
"text": "Events are very useful to perform and manage multiple tasks in a large-scale application. We can bind a particular event with the keyboard buttons or mouse buttons using the bind(‘handler’, ‘callback’) method. Generally, the mouse pointer and its motion are tracked for the purpose of building a screensaver, 2D or 3D games. In order to print the coordinates of the pointer, we have to bind the Motion with a callback function that gets the position of the pointer in x and y variables."
},
{
"code": null,
"e": 1843,
"s": 1549,
"text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\ndef callback(e):\n x= e.x\n y= e.y\n print(\"Pointer is currently at %d, %d\" %(x,y))\nwin.bind('<Motion>',callback)\nwin.mainloop()"
},
{
"code": null,
"e": 1945,
"s": 1843,
"text": "Running the above code will print the actual position of the pointer whenever we hover on the window."
},
{
"code": null,
"e": 2060,
"s": 1945,
"text": "On the console, you will get to see the actual position of the mouse pointer as you hover the mouse on the screen."
},
{
"code": null,
"e": 2390,
"s": 2060,
"text": "Pointer is currently at 452, 225\nPointer is currently at 426, 200\nPointer is currently at 409, 187\nPointer is currently at 392, 174\nPointer is currently at 382, 168\nPointer is currently at 378, 163\nPointer is currently at 376, 159\nPointer is currently at 369, 150\nPointer is currently at 366, 141\nPointer is currently at 362, 130"
}
] |
How to change the line color in a Seaborn linear regression jointplot?
|
To change the line color in seaborn linear regression jointplot, we can use joint_kws in jointplot() method.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy to make a Pandas dataframe.
Use jointplot() method with joint_kws in the arguments.
To display the figure, use show() method.
import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
X = np.random.randn(1000,)
Y = 0.2 * np.random.randn(1000) + 0.5
df = pd.DataFrame(dict(x=X, y=Y))
g = sns.jointplot(x="x", y="y", data=df, kind='reg', height=3.5, joint_kws={'color':'green'})
plt.show()
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To change the line color in seaborn linear regression jointplot, we can use joint_kws in jointplot() method."
},
{
"code": null,
"e": 1247,
"s": 1171,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1314,
"s": 1247,
"text": "Create x and y data points using numpy to make a Pandas dataframe."
},
{
"code": null,
"e": 1370,
"s": 1314,
"text": "Use jointplot() method with joint_kws in the arguments."
},
{
"code": null,
"e": 1412,
"s": 1370,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1805,
"s": 1412,
"text": "import seaborn as sns\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nX = np.random.randn(1000,)\nY = 0.2 * np.random.randn(1000) + 0.5\n\ndf = pd.DataFrame(dict(x=X, y=Y))\ng = sns.jointplot(x=\"x\", y=\"y\", data=df, kind='reg', height=3.5, joint_kws={'color':'green'})\n\nplt.show()"
}
] |
Create Dismissal Alerts in Bootstrap
|
To create a dismissal alert −
Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes, for example, .alert-success, .alert-info, etc.
Also add optional .alert-dismissable to the above <div> class.
Add a close button.
You can try to run the following code to create dismissal alerts −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "alert alert-success alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Success! Well done its submitted.
</div>
<div class = "alert alert-info alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Info! Take this info.
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "To create a dismissal alert −"
},
{
"code": null,
"e": 1254,
"s": 1092,
"text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes, for example, .alert-success, .alert-info, etc."
},
{
"code": null,
"e": 1317,
"s": 1254,
"text": "Also add optional .alert-dismissable to the above <div> class."
},
{
"code": null,
"e": 1337,
"s": 1317,
"text": "Add a close button."
},
{
"code": null,
"e": 1404,
"s": 1337,
"text": "You can try to run the following code to create dismissal alerts −"
},
{
"code": null,
"e": 1414,
"s": 1404,
"text": "Live Demo"
},
{
"code": null,
"e": 2189,
"s": 1414,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"alert alert-success alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n Success! Well done its submitted.\n </div>\n <div class = \"alert alert-info alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n Info! Take this info.\n </div>\n </body>\n</html>"
}
] |
How to measure the relationship between variables | by Trisha Chandra | Towards Data Science
|
Analyzing and visualizing variables one at a time is not enough. To make various conclusions and analyses when performing exploratory data analysis, we need to understand how the variables in a dataset interact with respect to each other. There are numerous ways to analyze this relationship visually, one of the most common methods is the use of popular scatterplots. But scatterplots come with certain limitations which we will see in the later sections. Quantitatively, covariance and correlations are used to define the relationship between variables.
A scatterplot is one of the most common visual forms when it comes to comprehending the relationship between variables at a glance. In the simplest form, this is nothing but a plot of Variable A against Variable B: either one being plotted on the x-axis and the remaining one on the y-axis
%matplotlib inlineimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid')import numpy as npdf = pd.read_csv('weight-height.csv')df.head()plt.plot(df.Height, df.Weight,'o',markersize=2, color='brown')plt.xlabel('Height')plt.ylabel('Weight')
In the above graph, it’s easy to see that there seems to be a positive relationship between the two variables i.e. as one increases the other increases as well. A scatterplot with a negative relationship i.e. as one variable increases the other reduces may take the form of Image 2.
#Just for demonstration purposes I have taken 'a' and 'b'import numpy as npimport randomimport matplotlib.pyplot as plta = np.random.rand(100)*70b = 100-aplt.plot(a, b,'o',markersize=2, color='brown')plt.xlabel('a')plt.ylabel('b')
A scatterplot with no apparent relationship between the two variables would take the form of Image 3:
import numpy as npimport randomimport matplotlib.pyplot as plta = np.random.rand(1000)*70b = np.random.rand(1000)*100plt.plot(a, b,'o',markersize=2, color='brown')plt.xlabel('a')plt.ylabel('b')
In general, scatterplots are best for analyzing two continuous variables. Visualizing two discrete variables using a scatterplot may cause the data points to overlap. Let’s see how a scatterplot would look like in the case of discrete variables.
x = [1,1,1,1,2,2,2,2,3,3,3,3]y = [10,15,15,15,16,16,20,20,20,25,25,25]plt.plot(x,y,'o',markersize=5, color='brown')plt.xlabel('X')plt.ylabel('Y')
In the above image, not all points are visible. To overcome this, we add random noise to the data called “Jitter”. The process is naturally called jittering to allow for a somewhat clear visualization of those overlapped points.
def Jitter(values, jitter): n = len(values) return np.random.uniform(-jitter, +jitter, n) + valuesy1 = Jitter(y,0.9)plt.plot(x,y1,'o',markersize=4, color='brown')plt.xlabel('X')plt.ylabel('Y1')
As seen in Image 5, more data points are now visible. However, jitter should be used only for visualization purposes and should be avoided for analysis purposes.
There can be an overlap of data in the case of continuous variables as well, where overlapping points can hide in the dense part of the data and outliers may be given disproportionate emphasis as seen in Image 1. This is called Saturation.
Scatterplot comes with its own disadvantages as it doesn’t provide quantitative measurement about the relationship, and simply shows the expression of quantitative change. We also can’t use scatterplots to display the relationship between more than two variables. Covariance and Correlation solve both these problems.
Covariance measures how variables vary together. A positive covariance means that the variables vary together in the same direction, a negative covariance means they vary in the opposite direction and 0 covariance means that the variables don’t vary together or they are independent of each other. In other words, if there are two variables X & Y, positive covariance means a larger value of X implies a larger value of Y and negative covariance means a larger value of X implies a smaller value of Y.
Mathematically, Cov(x,y) is given by the following formula, where dxi = xi-xmean and dyi = yi -ymean. Note that the following is the formula for the covariance of a population, when calculating covariance of a sample 1/n is replaced by 1/(n-1). Why is it so, is beyond the scope of this article.
Let’s understand this with an example: Consider, x = [34,56,78,23] y = [20,45,91,16] => xmean = 47.75 => ymean = 43 => Sum of (dxi*dyi) = (34–47.75)*(20–43) + (56–47.75)*(45–43) + (78–47.75)*(91–43) + (23–47.75)*(16–43) = 2453. => Cov(x,y) = 2453/4 = 613.25
In the above example, we can clearly see that as x increases, y increases too and hence we get a positive covariance. Now, let’s consider that x and y have units. x is height in ‘cm’ and y is weight in ‘lbs’. The unit for covariance would then be cm-lbs. Whatever that means!
Covariance can practically take any number which can be overcome using correlation which is in the range of -1 to 1. So covariance doesn’t exactly tell how strong the relationship is but simply the direction of the relationship. For these reasons, it’s also difficult to interpret covariance. To overcome some of these disadvantages we use Correlation.
Correlation again provides quantitive information regarding the relationship between variables. Measuring correlation can be challenging if the variables have different units or if the data distributions of the variables are different from each other. Two methods of calculating correlation can help with these issues: 1) Pearson Correlation 2) Spearman Rank Correlation.
Both these methods of calculating correlation involve transforming the data in the variables being compared to some standard comparable format. Let’s see what transformations are done in both these methods.
Pearson correlation involves transforming each of the values in the variables to a standard score or Z score i.e. finding the number of standard deviations away from each of the values is from the mean and calculating the sum of the corresponding products of the standard scores.
Z score = (Xi-Xmean)/Sigma, where sigma implies standard deviation
Suppose we have 2 variables 'x' and 'y' Z score of x i.e. Zx = (x-xmu)/Sx Where xmu is the mean, Sx is standard deviationTranslating this info to our understanding of Pearson Correlation (p): => pi = Zxi*Zyi => pi = ((xi-xmean)*(yi-ymean))/Sx*Sy => p = mean of pi values => p = (sum of all values of pi)/n=> p = (summation (xi-xmean)*(yi-ymean))/Sx*Sy*n As seen above: (summation (xi-xmean)*(yi-ymean))/n is actually Cov(x,y). So we can rewrite Pearson correlation (p) as Cov(x,y)/Sx*SyNOTE: Here, pi is not the same as mathematical constant Pi (22/7)
Pearson correlation ‘p’ will always be in the range of -1 to 1. A positive value of ‘p’ means as ‘x’ increases ‘y’ increases too, negative means as ‘x’ increases ‘y’ decreases and 0 means there is no apparent linear relationship between ‘x’ and ‘y’. Note that a zero Pearson correlation doesn’t imply ‘no relationship’, it simply means that there isn’t a linear relationship between ‘x’ and ‘y’.
Pearson correlation ‘p’ = 1 means a perfect positive relationship, however, a value of 0.5 or 0.4 implies there is a positive relationship but the relationship may not be as strong. The magnitude or the value of Pearson correlation determines the strength of the relationship.
But again, Pearson correlation does come with certain disadvantages. This method of correlation doesn’t work well if there are outliers in the data, as it can get affected by the outliers. Pearson Correlation works well if the changes in variable x with respect to variable y is linear i.e. when the change happens at a constant rate and when x and y are both somewhat normally distributed or when the data is on an interval scale.
These disadvantages of Pearson correlation can be overcome using the Spearman Rank Correlation.
In the Spearman method, we transform each of the values in both variables to its corresponding rank in the given variable and then calculate the Pearson correlation of the ranks.
Consider x = [23,98,56,1,0,56,1999,12], Corresponding Rankx = [4,7,5,2,1,6,8,3] Similarly, for y = [5,92,88,45,2,54,90,1], Corresponding Ranky = [3,8,6,4,2,5,7,1]
Looking at Rankx and Ranky, the advantage of this method seems to be apparent. Both Rankx and Ranky do not contain any outliers, even if the actual data has any outliers, the outlier will be converted into a rank that is nothing but the relative positive of the number in the dataset. Hence, this method is robust against outliers. This method also solves the problem of data distributions. The data distributions of the ranks will always be uniform. We then calculate the Pearson correlation of Rankx and Ranky using the formula seen in the Pearson correlation section.
But Spearman Rank method works well:
When x changes as y does, but not necessarily at a constant rate i.e. when there is a non-linear relationship between x and yWhen x and y have different data distributions or non-normal distributionIf you want to avoid the effect of outliersWhen data is on an ordinal scale
When x changes as y does, but not necessarily at a constant rate i.e. when there is a non-linear relationship between x and y
When x and y have different data distributions or non-normal distribution
If you want to avoid the effect of outliers
When data is on an ordinal scale
Spearman should be avoided when there is a chance of ranks overlapping.
There are many other ways out there that are used to determine the relationship between variables. This article is simply a primer to get you started on this topic.
If you like geeking out on Twitter and are interested in receiving digestible chunks of such articles in tweet format, don’t forget to follow me at https://twitter.com/TrishaChandra16 and check out the following tweet threads:
The compilation of this topic is heavily influenced by the book Thinkstats by Allen B. Downey and lots of amazing data science and statistics articles out there.
|
[
{
"code": null,
"e": 727,
"s": 171,
"text": "Analyzing and visualizing variables one at a time is not enough. To make various conclusions and analyses when performing exploratory data analysis, we need to understand how the variables in a dataset interact with respect to each other. There are numerous ways to analyze this relationship visually, one of the most common methods is the use of popular scatterplots. But scatterplots come with certain limitations which we will see in the later sections. Quantitatively, covariance and correlations are used to define the relationship between variables."
},
{
"code": null,
"e": 1017,
"s": 727,
"text": "A scatterplot is one of the most common visual forms when it comes to comprehending the relationship between variables at a glance. In the simplest form, this is nothing but a plot of Variable A against Variable B: either one being plotted on the x-axis and the remaining one on the y-axis"
},
{
"code": null,
"e": 1267,
"s": 1017,
"text": "%matplotlib inlineimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid')import numpy as npdf = pd.read_csv('weight-height.csv')df.head()plt.plot(df.Height, df.Weight,'o',markersize=2, color='brown')plt.xlabel('Height')plt.ylabel('Weight')"
},
{
"code": null,
"e": 1550,
"s": 1267,
"text": "In the above graph, it’s easy to see that there seems to be a positive relationship between the two variables i.e. as one increases the other increases as well. A scatterplot with a negative relationship i.e. as one variable increases the other reduces may take the form of Image 2."
},
{
"code": null,
"e": 1781,
"s": 1550,
"text": "#Just for demonstration purposes I have taken 'a' and 'b'import numpy as npimport randomimport matplotlib.pyplot as plta = np.random.rand(100)*70b = 100-aplt.plot(a, b,'o',markersize=2, color='brown')plt.xlabel('a')plt.ylabel('b')"
},
{
"code": null,
"e": 1883,
"s": 1781,
"text": "A scatterplot with no apparent relationship between the two variables would take the form of Image 3:"
},
{
"code": null,
"e": 2077,
"s": 1883,
"text": "import numpy as npimport randomimport matplotlib.pyplot as plta = np.random.rand(1000)*70b = np.random.rand(1000)*100plt.plot(a, b,'o',markersize=2, color='brown')plt.xlabel('a')plt.ylabel('b')"
},
{
"code": null,
"e": 2323,
"s": 2077,
"text": "In general, scatterplots are best for analyzing two continuous variables. Visualizing two discrete variables using a scatterplot may cause the data points to overlap. Let’s see how a scatterplot would look like in the case of discrete variables."
},
{
"code": null,
"e": 2469,
"s": 2323,
"text": "x = [1,1,1,1,2,2,2,2,3,3,3,3]y = [10,15,15,15,16,16,20,20,20,25,25,25]plt.plot(x,y,'o',markersize=5, color='brown')plt.xlabel('X')plt.ylabel('Y')"
},
{
"code": null,
"e": 2698,
"s": 2469,
"text": "In the above image, not all points are visible. To overcome this, we add random noise to the data called “Jitter”. The process is naturally called jittering to allow for a somewhat clear visualization of those overlapped points."
},
{
"code": null,
"e": 2898,
"s": 2698,
"text": "def Jitter(values, jitter): n = len(values) return np.random.uniform(-jitter, +jitter, n) + valuesy1 = Jitter(y,0.9)plt.plot(x,y1,'o',markersize=4, color='brown')plt.xlabel('X')plt.ylabel('Y1')"
},
{
"code": null,
"e": 3060,
"s": 2898,
"text": "As seen in Image 5, more data points are now visible. However, jitter should be used only for visualization purposes and should be avoided for analysis purposes."
},
{
"code": null,
"e": 3300,
"s": 3060,
"text": "There can be an overlap of data in the case of continuous variables as well, where overlapping points can hide in the dense part of the data and outliers may be given disproportionate emphasis as seen in Image 1. This is called Saturation."
},
{
"code": null,
"e": 3618,
"s": 3300,
"text": "Scatterplot comes with its own disadvantages as it doesn’t provide quantitative measurement about the relationship, and simply shows the expression of quantitative change. We also can’t use scatterplots to display the relationship between more than two variables. Covariance and Correlation solve both these problems."
},
{
"code": null,
"e": 4120,
"s": 3618,
"text": "Covariance measures how variables vary together. A positive covariance means that the variables vary together in the same direction, a negative covariance means they vary in the opposite direction and 0 covariance means that the variables don’t vary together or they are independent of each other. In other words, if there are two variables X & Y, positive covariance means a larger value of X implies a larger value of Y and negative covariance means a larger value of X implies a smaller value of Y."
},
{
"code": null,
"e": 4416,
"s": 4120,
"text": "Mathematically, Cov(x,y) is given by the following formula, where dxi = xi-xmean and dyi = yi -ymean. Note that the following is the formula for the covariance of a population, when calculating covariance of a sample 1/n is replaced by 1/(n-1). Why is it so, is beyond the scope of this article."
},
{
"code": null,
"e": 4674,
"s": 4416,
"text": "Let’s understand this with an example: Consider, x = [34,56,78,23] y = [20,45,91,16] => xmean = 47.75 => ymean = 43 => Sum of (dxi*dyi) = (34–47.75)*(20–43) + (56–47.75)*(45–43) + (78–47.75)*(91–43) + (23–47.75)*(16–43) = 2453. => Cov(x,y) = 2453/4 = 613.25"
},
{
"code": null,
"e": 4950,
"s": 4674,
"text": "In the above example, we can clearly see that as x increases, y increases too and hence we get a positive covariance. Now, let’s consider that x and y have units. x is height in ‘cm’ and y is weight in ‘lbs’. The unit for covariance would then be cm-lbs. Whatever that means!"
},
{
"code": null,
"e": 5303,
"s": 4950,
"text": "Covariance can practically take any number which can be overcome using correlation which is in the range of -1 to 1. So covariance doesn’t exactly tell how strong the relationship is but simply the direction of the relationship. For these reasons, it’s also difficult to interpret covariance. To overcome some of these disadvantages we use Correlation."
},
{
"code": null,
"e": 5675,
"s": 5303,
"text": "Correlation again provides quantitive information regarding the relationship between variables. Measuring correlation can be challenging if the variables have different units or if the data distributions of the variables are different from each other. Two methods of calculating correlation can help with these issues: 1) Pearson Correlation 2) Spearman Rank Correlation."
},
{
"code": null,
"e": 5882,
"s": 5675,
"text": "Both these methods of calculating correlation involve transforming the data in the variables being compared to some standard comparable format. Let’s see what transformations are done in both these methods."
},
{
"code": null,
"e": 6162,
"s": 5882,
"text": "Pearson correlation involves transforming each of the values in the variables to a standard score or Z score i.e. finding the number of standard deviations away from each of the values is from the mean and calculating the sum of the corresponding products of the standard scores."
},
{
"code": null,
"e": 6229,
"s": 6162,
"text": "Z score = (Xi-Xmean)/Sigma, where sigma implies standard deviation"
},
{
"code": null,
"e": 6783,
"s": 6229,
"text": "Suppose we have 2 variables 'x' and 'y' Z score of x i.e. Zx = (x-xmu)/Sx Where xmu is the mean, Sx is standard deviationTranslating this info to our understanding of Pearson Correlation (p): => pi = Zxi*Zyi => pi = ((xi-xmean)*(yi-ymean))/Sx*Sy => p = mean of pi values => p = (sum of all values of pi)/n=> p = (summation (xi-xmean)*(yi-ymean))/Sx*Sy*n As seen above: (summation (xi-xmean)*(yi-ymean))/n is actually Cov(x,y). So we can rewrite Pearson correlation (p) as Cov(x,y)/Sx*SyNOTE: Here, pi is not the same as mathematical constant Pi (22/7)"
},
{
"code": null,
"e": 7179,
"s": 6783,
"text": "Pearson correlation ‘p’ will always be in the range of -1 to 1. A positive value of ‘p’ means as ‘x’ increases ‘y’ increases too, negative means as ‘x’ increases ‘y’ decreases and 0 means there is no apparent linear relationship between ‘x’ and ‘y’. Note that a zero Pearson correlation doesn’t imply ‘no relationship’, it simply means that there isn’t a linear relationship between ‘x’ and ‘y’."
},
{
"code": null,
"e": 7456,
"s": 7179,
"text": "Pearson correlation ‘p’ = 1 means a perfect positive relationship, however, a value of 0.5 or 0.4 implies there is a positive relationship but the relationship may not be as strong. The magnitude or the value of Pearson correlation determines the strength of the relationship."
},
{
"code": null,
"e": 7888,
"s": 7456,
"text": "But again, Pearson correlation does come with certain disadvantages. This method of correlation doesn’t work well if there are outliers in the data, as it can get affected by the outliers. Pearson Correlation works well if the changes in variable x with respect to variable y is linear i.e. when the change happens at a constant rate and when x and y are both somewhat normally distributed or when the data is on an interval scale."
},
{
"code": null,
"e": 7984,
"s": 7888,
"text": "These disadvantages of Pearson correlation can be overcome using the Spearman Rank Correlation."
},
{
"code": null,
"e": 8163,
"s": 7984,
"text": "In the Spearman method, we transform each of the values in both variables to its corresponding rank in the given variable and then calculate the Pearson correlation of the ranks."
},
{
"code": null,
"e": 8326,
"s": 8163,
"text": "Consider x = [23,98,56,1,0,56,1999,12], Corresponding Rankx = [4,7,5,2,1,6,8,3] Similarly, for y = [5,92,88,45,2,54,90,1], Corresponding Ranky = [3,8,6,4,2,5,7,1]"
},
{
"code": null,
"e": 8897,
"s": 8326,
"text": "Looking at Rankx and Ranky, the advantage of this method seems to be apparent. Both Rankx and Ranky do not contain any outliers, even if the actual data has any outliers, the outlier will be converted into a rank that is nothing but the relative positive of the number in the dataset. Hence, this method is robust against outliers. This method also solves the problem of data distributions. The data distributions of the ranks will always be uniform. We then calculate the Pearson correlation of Rankx and Ranky using the formula seen in the Pearson correlation section."
},
{
"code": null,
"e": 8934,
"s": 8897,
"text": "But Spearman Rank method works well:"
},
{
"code": null,
"e": 9208,
"s": 8934,
"text": "When x changes as y does, but not necessarily at a constant rate i.e. when there is a non-linear relationship between x and yWhen x and y have different data distributions or non-normal distributionIf you want to avoid the effect of outliersWhen data is on an ordinal scale"
},
{
"code": null,
"e": 9334,
"s": 9208,
"text": "When x changes as y does, but not necessarily at a constant rate i.e. when there is a non-linear relationship between x and y"
},
{
"code": null,
"e": 9408,
"s": 9334,
"text": "When x and y have different data distributions or non-normal distribution"
},
{
"code": null,
"e": 9452,
"s": 9408,
"text": "If you want to avoid the effect of outliers"
},
{
"code": null,
"e": 9485,
"s": 9452,
"text": "When data is on an ordinal scale"
},
{
"code": null,
"e": 9557,
"s": 9485,
"text": "Spearman should be avoided when there is a chance of ranks overlapping."
},
{
"code": null,
"e": 9722,
"s": 9557,
"text": "There are many other ways out there that are used to determine the relationship between variables. This article is simply a primer to get you started on this topic."
},
{
"code": null,
"e": 9949,
"s": 9722,
"text": "If you like geeking out on Twitter and are interested in receiving digestible chunks of such articles in tweet format, don’t forget to follow me at https://twitter.com/TrishaChandra16 and check out the following tweet threads:"
}
] |
Solving Jigsaw puzzles with Python and OpenCV | by Riccardo Albertazzi | Towards Data Science
|
Source Code here
At the beginning of 2018 I was gifted an awesome Star Wars 5000 pieces jigsaw puzzle (you can find it on Amazon here). Completing the puzzle took me about 2 months of patience and perseverance, but now I can look at my masterpiece with satisfaction and joy.
However, I still remember when I had to complete the central part of the puzzle, which is composed by a massive Darth Vader and Luke Skywalker (spoiler alert: Darth Vader’s son!!). I basically found myself sitting in front of a thousand pieces in all possible shades of black and dark blue, and finding matching pieces became a real pain.
This is when I decided to give Computer Vision a chance and try to write a program that would be able to find matching pieces by looking at their shapes.
In this first part I’ll explain how I was able to extract the four sides from each piece, in order to match the shapes in future. Here I’ll show one output image to make clear what I’m trying to achieve here:
The first thing to do was taking pictures (with my phone) of more than 200 pieces in optimal light conditions. Notice that I took pictures of the back of the pieces since I won’t need the puzzle content bust just its shape. I also fixed the camera and the puzzle positions so that cropping the pieces out the entire image became a trivial task:
img = cv2.imread(join('images', filename))img = img[1750:2500, 1000:2000]
Since both light conditions and piece color don’t change inside the dataset, segmentation is achieved using simple binary thresholding. Before applying the binarization, a median filter is applied to the grayscale image in order to remove white noise on the puzzle piece. The binarized image is then smoothed using a mean filter:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)gray = cv2.medianBlur(gray, ksize=5)thresh = cv2.threshold(gray, 130, 255, cv2.THRESH_BINARY)[1]thresh = cv2.blur(thresh, ksize=(3, 3))
Once obtained the thresholded image, I clear potential false positives areas (background pixels marked as puzzle piece pixels) by using the cv2.connectedComponents OpenCV function and taking the connected component with the maximum area (i.e. the puzzle piece itself).Finally I further crop the piece into a square image that allows for piece rotations without losing part of it. Here’s an example of the output image from this phase:
In order to separate each side of a puzzle piece, we need to correctly find the 4 main corners of the puzzle piece. This is the most critical part since all the following steps will work perfectly if the corners are correct.
During the first step I found an approximate location of the corners, while in section 4 I’ll explain how to refine the corner detections in order to obtain the exact locations.
In my first attempt I used the Hough Transform to find the main lines of the puzzle piece and tried to cluster them into 4 different subsets (one for each side). Here I’ll explain briefly the algorithm steps:
Perform edge detection on the binarized image by applying the cv2.Canny function.Apply the Hough Transform for line detection: cv2.HoughLines . For each line returned by this function, we get its coefficients in parametric form.Remove unwanted lines by estimating the piece orientation: since we expect the four lines passing through the four piece corners to form a rectangle, I grouped together lines with the same orientation in order to prune lines that do not belong to this group.Clustering the lines with KMeans: we can group all lines into 4 different clusters, one for each side of the piece, based on their coefficients.Compute the mean line for each cluster.Compute the intersections between the four mean lines to finally obtain the 4 piece corners.
Perform edge detection on the binarized image by applying the cv2.Canny function.
Apply the Hough Transform for line detection: cv2.HoughLines . For each line returned by this function, we get its coefficients in parametric form.
Remove unwanted lines by estimating the piece orientation: since we expect the four lines passing through the four piece corners to form a rectangle, I grouped together lines with the same orientation in order to prune lines that do not belong to this group.
Clustering the lines with KMeans: we can group all lines into 4 different clusters, one for each side of the piece, based on their coefficients.
Compute the mean line for each cluster.
Compute the intersections between the four mean lines to finally obtain the 4 piece corners.
Although straightforward, this algorithm didn’t prove to be robust: this happened especially when a few or no lines where found on one side of the puzzle piece, making the clustering result become unpredictable. Also, the lines do not always approximate enough the true side lines, making their intersection too far from the real corner.
In this second attempt, which proved to be accurate and robust, I applied the Harris corner detection in order to find the best corner candidates and refined this estimation with an algorithm that is able to always detect the right corners.
I first applied the cv2.Harris function, which returns a new floating-point image, where at each pixel a ‘cornerness’ value is computed (the higher, the more robustI then found the local maxima of the Harris image above a certain threshold. After this passage I have discrete points which represent candidate corners of the puzzle piece. The good thing is that for each puzzle piece in my dataset the algorithm returns a candidate corner where a real corner is present. See an example here:
I first applied the cv2.Harris function, which returns a new floating-point image, where at each pixel a ‘cornerness’ value is computed (the higher, the more robust
I then found the local maxima of the Harris image above a certain threshold. After this passage I have discrete points which represent candidate corners of the puzzle piece. The good thing is that for each puzzle piece in my dataset the algorithm returns a candidate corner where a real corner is present. See an example here:
3. Given all the candidate corners, find the set of four corners which maximizes a function that takes into account:- the ‘rectangularness’ of the shape formed by the four points: the more the four angles are close to 90°, the better- the area of the shape: the bigger the shape, the better (that’s because we expect that the furthest points that we can find are the real corners themselves)
This algorithm proved to be successful for all my dataset images. Yay!
Before entering the next phases, I rotated the puzzle piece to make it horizontal (or vertical, depending on your point of view...) and computed its edges by using the Canny edge detector.
I then refined the detected corners’ positions by selecting a window centered on the detected corner and finding the furthest point from a 45° or 135° oriented line passing through the center of the puzzle piece.As you can see, the results are quite accurate:
Now that we have some good puzzle corners, we need to separate the perimeter of the puzzle piece into its four sides. Each side is a connected curve which starts from one corner and ends into another.
The most simple idea works pretty well: compute the four lines passing through the four corners and classify each perimeter point based on the closest line to the point.However, there are cases where a side has a big protrusion and part of it gets classified as belonging to the wrong side, since it is closest to the wrong line!To solve this, I modified the simple approach into a more robust one:
Apply the ‘closest line’ idea until a maximum threshold: if a point is far from all four lines, it doesn’t get classifiedApply a hysteresis algorithm to all unclassified points: for each unclassified point, check if a perimeter point in its neighborhood has been classified; if that is true, set the same ‘side class’ to the point and continue. The algorithm ends when all points have been classified.
Apply the ‘closest line’ idea until a maximum threshold: if a point is far from all four lines, it doesn’t get classified
Apply a hysteresis algorithm to all unclassified points: for each unclassified point, check if a perimeter point in its neighborhood has been classified; if that is true, set the same ‘side class’ to the point and continue. The algorithm ends when all points have been classified.
The final result is amazing! Here’s one example:
The last information that we need is the orientation of each side: we need to know if the side is going in or going out! (It would be bad if the algorithm would tell us to connect two sides that are both going out...)This step is quite simple, since we just need to check for each side if the average point, which is obtained by averaging all point coordinates belonging to the same side, and the barycentre of the puzzle piece lie on the same half-plane identified by the side line connecting its two corners; if this condition is true, then the side is going in, otherwise it’s going out.
Although I decided to finish my Star Wars puzzle using the brute force approach, I really enjoyed applying Computer Vision algorithms to puzzle pieces. Even if the task seems simple at first glance, a lot of algorithms need to be used (binarization, mean filtering, edge detection, corner detection, connected components, ... and a lot of geometry!).
Please share your opinions and possible improvements of this work, and maybe together we will be able to build an entirely autonomous puzzle-solver robot :)
|
[
{
"code": null,
"e": 189,
"s": 172,
"text": "Source Code here"
},
{
"code": null,
"e": 447,
"s": 189,
"text": "At the beginning of 2018 I was gifted an awesome Star Wars 5000 pieces jigsaw puzzle (you can find it on Amazon here). Completing the puzzle took me about 2 months of patience and perseverance, but now I can look at my masterpiece with satisfaction and joy."
},
{
"code": null,
"e": 786,
"s": 447,
"text": "However, I still remember when I had to complete the central part of the puzzle, which is composed by a massive Darth Vader and Luke Skywalker (spoiler alert: Darth Vader’s son!!). I basically found myself sitting in front of a thousand pieces in all possible shades of black and dark blue, and finding matching pieces became a real pain."
},
{
"code": null,
"e": 940,
"s": 786,
"text": "This is when I decided to give Computer Vision a chance and try to write a program that would be able to find matching pieces by looking at their shapes."
},
{
"code": null,
"e": 1149,
"s": 940,
"text": "In this first part I’ll explain how I was able to extract the four sides from each piece, in order to match the shapes in future. Here I’ll show one output image to make clear what I’m trying to achieve here:"
},
{
"code": null,
"e": 1494,
"s": 1149,
"text": "The first thing to do was taking pictures (with my phone) of more than 200 pieces in optimal light conditions. Notice that I took pictures of the back of the pieces since I won’t need the puzzle content bust just its shape. I also fixed the camera and the puzzle positions so that cropping the pieces out the entire image became a trivial task:"
},
{
"code": null,
"e": 1568,
"s": 1494,
"text": "img = cv2.imread(join('images', filename))img = img[1750:2500, 1000:2000]"
},
{
"code": null,
"e": 1898,
"s": 1568,
"text": "Since both light conditions and piece color don’t change inside the dataset, segmentation is achieved using simple binary thresholding. Before applying the binarization, a median filter is applied to the grayscale image in order to remove white noise on the puzzle piece. The binarized image is then smoothed using a mean filter:"
},
{
"code": null,
"e": 2082,
"s": 1898,
"text": "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)gray = cv2.medianBlur(gray, ksize=5)thresh = cv2.threshold(gray, 130, 255, cv2.THRESH_BINARY)[1]thresh = cv2.blur(thresh, ksize=(3, 3))"
},
{
"code": null,
"e": 2517,
"s": 2082,
"text": "Once obtained the thresholded image, I clear potential false positives areas (background pixels marked as puzzle piece pixels) by using the cv2.connectedComponents OpenCV function and taking the connected component with the maximum area (i.e. the puzzle piece itself).Finally I further crop the piece into a square image that allows for piece rotations without losing part of it. Here’s an example of the output image from this phase:"
},
{
"code": null,
"e": 2742,
"s": 2517,
"text": "In order to separate each side of a puzzle piece, we need to correctly find the 4 main corners of the puzzle piece. This is the most critical part since all the following steps will work perfectly if the corners are correct."
},
{
"code": null,
"e": 2920,
"s": 2742,
"text": "During the first step I found an approximate location of the corners, while in section 4 I’ll explain how to refine the corner detections in order to obtain the exact locations."
},
{
"code": null,
"e": 3129,
"s": 2920,
"text": "In my first attempt I used the Hough Transform to find the main lines of the puzzle piece and tried to cluster them into 4 different subsets (one for each side). Here I’ll explain briefly the algorithm steps:"
},
{
"code": null,
"e": 3891,
"s": 3129,
"text": "Perform edge detection on the binarized image by applying the cv2.Canny function.Apply the Hough Transform for line detection: cv2.HoughLines . For each line returned by this function, we get its coefficients in parametric form.Remove unwanted lines by estimating the piece orientation: since we expect the four lines passing through the four piece corners to form a rectangle, I grouped together lines with the same orientation in order to prune lines that do not belong to this group.Clustering the lines with KMeans: we can group all lines into 4 different clusters, one for each side of the piece, based on their coefficients.Compute the mean line for each cluster.Compute the intersections between the four mean lines to finally obtain the 4 piece corners."
},
{
"code": null,
"e": 3973,
"s": 3891,
"text": "Perform edge detection on the binarized image by applying the cv2.Canny function."
},
{
"code": null,
"e": 4121,
"s": 3973,
"text": "Apply the Hough Transform for line detection: cv2.HoughLines . For each line returned by this function, we get its coefficients in parametric form."
},
{
"code": null,
"e": 4380,
"s": 4121,
"text": "Remove unwanted lines by estimating the piece orientation: since we expect the four lines passing through the four piece corners to form a rectangle, I grouped together lines with the same orientation in order to prune lines that do not belong to this group."
},
{
"code": null,
"e": 4525,
"s": 4380,
"text": "Clustering the lines with KMeans: we can group all lines into 4 different clusters, one for each side of the piece, based on their coefficients."
},
{
"code": null,
"e": 4565,
"s": 4525,
"text": "Compute the mean line for each cluster."
},
{
"code": null,
"e": 4658,
"s": 4565,
"text": "Compute the intersections between the four mean lines to finally obtain the 4 piece corners."
},
{
"code": null,
"e": 4996,
"s": 4658,
"text": "Although straightforward, this algorithm didn’t prove to be robust: this happened especially when a few or no lines where found on one side of the puzzle piece, making the clustering result become unpredictable. Also, the lines do not always approximate enough the true side lines, making their intersection too far from the real corner."
},
{
"code": null,
"e": 5237,
"s": 4996,
"text": "In this second attempt, which proved to be accurate and robust, I applied the Harris corner detection in order to find the best corner candidates and refined this estimation with an algorithm that is able to always detect the right corners."
},
{
"code": null,
"e": 5728,
"s": 5237,
"text": "I first applied the cv2.Harris function, which returns a new floating-point image, where at each pixel a ‘cornerness’ value is computed (the higher, the more robustI then found the local maxima of the Harris image above a certain threshold. After this passage I have discrete points which represent candidate corners of the puzzle piece. The good thing is that for each puzzle piece in my dataset the algorithm returns a candidate corner where a real corner is present. See an example here:"
},
{
"code": null,
"e": 5893,
"s": 5728,
"text": "I first applied the cv2.Harris function, which returns a new floating-point image, where at each pixel a ‘cornerness’ value is computed (the higher, the more robust"
},
{
"code": null,
"e": 6220,
"s": 5893,
"text": "I then found the local maxima of the Harris image above a certain threshold. After this passage I have discrete points which represent candidate corners of the puzzle piece. The good thing is that for each puzzle piece in my dataset the algorithm returns a candidate corner where a real corner is present. See an example here:"
},
{
"code": null,
"e": 6612,
"s": 6220,
"text": "3. Given all the candidate corners, find the set of four corners which maximizes a function that takes into account:- the ‘rectangularness’ of the shape formed by the four points: the more the four angles are close to 90°, the better- the area of the shape: the bigger the shape, the better (that’s because we expect that the furthest points that we can find are the real corners themselves)"
},
{
"code": null,
"e": 6683,
"s": 6612,
"text": "This algorithm proved to be successful for all my dataset images. Yay!"
},
{
"code": null,
"e": 6872,
"s": 6683,
"text": "Before entering the next phases, I rotated the puzzle piece to make it horizontal (or vertical, depending on your point of view...) and computed its edges by using the Canny edge detector."
},
{
"code": null,
"e": 7132,
"s": 6872,
"text": "I then refined the detected corners’ positions by selecting a window centered on the detected corner and finding the furthest point from a 45° or 135° oriented line passing through the center of the puzzle piece.As you can see, the results are quite accurate:"
},
{
"code": null,
"e": 7333,
"s": 7132,
"text": "Now that we have some good puzzle corners, we need to separate the perimeter of the puzzle piece into its four sides. Each side is a connected curve which starts from one corner and ends into another."
},
{
"code": null,
"e": 7732,
"s": 7333,
"text": "The most simple idea works pretty well: compute the four lines passing through the four corners and classify each perimeter point based on the closest line to the point.However, there are cases where a side has a big protrusion and part of it gets classified as belonging to the wrong side, since it is closest to the wrong line!To solve this, I modified the simple approach into a more robust one:"
},
{
"code": null,
"e": 8134,
"s": 7732,
"text": "Apply the ‘closest line’ idea until a maximum threshold: if a point is far from all four lines, it doesn’t get classifiedApply a hysteresis algorithm to all unclassified points: for each unclassified point, check if a perimeter point in its neighborhood has been classified; if that is true, set the same ‘side class’ to the point and continue. The algorithm ends when all points have been classified."
},
{
"code": null,
"e": 8256,
"s": 8134,
"text": "Apply the ‘closest line’ idea until a maximum threshold: if a point is far from all four lines, it doesn’t get classified"
},
{
"code": null,
"e": 8537,
"s": 8256,
"text": "Apply a hysteresis algorithm to all unclassified points: for each unclassified point, check if a perimeter point in its neighborhood has been classified; if that is true, set the same ‘side class’ to the point and continue. The algorithm ends when all points have been classified."
},
{
"code": null,
"e": 8586,
"s": 8537,
"text": "The final result is amazing! Here’s one example:"
},
{
"code": null,
"e": 9177,
"s": 8586,
"text": "The last information that we need is the orientation of each side: we need to know if the side is going in or going out! (It would be bad if the algorithm would tell us to connect two sides that are both going out...)This step is quite simple, since we just need to check for each side if the average point, which is obtained by averaging all point coordinates belonging to the same side, and the barycentre of the puzzle piece lie on the same half-plane identified by the side line connecting its two corners; if this condition is true, then the side is going in, otherwise it’s going out."
},
{
"code": null,
"e": 9528,
"s": 9177,
"text": "Although I decided to finish my Star Wars puzzle using the brute force approach, I really enjoyed applying Computer Vision algorithms to puzzle pieces. Even if the task seems simple at first glance, a lot of algorithms need to be used (binarization, mean filtering, edge detection, corner detection, connected components, ... and a lot of geometry!)."
}
] |
CSS - text-decoration
|
The text-decoration property is used to add "decorations" to inline content.
none − No decoration should be added to the inline text.
none − No decoration should be added to the inline text.
underline − An underline is drawn beneath the inline text.
underline − An underline is drawn beneath the inline text.
overline − An overline is drawn above the inline text.
overline − An overline is drawn above the inline text.
line-through − A line should be drawn through the middle of the inline text.
line-through − A line should be drawn through the middle of the inline text.
blink − The inline text should blink on and off, analogous to the BLINK element introduced by Netscape.
blink − The inline text should blink on and off, analogous to the BLINK element introduced by Netscape.
All the HTML elements.
object.style.textDecoration = "underline";
Following is the example which demonstrates how to decorate a text.
NOTE − Blink property does not work with all the browsers.
<html>
<head>
</head>
<body>
<p style = "text-decoration:underline;">
This will be underlined
</p>
<p style = "text-decoration:line-through;">
This will be striked through.
</p>
<p style = "text-decoration:overline;">
This will have a over line.
</p>
<p style = "text-decoration:blink;">
This text will have blinking effect
</p>
</body>
</html>
This will produce following result −
This will be underlined
This will be striked through.
This will have a over line.
This text will have blinking effect
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2704,
"s": 2626,
"text": "The text-decoration property is used to add \"decorations\" to inline content."
},
{
"code": null,
"e": 2761,
"s": 2704,
"text": "none − No decoration should be added to the inline text."
},
{
"code": null,
"e": 2818,
"s": 2761,
"text": "none − No decoration should be added to the inline text."
},
{
"code": null,
"e": 2877,
"s": 2818,
"text": "underline − An underline is drawn beneath the inline text."
},
{
"code": null,
"e": 2936,
"s": 2877,
"text": "underline − An underline is drawn beneath the inline text."
},
{
"code": null,
"e": 2991,
"s": 2936,
"text": "overline − An overline is drawn above the inline text."
},
{
"code": null,
"e": 3046,
"s": 2991,
"text": "overline − An overline is drawn above the inline text."
},
{
"code": null,
"e": 3123,
"s": 3046,
"text": "line-through − A line should be drawn through the middle of the inline text."
},
{
"code": null,
"e": 3200,
"s": 3123,
"text": "line-through − A line should be drawn through the middle of the inline text."
},
{
"code": null,
"e": 3304,
"s": 3200,
"text": "blink − The inline text should blink on and off, analogous to the BLINK element introduced by Netscape."
},
{
"code": null,
"e": 3408,
"s": 3304,
"text": "blink − The inline text should blink on and off, analogous to the BLINK element introduced by Netscape."
},
{
"code": null,
"e": 3431,
"s": 3408,
"text": "All the HTML elements."
},
{
"code": null,
"e": 3475,
"s": 3431,
"text": "object.style.textDecoration = \"underline\";\n"
},
{
"code": null,
"e": 3543,
"s": 3475,
"text": "Following is the example which demonstrates how to decorate a text."
},
{
"code": null,
"e": 3602,
"s": 3543,
"text": "NOTE − Blink property does not work with all the browsers."
},
{
"code": null,
"e": 4066,
"s": 3602,
"text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"text-decoration:underline;\">\n This will be underlined\n </p>\n \n <p style = \"text-decoration:line-through;\">\n This will be striked through.\n </p>\n \n <p style = \"text-decoration:overline;\">\n This will have a over line.\n </p>\n \n <p style = \"text-decoration:blink;\">\n This text will have blinking effect\n </p>\n </body>\n</html> "
},
{
"code": null,
"e": 4103,
"s": 4066,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4132,
"s": 4103,
"text": "\n This will be underlined\n"
},
{
"code": null,
"e": 4167,
"s": 4132,
"text": "\n This will be striked through.\n"
},
{
"code": null,
"e": 4200,
"s": 4167,
"text": "\n This will have a over line.\n"
},
{
"code": null,
"e": 4241,
"s": 4200,
"text": "\n This text will have blinking effect\n"
},
{
"code": null,
"e": 4276,
"s": 4241,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4290,
"s": 4276,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4325,
"s": 4290,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4342,
"s": 4325,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4377,
"s": 4342,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4408,
"s": 4377,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4443,
"s": 4408,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4474,
"s": 4443,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4509,
"s": 4474,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4540,
"s": 4509,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4573,
"s": 4540,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4604,
"s": 4573,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4611,
"s": 4604,
"text": " Print"
},
{
"code": null,
"e": 4622,
"s": 4611,
"text": " Add Notes"
}
] |
Dart - Classes And Objects - GeeksforGeeks
|
13 Aug, 2021
Dart is an object-oriented programming language, so it supports the concept of class, object ... etc. In Dart, we can define classes and objects of our own. We use the class keyword to do so.
Syntax:
class class_name {
// Body of class
}
In the above syntax:
Class is the keyword use to initialize the class.
class_name is the name of the class.
Body of class consists of fields, constructors, getter and setter methods, etc.
Objects are the instance of the class and they are declared by using new keyword followed by the class name.
Syntax:
var object_name = new class_name([ arguments ]);
In the above syntax:
new is the keyword use to declare the instance of the class
object_name is the name of the object and its naming is similar to the variable name in dart.
class_name is the name of the class whose instance variable is been created.
arguments are the input which are needed to be pass if we are willing to call a constructor.
After the object is created, there will be the need to access the fields which we will create. We use the dot(.) operator for that purpose.
Syntax:
// For accessing the property
object_name.property_name;
// For accessing the method
object_name.method_name();
Dart
// Creating Class named Gfgclass Gfg { // Creating Field inside the class String geek1; // Creating Function inside class void geek() { print("Welcome to $geek1"); }} void main(){ // Creating Instance of class Gfg geek = new Gfg(); // Calling field name geek1 and assigning value // to it using object of the class Gfg geek.geek1 = 'GeeksforGeeks'; // Calling function name geek using object of the class Gfg geek.geek();}
Output:
Welcome to GeeksforGeeks
Explanation: Here we have first created the class named Gfg with a field geek1 and a function geek. Now in the main function, we have created an object of the class Gfg of name geek. Using this object we have assigned the value ‘GeeksforGeeks‘ to the string variable of the class and then we have called the geek function which has printed the output.
Akanksha_Rai
sweetyty
Dart-OOPs
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
How to Append or Concatenate Strings in Dart?
Flutter - Flexible Widget
Dart Tutorial
ListView Class in Flutter
Operators in Dart
Flutter - BoxShadow Widget
Flutter - Stack Widget
|
[
{
"code": null,
"e": 23727,
"s": 23699,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 23920,
"s": 23727,
"text": "Dart is an object-oriented programming language, so it supports the concept of class, object ... etc. In Dart, we can define classes and objects of our own. We use the class keyword to do so. "
},
{
"code": null,
"e": 23930,
"s": 23920,
"text": "Syntax: "
},
{
"code": null,
"e": 23972,
"s": 23930,
"text": "class class_name {\n\n // Body of class\n}"
},
{
"code": null,
"e": 23994,
"s": 23972,
"text": "In the above syntax: "
},
{
"code": null,
"e": 24044,
"s": 23994,
"text": "Class is the keyword use to initialize the class."
},
{
"code": null,
"e": 24081,
"s": 24044,
"text": "class_name is the name of the class."
},
{
"code": null,
"e": 24161,
"s": 24081,
"text": "Body of class consists of fields, constructors, getter and setter methods, etc."
},
{
"code": null,
"e": 24270,
"s": 24161,
"text": "Objects are the instance of the class and they are declared by using new keyword followed by the class name."
},
{
"code": null,
"e": 24280,
"s": 24270,
"text": "Syntax: "
},
{
"code": null,
"e": 24329,
"s": 24280,
"text": "var object_name = new class_name([ arguments ]);"
},
{
"code": null,
"e": 24352,
"s": 24329,
"text": "In the above syntax: "
},
{
"code": null,
"e": 24412,
"s": 24352,
"text": "new is the keyword use to declare the instance of the class"
},
{
"code": null,
"e": 24506,
"s": 24412,
"text": "object_name is the name of the object and its naming is similar to the variable name in dart."
},
{
"code": null,
"e": 24583,
"s": 24506,
"text": "class_name is the name of the class whose instance variable is been created."
},
{
"code": null,
"e": 24676,
"s": 24583,
"text": "arguments are the input which are needed to be pass if we are willing to call a constructor."
},
{
"code": null,
"e": 24816,
"s": 24676,
"text": "After the object is created, there will be the need to access the fields which we will create. We use the dot(.) operator for that purpose."
},
{
"code": null,
"e": 24826,
"s": 24816,
"text": "Syntax: "
},
{
"code": null,
"e": 24940,
"s": 24826,
"text": " // For accessing the property\nobject_name.property_name;\n\n// For accessing the method\nobject_name.method_name();"
},
{
"code": null,
"e": 24945,
"s": 24940,
"text": "Dart"
},
{
"code": "// Creating Class named Gfgclass Gfg { // Creating Field inside the class String geek1; // Creating Function inside class void geek() { print(\"Welcome to $geek1\"); }} void main(){ // Creating Instance of class Gfg geek = new Gfg(); // Calling field name geek1 and assigning value // to it using object of the class Gfg geek.geek1 = 'GeeksforGeeks'; // Calling function name geek using object of the class Gfg geek.geek();}",
"e": 25418,
"s": 24945,
"text": null
},
{
"code": null,
"e": 25427,
"s": 25418,
"text": "Output: "
},
{
"code": null,
"e": 25452,
"s": 25427,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 25805,
"s": 25452,
"text": "Explanation: Here we have first created the class named Gfg with a field geek1 and a function geek. Now in the main function, we have created an object of the class Gfg of name geek. Using this object we have assigned the value ‘GeeksforGeeks‘ to the string variable of the class and then we have called the geek function which has printed the output. "
},
{
"code": null,
"e": 25818,
"s": 25805,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 25827,
"s": 25818,
"text": "sweetyty"
},
{
"code": null,
"e": 25837,
"s": 25827,
"text": "Dart-OOPs"
},
{
"code": null,
"e": 25842,
"s": 25837,
"text": "Dart"
},
{
"code": null,
"e": 25940,
"s": 25842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25949,
"s": 25940,
"text": "Comments"
},
{
"code": null,
"e": 25962,
"s": 25949,
"text": "Old Comments"
},
{
"code": null,
"e": 25994,
"s": 25962,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 26033,
"s": 25994,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 26059,
"s": 26033,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 26105,
"s": 26059,
"text": "How to Append or Concatenate Strings in Dart?"
},
{
"code": null,
"e": 26131,
"s": 26105,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 26145,
"s": 26131,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 26171,
"s": 26145,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 26189,
"s": 26171,
"text": "Operators in Dart"
},
{
"code": null,
"e": 26216,
"s": 26189,
"text": "Flutter - BoxShadow Widget"
}
] |
A Beginner’s Guide to End to End Machine Learning | by Rebecca Vickery | Towards Data Science
|
Supervised machine learning is a technique that maps a series of inputs (X) to some known outputs (y) without being explicitly programmed. Training a machine learning model refers to the process where a machine learns a mapping between X and y. Once trained the model can be used to make predictions on new inputs where the output is unknown.
The training of a machine learning model is only one element of the end to end machine learning lifecycle. For a model to be truly useful this mapping needs to be stored and deployed for use. This is often referred to as putting the model into production. Additionally once a model is in production, the predictions and overall performance of the model need to be monitored to ensure that the quality of the predictions does not degrade over time.
To introduce the basic concepts in the end to end machine learning workflow I am going to use the python library, Pycaret. Pycaret is a low code machine learning library that seeks to simplify and speed up the overall machine learning workflow by providing a high-level programming interface and seeking to automate some of the repetitive tasks in machine learning.
The library is developing quickly and has more recently added functionality to encompass the entire end to end machine learning workflow. From model development to deployment and monitoring. In the following article, I will be using this package to give a simple introduction to the end to end machine learning lifecycle.
In this tutorial, I am going to use one of Pycaret’s built-in datasets known as “employee”. This consists of a set of features about employees at an unspecified company and a target variable that denotes if that employee has left the company. This is a classic classification task in machine learning where the goal is to train a model that can predict if an employee is likely to leave.
The data can easily be imported through the Pycaret API. In the below code we read in the data and reserve a validation sample for later use in the workflow.
The first few lines of the data look as follows:
Pycaret has a set of modules that contain a suite of functions for a specific machine learning task. The dataset we are using contains a classification problem so we will be primarily using the classification module.
The first step is to import the setup function. This function is run prior to performing any other steps. It initialises the Pycaret environment and creates a transformation pipeline for preprocessing the data ready for modelling. When run Pycaret will infer the data types for all feature and target columns.
If we are happy that these data types are correct and are also happy to rely on Pycaret’s default preprocessing methods then we can simply hit enter and Pycaret will prepare the data for modelling, and print a report describing the steps that have been taken.
Below is just the first 15 lines of this 59 line report. The setup functions has a large number of optional parameters that can be used to create custom preprocessing. For example, the parameter categorical_features can be used to manually specify categorical columns where the data type has not been inferred correctly. A full list of available parameters can be found here.
In a real-world machine learning project, it is likely that we would perform more in-depth exploratory analysis and custom preprocessing. However, for the purposes of this tutorial, we will continue with the default preprocessing.
Typically in machine learning workflows, it is sensible to train a simple model first to develop a baseline for performance before moving onto more complex algorithms.
At the time of writing, Pycaret supports 18 different algorithms for classification. The full list can be found here. For the baseline model, we will use logistic regression and we use the function create_model to train. To select the algorithm we pass in the abbreviated string found in the documentation. After training, Pycaret will print a report detailing the performance of our model.
By establishing a baseline model we have determined that the preprocessing and setup is sufficient to build a classification model.
The next step is to compare the different classification algorithms to determine which is the best one to use for our dataset and problem. Pycaret has a function called compare_models() which allows us to compare the performance of all available algorithms with one line of code.
This function will try all algorithms and output a list ranked by accuracy. You can change the metric to target using the sort argument.
We can see from this that Random Forest is overall the best model. We will use this model in the rest of our workflow.
We run create_model() again this time selecting the Random Forest algorithm.
When we run create_model it automatically uses the default parameters. These are not necessarily the best set of parameters to use so we need to tune the model to find the best selection. Running the tune_model() function tunes the hyperparameters of the model using Random grid search.
By default, the function will use a pre-defined grid of parameters but this can be customised by passing a custom grid into the custom_grid parameter. By default, the function will also optimise the accuracy score but this can also be customised using the optimize parameter.
In the below code we use the default parameter grid to tune the model and optimise for the MCC score.
The function returns a table containing k-fold validated scores, by default the number of folds is 10.
Pycaret has a selection of built-in plots to interpret the results of the model which can be accessed using the plot_model() function.
Below we inspect feature importances using this function.
Let’s also visualise the confusion matrix.
Pycaret has additional functionality to deploy models to the cloud using AWS.
To deploy the model on AWS you must first create an account on aws.amazon.com. Once created you need to generate an access key so that you can allow the Pycaret function to write to your account. To do this follow the following steps.
Login to your AWS account.Hover over your username in the top right corner.Select security credentials from the list that appears.
Login to your AWS account.
Hover over your username in the top right corner.
Select security credentials from the list that appears.
4. From here expand the Access keys section and click on ‘Create new access key’.
5. At this stage you need to download the credentials file when prompted. You will need the credentials contained file in this later.
6. To allow Pycaret to interact with your AWS account you also need to install and configure the AWS CLI. To do this first run the following.
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
Then run this:
sudo installer -pkg ./AWSCLIV2.pkg -target /
Now type aws --version to confirm everything has been installed correctly. You should see something like this.
Now that this is installed we can configure the AWS CLI with your account details. To do this run the command shown below. It will ask you to input the following pieces of information.
AWS Access Key ID: this can be found in the credentials file we downloaded earlier.
AWS Secret Acess Key: also found in the credentials file.
Default region name: this can be found on the AWS console.
Default output format: this should be left blank.
Next, we create an S3 bucket to store the deployed model. From the AWS console select S3 and then create a bucket with your chosen name.
Now we are ready to use Pycaret to deploy our chosen model.
If the model has deployed you will see the following message.
To use the model we generate predictions on the validation data we reserved earlier.
The code shown below loads the model from S3 and generates predictions on the validation data with the labels removed.
Let’s view the first 5 predictions by running predictions[:5].
An important aspect of the production machine learning workflow is tracking and monitoring the experiments that are performed. Pycaret has integration with MLflow an open-source platform for managing the end to end machine learning lifecycle.
To use MLflow via Pycaret we need to import MLflow (this should already have been installed along with Pycaret) and set the tracking URI. We then add a couple of extra parameters as shown below when calling the setup function.
Now if we copy the tracking URI into a browser you should see the mlflow UI and the experiments it has tracked.
We can click through to view the metrics, artifacts and params for each experiment performed.
This is a simple tutorial to learn the basic steps involved in an end to end machine learning project. In the real world most machine learning problems, data and deployment solutions require much more complex treatment. However, for the purposes of this tutorial I have used a simple dataset and python library to get you started with learning about the end to end machine learning lifecycle.
Pycaret is an example of a low-code machine learning library. There are a number of tools being developed that seek to simplify machine learning development in different ways. To learn more about these low effort machine learning libraries see my earlier article.
towardsdatascience.com
For more information about machine learning in the real world see the article below.
towardsdatascience.com
Thanks for reading!
|
[
{
"code": null,
"e": 515,
"s": 172,
"text": "Supervised machine learning is a technique that maps a series of inputs (X) to some known outputs (y) without being explicitly programmed. Training a machine learning model refers to the process where a machine learns a mapping between X and y. Once trained the model can be used to make predictions on new inputs where the output is unknown."
},
{
"code": null,
"e": 963,
"s": 515,
"text": "The training of a machine learning model is only one element of the end to end machine learning lifecycle. For a model to be truly useful this mapping needs to be stored and deployed for use. This is often referred to as putting the model into production. Additionally once a model is in production, the predictions and overall performance of the model need to be monitored to ensure that the quality of the predictions does not degrade over time."
},
{
"code": null,
"e": 1329,
"s": 963,
"text": "To introduce the basic concepts in the end to end machine learning workflow I am going to use the python library, Pycaret. Pycaret is a low code machine learning library that seeks to simplify and speed up the overall machine learning workflow by providing a high-level programming interface and seeking to automate some of the repetitive tasks in machine learning."
},
{
"code": null,
"e": 1651,
"s": 1329,
"text": "The library is developing quickly and has more recently added functionality to encompass the entire end to end machine learning workflow. From model development to deployment and monitoring. In the following article, I will be using this package to give a simple introduction to the end to end machine learning lifecycle."
},
{
"code": null,
"e": 2039,
"s": 1651,
"text": "In this tutorial, I am going to use one of Pycaret’s built-in datasets known as “employee”. This consists of a set of features about employees at an unspecified company and a target variable that denotes if that employee has left the company. This is a classic classification task in machine learning where the goal is to train a model that can predict if an employee is likely to leave."
},
{
"code": null,
"e": 2197,
"s": 2039,
"text": "The data can easily be imported through the Pycaret API. In the below code we read in the data and reserve a validation sample for later use in the workflow."
},
{
"code": null,
"e": 2246,
"s": 2197,
"text": "The first few lines of the data look as follows:"
},
{
"code": null,
"e": 2463,
"s": 2246,
"text": "Pycaret has a set of modules that contain a suite of functions for a specific machine learning task. The dataset we are using contains a classification problem so we will be primarily using the classification module."
},
{
"code": null,
"e": 2773,
"s": 2463,
"text": "The first step is to import the setup function. This function is run prior to performing any other steps. It initialises the Pycaret environment and creates a transformation pipeline for preprocessing the data ready for modelling. When run Pycaret will infer the data types for all feature and target columns."
},
{
"code": null,
"e": 3033,
"s": 2773,
"text": "If we are happy that these data types are correct and are also happy to rely on Pycaret’s default preprocessing methods then we can simply hit enter and Pycaret will prepare the data for modelling, and print a report describing the steps that have been taken."
},
{
"code": null,
"e": 3409,
"s": 3033,
"text": "Below is just the first 15 lines of this 59 line report. The setup functions has a large number of optional parameters that can be used to create custom preprocessing. For example, the parameter categorical_features can be used to manually specify categorical columns where the data type has not been inferred correctly. A full list of available parameters can be found here."
},
{
"code": null,
"e": 3640,
"s": 3409,
"text": "In a real-world machine learning project, it is likely that we would perform more in-depth exploratory analysis and custom preprocessing. However, for the purposes of this tutorial, we will continue with the default preprocessing."
},
{
"code": null,
"e": 3808,
"s": 3640,
"text": "Typically in machine learning workflows, it is sensible to train a simple model first to develop a baseline for performance before moving onto more complex algorithms."
},
{
"code": null,
"e": 4199,
"s": 3808,
"text": "At the time of writing, Pycaret supports 18 different algorithms for classification. The full list can be found here. For the baseline model, we will use logistic regression and we use the function create_model to train. To select the algorithm we pass in the abbreviated string found in the documentation. After training, Pycaret will print a report detailing the performance of our model."
},
{
"code": null,
"e": 4331,
"s": 4199,
"text": "By establishing a baseline model we have determined that the preprocessing and setup is sufficient to build a classification model."
},
{
"code": null,
"e": 4611,
"s": 4331,
"text": "The next step is to compare the different classification algorithms to determine which is the best one to use for our dataset and problem. Pycaret has a function called compare_models() which allows us to compare the performance of all available algorithms with one line of code."
},
{
"code": null,
"e": 4748,
"s": 4611,
"text": "This function will try all algorithms and output a list ranked by accuracy. You can change the metric to target using the sort argument."
},
{
"code": null,
"e": 4867,
"s": 4748,
"text": "We can see from this that Random Forest is overall the best model. We will use this model in the rest of our workflow."
},
{
"code": null,
"e": 4944,
"s": 4867,
"text": "We run create_model() again this time selecting the Random Forest algorithm."
},
{
"code": null,
"e": 5231,
"s": 4944,
"text": "When we run create_model it automatically uses the default parameters. These are not necessarily the best set of parameters to use so we need to tune the model to find the best selection. Running the tune_model() function tunes the hyperparameters of the model using Random grid search."
},
{
"code": null,
"e": 5507,
"s": 5231,
"text": "By default, the function will use a pre-defined grid of parameters but this can be customised by passing a custom grid into the custom_grid parameter. By default, the function will also optimise the accuracy score but this can also be customised using the optimize parameter."
},
{
"code": null,
"e": 5609,
"s": 5507,
"text": "In the below code we use the default parameter grid to tune the model and optimise for the MCC score."
},
{
"code": null,
"e": 5712,
"s": 5609,
"text": "The function returns a table containing k-fold validated scores, by default the number of folds is 10."
},
{
"code": null,
"e": 5847,
"s": 5712,
"text": "Pycaret has a selection of built-in plots to interpret the results of the model which can be accessed using the plot_model() function."
},
{
"code": null,
"e": 5905,
"s": 5847,
"text": "Below we inspect feature importances using this function."
},
{
"code": null,
"e": 5948,
"s": 5905,
"text": "Let’s also visualise the confusion matrix."
},
{
"code": null,
"e": 6026,
"s": 5948,
"text": "Pycaret has additional functionality to deploy models to the cloud using AWS."
},
{
"code": null,
"e": 6261,
"s": 6026,
"text": "To deploy the model on AWS you must first create an account on aws.amazon.com. Once created you need to generate an access key so that you can allow the Pycaret function to write to your account. To do this follow the following steps."
},
{
"code": null,
"e": 6392,
"s": 6261,
"text": "Login to your AWS account.Hover over your username in the top right corner.Select security credentials from the list that appears."
},
{
"code": null,
"e": 6419,
"s": 6392,
"text": "Login to your AWS account."
},
{
"code": null,
"e": 6469,
"s": 6419,
"text": "Hover over your username in the top right corner."
},
{
"code": null,
"e": 6525,
"s": 6469,
"text": "Select security credentials from the list that appears."
},
{
"code": null,
"e": 6607,
"s": 6525,
"text": "4. From here expand the Access keys section and click on ‘Create new access key’."
},
{
"code": null,
"e": 6741,
"s": 6607,
"text": "5. At this stage you need to download the credentials file when prompted. You will need the credentials contained file in this later."
},
{
"code": null,
"e": 6883,
"s": 6741,
"text": "6. To allow Pycaret to interact with your AWS account you also need to install and configure the AWS CLI. To do this first run the following."
},
{
"code": null,
"e": 6950,
"s": 6883,
"text": "curl \"https://awscli.amazonaws.com/AWSCLIV2.pkg\" -o \"AWSCLIV2.pkg\""
},
{
"code": null,
"e": 6965,
"s": 6950,
"text": "Then run this:"
},
{
"code": null,
"e": 7010,
"s": 6965,
"text": "sudo installer -pkg ./AWSCLIV2.pkg -target /"
},
{
"code": null,
"e": 7121,
"s": 7010,
"text": "Now type aws --version to confirm everything has been installed correctly. You should see something like this."
},
{
"code": null,
"e": 7306,
"s": 7121,
"text": "Now that this is installed we can configure the AWS CLI with your account details. To do this run the command shown below. It will ask you to input the following pieces of information."
},
{
"code": null,
"e": 7390,
"s": 7306,
"text": "AWS Access Key ID: this can be found in the credentials file we downloaded earlier."
},
{
"code": null,
"e": 7448,
"s": 7390,
"text": "AWS Secret Acess Key: also found in the credentials file."
},
{
"code": null,
"e": 7507,
"s": 7448,
"text": "Default region name: this can be found on the AWS console."
},
{
"code": null,
"e": 7557,
"s": 7507,
"text": "Default output format: this should be left blank."
},
{
"code": null,
"e": 7694,
"s": 7557,
"text": "Next, we create an S3 bucket to store the deployed model. From the AWS console select S3 and then create a bucket with your chosen name."
},
{
"code": null,
"e": 7754,
"s": 7694,
"text": "Now we are ready to use Pycaret to deploy our chosen model."
},
{
"code": null,
"e": 7816,
"s": 7754,
"text": "If the model has deployed you will see the following message."
},
{
"code": null,
"e": 7901,
"s": 7816,
"text": "To use the model we generate predictions on the validation data we reserved earlier."
},
{
"code": null,
"e": 8020,
"s": 7901,
"text": "The code shown below loads the model from S3 and generates predictions on the validation data with the labels removed."
},
{
"code": null,
"e": 8083,
"s": 8020,
"text": "Let’s view the first 5 predictions by running predictions[:5]."
},
{
"code": null,
"e": 8326,
"s": 8083,
"text": "An important aspect of the production machine learning workflow is tracking and monitoring the experiments that are performed. Pycaret has integration with MLflow an open-source platform for managing the end to end machine learning lifecycle."
},
{
"code": null,
"e": 8553,
"s": 8326,
"text": "To use MLflow via Pycaret we need to import MLflow (this should already have been installed along with Pycaret) and set the tracking URI. We then add a couple of extra parameters as shown below when calling the setup function."
},
{
"code": null,
"e": 8665,
"s": 8553,
"text": "Now if we copy the tracking URI into a browser you should see the mlflow UI and the experiments it has tracked."
},
{
"code": null,
"e": 8759,
"s": 8665,
"text": "We can click through to view the metrics, artifacts and params for each experiment performed."
},
{
"code": null,
"e": 9152,
"s": 8759,
"text": "This is a simple tutorial to learn the basic steps involved in an end to end machine learning project. In the real world most machine learning problems, data and deployment solutions require much more complex treatment. However, for the purposes of this tutorial I have used a simple dataset and python library to get you started with learning about the end to end machine learning lifecycle."
},
{
"code": null,
"e": 9416,
"s": 9152,
"text": "Pycaret is an example of a low-code machine learning library. There are a number of tools being developed that seek to simplify machine learning development in different ways. To learn more about these low effort machine learning libraries see my earlier article."
},
{
"code": null,
"e": 9439,
"s": 9416,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9524,
"s": 9439,
"text": "For more information about machine learning in the real world see the article below."
},
{
"code": null,
"e": 9547,
"s": 9524,
"text": "towardsdatascience.com"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.