title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
numpy.ndarray.T | This function belongs to ndarray class. It behaves similar to numpy.transpose.
import numpy as np
a = np.arange(12).reshape(3,4)
print 'The original array is:'
print a
print '\n'
print 'Array after applying the function:'
print a.T
The output of the above program would be −
The original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array after applying the function:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2322,
"s": 2243,
"text": "This function belongs to ndarray class. It behaves similar to numpy.transpose."
},
{
"code": null,
"e": 2484,
"s": 2322,
"text": "import numpy as np \na = np.arange(12).reshape(3,4) \n\nprint 'The original array is:' \nprint a \nprint '\\n' \n\nprint 'Array after applying the function:' \nprint a.T"
},
{
"code": null,
"e": 2527,
"s": 2484,
"text": "The output of the above program would be −"
},
{
"code": null,
"e": 2669,
"s": 2527,
"text": "The original array is:\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nArray after applying the function:\n[[ 0 4 8]\n [ 1 5 9]\n [ 2 6 10]\n [ 3 7 11]]\n"
},
{
"code": null,
"e": 2702,
"s": 2669,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2719,
"s": 2702,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 2752,
"s": 2719,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2787,
"s": 2752,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 2820,
"s": 2787,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2855,
"s": 2820,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 2890,
"s": 2855,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2902,
"s": 2890,
"text": " Akbar Khan"
},
{
"code": null,
"e": 2935,
"s": 2902,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2950,
"s": 2935,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 2983,
"s": 2950,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2990,
"s": 2983,
"text": " Anmol"
},
{
"code": null,
"e": 2997,
"s": 2990,
"text": " Print"
},
{
"code": null,
"e": 3008,
"s": 2997,
"text": " Add Notes"
}
] |
Common prime factors of two numbers - GeeksforGeeks | 06 Jun, 2021
Given two integer and , the task is to find the common prime divisors of these numbers.Examples:
Input: A = 6, B = 12 Output: 2 3 2 and 3 are the only common prime divisors of 6 and 12Input: A = 4, B = 8 Output: 2
Naive Approach: Iterate from 1 to min(A, B) and check whether i is prime and a factor of both A and B, if yes then display the number.Efficient Approach is to do following:
Find Greatest Common Divisor (gcd) of the given numbers.Find prime factors of the GCD.
Find Greatest Common Divisor (gcd) of the given numbers.
Find prime factors of the GCD.
Efficient Approach for multiple queries: The above solution can be further optimized if there are multiple queries for common factors. The idea is based on Prime Factorization using Sieve O(log n) for multiple queries.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define MAXN 100001 bool prime[MAXN];void SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p <= MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i <= MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsvoid common_prime(int a, int b){ // Get the GCD of the given numbers int gcd = __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { cout << i << " "; } }} // Driver codeint main(){ // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); return 0;}
//Java implementation of above approach class GFG { static final int MAXN = 100001;static boolean prime[] = new boolean[MAXN]; static void SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for(int i = 0;i<prime.length;i++) prime[i]=true; // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p < MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i < MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsstatic void common_prime(int a, int b){ // Get the GCD of the given numbers int gcd = (int) __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { System.out.print(i + " "); } }}static long __gcd(long a, long b) { if (a == 0) return b; return __gcd(b % a, a); }// Driver code public static void main(String[] args) { // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); }} /*This code is contributed by 29AjayKumar*/
# Python implementation of above approachfrom math import gcd, sqrt # Create a boolean array "prime[0..n]"# and initialize all entries it as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True] * 100001 def SieveOfEratosthenes() : # 0 and 1 are not prime numbers prime[0] = False prime[1] = False for p in range(2, int(sqrt(100001)) + 1) : # If prime[p] is not changed, # then it is a prime if prime[p] == True : # Update all multiples of # p as non-prime for i in range(p**2, 100001, p) : prime[i] = False # Find the common prime divisorsdef common_prime(a, b) : # Get the GCD of the given numbers __gcd = gcd(a, b) # Find the prime divisors of the gcd for i in range(2, __gcd + 1) : # If i is prime and a divisor of gcd if prime[i] and __gcd % i == 0 : print(i, end = " ") # Driver codeif __name__ == "__main__" : # Create the Sieve SieveOfEratosthenes() a, b = 6, 12 common_prime(a, b) # This code is contributed by ANKITRAI1
//C# implementation of above approachusing System;public class GFG { static bool []prime = new bool[100001]; static void SieveOfEratosthenes() { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for(int i = 0;i<prime.Length;i++) prime[i]=true; // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p < 100001; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i < 100001; i += p) prime[i] = false; } } } // Find the common prime divisors static void common_prime(int a, int b) { // Get the GCD of the given numbers int gcd = (int) __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { Console.Write(i + " "); } } } static long __gcd(long a, long b) { if (a == 0) return b; return __gcd(b % a, a); } // Driver code public static void Main() { // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); }} /*This code is contributed by 29AjayKumar*/
<script>// Javascript program to implement the above approach MAXN = parseInt(100001);prime = new Array(MAXN); function __gcd(a, b) { if (a == 0) return b; return __gcd(b % a, a); }function SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. prime.fill(true); // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (var p = 2; p * p <= MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (var i = p * p; i <= MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsfunction common_prime( a, b){ // Get the GCD of the given numbers var gcd = __gcd(a, b); // Find the prime divisors of the gcd for (var i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { document.write( i + " "); } }} SieveOfEratosthenes();var a = 6, b = 12;common_prime(a, b); //This code is contributed by SoumikModnal</script>
2 3
ankthon
29AjayKumar
SoumikMondal
saurabh1990aror
Numbers
prime-factor
sieve
Technical Scripter 2018
Mathematical
Mathematical
Numbers
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 24698,
"s": 24670,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 24797,
"s": 24698,
"text": "Given two integer and , the task is to find the common prime divisors of these numbers.Examples: "
},
{
"code": null,
"e": 24916,
"s": 24797,
"text": "Input: A = 6, B = 12 Output: 2 3 2 and 3 are the only common prime divisors of 6 and 12Input: A = 4, B = 8 Output: 2 "
},
{
"code": null,
"e": 25093,
"s": 24918,
"text": "Naive Approach: Iterate from 1 to min(A, B) and check whether i is prime and a factor of both A and B, if yes then display the number.Efficient Approach is to do following: "
},
{
"code": null,
"e": 25180,
"s": 25093,
"text": "Find Greatest Common Divisor (gcd) of the given numbers.Find prime factors of the GCD."
},
{
"code": null,
"e": 25237,
"s": 25180,
"text": "Find Greatest Common Divisor (gcd) of the given numbers."
},
{
"code": null,
"e": 25268,
"s": 25237,
"text": "Find prime factors of the GCD."
},
{
"code": null,
"e": 25539,
"s": 25268,
"text": "Efficient Approach for multiple queries: The above solution can be further optimized if there are multiple queries for common factors. The idea is based on Prime Factorization using Sieve O(log n) for multiple queries.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25543,
"s": 25539,
"text": "C++"
},
{
"code": null,
"e": 25548,
"s": 25543,
"text": "Java"
},
{
"code": null,
"e": 25556,
"s": 25548,
"text": "Python3"
},
{
"code": null,
"e": 25559,
"s": 25556,
"text": "C#"
},
{
"code": null,
"e": 25570,
"s": 25559,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define MAXN 100001 bool prime[MAXN];void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p <= MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i <= MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsvoid common_prime(int a, int b){ // Get the GCD of the given numbers int gcd = __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { cout << i << \" \"; } }} // Driver codeint main(){ // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); return 0;}",
"e": 26769,
"s": 25570,
"text": null
},
{
"code": "//Java implementation of above approach class GFG { static final int MAXN = 100001;static boolean prime[] = new boolean[MAXN]; static void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for(int i = 0;i<prime.length;i++) prime[i]=true; // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p < MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i < MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsstatic void common_prime(int a, int b){ // Get the GCD of the given numbers int gcd = (int) __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { System.out.print(i + \" \"); } }}static long __gcd(long a, long b) { if (a == 0) return b; return __gcd(b % a, a); }// Driver code public static void main(String[] args) { // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); }} /*This code is contributed by 29AjayKumar*/",
"e": 28198,
"s": 26769,
"text": null
},
{
"code": "# Python implementation of above approachfrom math import gcd, sqrt # Create a boolean array \"prime[0..n]\"# and initialize all entries it as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True] * 100001 def SieveOfEratosthenes() : # 0 and 1 are not prime numbers prime[0] = False prime[1] = False for p in range(2, int(sqrt(100001)) + 1) : # If prime[p] is not changed, # then it is a prime if prime[p] == True : # Update all multiples of # p as non-prime for i in range(p**2, 100001, p) : prime[i] = False # Find the common prime divisorsdef common_prime(a, b) : # Get the GCD of the given numbers __gcd = gcd(a, b) # Find the prime divisors of the gcd for i in range(2, __gcd + 1) : # If i is prime and a divisor of gcd if prime[i] and __gcd % i == 0 : print(i, end = \" \") # Driver codeif __name__ == \"__main__\" : # Create the Sieve SieveOfEratosthenes() a, b = 6, 12 common_prime(a, b) # This code is contributed by ANKITRAI1",
"e": 29330,
"s": 28198,
"text": null
},
{
"code": "//C# implementation of above approachusing System;public class GFG { static bool []prime = new bool[100001]; static void SieveOfEratosthenes() { // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for(int i = 0;i<prime.Length;i++) prime[i]=true; // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p < 100001; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (int i = p * p; i < 100001; i += p) prime[i] = false; } } } // Find the common prime divisors static void common_prime(int a, int b) { // Get the GCD of the given numbers int gcd = (int) __gcd(a, b); // Find the prime divisors of the gcd for (int i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { Console.Write(i + \" \"); } } } static long __gcd(long a, long b) { if (a == 0) return b; return __gcd(b % a, a); } // Driver code public static void Main() { // Create the Sieve SieveOfEratosthenes(); int a = 6, b = 12; common_prime(a, b); }} /*This code is contributed by 29AjayKumar*/",
"e": 30892,
"s": 29330,
"text": null
},
{
"code": "<script>// Javascript program to implement the above approach MAXN = parseInt(100001);prime = new Array(MAXN); function __gcd(a, b) { if (a == 0) return b; return __gcd(b % a, a); }function SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. prime.fill(true); // 0 and 1 are not prime numbers prime[0] = false; prime[1] = false; for (var p = 2; p * p <= MAXN; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p as non-prime for (var i = p * p; i <= MAXN; i += p) prime[i] = false; } }} // Find the common prime divisorsfunction common_prime( a, b){ // Get the GCD of the given numbers var gcd = __gcd(a, b); // Find the prime divisors of the gcd for (var i = 2; i <= (gcd); i++) { // If i is prime and a divisor of gcd if (prime[i] && gcd % i == 0) { document.write( i + \" \"); } }} SieveOfEratosthenes();var a = 6, b = 12;common_prime(a, b); //This code is contributed by SoumikModnal</script>",
"e": 32131,
"s": 30892,
"text": null
},
{
"code": null,
"e": 32135,
"s": 32131,
"text": "2 3"
},
{
"code": null,
"e": 32145,
"s": 32137,
"text": "ankthon"
},
{
"code": null,
"e": 32157,
"s": 32145,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32170,
"s": 32157,
"text": "SoumikMondal"
},
{
"code": null,
"e": 32186,
"s": 32170,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 32194,
"s": 32186,
"text": "Numbers"
},
{
"code": null,
"e": 32207,
"s": 32194,
"text": "prime-factor"
},
{
"code": null,
"e": 32213,
"s": 32207,
"text": "sieve"
},
{
"code": null,
"e": 32237,
"s": 32213,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 32250,
"s": 32237,
"text": "Mathematical"
},
{
"code": null,
"e": 32263,
"s": 32250,
"text": "Mathematical"
},
{
"code": null,
"e": 32271,
"s": 32263,
"text": "Numbers"
},
{
"code": null,
"e": 32277,
"s": 32271,
"text": "sieve"
},
{
"code": null,
"e": 32375,
"s": 32277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32384,
"s": 32375,
"text": "Comments"
},
{
"code": null,
"e": 32397,
"s": 32384,
"text": "Old Comments"
},
{
"code": null,
"e": 32421,
"s": 32397,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32464,
"s": 32421,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32478,
"s": 32464,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32527,
"s": 32478,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32561,
"s": 32527,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 32582,
"s": 32561,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 32623,
"s": 32582,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 32655,
"s": 32623,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 32692,
"s": 32655,
"text": "Minimum number of jumps to reach end"
}
] |
Java Singleton Design Pattern Practices with Examples - GeeksforGeeks | 16 Jun, 2021
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your use, simplicity and removed bottlenecks. There are many ways this can be done in Java. All these ways differs in their implementation of the pattern, but in the end, they all achieve the same end result of a single instance.
Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time.
Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time.
JAVA
// Java code to create singleton class by// Eager Initializationpublic class GFG{ // public instance initialized when loading the class private static final GFG instance = new GFG(); private GFG() { // private constructor } public static GFG getInstance(){ return instance; }}
Pros:Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible.Using static block: This is also a sub part of Eager initialization. The only difference is object is created in a static block so that we can have access on its creation, like exception handling. In this way also, object is created at the time of class loading. It can be used when there is a chance of exceptions in creating object with eager initialization.
Pros:Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible.
Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible.
Very simple to implement.
May lead to resource wastage. Because instance of class is created always, whether it is required or not.
CPU time is also wasted in creation of instance if it is not required.
Exception handling is not possible.
Using static block: This is also a sub part of Eager initialization. The only difference is object is created in a static block so that we can have access on its creation, like exception handling. In this way also, object is created at the time of class loading. It can be used when there is a chance of exceptions in creating object with eager initialization.
JAVA
// Java code to create singleton class// Using Static blockpublic class GFG{ // public instance public static GFG instance; private GFG() { // private constructor }static { // static block to initialize instance instance = new GFG(); }}
Pros:Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created. To make sure that class cannot be instantiated in any other way, constructor is made final. As object is created with in a method, it ensures that object will not be created until and unless it is required. Instance is kept private so that no one can access it directly. It can be used in a single threaded environment because multiple threads can break singleton property because they can access get instance method simultaneously and create multiple objects.
Pros:Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.
Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.
Very simple to implement.
No need to implement getInstance() method. Instance can be accessed directly.
Exceptions can be handled in static block.
May lead to resource wastage. Because instance of class is created always, whether it is required or not.
CPU time is also wasted in creation of instance if it is not required.
Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created. To make sure that class cannot be instantiated in any other way, constructor is made final. As object is created with in a method, it ensures that object will not be created until and unless it is required. Instance is kept private so that no one can access it directly. It can be used in a single threaded environment because multiple threads can break singleton property because they can access get instance method simultaneously and create multiple objects.
JAVA
//Java Code to create singleton class// With Lazy initializationpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } //method to return instance of class public static GFG getInstance() { if (instance == null) { // if instance is null, initialize instance = new GFG(); } return instance; }}
Pros:Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property.Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously.
Pros:Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property.
Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property.
Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.
Exception handling is also possible in method.
Every time a condition of null has to be checked.
instance can’t be accessed directly.
In multithreaded environment, it may break singleton property.
Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously.
JAVA
// Java program to create Thread Safe// Singleton classpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } //synchronized method to control simultaneous access synchronized public static GFG getInstance() { if (instance == null) { // if instance is null, initialize instance = new GFG(); } return instance; }}
Pros:Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.Lazy initialization with Double check locking: In this mechanism, we overcome the overhead problem of synchronized code. In this method, getInstance is not synchronized but the block which creates instance is synchronized so that minimum number of threads have to wait and that’s only for first time.
Pros:Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.
Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.
Lazy initialization is possible.
It is also thread safe.
getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.
Lazy initialization with Double check locking: In this mechanism, we overcome the overhead problem of synchronized code. In this method, getInstance is not synchronized but the block which creates instance is synchronized so that minimum number of threads have to wait and that’s only for first time.
JAVA
// Java code to explain double check lockingpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } public static GFG getInstance() { if (instance == null) { //synchronized block to remove overhead synchronized (GFG.class) { if(instance==null) { // if instance is null, initialize instance = new GFG(); } } } return instance; }}
Pros:Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance.Bill Pugh Singleton Implementation: Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton.
Pros:Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance.
Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance.
Lazy initialization is possible.
It is also thread safe.
Performance overhead gets reduced because of synchronized keyword.
First time, it can affect performance.
Bill Pugh Singleton Implementation: Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton.
JAVA
// Java code for Bill Pugh Singleton Implementationpublic class GFG{ private GFG() { // private constructor } // Inner class to provide instance of class private static class BillPughSingleton { private static final GFG INSTANCE = new GFG(); } public static GFG getInstance() { return BillPughSingleton.INSTANCE; }}
When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class. Inner class is created only when getInstance() method is called. So it may seem like eager initialization but it is lazy initialization. This is the most widely used approach as it doesn’t use synchronization.
When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class. Inner class is created only when getInstance() method is called. So it may seem like eager initialization but it is lazy initialization. This is the most widely used approach as it doesn’t use synchronization.
When to use What
Eager initialization is easy to implement but it may cause resource and CPU time wastage. Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class.By using Static block in Eager initialization we can provide exception handling and also can control over instance.Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages.
Eager initialization is easy to implement but it may cause resource and CPU time wastage. Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class.
By using Static block in Eager initialization we can provide exception handling and also can control over instance.
Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism.
Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages.
This article is contributed by Vishal Garg. 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.
Pawankumar76
Sachin Araballi
Sushil Yadav
arorakashish0911
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Factory method design pattern in Java
Unified Modeling Language (UML) | An Introduction
Builder Design Pattern
MVC Design Pattern
Unified Modeling Language (UML) | Activity Diagrams
Unified Modeling Language (UML) | State Diagrams
Observer Pattern | Set 1 (Introduction)
Introduction of Programming Paradigms
Abstract Factory Pattern | [
{
"code": null,
"e": 24884,
"s": 24856,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 25382,
"s": 24884,
"text": "In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your use, simplicity and removed bottlenecks. There are many ways this can be done in Java. All these ways differs in their implementation of the pattern, but in the end, they all achieve the same end result of a single instance. "
},
{
"code": null,
"e": 25754,
"s": 25382,
"text": "Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time. "
},
{
"code": null,
"e": 26126,
"s": 25754,
"text": "Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time. "
},
{
"code": null,
"e": 26131,
"s": 26126,
"text": "JAVA"
},
{
"code": "// Java code to create singleton class by// Eager Initializationpublic class GFG{ // public instance initialized when loading the class private static final GFG instance = new GFG(); private GFG() { // private constructor } public static GFG getInstance(){ return instance; }}",
"e": 26428,
"s": 26131,
"text": null
},
{
"code": null,
"e": 27031,
"s": 26428,
"text": "Pros:Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible.Using static block: This is also a sub part of Eager initialization. The only difference is object is created in a static block so that we can have access on its creation, like exception handling. In this way also, object is created at the time of class loading. It can be used when there is a chance of exceptions in creating object with eager initialization. "
},
{
"code": null,
"e": 27272,
"s": 27031,
"text": "Pros:Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible."
},
{
"code": null,
"e": 27508,
"s": 27272,
"text": "Very simple to implement.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Exception handling is not possible."
},
{
"code": null,
"e": 27534,
"s": 27508,
"text": "Very simple to implement."
},
{
"code": null,
"e": 27640,
"s": 27534,
"text": "May lead to resource wastage. Because instance of class is created always, whether it is required or not."
},
{
"code": null,
"e": 27711,
"s": 27640,
"text": "CPU time is also wasted in creation of instance if it is not required."
},
{
"code": null,
"e": 27747,
"s": 27711,
"text": "Exception handling is not possible."
},
{
"code": null,
"e": 28110,
"s": 27747,
"text": "Using static block: This is also a sub part of Eager initialization. The only difference is object is created in a static block so that we can have access on its creation, like exception handling. In this way also, object is created at the time of class loading. It can be used when there is a chance of exceptions in creating object with eager initialization. "
},
{
"code": null,
"e": 28115,
"s": 28110,
"text": "JAVA"
},
{
"code": "// Java code to create singleton class// Using Static blockpublic class GFG{ // public instance public static GFG instance; private GFG() { // private constructor }static { // static block to initialize instance instance = new GFG(); }}",
"e": 28369,
"s": 28115,
"text": null
},
{
"code": null,
"e": 29451,
"s": 28369,
"text": "Pros:Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required.Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created. To make sure that class cannot be instantiated in any other way, constructor is made final. As object is created with in a method, it ensures that object will not be created until and unless it is required. Instance is kept private so that no one can access it directly. It can be used in a single threaded environment because multiple threads can break singleton property because they can access get instance method simultaneously and create multiple objects. "
},
{
"code": null,
"e": 29776,
"s": 29451,
"text": "Pros:Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required."
},
{
"code": null,
"e": 30096,
"s": 29776,
"text": "Very simple to implement.No need to implement getInstance() method. Instance can be accessed directly.Exceptions can be handled in static block.May lead to resource wastage. Because instance of class is created always, whether it is required or not.CPU time is also wasted in creation of instance if it is not required."
},
{
"code": null,
"e": 30122,
"s": 30096,
"text": "Very simple to implement."
},
{
"code": null,
"e": 30200,
"s": 30122,
"text": "No need to implement getInstance() method. Instance can be accessed directly."
},
{
"code": null,
"e": 30243,
"s": 30200,
"text": "Exceptions can be handled in static block."
},
{
"code": null,
"e": 30349,
"s": 30243,
"text": "May lead to resource wastage. Because instance of class is created always, whether it is required or not."
},
{
"code": null,
"e": 30420,
"s": 30349,
"text": "CPU time is also wasted in creation of instance if it is not required."
},
{
"code": null,
"e": 31178,
"s": 30420,
"text": "Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created. To make sure that class cannot be instantiated in any other way, constructor is made final. As object is created with in a method, it ensures that object will not be created until and unless it is required. Instance is kept private so that no one can access it directly. It can be used in a single threaded environment because multiple threads can break singleton property because they can access get instance method simultaneously and create multiple objects. "
},
{
"code": null,
"e": 31183,
"s": 31178,
"text": "JAVA"
},
{
"code": "//Java Code to create singleton class// With Lazy initializationpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } //method to return instance of class public static GFG getInstance() { if (instance == null) { // if instance is null, initialize instance = new GFG(); } return instance; }}",
"e": 31629,
"s": 31183,
"text": null
},
{
"code": null,
"e": 32198,
"s": 31629,
"text": "Pros:Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property.Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously. "
},
{
"code": null,
"e": 32495,
"s": 32198,
"text": "Pros:Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property."
},
{
"code": null,
"e": 32787,
"s": 32495,
"text": "Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.Exception handling is also possible in method.Every time a condition of null has to be checked.instance can’t be accessed directly.In multithreaded environment, it may break singleton property."
},
{
"code": null,
"e": 32886,
"s": 32787,
"text": "Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time."
},
{
"code": null,
"e": 32933,
"s": 32886,
"text": "Exception handling is also possible in method."
},
{
"code": null,
"e": 32983,
"s": 32933,
"text": "Every time a condition of null has to be checked."
},
{
"code": null,
"e": 33020,
"s": 32983,
"text": "instance can’t be accessed directly."
},
{
"code": null,
"e": 33083,
"s": 33020,
"text": "In multithreaded environment, it may break singleton property."
},
{
"code": null,
"e": 33356,
"s": 33083,
"text": "Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously. "
},
{
"code": null,
"e": 33361,
"s": 33356,
"text": "JAVA"
},
{
"code": "// Java program to create Thread Safe// Singleton classpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } //synchronized method to control simultaneous access synchronized public static GFG getInstance() { if (instance == null) { // if instance is null, initialize instance = new GFG(); } return instance; }}",
"e": 33826,
"s": 33361,
"text": null
},
{
"code": null,
"e": 34306,
"s": 33826,
"text": "Pros:Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.Lazy initialization with Double check locking: In this mechanism, we overcome the overhead problem of synchronized code. In this method, getInstance is not synchronized but the block which creates instance is synchronized so that minimum number of threads have to wait and that’s only for first time. "
},
{
"code": null,
"e": 34485,
"s": 34306,
"text": "Pros:Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously."
},
{
"code": null,
"e": 34659,
"s": 34485,
"text": "Lazy initialization is possible.It is also thread safe.getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously."
},
{
"code": null,
"e": 34692,
"s": 34659,
"text": "Lazy initialization is possible."
},
{
"code": null,
"e": 34716,
"s": 34692,
"text": "It is also thread safe."
},
{
"code": null,
"e": 34835,
"s": 34716,
"text": "getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously."
},
{
"code": null,
"e": 35137,
"s": 34835,
"text": "Lazy initialization with Double check locking: In this mechanism, we overcome the overhead problem of synchronized code. In this method, getInstance is not synchronized but the block which creates instance is synchronized so that minimum number of threads have to wait and that’s only for first time. "
},
{
"code": null,
"e": 35142,
"s": 35137,
"text": "JAVA"
},
{
"code": "// Java code to explain double check lockingpublic class GFG{ // private instance, so that it can be // accessed by only by getInstance() method private static GFG instance; private GFG() { // private constructor } public static GFG getInstance() { if (instance == null) { //synchronized block to remove overhead synchronized (GFG.class) { if(instance==null) { // if instance is null, initialize instance = new GFG(); } } } return instance; }}",
"e": 35678,
"s": 35142,
"text": null
},
{
"code": null,
"e": 36092,
"s": 35678,
"text": "Pros:Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance.Bill Pugh Singleton Implementation: Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton. "
},
{
"code": null,
"e": 36257,
"s": 36092,
"text": "Pros:Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance."
},
{
"code": null,
"e": 36417,
"s": 36257,
"text": "Lazy initialization is possible.It is also thread safe.Performance overhead gets reduced because of synchronized keyword.First time, it can affect performance."
},
{
"code": null,
"e": 36450,
"s": 36417,
"text": "Lazy initialization is possible."
},
{
"code": null,
"e": 36474,
"s": 36450,
"text": "It is also thread safe."
},
{
"code": null,
"e": 36541,
"s": 36474,
"text": "Performance overhead gets reduced because of synchronized keyword."
},
{
"code": null,
"e": 36580,
"s": 36541,
"text": "First time, it can affect performance."
},
{
"code": null,
"e": 36830,
"s": 36580,
"text": "Bill Pugh Singleton Implementation: Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton. "
},
{
"code": null,
"e": 36835,
"s": 36830,
"text": "JAVA"
},
{
"code": "// Java code for Bill Pugh Singleton Implementationpublic class GFG{ private GFG() { // private constructor } // Inner class to provide instance of class private static class BillPughSingleton { private static final GFG INSTANCE = new GFG(); } public static GFG getInstance() { return BillPughSingleton.INSTANCE; }}",
"e": 37173,
"s": 36835,
"text": null
},
{
"code": null,
"e": 37501,
"s": 37173,
"text": "When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class. Inner class is created only when getInstance() method is called. So it may seem like eager initialization but it is lazy initialization. This is the most widely used approach as it doesn’t use synchronization."
},
{
"code": null,
"e": 37829,
"s": 37501,
"text": "When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class. Inner class is created only when getInstance() method is called. So it may seem like eager initialization but it is lazy initialization. This is the most widely used approach as it doesn’t use synchronization."
},
{
"code": null,
"e": 37848,
"s": 37831,
"text": "When to use What"
},
{
"code": null,
"e": 38496,
"s": 37850,
"text": "Eager initialization is easy to implement but it may cause resource and CPU time wastage. Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class.By using Static block in Eager initialization we can provide exception handling and also can control over instance.Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages."
},
{
"code": null,
"e": 38716,
"s": 38496,
"text": "Eager initialization is easy to implement but it may cause resource and CPU time wastage. Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class."
},
{
"code": null,
"e": 38832,
"s": 38716,
"text": "By using Static block in Eager initialization we can provide exception handling and also can control over instance."
},
{
"code": null,
"e": 39000,
"s": 38832,
"text": "Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. "
},
{
"code": null,
"e": 39145,
"s": 39000,
"text": "Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages."
},
{
"code": null,
"e": 39565,
"s": 39145,
"text": "This article is contributed by Vishal Garg. 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": 39578,
"s": 39565,
"text": "Pawankumar76"
},
{
"code": null,
"e": 39594,
"s": 39578,
"text": "Sachin Araballi"
},
{
"code": null,
"e": 39607,
"s": 39594,
"text": "Sushil Yadav"
},
{
"code": null,
"e": 39624,
"s": 39607,
"text": "arorakashish0911"
},
{
"code": null,
"e": 39639,
"s": 39624,
"text": "Design Pattern"
},
{
"code": null,
"e": 39737,
"s": 39639,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39746,
"s": 39737,
"text": "Comments"
},
{
"code": null,
"e": 39759,
"s": 39746,
"text": "Old Comments"
},
{
"code": null,
"e": 39808,
"s": 39759,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 39846,
"s": 39808,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 39896,
"s": 39846,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 39919,
"s": 39896,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 39938,
"s": 39919,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 39990,
"s": 39938,
"text": "Unified Modeling Language (UML) | Activity Diagrams"
},
{
"code": null,
"e": 40039,
"s": 39990,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 40079,
"s": 40039,
"text": "Observer Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 40117,
"s": 40079,
"text": "Introduction of Programming Paradigms"
}
] |
array_merge_recursive() function in PHP | The array_merge_recursive() function merges one or more arrays into one array recursively. The difference between this function and array_merge() is that if two or more elements have the same key, the array_merge_recursive() function forms the value as an array. In this case, array_merge() function considers the last one.
array_merge_recursive(arr1, arr2, arr3, ...)
arr1 − Initial array to merge
arr1 − Initial array to merge
arr2 − Another array
arr2 − Another array
arr3 − Another array
arr3 − Another array
The array_merge_recursive() function returns an array in which the elements of all arrays passed in parameters are merged.
The following is an example that merges two array with a key repeated in the second array. In this case the array_merge_recursive() function forms the value as an array.
Live Demo
<?php
$arr1 = array("p"=>"one","q"=>"two");
$arr2 = array("q"=>"three","r"=>"four");
print_r(array_merge_recursive($arr1,$arr2));
?>
Array
(
[p] => one
[q] => Array
(
[0] => two
[1] => three
)
[r] => four
) | [
{
"code": null,
"e": 1386,
"s": 1062,
"text": "The array_merge_recursive() function merges one or more arrays into one array recursively. The difference between this function and array_merge() is that if two or more elements have the same key, the array_merge_recursive() function forms the value as an array. In this case, array_merge() function considers the last one."
},
{
"code": null,
"e": 1432,
"s": 1386,
"text": "array_merge_recursive(arr1, arr2, arr3, ...)\n"
},
{
"code": null,
"e": 1462,
"s": 1432,
"text": "arr1 − Initial array to merge"
},
{
"code": null,
"e": 1492,
"s": 1462,
"text": "arr1 − Initial array to merge"
},
{
"code": null,
"e": 1513,
"s": 1492,
"text": "arr2 − Another array"
},
{
"code": null,
"e": 1534,
"s": 1513,
"text": "arr2 − Another array"
},
{
"code": null,
"e": 1555,
"s": 1534,
"text": "arr3 − Another array"
},
{
"code": null,
"e": 1576,
"s": 1555,
"text": "arr3 − Another array"
},
{
"code": null,
"e": 1699,
"s": 1576,
"text": "The array_merge_recursive() function returns an array in which the elements of all arrays passed in parameters are merged."
},
{
"code": null,
"e": 1869,
"s": 1699,
"text": "The following is an example that merges two array with a key repeated in the second array. In this case the array_merge_recursive() function forms the value as an array."
},
{
"code": null,
"e": 1880,
"s": 1869,
"text": " Live Demo"
},
{
"code": null,
"e": 2022,
"s": 1880,
"text": "<?php\n $arr1 = array(\"p\"=>\"one\",\"q\"=>\"two\");\n $arr2 = array(\"q\"=>\"three\",\"r\"=>\"four\");\n print_r(array_merge_recursive($arr1,$arr2));\n?>"
},
{
"code": null,
"e": 2139,
"s": 2022,
"text": "Array\n(\n [p] => one\n [q] => Array\n (\n [0] => two\n [1] => three\n )\n [r] => four\n)\n"
}
] |
DAX Date & Time - WEEKNUM function | Returns the week number for the given date and year according to the return_type value. The week number indicates where the week falls numerically within a year.
WEEKNUM (<date>, [<return_type>])
date
Date in datetime format.
return_type
A number that determines the return value −
1 - Week begins on Sunday. Weekdays are numbered 1 through 7.
2 - Week begins on Monday. Weekdays are numbered 1 through 7.
If omitted, the default value is 1.
An integer, in the range 1 to 53.
DAX uses datetime data type to work with dates and times.
If the source data is in a different format, DAX implicitly converts the data to datetime to perform calculations.
By default, the WEEKNUM function uses a calendar convention in which the week containing January 1 is considered to be the first week of the year.
Note − The ISO 8601 calendar standard, widely used in Europe, defines the first week as the one with the majority of days (four or more) falling in the New Year.
This means that for years in which there are three days or less in the first week of January, the WEEKNUM function returns week numbers that are different from the ISO 8601 definition.
= WEEKNUM ("Oct 2, 2016", 1) returns 41.
= WEEKNUM ("Dec 31, 2016", 1) returns 53.
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": 2163,
"s": 2001,
"text": "Returns the week number for the given date and year according to the return_type value. The week number indicates where the week falls numerically within a year."
},
{
"code": null,
"e": 2199,
"s": 2163,
"text": "WEEKNUM (<date>, [<return_type>]) \n"
},
{
"code": null,
"e": 2204,
"s": 2199,
"text": "date"
},
{
"code": null,
"e": 2229,
"s": 2204,
"text": "Date in datetime format."
},
{
"code": null,
"e": 2241,
"s": 2229,
"text": "return_type"
},
{
"code": null,
"e": 2285,
"s": 2241,
"text": "A number that determines the return value −"
},
{
"code": null,
"e": 2347,
"s": 2285,
"text": "1 - Week begins on Sunday. Weekdays are numbered 1 through 7."
},
{
"code": null,
"e": 2409,
"s": 2347,
"text": "2 - Week begins on Monday. Weekdays are numbered 1 through 7."
},
{
"code": null,
"e": 2445,
"s": 2409,
"text": "If omitted, the default value is 1."
},
{
"code": null,
"e": 2479,
"s": 2445,
"text": "An integer, in the range 1 to 53."
},
{
"code": null,
"e": 2537,
"s": 2479,
"text": "DAX uses datetime data type to work with dates and times."
},
{
"code": null,
"e": 2652,
"s": 2537,
"text": "If the source data is in a different format, DAX implicitly converts the data to datetime to perform calculations."
},
{
"code": null,
"e": 2799,
"s": 2652,
"text": "By default, the WEEKNUM function uses a calendar convention in which the week containing January 1 is considered to be the first week of the year."
},
{
"code": null,
"e": 2961,
"s": 2799,
"text": "Note − The ISO 8601 calendar standard, widely used in Europe, defines the first week as the one with the majority of days (four or more) falling in the New Year."
},
{
"code": null,
"e": 3146,
"s": 2961,
"text": "This means that for years in which there are three days or less in the first week of January, the WEEKNUM function returns week numbers that are different from the ISO 8601 definition."
},
{
"code": null,
"e": 3231,
"s": 3146,
"text": "= WEEKNUM (\"Oct 2, 2016\", 1) returns 41. \n= WEEKNUM (\"Dec 31, 2016\", 1) returns 53. "
},
{
"code": null,
"e": 3266,
"s": 3231,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3280,
"s": 3266,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3313,
"s": 3280,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3327,
"s": 3313,
"text": " Randy Minder"
},
{
"code": null,
"e": 3362,
"s": 3327,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3376,
"s": 3362,
"text": " Randy Minder"
},
{
"code": null,
"e": 3383,
"s": 3376,
"text": " Print"
},
{
"code": null,
"e": 3394,
"s": 3383,
"text": " Add Notes"
}
] |
Asynchronous Patterns in Node.js - GeeksforGeeks | 14 Aug, 2021
Since the node is a language that runs on a single thread which in turn uses multiple threads in the background. A code in node.js should be nonblocking because if a particular line of code, for ex: Reading a large document can halt the execution of all the lines of code ahead of it which is not a good practice.That’s why to implement functionality that could take some time, is being done in an asynchronous way which takes the execution of that particular part out of the main event loop and the program runs normally.
There are three patterns of asynchronous:
CallbacksPromisesAsync-await
Callbacks
Promises
Async-await
1. Callbacks: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
This function is called when the asynchronous operation is completed. Mainly the body of callback function contains the asynchronous operation.
The most common form is “error-first” callback in which if the parent function and takes error parameter, if there is an error then it executes the error part otherwise execute the other part.
Filename: index.js
javascript
arr = ["Geeks", "Geeks", "pop", "Geeks"]console.log("calling") var value = arr.filter(function(element) { if(element != "pop") return element}); console.log("called")console.log(value)
Run index.js file using the following command:
node index.js
Output:
calling
called
[ 'Geeks', 'Geeks', 'Geeks' ]
Generally, callbacks are not used because all the code after an asynchronous operation is nested inside a function. More asynchronous operations mean more indentation which ultimately results in unreadability and confusion and the problem becomes more and more significant by larger functions. It is also referred to as “Pyramids of deaths”.
2. Promises: A promise is a proxy for a state or value that is unknown for the moment when the promise is created but could be determined in the near future. This lets asynchronous methods return a promise to supply value at some point in the future.
Basic Syntax:
const promise = new Promise(function)
They have methods such as:
prototype.then()
prototype.catch()
The .then() is used to specify what to do if the promise is fulfilled and .catch() specifies what to do if the promise is not fulfilled.
Filename: index.js
javascript
const multiplication = (numberOne, numberTwo) => { return new Promise((resolve, reject) => { setTimeout(() => { // Checking if any number is negative or not if (numberOne < 0 || numberTwo < 0) { // If everything is not fine return reject("Only Positive number allowed") } // If everything is fine resolve(numberOne * numberTwo) }, 1000) }) } // Call for positive numbers multiplication(5, 3).then((product) => { console.log("The product is:", product) }).catch((error) => { console.log(error) }) // Call for negative numbersmultiplication(5, -3).then((product) => { console.log("The product is:", product)}).catch((error) => { console.log(error)})
Run index.js file using the following command:
node index.js
Output:
The product is: 15
Only Positive number allowed
3. Async-await: It is a method in which parent function is declared with the async keyword and inside it await keyword is permitted. The async and await keyword enables asynchronous, promise-based behavior so that code could be written a lot cleaner and avoid promise chains.Basic syntax:
async function name(params) {
const result = await waitforfunction()
}
The async functions can contain more than one await expression. This await keyword is used to wait for the promise either to be fulfilled or rejected.
Filename: index.js
javascript
function resolvelater() { return new Promise(resolve => { setTimeout(() => { resolve('GeeksforGeeks'); }, 2000); });} async function waitforGeeksforGeeks() { console.log('calling'); const result = await resolvelater(); console.log(result);} waitforGeeksforGeeks()
Run index.js file using the following command:
node index.js
Output:
calling
GeeksforGeeks
varshagumber28
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26377,
"s": 26349,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 26900,
"s": 26377,
"text": "Since the node is a language that runs on a single thread which in turn uses multiple threads in the background. A code in node.js should be nonblocking because if a particular line of code, for ex: Reading a large document can halt the execution of all the lines of code ahead of it which is not a good practice.That’s why to implement functionality that could take some time, is being done in an asynchronous way which takes the execution of that particular part out of the main event loop and the program runs normally."
},
{
"code": null,
"e": 26942,
"s": 26900,
"text": "There are three patterns of asynchronous:"
},
{
"code": null,
"e": 26971,
"s": 26942,
"text": "CallbacksPromisesAsync-await"
},
{
"code": null,
"e": 26981,
"s": 26971,
"text": "Callbacks"
},
{
"code": null,
"e": 26990,
"s": 26981,
"text": "Promises"
},
{
"code": null,
"e": 27002,
"s": 26990,
"text": "Async-await"
},
{
"code": null,
"e": 27187,
"s": 27002,
"text": "1. Callbacks: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."
},
{
"code": null,
"e": 27331,
"s": 27187,
"text": "This function is called when the asynchronous operation is completed. Mainly the body of callback function contains the asynchronous operation."
},
{
"code": null,
"e": 27524,
"s": 27331,
"text": "The most common form is “error-first” callback in which if the parent function and takes error parameter, if there is an error then it executes the error part otherwise execute the other part."
},
{
"code": null,
"e": 27544,
"s": 27524,
"text": "Filename: index.js "
},
{
"code": null,
"e": 27555,
"s": 27544,
"text": "javascript"
},
{
"code": "arr = [\"Geeks\", \"Geeks\", \"pop\", \"Geeks\"]console.log(\"calling\") var value = arr.filter(function(element) { if(element != \"pop\") return element}); console.log(\"called\")console.log(value)",
"e": 27748,
"s": 27555,
"text": null
},
{
"code": null,
"e": 27797,
"s": 27748,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 27811,
"s": 27797,
"text": "node index.js"
},
{
"code": null,
"e": 27820,
"s": 27811,
"text": "Output: "
},
{
"code": null,
"e": 27865,
"s": 27820,
"text": "calling\ncalled\n[ 'Geeks', 'Geeks', 'Geeks' ]"
},
{
"code": null,
"e": 28208,
"s": 27865,
"text": "Generally, callbacks are not used because all the code after an asynchronous operation is nested inside a function. More asynchronous operations mean more indentation which ultimately results in unreadability and confusion and the problem becomes more and more significant by larger functions. It is also referred to as “Pyramids of deaths”. "
},
{
"code": null,
"e": 28459,
"s": 28208,
"text": "2. Promises: A promise is a proxy for a state or value that is unknown for the moment when the promise is created but could be determined in the near future. This lets asynchronous methods return a promise to supply value at some point in the future."
},
{
"code": null,
"e": 28474,
"s": 28459,
"text": "Basic Syntax: "
},
{
"code": null,
"e": 28512,
"s": 28474,
"text": "const promise = new Promise(function)"
},
{
"code": null,
"e": 28539,
"s": 28512,
"text": "They have methods such as:"
},
{
"code": null,
"e": 28556,
"s": 28539,
"text": "prototype.then()"
},
{
"code": null,
"e": 28575,
"s": 28556,
"text": "prototype.catch() "
},
{
"code": null,
"e": 28712,
"s": 28575,
"text": "The .then() is used to specify what to do if the promise is fulfilled and .catch() specifies what to do if the promise is not fulfilled."
},
{
"code": null,
"e": 28732,
"s": 28712,
"text": "Filename: index.js "
},
{
"code": null,
"e": 28743,
"s": 28732,
"text": "javascript"
},
{
"code": "const multiplication = (numberOne, numberTwo) => { return new Promise((resolve, reject) => { setTimeout(() => { // Checking if any number is negative or not if (numberOne < 0 || numberTwo < 0) { // If everything is not fine return reject(\"Only Positive number allowed\") } // If everything is fine resolve(numberOne * numberTwo) }, 1000) }) } // Call for positive numbers multiplication(5, 3).then((product) => { console.log(\"The product is:\", product) }).catch((error) => { console.log(error) }) // Call for negative numbersmultiplication(5, -3).then((product) => { console.log(\"The product is:\", product)}).catch((error) => { console.log(error)})",
"e": 29505,
"s": 28743,
"text": null
},
{
"code": null,
"e": 29554,
"s": 29505,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 29568,
"s": 29554,
"text": "node index.js"
},
{
"code": null,
"e": 29578,
"s": 29568,
"text": "Output: "
},
{
"code": null,
"e": 29626,
"s": 29578,
"text": "The product is: 15\nOnly Positive number allowed"
},
{
"code": null,
"e": 29916,
"s": 29626,
"text": "3. Async-await: It is a method in which parent function is declared with the async keyword and inside it await keyword is permitted. The async and await keyword enables asynchronous, promise-based behavior so that code could be written a lot cleaner and avoid promise chains.Basic syntax: "
},
{
"code": null,
"e": 29990,
"s": 29916,
"text": "async function name(params) {\n const result = await waitforfunction()\n} "
},
{
"code": null,
"e": 30141,
"s": 29990,
"text": "The async functions can contain more than one await expression. This await keyword is used to wait for the promise either to be fulfilled or rejected."
},
{
"code": null,
"e": 30161,
"s": 30141,
"text": "Filename: index.js "
},
{
"code": null,
"e": 30172,
"s": 30161,
"text": "javascript"
},
{
"code": "function resolvelater() { return new Promise(resolve => { setTimeout(() => { resolve('GeeksforGeeks'); }, 2000); });} async function waitforGeeksforGeeks() { console.log('calling'); const result = await resolvelater(); console.log(result);} waitforGeeksforGeeks()",
"e": 30452,
"s": 30172,
"text": null
},
{
"code": null,
"e": 30501,
"s": 30452,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 30515,
"s": 30501,
"text": "node index.js"
},
{
"code": null,
"e": 30524,
"s": 30515,
"text": "Output: "
},
{
"code": null,
"e": 30546,
"s": 30524,
"text": "calling\nGeeksforGeeks"
},
{
"code": null,
"e": 30561,
"s": 30546,
"text": "varshagumber28"
},
{
"code": null,
"e": 30574,
"s": 30561,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 30581,
"s": 30574,
"text": "Picked"
},
{
"code": null,
"e": 30589,
"s": 30581,
"text": "Node.js"
},
{
"code": null,
"e": 30606,
"s": 30589,
"text": "Web Technologies"
},
{
"code": null,
"e": 30704,
"s": 30606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30774,
"s": 30704,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 30799,
"s": 30774,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 30838,
"s": 30799,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 30860,
"s": 30838,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 30887,
"s": 30860,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 30927,
"s": 30887,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30972,
"s": 30927,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31015,
"s": 30972,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31065,
"s": 31015,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Octet Class in JavaTuples - GeeksforGeeks | 04 Aug, 2021
A Octet is a Tuple from JavaTuples library that deals with 3 elements. Since this Octet is a generic class, it can hold any type of value in it.Since Octet is a Tuple, hence it also has all the characteristics of JavaTuples:
They are Typesafe
They are Immutable
They are Iterable
They are Serializable
They are Comparable (implements Comparable<Tuple>)
They implement equals() and hashCode()
They also implement toString()
Class Declaration
public final class Octet<A, B, C, D, E, F, G, H> extends Tuple
implements IValue0<A>, IValue1<B>, IValue2<C>, IValue3<D>, IValue4<E>,
IValue5<F, IValue6<G, IValue7<H>
Class hierarchy
Object
↳ org.javatuples.Tuple
↳ org.javatuples.Octet<A, B, C, D, E, F, G, H>
Creating Octet Tuple
From Constructor:Syntax:
Octet<A, B, C, D, E, F, G, H> octet =
new Octet<A, B, C, D, E, F, G, H>
(value1, value2, value3, value4, value5, value6, value7, value8);
Example:
Java
// Below is a Java program to create// a Octet tuple from Constructor import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet); }}
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
Octet.with(value1, value2, value3, value4, value5, value6, value7, value8);
Example:
Java
// Below is a Java program to create// a Octet tuple from with() method import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet); }}
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
Octet.fromCollection(collectionWith_8_value);
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
Octet.fromArray(arrayWith_8_value);
Example:
Java
// Below is a Java program to create// a Octet tuple from Collection import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { // Creating Octet from List List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); list.add(8); Octet<Integer, Integer, Integer, Integer, Integer, Integer, Integer> octet = Octet.fromCollection(list); // Creating Octet from Array Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 }; Octet<Integer, Integer, Integer, Integer, Integer, Integer, Integer> otherOctet = Octet.fromArray(arr); System.out.println(octet); System.out.println(otherOctet); }}
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
Getting ValueThe getValueX() method can be used to fetch the value in a Tuple at index X. The indexing in Tuples start with 0. Hence the value at index X represents the value at position X+1.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
new Octet<type1, type2, type3, type4, type5, type6, type7>
(value1, value2, value3, value4, value5, value6, value7, value8);
type1 val1 = octet.getValue0();
Example:
Java
// Below is a Java program to get// a Octet value import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet.getValue0()); System.out.println(octet.getValue2()); }}
Output:
1
3
Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
new Octet<type1, type2, type3, type4, type5, type6, type7>
(value1, value2, value3, value4, value5, value6, value7, value8);
Octet<type1, type2, type3, type4, type5, type6, type7>
otherOctet = octet.setAtX(value);
Example:
Java
// Below is a Java program to set// a Octet value import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> otherOctet = octet.setAt3(40); System.out.println(otherOctet); }}
Output:
[1, 2, 3, 40, 5, 6, 7, 8]
Adding a value
Adding a value can be done with the help of addAtX() method, where X represent the index at which the value is to be added. This method returns a Tuple of element one more than the called Tuple.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
new Octet<type1, type2, type3, type4, type5, type6, type7>
(value1, value2, value3, value4, value5, value6, value7, value8);
Octet<type 1, type 2, type 3, type 4, type 5, type 6, type 7> octet =
octet.addAtx(value);
Example:
Java
// Below is a Java program to add// a value import java.util.*;import org.javatuples.Octet;import org.javatuples.Ennead; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); Ennead<Integer, Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> ennead = octet.addAt8(9); System.out.println(ennead); }}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
new Octet<type1, type2, type3, type4, type5, type6, type7>
(value1, value2, value3, value4, value5, value6, value7, value8);
boolean res = octet.contains(value2);
Example:
Java
// Below is a Java program to search// a value in a Octet import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); boolean exist = octet.contains(5); boolean exist1 = octet.contains(false); System.out.println(exist); System.out.println(exist1); }}
Output:
true
false
Iterating through Octet
Since Octet implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays.Syntax:
Octet<type1, type2, type3, type4, type5, type6, type7> octet =
new Octet<type1, type2, type3, type4, type5, type6, type7>
(value1, value2, value3, value4, value5, value6, value7, value8);
for (Object item : octet) {
...
}
Example:
Java
// Below is a Java program to iterate// a Octet import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); for (Object item : octet) System.out.println(item); }}
Output:
1
2
3
4
5
6
7
8
as5853535
JavaTuples
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Reverse a string in Java
Arrays.sort() in Java with examples
Interfaces in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 25517,
"s": 25489,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 25744,
"s": 25517,
"text": "A Octet is a Tuple from JavaTuples library that deals with 3 elements. Since this Octet is a generic class, it can hold any type of value in it.Since Octet is a Tuple, hence it also has all the characteristics of JavaTuples: "
},
{
"code": null,
"e": 25762,
"s": 25744,
"text": "They are Typesafe"
},
{
"code": null,
"e": 25781,
"s": 25762,
"text": "They are Immutable"
},
{
"code": null,
"e": 25799,
"s": 25781,
"text": "They are Iterable"
},
{
"code": null,
"e": 25821,
"s": 25799,
"text": "They are Serializable"
},
{
"code": null,
"e": 25872,
"s": 25821,
"text": "They are Comparable (implements Comparable<Tuple>)"
},
{
"code": null,
"e": 25911,
"s": 25872,
"text": "They implement equals() and hashCode()"
},
{
"code": null,
"e": 25942,
"s": 25911,
"text": "They also implement toString()"
},
{
"code": null,
"e": 25961,
"s": 25942,
"text": " Class Declaration"
},
{
"code": null,
"e": 26173,
"s": 25961,
"text": "public final class Octet<A, B, C, D, E, F, G, H> extends Tuple\nimplements IValue0<A>, IValue1<B>, IValue2<C>, IValue3<D>, IValue4<E>, \n IValue5<F, IValue6<G, IValue7<H>"
},
{
"code": null,
"e": 26190,
"s": 26173,
"text": " Class hierarchy"
},
{
"code": null,
"e": 26275,
"s": 26190,
"text": "Object\n ↳ org.javatuples.Tuple\n ↳ org.javatuples.Octet<A, B, C, D, E, F, G, H>"
},
{
"code": null,
"e": 26297,
"s": 26275,
"text": " Creating Octet Tuple"
},
{
"code": null,
"e": 26324,
"s": 26297,
"text": "From Constructor:Syntax: "
},
{
"code": null,
"e": 26475,
"s": 26324,
"text": "Octet<A, B, C, D, E, F, G, H> octet = \n new Octet<A, B, C, D, E, F, G, H>\n (value1, value2, value3, value4, value5, value6, value7, value8);"
},
{
"code": null,
"e": 26486,
"s": 26475,
"text": "Example: "
},
{
"code": null,
"e": 26491,
"s": 26486,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a Octet tuple from Constructor import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet); }}",
"e": 27152,
"s": 26491,
"text": null
},
{
"code": null,
"e": 27162,
"s": 27152,
"text": "Output: "
},
{
"code": null,
"e": 27187,
"s": 27162,
"text": "[1, 2, 3, 4, 5, 6, 7, 8]"
},
{
"code": null,
"e": 27329,
"s": 27187,
"text": "Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax: "
},
{
"code": null,
"e": 27473,
"s": 27329,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n Octet.with(value1, value2, value3, value4, value5, value6, value7, value8);"
},
{
"code": null,
"e": 27483,
"s": 27473,
"text": "Example: "
},
{
"code": null,
"e": 27488,
"s": 27483,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a Octet tuple from with() method import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet); }}",
"e": 28151,
"s": 27488,
"text": null
},
{
"code": null,
"e": 28161,
"s": 28151,
"text": "Output: "
},
{
"code": null,
"e": 28186,
"s": 28161,
"text": "[1, 2, 3, 4, 5, 6, 7, 8]"
},
{
"code": null,
"e": 28486,
"s": 28186,
"text": "From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax: "
},
{
"code": null,
"e": 28705,
"s": 28486,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n Octet.fromCollection(collectionWith_8_value);\n\nOctet<type1, type2, type3, type4, type5, type6, type7> octet = \n Octet.fromArray(arrayWith_8_value);"
},
{
"code": null,
"e": 28715,
"s": 28705,
"text": "Example: "
},
{
"code": null,
"e": 28720,
"s": 28715,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a Octet tuple from Collection import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { // Creating Octet from List List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); list.add(8); Octet<Integer, Integer, Integer, Integer, Integer, Integer, Integer> octet = Octet.fromCollection(list); // Creating Octet from Array Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 }; Octet<Integer, Integer, Integer, Integer, Integer, Integer, Integer> otherOctet = Octet.fromArray(arr); System.out.println(octet); System.out.println(otherOctet); }}",
"e": 29560,
"s": 28720,
"text": null
},
{
"code": null,
"e": 29570,
"s": 29560,
"text": "Output: "
},
{
"code": null,
"e": 29620,
"s": 29570,
"text": "[1, 2, 3, 4, 5, 6, 7, 8]\n[1, 2, 3, 4, 5, 6, 7, 8]"
},
{
"code": null,
"e": 29821,
"s": 29620,
"text": "Getting ValueThe getValueX() method can be used to fetch the value in a Tuple at index X. The indexing in Tuples start with 0. Hence the value at index X represents the value at position X+1.Syntax: "
},
{
"code": null,
"e": 30055,
"s": 29821,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n new Octet<type1, type2, type3, type4, type5, type6, type7>\n (value1, value2, value3, value4, value5, value6, value7, value8);\n\ntype1 val1 = octet.getValue0();"
},
{
"code": null,
"e": 30065,
"s": 30055,
"text": "Example: "
},
{
"code": null,
"e": 30070,
"s": 30065,
"text": "Java"
},
{
"code": "// Below is a Java program to get// a Octet value import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); System.out.println(octet.getValue0()); System.out.println(octet.getValue2()); }}",
"e": 30769,
"s": 30070,
"text": null
},
{
"code": null,
"e": 30779,
"s": 30769,
"text": "Output: "
},
{
"code": null,
"e": 30783,
"s": 30779,
"text": "1\n3"
},
{
"code": null,
"e": 31009,
"s": 30783,
"text": "Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple.Syntax: "
},
{
"code": null,
"e": 31303,
"s": 31009,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n new Octet<type1, type2, type3, type4, type5, type6, type7>\n (value1, value2, value3, value4, value5, value6, value7, value8);\n\nOctet<type1, type2, type3, type4, type5, type6, type7> \n otherOctet = octet.setAtX(value);"
},
{
"code": null,
"e": 31313,
"s": 31303,
"text": "Example: "
},
{
"code": null,
"e": 31318,
"s": 31313,
"text": "Java"
},
{
"code": "// Below is a Java program to set// a Octet value import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> otherOctet = octet.setAt3(40); System.out.println(otherOctet); }}",
"e": 32091,
"s": 31318,
"text": null
},
{
"code": null,
"e": 32101,
"s": 32091,
"text": "Output: "
},
{
"code": null,
"e": 32127,
"s": 32101,
"text": "[1, 2, 3, 40, 5, 6, 7, 8]"
},
{
"code": null,
"e": 32142,
"s": 32127,
"text": "Adding a value"
},
{
"code": null,
"e": 32346,
"s": 32142,
"text": "Adding a value can be done with the help of addAtX() method, where X represent the index at which the value is to be added. This method returns a Tuple of element one more than the called Tuple.Syntax: "
},
{
"code": null,
"e": 32644,
"s": 32346,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n new Octet<type1, type2, type3, type4, type5, type6, type7>\n (value1, value2, value3, value4, value5, value6, value7, value8);\n\nOctet<type 1, type 2, type 3, type 4, type 5, type 6, type 7> octet = \n octet.addAtx(value);"
},
{
"code": null,
"e": 32654,
"s": 32644,
"text": "Example: "
},
{
"code": null,
"e": 32659,
"s": 32654,
"text": "Java"
},
{
"code": "// Below is a Java program to add// a value import java.util.*;import org.javatuples.Octet;import org.javatuples.Ennead; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); Ennead<Integer, Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> ennead = octet.addAt8(9); System.out.println(ennead); }}",
"e": 33456,
"s": 32659,
"text": null
},
{
"code": null,
"e": 33466,
"s": 33456,
"text": "Output: "
},
{
"code": null,
"e": 33494,
"s": 33466,
"text": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 33647,
"s": 33496,
"text": "An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not.Syntax: "
},
{
"code": null,
"e": 33887,
"s": 33647,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n new Octet<type1, type2, type3, type4, type5, type6, type7>\n (value1, value2, value3, value4, value5, value6, value7, value8);\n\nboolean res = octet.contains(value2);"
},
{
"code": null,
"e": 33897,
"s": 33887,
"text": "Example: "
},
{
"code": null,
"e": 33902,
"s": 33897,
"text": "Java"
},
{
"code": "// Below is a Java program to search// a value in a Octet import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); boolean exist = octet.contains(5); boolean exist1 = octet.contains(false); System.out.println(exist); System.out.println(exist1); }}",
"e": 34676,
"s": 33902,
"text": null
},
{
"code": null,
"e": 34686,
"s": 34676,
"text": "Output: "
},
{
"code": null,
"e": 34697,
"s": 34686,
"text": "true\nfalse"
},
{
"code": null,
"e": 34722,
"s": 34697,
"text": " Iterating through Octet"
},
{
"code": null,
"e": 34862,
"s": 34722,
"text": "Since Octet implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays.Syntax: "
},
{
"code": null,
"e": 35110,
"s": 34862,
"text": "Octet<type1, type2, type3, type4, type5, type6, type7> octet = \n new Octet<type1, type2, type3, type4, type5, type6, type7>\n (value1, value2, value3, value4, value5, value6, value7, value8);\n\nfor (Object item : octet) {\n ...\n}"
},
{
"code": null,
"e": 35120,
"s": 35110,
"text": "Example: "
},
{
"code": null,
"e": 35125,
"s": 35120,
"text": "Java"
},
{
"code": "// Below is a Java program to iterate// a Octet import java.util.*;import org.javatuples.Octet; class GfG { public static void main(String[] args) { Octet<Integer, Integer, Integer.Integer, Integer, Integer, Integer, Integer> octet = Octet.with(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)); for (Object item : octet) System.out.println(item); }}",
"e": 35800,
"s": 35125,
"text": null
},
{
"code": null,
"e": 35810,
"s": 35800,
"text": "Output: "
},
{
"code": null,
"e": 35826,
"s": 35810,
"text": "1\n2\n3\n4\n5\n6\n7\n8"
},
{
"code": null,
"e": 35838,
"s": 35828,
"text": "as5853535"
},
{
"code": null,
"e": 35849,
"s": 35838,
"text": "JavaTuples"
},
{
"code": null,
"e": 35854,
"s": 35849,
"text": "Java"
},
{
"code": null,
"e": 35859,
"s": 35854,
"text": "Java"
},
{
"code": null,
"e": 35957,
"s": 35859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35972,
"s": 35957,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36016,
"s": 35972,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36038,
"s": 36016,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36053,
"s": 36038,
"text": "Stream In Java"
},
{
"code": null,
"e": 36104,
"s": 36053,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 36134,
"s": 36104,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 36159,
"s": 36134,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36195,
"s": 36159,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 36214,
"s": 36195,
"text": "Interfaces in Java"
}
] |
Approximation Algorithms - GeeksforGeeks | 09 May, 2022
Overview :An approximation algorithm is a way of dealing with NP-completeness for an optimization problem. This technique does not guarantee the best solution. The goal of the approximation algorithm is to come as close as possible to the optimal solution in polynomial time. Such algorithms are called approximation algorithms or heuristic algorithms.
Features of Approximation Algorithm : Here, we will discuss the features of the Approximation Algorithm as follows.
An approximation algorithm guarantees to run in polynomial time though it does not guarantee the most effective solution.
An approximation algorithm guarantees to seek out high accuracy and top quality solution(say within 1% of optimum)
Approximation algorithms are used to get an answer near the (optimal) solution of an optimization problem in polynomial time
Performance Ratios for approximation algorithms :Here, we will discuss the performance ratios of the Approximation Algorithm as follows.
Scenario-1 :
Suppose that we are working on an optimization problem in which each potential solution has a cost, and we wish to find a near-optimal solution. Depending on the problem, we may define an optimal solution as one with maximum possible cost or one with minimum possible cost,i.e, the problem can either be a maximization or minimization problem.We say that an algorithm for a problem has an appropriate ratio of P(n) if, for any input size n, the cost C of the solution produced by the algorithm is within a factor of P(n) of the cost C* of an optimal solution as follows.
Suppose that we are working on an optimization problem in which each potential solution has a cost, and we wish to find a near-optimal solution. Depending on the problem, we may define an optimal solution as one with maximum possible cost or one with minimum possible cost,i.e, the problem can either be a maximization or minimization problem.
We say that an algorithm for a problem has an appropriate ratio of P(n) if, for any input size n, the cost C of the solution produced by the algorithm is within a factor of P(n) of the cost C* of an optimal solution as follows.
max(C/C*,C*/C)<=P(n)
Scenario-2 :If an algorithm reaches an approximation ratio of P(n), then we call it a P(n)-approximation algorithm.
For a maximization problem, 0< C < C*, and the ratio of C*/C gives the factor by which the cost of an optimal solution is larger than the cost of the approximate algorithm.
For a minimization problem, 0< C* < C, and the ratio of C/C* gives the factor by which the cost of an approximate solution is larger than the cost of an optimal solution.
Some examples of the Approximation algorithm :Here, we will discuss some examples of the Approximation Algorithm as follows.
The Vertex Cover Problem – In the vertex cover problem, the optimization problem is to find the vertex cover with the fewest vertices, and the approximation problem is to find the vertex cover with few vertices. Travelling Salesman Problem –In the traveling salesperson problem, the optimization problem is to find the shortest cycle, and the approximation problem is to find a short cycle. The Set Covering Problem – This is an optimization problem that models many problems that require resources to be allocated. Here, a logarithmic approximation ratio is used. The Subset Sum Problem – In the Subset sum problem, the optimization problem is to find a subset of {x1,×2,×3...xn} whose sum is as large as possible but not larger than the target value t.
The Vertex Cover Problem – In the vertex cover problem, the optimization problem is to find the vertex cover with the fewest vertices, and the approximation problem is to find the vertex cover with few vertices.
Travelling Salesman Problem –In the traveling salesperson problem, the optimization problem is to find the shortest cycle, and the approximation problem is to find a short cycle.
The Set Covering Problem – This is an optimization problem that models many problems that require resources to be allocated. Here, a logarithmic approximation ratio is used.
The Subset Sum Problem – In the Subset sum problem, the optimization problem is to find a subset of {x1,×2,×3...xn} whose sum is as large as possible but not larger than the target value t.
111arpit1
satejbidvai
Picked
Algorithms
GATE CS
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between Algorithm, Pseudocode and Program
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 26296,
"s": 25943,
"text": "Overview :An approximation algorithm is a way of dealing with NP-completeness for an optimization problem. This technique does not guarantee the best solution. The goal of the approximation algorithm is to come as close as possible to the optimal solution in polynomial time. Such algorithms are called approximation algorithms or heuristic algorithms."
},
{
"code": null,
"e": 26412,
"s": 26296,
"text": "Features of Approximation Algorithm : Here, we will discuss the features of the Approximation Algorithm as follows."
},
{
"code": null,
"e": 26534,
"s": 26412,
"text": "An approximation algorithm guarantees to run in polynomial time though it does not guarantee the most effective solution."
},
{
"code": null,
"e": 26649,
"s": 26534,
"text": "An approximation algorithm guarantees to seek out high accuracy and top quality solution(say within 1% of optimum)"
},
{
"code": null,
"e": 26774,
"s": 26649,
"text": "Approximation algorithms are used to get an answer near the (optimal) solution of an optimization problem in polynomial time"
},
{
"code": null,
"e": 26911,
"s": 26774,
"text": "Performance Ratios for approximation algorithms :Here, we will discuss the performance ratios of the Approximation Algorithm as follows."
},
{
"code": null,
"e": 26924,
"s": 26911,
"text": "Scenario-1 :"
},
{
"code": null,
"e": 27495,
"s": 26924,
"text": "Suppose that we are working on an optimization problem in which each potential solution has a cost, and we wish to find a near-optimal solution. Depending on the problem, we may define an optimal solution as one with maximum possible cost or one with minimum possible cost,i.e, the problem can either be a maximization or minimization problem.We say that an algorithm for a problem has an appropriate ratio of P(n) if, for any input size n, the cost C of the solution produced by the algorithm is within a factor of P(n) of the cost C* of an optimal solution as follows."
},
{
"code": null,
"e": 27839,
"s": 27495,
"text": "Suppose that we are working on an optimization problem in which each potential solution has a cost, and we wish to find a near-optimal solution. Depending on the problem, we may define an optimal solution as one with maximum possible cost or one with minimum possible cost,i.e, the problem can either be a maximization or minimization problem."
},
{
"code": null,
"e": 28067,
"s": 27839,
"text": "We say that an algorithm for a problem has an appropriate ratio of P(n) if, for any input size n, the cost C of the solution produced by the algorithm is within a factor of P(n) of the cost C* of an optimal solution as follows."
},
{
"code": null,
"e": 28088,
"s": 28067,
"text": "max(C/C*,C*/C)<=P(n)"
},
{
"code": null,
"e": 28204,
"s": 28088,
"text": "Scenario-2 :If an algorithm reaches an approximation ratio of P(n), then we call it a P(n)-approximation algorithm."
},
{
"code": null,
"e": 28377,
"s": 28204,
"text": "For a maximization problem, 0< C < C*, and the ratio of C*/C gives the factor by which the cost of an optimal solution is larger than the cost of the approximate algorithm."
},
{
"code": null,
"e": 28548,
"s": 28377,
"text": "For a minimization problem, 0< C* < C, and the ratio of C/C* gives the factor by which the cost of an approximate solution is larger than the cost of an optimal solution."
},
{
"code": null,
"e": 28673,
"s": 28548,
"text": "Some examples of the Approximation algorithm :Here, we will discuss some examples of the Approximation Algorithm as follows."
},
{
"code": null,
"e": 29428,
"s": 28673,
"text": "The Vertex Cover Problem – In the vertex cover problem, the optimization problem is to find the vertex cover with the fewest vertices, and the approximation problem is to find the vertex cover with few vertices. Travelling Salesman Problem –In the traveling salesperson problem, the optimization problem is to find the shortest cycle, and the approximation problem is to find a short cycle. The Set Covering Problem – This is an optimization problem that models many problems that require resources to be allocated. Here, a logarithmic approximation ratio is used. The Subset Sum Problem – In the Subset sum problem, the optimization problem is to find a subset of {x1,×2,×3...xn} whose sum is as large as possible but not larger than the target value t."
},
{
"code": null,
"e": 29641,
"s": 29428,
"text": "The Vertex Cover Problem – In the vertex cover problem, the optimization problem is to find the vertex cover with the fewest vertices, and the approximation problem is to find the vertex cover with few vertices. "
},
{
"code": null,
"e": 29821,
"s": 29641,
"text": "Travelling Salesman Problem –In the traveling salesperson problem, the optimization problem is to find the shortest cycle, and the approximation problem is to find a short cycle. "
},
{
"code": null,
"e": 29996,
"s": 29821,
"text": "The Set Covering Problem – This is an optimization problem that models many problems that require resources to be allocated. Here, a logarithmic approximation ratio is used. "
},
{
"code": null,
"e": 30186,
"s": 29996,
"text": "The Subset Sum Problem – In the Subset sum problem, the optimization problem is to find a subset of {x1,×2,×3...xn} whose sum is as large as possible but not larger than the target value t."
},
{
"code": null,
"e": 30196,
"s": 30186,
"text": "111arpit1"
},
{
"code": null,
"e": 30208,
"s": 30196,
"text": "satejbidvai"
},
{
"code": null,
"e": 30215,
"s": 30208,
"text": "Picked"
},
{
"code": null,
"e": 30226,
"s": 30215,
"text": "Algorithms"
},
{
"code": null,
"e": 30234,
"s": 30226,
"text": "GATE CS"
},
{
"code": null,
"e": 30245,
"s": 30234,
"text": "Algorithms"
},
{
"code": null,
"e": 30343,
"s": 30245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30368,
"s": 30343,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30395,
"s": 30368,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 30429,
"s": 30395,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 30496,
"s": 30429,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 30549,
"s": 30496,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 30569,
"s": 30549,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 30593,
"s": 30569,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30606,
"s": 30593,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 30633,
"s": 30606,
"text": "Types of Operating Systems"
}
] |
Better Logging using Timber Library in Android - GeeksforGeeks | 30 Nov, 2021
In this article, we will build an application in Android to implement a logging utility class that is better than the default Log class of android. For that, we will be using Timber Library which is a small logger with an extensible API. As Android developers, we use a lot of log statements in our projects to generate outputs to test our application at different stages. Logs are of many types like Verbose, Debug, Warn, Info, Error. We use all sorts of Log statements in our application for finding errors and debugging. Once the application is ready to be released we need to remove all the log statements so that the generated APK doesn’t carry any additional application data. To tackle this problem we have several ways:
Condition-based logging
ProGuard
Timber
Using this method we check the level for which the logger is enabled and then log a message to that level. We just have to create a boolean variable in our Application class to check for logging. Use this boolean condition before every log statement in the application and before releasing the application change it to isDebug = false. Below is the code snippet of the Application class.
Java
Kotlin
import android.app.Application; public class LogApplication extends Application { public static boolean checkDebug; @Override public void onCreate() { super.onCreate(); checkDebug = true; }}
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var checkDebug = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) checkDebug = true }}
ProGuard is used to get rid of unused codes. Here we can use it to remove the Log statements in the release build. Add the log methods that you want to strip in your release build in proguard-android-optimize.txt. Open this file from Gradle Scripts and add all the log statements that need to be removed while releasing. Below is the code snippet
-assumenosideeffects class android.util.Log {
public static boolean isLoggable(java.lang.String, int);
public static int d(...);
public static int w(...);
public static int v(...);
public static int i(...);
}
This is where the Timber Logging library comes in to reduce the tedious task by automatically generating the tags and later removing the logs from the generated APKs. Let us discuss integrating Timber into our Android Project.
Step by Step Implementation
Step 1: Add Dependency
Timber is an open-source library made by Jake Wharton. To add its dependency open build.gradle file and add –
implementation ‘com.jakewharton.timber:timber:4.7.1’
and sync project.
Step 2: Make Application Class
We need to create a separate base class for the application so that the Timber library can be used in all the activities. To initialize timber as soon the app starts it should be best kept in the application class.
Java
Kotlin
import android.app.Application;import timber.log.Timber; public class MyTimber extends Application { @Override public void onCreate() { super.onCreate(); // initialize timber in application class Timber.plant(new Timber.DebugTree()); }}
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport timber.log.Timberimport timber.log.Timber.DebugTree class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initialize timber in application class Timber.plant(DebugTree()) }}
After creating Application Class change the default application class in the AndroiManifest.xml file
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" <application android:name=".MyTimber" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.TimberLogger"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 3: Use Timber for Logging
Now we can use timber for logging in to all our android activities.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import timber.log.Timber; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Timber.i("Timber logging is ready"); }}
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport timber.log.Timber class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Timber.i("Timber logging is ready"); }}
aashaypawar
sagar0719kumar
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 27109,
"s": 26381,
"text": "In this article, we will build an application in Android to implement a logging utility class that is better than the default Log class of android. For that, we will be using Timber Library which is a small logger with an extensible API. As Android developers, we use a lot of log statements in our projects to generate outputs to test our application at different stages. Logs are of many types like Verbose, Debug, Warn, Info, Error. We use all sorts of Log statements in our application for finding errors and debugging. Once the application is ready to be released we need to remove all the log statements so that the generated APK doesn’t carry any additional application data. To tackle this problem we have several ways:"
},
{
"code": null,
"e": 27134,
"s": 27109,
"text": "Condition-based logging "
},
{
"code": null,
"e": 27143,
"s": 27134,
"text": "ProGuard"
},
{
"code": null,
"e": 27150,
"s": 27143,
"text": "Timber"
},
{
"code": null,
"e": 27538,
"s": 27150,
"text": "Using this method we check the level for which the logger is enabled and then log a message to that level. We just have to create a boolean variable in our Application class to check for logging. Use this boolean condition before every log statement in the application and before releasing the application change it to isDebug = false. Below is the code snippet of the Application class."
},
{
"code": null,
"e": 27543,
"s": 27538,
"text": "Java"
},
{
"code": null,
"e": 27550,
"s": 27543,
"text": "Kotlin"
},
{
"code": "import android.app.Application; public class LogApplication extends Application { public static boolean checkDebug; @Override public void onCreate() { super.onCreate(); checkDebug = true; }}",
"e": 27768,
"s": 27550,
"text": null
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var checkDebug = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) checkDebug = true }}",
"e": 28085,
"s": 27768,
"text": null
},
{
"code": null,
"e": 28432,
"s": 28085,
"text": "ProGuard is used to get rid of unused codes. Here we can use it to remove the Log statements in the release build. Add the log methods that you want to strip in your release build in proguard-android-optimize.txt. Open this file from Gradle Scripts and add all the log statements that need to be removed while releasing. Below is the code snippet"
},
{
"code": null,
"e": 28478,
"s": 28432,
"text": "-assumenosideeffects class android.util.Log {"
},
{
"code": null,
"e": 28538,
"s": 28478,
"text": " public static boolean isLoggable(java.lang.String, int);"
},
{
"code": null,
"e": 28567,
"s": 28538,
"text": " public static int d(...);"
},
{
"code": null,
"e": 28596,
"s": 28567,
"text": " public static int w(...);"
},
{
"code": null,
"e": 28625,
"s": 28596,
"text": " public static int v(...);"
},
{
"code": null,
"e": 28654,
"s": 28625,
"text": " public static int i(...);"
},
{
"code": null,
"e": 28656,
"s": 28654,
"text": "}"
},
{
"code": null,
"e": 28884,
"s": 28656,
"text": "This is where the Timber Logging library comes in to reduce the tedious task by automatically generating the tags and later removing the logs from the generated APKs. Let us discuss integrating Timber into our Android Project."
},
{
"code": null,
"e": 28912,
"s": 28884,
"text": "Step by Step Implementation"
},
{
"code": null,
"e": 28935,
"s": 28912,
"text": "Step 1: Add Dependency"
},
{
"code": null,
"e": 29045,
"s": 28935,
"text": "Timber is an open-source library made by Jake Wharton. To add its dependency open build.gradle file and add –"
},
{
"code": null,
"e": 29099,
"s": 29045,
"text": "implementation ‘com.jakewharton.timber:timber:4.7.1’ "
},
{
"code": null,
"e": 29117,
"s": 29099,
"text": "and sync project."
},
{
"code": null,
"e": 29148,
"s": 29117,
"text": "Step 2: Make Application Class"
},
{
"code": null,
"e": 29363,
"s": 29148,
"text": "We need to create a separate base class for the application so that the Timber library can be used in all the activities. To initialize timber as soon the app starts it should be best kept in the application class."
},
{
"code": null,
"e": 29368,
"s": 29363,
"text": "Java"
},
{
"code": null,
"e": 29375,
"s": 29368,
"text": "Kotlin"
},
{
"code": "import android.app.Application;import timber.log.Timber; public class MyTimber extends Application { @Override public void onCreate() { super.onCreate(); // initialize timber in application class Timber.plant(new Timber.DebugTree()); }}",
"e": 29651,
"s": 29375,
"text": null
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport timber.log.Timberimport timber.log.Timber.DebugTree class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initialize timber in application class Timber.plant(DebugTree()) }}",
"e": 30057,
"s": 29651,
"text": null
},
{
"code": null,
"e": 30158,
"s": 30057,
"text": "After creating Application Class change the default application class in the AndroiManifest.xml file"
},
{
"code": null,
"e": 30162,
"s": 30158,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" <application android:name=\".MyTimber\" android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.TimberLogger\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 30865,
"s": 30162,
"text": null
},
{
"code": null,
"e": 30896,
"s": 30865,
"text": "Step 3: Use Timber for Logging"
},
{
"code": null,
"e": 30964,
"s": 30896,
"text": "Now we can use timber for logging in to all our android activities."
},
{
"code": null,
"e": 30969,
"s": 30964,
"text": "Java"
},
{
"code": null,
"e": 30976,
"s": 30969,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import timber.log.Timber; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Timber.i(\"Timber logging is ready\"); }}",
"e": 31339,
"s": 30976,
"text": null
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport timber.log.Timber class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Timber.i(\"Timber logging is ready\"); }}",
"e": 31673,
"s": 31339,
"text": null
},
{
"code": null,
"e": 31685,
"s": 31673,
"text": "aashaypawar"
},
{
"code": null,
"e": 31700,
"s": 31685,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 31707,
"s": 31700,
"text": "Picked"
},
{
"code": null,
"e": 31731,
"s": 31707,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31739,
"s": 31731,
"text": "Android"
},
{
"code": null,
"e": 31744,
"s": 31739,
"text": "Java"
},
{
"code": null,
"e": 31763,
"s": 31744,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31768,
"s": 31763,
"text": "Java"
},
{
"code": null,
"e": 31776,
"s": 31768,
"text": "Android"
},
{
"code": null,
"e": 31874,
"s": 31776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31912,
"s": 31874,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31951,
"s": 31912,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32001,
"s": 31951,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32027,
"s": 32001,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 32069,
"s": 32027,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32084,
"s": 32069,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32128,
"s": 32084,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32150,
"s": 32128,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32201,
"s": 32150,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
C# | How to get the last occurrence of the element in the List that match the specified conditions - GeeksforGeeks | 17 Jan, 2022
List<T>.FindLast(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the last occurrence of that element within the entire List<T>.
Properties of List:
It is different from the arrays. A list can be resized dynamically but arrays cannot.
List class can accept null as a valid value for reference types and it also allows duplicate elements.
If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public T FindLast (Predicate<T> match);
Parameter:
match: It is the Predicate<T> delegate which defines the conditions of the element which is to be searched.
Return Value: If the element found then this method will return the last element that matches the conditions defined by the specified predicate otherwise it returns the default value for type T.
Exception: This method will give ArgumentNullException if the match is null.
Below programs illustrate the use of List<T>.FindLast(Predicate<T>) Method:
Example 1:
// C# Program to get the last occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Methodpublic static void Main(String[] args){ // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(4); firstlist.Add(2); firstlist.Add(7); firstlist.Add(2); firstlist.Add(6); firstlist.Add(4); firstlist.Add(3); Console.WriteLine("Elements Present in List:\n"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write("At Position {0}: ", p); Console.WriteLine(k); p++; } Console.WriteLine(" "); // Will give the last occurrence of the // element of firstlist that match the // conditions defined by predicate Console.Write("Index of Last element that fulfill the conditions: "); Console.WriteLine(firstlist.LastIndexOf(firstlist.FindLast(isEven))); Console.Write("Element is: "); Console.Write((firstlist.FindLast(isEven)));}}
Elements Present in List:
At Position 0: 4
At Position 1: 2
At Position 2: 7
At Position 3: 2
At Position 4: 6
At Position 5: 4
At Position 6: 3
Index of Last element that fulfill the conditions: 5
Element is: 4
Example 2:
// C# Program to get the last occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Methodpublic static void Main(String[] args){ // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine("Elements Present in List:\n"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write("At Position {0}: ", p); Console.WriteLine(k); p++; } Console.WriteLine(" "); // it will return index -1 as no element // found in the list which specified // the conditions and so element value // will be 0 as the list contains Integers Console.Write("Index of Last element that fulfill the conditions: "); Console.WriteLine(firstlist.LastIndexOf(firstlist.FindLast(isEven))); Console.Write("Element is: "); Console.Write((firstlist.FindLast(isEven)));}}
Elements Present in List:
At Position 0: 17
At Position 1: 19
At Position 2: 21
At Position 3: 9
At Position 4: 75
At Position 5: 19
At Position 6: 73
Index of Last element that fulfill the conditions: -1
Element is: 0
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findlast?view=netframework-4.7.2
Akanksha_Rai
rkbhola5
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors | [
{
"code": null,
"e": 25773,
"s": 25745,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 25986,
"s": 25773,
"text": "List<T>.FindLast(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the last occurrence of that element within the entire List<T>."
},
{
"code": null,
"e": 26006,
"s": 25986,
"text": "Properties of List:"
},
{
"code": null,
"e": 26092,
"s": 26006,
"text": "It is different from the arrays. A list can be resized dynamically but arrays cannot."
},
{
"code": null,
"e": 26195,
"s": 26092,
"text": "List class can accept null as a valid value for reference types and it also allows duplicate elements."
},
{
"code": null,
"e": 26419,
"s": 26195,
"text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element."
},
{
"code": null,
"e": 26427,
"s": 26419,
"text": "Syntax:"
},
{
"code": null,
"e": 26468,
"s": 26427,
"text": "public T FindLast (Predicate<T> match);\n"
},
{
"code": null,
"e": 26479,
"s": 26468,
"text": "Parameter:"
},
{
"code": null,
"e": 26587,
"s": 26479,
"text": "match: It is the Predicate<T> delegate which defines the conditions of the element which is to be searched."
},
{
"code": null,
"e": 26782,
"s": 26587,
"text": "Return Value: If the element found then this method will return the last element that matches the conditions defined by the specified predicate otherwise it returns the default value for type T."
},
{
"code": null,
"e": 26859,
"s": 26782,
"text": "Exception: This method will give ArgumentNullException if the match is null."
},
{
"code": null,
"e": 26935,
"s": 26859,
"text": "Below programs illustrate the use of List<T>.FindLast(Predicate<T>) Method:"
},
{
"code": null,
"e": 26946,
"s": 26935,
"text": "Example 1:"
},
{
"code": "// C# Program to get the last occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Methodpublic static void Main(String[] args){ // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(4); firstlist.Add(2); firstlist.Add(7); firstlist.Add(2); firstlist.Add(6); firstlist.Add(4); firstlist.Add(3); Console.WriteLine(\"Elements Present in List:\\n\"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write(\"At Position {0}: \", p); Console.WriteLine(k); p++; } Console.WriteLine(\" \"); // Will give the last occurrence of the // element of firstlist that match the // conditions defined by predicate Console.Write(\"Index of Last element that fulfill the conditions: \"); Console.WriteLine(firstlist.LastIndexOf(firstlist.FindLast(isEven))); Console.Write(\"Element is: \"); Console.Write((firstlist.FindLast(isEven)));}}",
"e": 28291,
"s": 26946,
"text": null
},
{
"code": null,
"e": 28507,
"s": 28291,
"text": "Elements Present in List:\n\nAt Position 0: 4\nAt Position 1: 2\nAt Position 2: 7\nAt Position 3: 2\nAt Position 4: 6\nAt Position 5: 4\nAt Position 6: 3\n \nIndex of Last element that fulfill the conditions: 5\nElement is: 4\n"
},
{
"code": null,
"e": 28518,
"s": 28507,
"text": "Example 2:"
},
{
"code": "// C# Program to get the last occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Methodpublic static void Main(String[] args){ // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine(\"Elements Present in List:\\n\"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write(\"At Position {0}: \", p); Console.WriteLine(k); p++; } Console.WriteLine(\" \"); // it will return index -1 as no element // found in the list which specified // the conditions and so element value // will be 0 as the list contains Integers Console.Write(\"Index of Last element that fulfill the conditions: \"); Console.WriteLine(firstlist.LastIndexOf(firstlist.FindLast(isEven))); Console.Write(\"Element is: \"); Console.Write((firstlist.FindLast(isEven)));}}",
"e": 29918,
"s": 28518,
"text": null
},
{
"code": null,
"e": 30141,
"s": 29918,
"text": "Elements Present in List:\n\nAt Position 0: 17\nAt Position 1: 19\nAt Position 2: 21\nAt Position 3: 9\nAt Position 4: 75\nAt Position 5: 19\nAt Position 6: 73\n \nIndex of Last element that fulfill the conditions: -1\nElement is: 0\n"
},
{
"code": null,
"e": 30152,
"s": 30141,
"text": "Reference:"
},
{
"code": null,
"e": 30263,
"s": 30152,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findlast?view=netframework-4.7.2"
},
{
"code": null,
"e": 30276,
"s": 30263,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30285,
"s": 30276,
"text": "rkbhola5"
},
{
"code": null,
"e": 30314,
"s": 30285,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 30334,
"s": 30314,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 30359,
"s": 30334,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 30373,
"s": 30359,
"text": "CSharp-method"
},
{
"code": null,
"e": 30376,
"s": 30373,
"text": "C#"
},
{
"code": null,
"e": 30474,
"s": 30376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30502,
"s": 30474,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30517,
"s": 30502,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30540,
"s": 30517,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30562,
"s": 30540,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30608,
"s": 30562,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30631,
"s": 30608,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30653,
"s": 30631,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 30693,
"s": 30653,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 30715,
"s": 30693,
"text": "C# | Class and Object"
}
] |
PyQt5 QCalendarWidget - Setting Date Edit (Pop-Up) Accept Delay Property - GeeksforGeeks | 13 Dec, 2021
In this article, we will see how we can set/change the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget’s date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after the most recent user input. Once this time has elapsed, the date specified in the date edit is accepted and the popup is closed. By default, the delay is defined to be 1500 milliseconds (1.5 seconds).
The date edit pop-up appear when we try to select using a keyboard, the lesser the value of delay pop-will get closed more quickly
In order to do this we will use setDateEditAcceptDelay method with the QCalendarWidget object.Syntax : calendar.setDateEditAcceptDelay(n)Argument : It takes integer argumentReturn : It return None
Below 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, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calendar = QCalendarWidget(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # removing special cursor self.calendar.unsetCursor() # setting accept delay value self.calendar.setDateEditAcceptDelay(2000) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
arorakashish0911
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
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions | [
{
"code": null,
"e": 24270,
"s": 24242,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 24822,
"s": 24270,
"text": "In this article, we will see how we can set/change the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget’s date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after the most recent user input. Once this time has elapsed, the date specified in the date edit is accepted and the popup is closed. By default, the delay is defined to be 1500 milliseconds (1.5 seconds)."
},
{
"code": null,
"e": 24953,
"s": 24822,
"text": "The date edit pop-up appear when we try to select using a keyboard, the lesser the value of delay pop-will get closed more quickly"
},
{
"code": null,
"e": 25152,
"s": 24953,
"text": "In order to do this we will use setDateEditAcceptDelay method with the QCalendarWidget object.Syntax : calendar.setDateEditAcceptDelay(n)Argument : It takes integer argumentReturn : It return None "
},
{
"code": null,
"e": 25182,
"s": 25152,
"text": "Below is the implementation "
},
{
"code": null,
"e": 25190,
"s": 25182,
"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, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calendar = QCalendarWidget(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # removing special cursor self.calendar.unsetCursor() # setting accept delay value self.calendar.setDateEditAcceptDelay(2000) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26260,
"s": 25190,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26260,
"text": "Output : "
},
{
"code": null,
"e": 26280,
"s": 26272,
"text": "clintra"
},
{
"code": null,
"e": 26297,
"s": 26280,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26325,
"s": 26297,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 26336,
"s": 26325,
"text": "Python-gui"
},
{
"code": null,
"e": 26348,
"s": 26336,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26355,
"s": 26348,
"text": "Python"
},
{
"code": null,
"e": 26453,
"s": 26355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26462,
"s": 26453,
"text": "Comments"
},
{
"code": null,
"e": 26475,
"s": 26462,
"text": "Old Comments"
},
{
"code": null,
"e": 26493,
"s": 26475,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26528,
"s": 26493,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26550,
"s": 26528,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26580,
"s": 26550,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26612,
"s": 26580,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26654,
"s": 26612,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26680,
"s": 26654,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26717,
"s": 26680,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26761,
"s": 26717,
"text": "Reading and Writing to text files in Python"
}
] |
Adding a legend to a Matplotlib boxplot with multiple plots on the same axis | To add a legend to a matplotlib boxplot with multiple plots on the same axis, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create random data, a and b, using numpy.
Create random data, a and b, using numpy.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add an axes to the current figure as a subplot arrangement.
Add an axes to the current figure as a subplot arrangement.
Make a box and whisker plot using boxplot() method with different facecolors.
Make a box and whisker plot using boxplot() method with different facecolors.
To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements.
To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
a = np.random.rand(100, 2)
b = np.random.rand(100, 2)
fig = plt.figure()
ax = fig.add_subplot(111)
bp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C0"))
bp2 = ax.boxplot(a, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C2"))
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ["Box Plot 1", "Box Plot 2"], loc='upper right')
plt.show() | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To add a legend to a matplotlib boxplot with multiple plots on the same axis, we can take the following steps −"
},
{
"code": null,
"e": 1250,
"s": 1174,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1326,
"s": 1250,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1368,
"s": 1326,
"text": "Create random data, a and b, using numpy."
},
{
"code": null,
"e": 1410,
"s": 1368,
"text": "Create random data, a and b, using numpy."
},
{
"code": null,
"e": 1484,
"s": 1410,
"text": "Create a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1558,
"s": 1484,
"text": "Create a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1618,
"s": 1558,
"text": "Add an axes to the current figure as a subplot arrangement."
},
{
"code": null,
"e": 1678,
"s": 1618,
"text": "Add an axes to the current figure as a subplot arrangement."
},
{
"code": null,
"e": 1756,
"s": 1678,
"text": "Make a box and whisker plot using boxplot() method with different facecolors."
},
{
"code": null,
"e": 1834,
"s": 1756,
"text": "Make a box and whisker plot using boxplot() method with different facecolors."
},
{
"code": null,
"e": 1946,
"s": 1834,
"text": "To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements."
},
{
"code": null,
"e": 2058,
"s": 1946,
"text": "To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements."
},
{
"code": null,
"e": 2100,
"s": 2058,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2142,
"s": 2100,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2716,
"s": 2142,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\na = np.random.rand(100, 2)\nb = np.random.rand(100, 2)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nbp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor=\"C0\"))\nbp2 = ax.boxplot(a, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor=\"C2\"))\nax.legend([bp1[\"boxes\"][0], bp2[\"boxes\"][0]], [\"Box Plot 1\", \"Box Plot 2\"], loc='upper right')\n\nplt.show()"
}
] |
How to change the font size of legend in base R plot? | In base R, we can use legend function to add a legend to the plot. For example, if we want to create a histogram with legend on top-right position then we can use legend("topright",legend="Normal Distribution") and if we want to change the font size then we need to as cex argument as shown below:
legend("topright",legend="Normal Distribution",cex=2)
Live Demo
Consider the below histogram −
x<−rnorm(5000)
hist(x)
Adding legend of different sizes −
legend("topright",legend="Normal Distribution",cex=1)
legend("topleft",legend="Histogram of",cex=1.5) | [
{
"code": null,
"e": 1360,
"s": 1062,
"text": "In base R, we can use legend function to add a legend to the plot. For example, if we want to create a histogram with legend on top-right position then we can use legend(\"topright\",legend=\"Normal Distribution\") and if we want to change the font size then we need to as cex argument as shown below:"
},
{
"code": null,
"e": 1414,
"s": 1360,
"text": "legend(\"topright\",legend=\"Normal Distribution\",cex=2)"
},
{
"code": null,
"e": 1425,
"s": 1414,
"text": " Live Demo"
},
{
"code": null,
"e": 1456,
"s": 1425,
"text": "Consider the below histogram −"
},
{
"code": null,
"e": 1479,
"s": 1456,
"text": "x<−rnorm(5000)\nhist(x)"
},
{
"code": null,
"e": 1514,
"s": 1479,
"text": "Adding legend of different sizes −"
},
{
"code": null,
"e": 1568,
"s": 1514,
"text": "legend(\"topright\",legend=\"Normal Distribution\",cex=1)"
},
{
"code": null,
"e": 1616,
"s": 1568,
"text": "legend(\"topleft\",legend=\"Histogram of\",cex=1.5)"
}
] |
Pandas equivalent of 10 useful SQL queries | by Dorian Lazar | Towards Data Science | In case you don’t know, pandas is a python library for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. The name is derived from the term “panel data”, an econometrics term for data sets that include observations over multiple time periods for the same individuals.
Basically, it is a way of working with tables in python. In pandas tables of data are called DataFrames.
As the title suggests, in this article I'll show you the pandas equivalents of some of the most useful SQL queries. This can serve both as an introduction to pandas for those who already know SQL or as a cheat sheet of common pandas operations you may need.
For the examples below I will use this dataset which consists of data about trending YouTube videos in the US. It consists of 40949 rows with 16 columns: video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, thumbnail_link, comments_disabled, ratings_disabled, video_error_or_removed, description.
import numpy as npimport pandas as pd# Reading the csv file into a DataFramedf = pd.read_csv('USvideos.csv')
Pandas operations, by default, don’t modify the data frame which you are working with; they just return other data frames which you need to assign to a variable or use parameter inplace=True if you want to save the changes. For most examples below we don’t change our original data frame, we just show the returned result.
SELECT col1, col2, ... FROM table
The SELECT statement is used to select columns of data from a table.
To do the same thing in pandas we just have to use the array notation on the data frame and inside the square brackets pass a list with the column names you want to select.
df[['video_id', 'title']]
The same thing can be made with the following syntax which makes easier to translate WHERE statements later:
df.loc[:, ['video_id', 'title']]
SELECT DISTINCT col1, col2, ... FROM table
The SELECT DISTINCT statement returns only unique rows form a table.
In a data frame there may be duplicate values. If you want to get only distinct rows (remove duplicates) it is as simple as calling the .drop_duplicates() method. Judging based on this method's name you may think that it removes duplicate rows from your initial data frame, but what it actually does is to return a new data frame with duplicate rows removed.
df.loc[:, ['channel_title']].drop_duplicates()
SELECT TOP number col1, col2, ... FROM tableorSELECT col1, col2, ... FROM table LIMIT number
The TOP or LIMIT keyword in SQL is used to limit the number of returned rows from the top of the table.In pandas this is very easy to do with .head(number) method. Pandas also has the .tail(number) method for showing the rows from the end of data frame.
df.loc[:, ['video_id', 'title']].head(5)
df.loc[:, ['video_id', 'title']].tail(5)
SQL’s MIN(), MAX(), COUNT(), AVG(), and SUM() functions are pretty straightforward to translate to pandas:
SELECT MIN(col) FROM table
df.loc[:, ['views']].min()
SELECT MAX(col) FROM table
df.loc[:, ['views']].max()
SELECT COUNT(col) FROM table
df.loc[:, ['views']].count()
SELECT AVG(col) FROM table
df.loc[:, ['views']].mean()
SELECT SUM(col) FROM table
df.loc[:, ['views']].sum()
Now, what if we want to do something like this:SELECT MAX(likes), MIN(dislikes) FROM table? We need to do this in more steps:
new_df = df.loc[:, ['likes']].max().rename({'likes': 'MAX(likes)'})new_df['MIN(dislikes)'] = df.loc[:, ['dislikes']].min().values[0]
SELECT col1, col2, ... FROM table WHERE condition
The WHERE clause is used to extract only the rows that fulfill a specified condition.
Recall the syntax we used so far for selecting columns:df.loc[:, ['col1', 'col2']]Inside the square brackets of .loc there is place for two parameters; so far we only used the second one which is used to specify what columns you want to select. Guess for what is the first parameter? Is for selecting rows. Pandas data frames expect a list of row indices or boolean flags based on which it extracts the rows we need. So far we used only the : symbol which means "return all rows". If we want to extract only rows with indices from 50 to 80 we can use 50:80 in that place.
For extracting rows based on some condition, most often we will pass there an array of boolean flags returned by some (vectorized) boolean operation. The rows on positions where we will have False will not be included in the result, only those rows with True on their positions will be returned.
Using equality and inequality operators ==, <, <=, >, >=, != in conditions is straightforward. For example, to return only rows that have number of likes >= 1000000 we can use:
df.loc[df['likes'] >= 1000000, ['video_id', 'title']]
Note that the reason for which we could do what we did above (df['likes'] >= 1000000) is that pandas has overwritten the default behavior for >= operator so that it applies the operator element-wise and returns an array of booleans of the shape that we need (number of rows).But the operators and, or, not don't work like that. So, we will use & instead of and, | instead of or, ~ instead of not.
df.loc[(df['likes'] >= 1000000) & (df['dislikes'] <= 5000), ['video_id', 'title']].drop_duplicates()
SELECT col1, col2, ... FROM table WHERE colN IS NOT NULL
In SQL you can use IS NULL or IS NOT NULL to get rows that contain/don't contain null values.
How to check for null values in pandas?We will use isnull(array-like) function from pandas package to do that. Note that this is not a method of data frame objects, don't use df.isnull(...); instead do pd.isnull(df['column']). So be careful.
The example below returns all rows where the description is not null.
SELECT col1, col2, ... FROM table WHERE colN LIKE pattern
The LIKE keyword can be used in a WHERE clause to test if a column matches a pattern.
In pandas we can use python’s native re module for regular expressions to accomplish the same thing, or even more as the python’s re module allows for a richer set of patterns to be tested rather than SQL’s LIKE.
We will create a function like(x, pattern) where x is an array-like object and pattern is a string containing the pattern which we want to test for. This function will first compile the pattern into a regular expression object, then we can use the .fullmatch(val) method to test the val's value against our pattern. In order to apply this test to each element in our x vector we will use numpy's vectorize(func) function to create a vector equivalent for our operation of regex matching. Finally we apply this vectorized function to our x input vector. Then all we need to do is to pass like(df['column'], pattern) as first parameter in .loc[].
import redef like(x, pattern): r = re.compile(pattern) vlike = np.vectorize(lambda val: bool(r.fullmatch(val))) return vlike(x)
As an example the below code returns all videos that contains the word ‘math’ in their description.
df_notnull = df.loc[~pd.isnull(df['description']), :]df_notnull.loc[like(df_notnull['description'], '.* math .*'), ['video_id', 'title']].drop_duplicates()
SELECT col1, col2, ... FROM table ORDER BY col1, col2 ASC|DESC
This SQL keyword is used to sort the results in ascending or descending order.
It is straightforward to translate this to pandas, you just call the .sort_values(by=['col1', ...], ascending=True/False) method on a data frame.
df.loc[df['likes'] >= 2000000, ['video_id', 'title'] ].sort_values(by=['title'], ascending=True).drop_duplicates()
SELECT col1, col2, ... FROM table GROUP BY colN
The GROUP BY statement groups rows that have the same value for a specific column. It is often used with aggregate functions (MIN, MAX, COUNT, SUM, AVG).
In pandas it is as simple as calling the .groupby(['col1', ...]) method, followed by a call to one of .min(), .max(), .count(), .sum, .mean() methods.
df.loc[:, ['channel_title', 'views', 'likes', 'dislikes'] ].groupby(['channel_title']).sum()
SELECT col1, col2, ... FROM table GROUP BY colN HAVING condition
The HAVING keyword is used to filter the results based on group-level conditions.
In pandas we have the .filter(func) method that can be called after a groupby() call. We need to pass to this method a function that takes a data frame of a group as a parameter and returns a boolean value that decides whether this group is included in the results or not.But if we want to do more things at once in pandas, e.g. apply aggregate functions on columns and filter results based on group-level conditions, we need to do this in more steps. Whereas in SQL we could have done this in only one query.
In the example below we want to group by channel_title, allow only channels that have at least 100 videos in the table, and apply average function on views, likes, and dislikes.
In SQL this would be:
SELECT channel_title, AVG(views), AVG(likes), AVG(dislikes)FROM videos_tableGROUP BY channel_titleHAVING COUNT(video_id) >= 100;
In pandas:
g = df.groupby(['channel_title'])g = g.filter(lambda x: x['video_id'].count() > 100)g = g.loc[:, ['channel_title', 'views', 'likes', 'dislikes']]g = g.groupby(['channel_title']).mean()
INSERT INTO table (column1, column2, ...) VALUES (value1, value2, ...)
This SQL statement is used to insert new rows in the table.
In pandas we can use the .append() method to append a new data frame at the end of an existing one. We will use ignore_index=True in order to continue indexing from the last row in the old data frame.
new_row = pd.DataFrame({'video_id': ['EkZGBdY0vlg'], 'channel_title': ['Professor Leonard'], 'title': ['Calculus 3 Lecture 13.3: Partial Derivatives']})df = df.append(new_row, ignore_index=True)
DELETE FROM table WHERE condition
DELETE statement is used to delete existing rows from a table based on some condition.
In pandas we can use .drop() method to remove the rows whose indices we pass in. Unlike other methods this one doesn't accept boolean arrays as input. So we must convert our condition's output to indices. We can do that with np.where() function.
In the example below we deleted all the rows where channel_title != '3Blue1Brown'.
df = df.drop(np.where(df['channel_title'] != '3Blue1Brown')[0])
ALTER TABLE table ADD column
This SQL statement adds new columns.
In pandas we can do this by: df['new_column'] = array-like.
Below we add a new column ‘like_ratio’:
df['like_ratio'] = df['likes'] / (df['likes'] + df['dislikes'])
ALTER TABLE table DROP COLUMN column
This SQL statement deletes a column.
del df['column'] is how we do this in pandas.
For example, deleting ‘comments_disabled’ column would be:
del df['comments_disabled']
UPDATE table_nameSET column1 = value1, column2 = value2, ...WHERE condition;
The UPDATE statement is used to change values in our table based on some condition.
For doing this in python we can use numpy's where() function. We also saw this function a few lines above when we used it to convert a boolean array to indices array. That is what this function does when given just one parameter. This function can receive 3 arrays of the same size as parameters, first one being a boolean array. Let's call them c, x, y. It returns an array of the same size filled with elements from x and y chosen in this way: if c[i] is true choose x[i] else choose y[i].To modify a data frame column we can do:
df['column'] = np.where(condition, new_values, df['column'])
In the example below we increase the number of likes by 100 where channel_title == 'Veritasium'.
This is how the data looks before:
df.loc[df['channel_title'] == 'Veritasium', ['title', 'likes']]
Increment likes by 100 for Veritasium channel:
df['likes'] = np.where(df['channel_title'] == 'Veritasium', df['likes']+100, df['likes'])
After we ran the above query:
A JOIN clause is used to combine rows from two or more tables based on a related column between them.
In order to show examples of joins I need at least two tables, so I will split the data frame used so far into two smaller tables.
df_titles = df.loc[:, ['video_id', 'title']].drop_duplicates()
df_stats = df.loc[:, ['video_id', 'views', 'likes', 'dislikes'] ].groupby('video_id').max()# transform video_id from index to columndf_stats = df_stats.reset_index()
Doing joins in pandas is straightforward: data frames have a .join() method that we can use like this:df1.join(df2.set_index('key_column'), on='key_column')
There are more types of joins: inner, full, left, and right joins.
INNER JOIN: returns rows that have matching values in both tables
FULL (OUTER) JOIN: returns rows that have matching values in any of the tables
LEFT JOIN: returns all rows from the left table, and the matched rows from the right one
RIGHT JOIN: returns all rows from the right table, and the matched rows from the left one
To specify which type of join you want in pandas you can use the how parameter in .join() method. This parameter can be one of: 'inner', 'outer', 'left', 'right'.
Below is an example of inner join of the two data frames above on ‘video_id’ column. The other types of joins are done in the same way, just change the ‘how’ parameter accordingly.
Inner join in SQL:
SELECT *FROM df_titlesINNER JOIN df_statsON df_titles.video_id = df_stats.video_id;
Inner join in pandas:
df_titles.join(df_stats.set_index('video_id'), on='video_id', how='inner')
A notebook for this article can be found here.
I hope you found this information useful and thanks for reading!
This article is also posted on my own website here. Feel free to have a look! | [
{
"code": null,
"e": 528,
"s": 172,
"text": "In case you don’t know, pandas is a python library for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. The name is derived from the term “panel data”, an econometrics term for data sets that include observations over multiple time periods for the same individuals."
},
{
"code": null,
"e": 633,
"s": 528,
"text": "Basically, it is a way of working with tables in python. In pandas tables of data are called DataFrames."
},
{
"code": null,
"e": 891,
"s": 633,
"text": "As the title suggests, in this article I'll show you the pandas equivalents of some of the most useful SQL queries. This can serve both as an introduction to pandas for those who already know SQL or as a cheat sheet of common pandas operations you may need."
},
{
"code": null,
"e": 1254,
"s": 891,
"text": "For the examples below I will use this dataset which consists of data about trending YouTube videos in the US. It consists of 40949 rows with 16 columns: video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, thumbnail_link, comments_disabled, ratings_disabled, video_error_or_removed, description."
},
{
"code": null,
"e": 1363,
"s": 1254,
"text": "import numpy as npimport pandas as pd# Reading the csv file into a DataFramedf = pd.read_csv('USvideos.csv')"
},
{
"code": null,
"e": 1686,
"s": 1363,
"text": "Pandas operations, by default, don’t modify the data frame which you are working with; they just return other data frames which you need to assign to a variable or use parameter inplace=True if you want to save the changes. For most examples below we don’t change our original data frame, we just show the returned result."
},
{
"code": null,
"e": 1720,
"s": 1686,
"text": "SELECT col1, col2, ... FROM table"
},
{
"code": null,
"e": 1789,
"s": 1720,
"text": "The SELECT statement is used to select columns of data from a table."
},
{
"code": null,
"e": 1962,
"s": 1789,
"text": "To do the same thing in pandas we just have to use the array notation on the data frame and inside the square brackets pass a list with the column names you want to select."
},
{
"code": null,
"e": 1988,
"s": 1962,
"text": "df[['video_id', 'title']]"
},
{
"code": null,
"e": 2097,
"s": 1988,
"text": "The same thing can be made with the following syntax which makes easier to translate WHERE statements later:"
},
{
"code": null,
"e": 2130,
"s": 2097,
"text": "df.loc[:, ['video_id', 'title']]"
},
{
"code": null,
"e": 2173,
"s": 2130,
"text": "SELECT DISTINCT col1, col2, ... FROM table"
},
{
"code": null,
"e": 2242,
"s": 2173,
"text": "The SELECT DISTINCT statement returns only unique rows form a table."
},
{
"code": null,
"e": 2601,
"s": 2242,
"text": "In a data frame there may be duplicate values. If you want to get only distinct rows (remove duplicates) it is as simple as calling the .drop_duplicates() method. Judging based on this method's name you may think that it removes duplicate rows from your initial data frame, but what it actually does is to return a new data frame with duplicate rows removed."
},
{
"code": null,
"e": 2648,
"s": 2601,
"text": "df.loc[:, ['channel_title']].drop_duplicates()"
},
{
"code": null,
"e": 2741,
"s": 2648,
"text": "SELECT TOP number col1, col2, ... FROM tableorSELECT col1, col2, ... FROM table LIMIT number"
},
{
"code": null,
"e": 2995,
"s": 2741,
"text": "The TOP or LIMIT keyword in SQL is used to limit the number of returned rows from the top of the table.In pandas this is very easy to do with .head(number) method. Pandas also has the .tail(number) method for showing the rows from the end of data frame."
},
{
"code": null,
"e": 3036,
"s": 2995,
"text": "df.loc[:, ['video_id', 'title']].head(5)"
},
{
"code": null,
"e": 3077,
"s": 3036,
"text": "df.loc[:, ['video_id', 'title']].tail(5)"
},
{
"code": null,
"e": 3184,
"s": 3077,
"text": "SQL’s MIN(), MAX(), COUNT(), AVG(), and SUM() functions are pretty straightforward to translate to pandas:"
},
{
"code": null,
"e": 3211,
"s": 3184,
"text": "SELECT MIN(col) FROM table"
},
{
"code": null,
"e": 3238,
"s": 3211,
"text": "df.loc[:, ['views']].min()"
},
{
"code": null,
"e": 3265,
"s": 3238,
"text": "SELECT MAX(col) FROM table"
},
{
"code": null,
"e": 3292,
"s": 3265,
"text": "df.loc[:, ['views']].max()"
},
{
"code": null,
"e": 3321,
"s": 3292,
"text": "SELECT COUNT(col) FROM table"
},
{
"code": null,
"e": 3350,
"s": 3321,
"text": "df.loc[:, ['views']].count()"
},
{
"code": null,
"e": 3377,
"s": 3350,
"text": "SELECT AVG(col) FROM table"
},
{
"code": null,
"e": 3405,
"s": 3377,
"text": "df.loc[:, ['views']].mean()"
},
{
"code": null,
"e": 3432,
"s": 3405,
"text": "SELECT SUM(col) FROM table"
},
{
"code": null,
"e": 3459,
"s": 3432,
"text": "df.loc[:, ['views']].sum()"
},
{
"code": null,
"e": 3585,
"s": 3459,
"text": "Now, what if we want to do something like this:SELECT MAX(likes), MIN(dislikes) FROM table? We need to do this in more steps:"
},
{
"code": null,
"e": 3718,
"s": 3585,
"text": "new_df = df.loc[:, ['likes']].max().rename({'likes': 'MAX(likes)'})new_df['MIN(dislikes)'] = df.loc[:, ['dislikes']].min().values[0]"
},
{
"code": null,
"e": 3768,
"s": 3718,
"text": "SELECT col1, col2, ... FROM table WHERE condition"
},
{
"code": null,
"e": 3854,
"s": 3768,
"text": "The WHERE clause is used to extract only the rows that fulfill a specified condition."
},
{
"code": null,
"e": 4426,
"s": 3854,
"text": "Recall the syntax we used so far for selecting columns:df.loc[:, ['col1', 'col2']]Inside the square brackets of .loc there is place for two parameters; so far we only used the second one which is used to specify what columns you want to select. Guess for what is the first parameter? Is for selecting rows. Pandas data frames expect a list of row indices or boolean flags based on which it extracts the rows we need. So far we used only the : symbol which means \"return all rows\". If we want to extract only rows with indices from 50 to 80 we can use 50:80 in that place."
},
{
"code": null,
"e": 4722,
"s": 4426,
"text": "For extracting rows based on some condition, most often we will pass there an array of boolean flags returned by some (vectorized) boolean operation. The rows on positions where we will have False will not be included in the result, only those rows with True on their positions will be returned."
},
{
"code": null,
"e": 4899,
"s": 4722,
"text": "Using equality and inequality operators ==, <, <=, >, >=, != in conditions is straightforward. For example, to return only rows that have number of likes >= 1000000 we can use:"
},
{
"code": null,
"e": 4953,
"s": 4899,
"text": "df.loc[df['likes'] >= 1000000, ['video_id', 'title']]"
},
{
"code": null,
"e": 5350,
"s": 4953,
"text": "Note that the reason for which we could do what we did above (df['likes'] >= 1000000) is that pandas has overwritten the default behavior for >= operator so that it applies the operator element-wise and returns an array of booleans of the shape that we need (number of rows).But the operators and, or, not don't work like that. So, we will use & instead of and, | instead of or, ~ instead of not."
},
{
"code": null,
"e": 5451,
"s": 5350,
"text": "df.loc[(df['likes'] >= 1000000) & (df['dislikes'] <= 5000), ['video_id', 'title']].drop_duplicates()"
},
{
"code": null,
"e": 5508,
"s": 5451,
"text": "SELECT col1, col2, ... FROM table WHERE colN IS NOT NULL"
},
{
"code": null,
"e": 5602,
"s": 5508,
"text": "In SQL you can use IS NULL or IS NOT NULL to get rows that contain/don't contain null values."
},
{
"code": null,
"e": 5844,
"s": 5602,
"text": "How to check for null values in pandas?We will use isnull(array-like) function from pandas package to do that. Note that this is not a method of data frame objects, don't use df.isnull(...); instead do pd.isnull(df['column']). So be careful."
},
{
"code": null,
"e": 5914,
"s": 5844,
"text": "The example below returns all rows where the description is not null."
},
{
"code": null,
"e": 5972,
"s": 5914,
"text": "SELECT col1, col2, ... FROM table WHERE colN LIKE pattern"
},
{
"code": null,
"e": 6058,
"s": 5972,
"text": "The LIKE keyword can be used in a WHERE clause to test if a column matches a pattern."
},
{
"code": null,
"e": 6271,
"s": 6058,
"text": "In pandas we can use python’s native re module for regular expressions to accomplish the same thing, or even more as the python’s re module allows for a richer set of patterns to be tested rather than SQL’s LIKE."
},
{
"code": null,
"e": 6916,
"s": 6271,
"text": "We will create a function like(x, pattern) where x is an array-like object and pattern is a string containing the pattern which we want to test for. This function will first compile the pattern into a regular expression object, then we can use the .fullmatch(val) method to test the val's value against our pattern. In order to apply this test to each element in our x vector we will use numpy's vectorize(func) function to create a vector equivalent for our operation of regex matching. Finally we apply this vectorized function to our x input vector. Then all we need to do is to pass like(df['column'], pattern) as first parameter in .loc[]."
},
{
"code": null,
"e": 7053,
"s": 6916,
"text": "import redef like(x, pattern): r = re.compile(pattern) vlike = np.vectorize(lambda val: bool(r.fullmatch(val))) return vlike(x)"
},
{
"code": null,
"e": 7153,
"s": 7053,
"text": "As an example the below code returns all videos that contains the word ‘math’ in their description."
},
{
"code": null,
"e": 7309,
"s": 7153,
"text": "df_notnull = df.loc[~pd.isnull(df['description']), :]df_notnull.loc[like(df_notnull['description'], '.* math .*'), ['video_id', 'title']].drop_duplicates()"
},
{
"code": null,
"e": 7372,
"s": 7309,
"text": "SELECT col1, col2, ... FROM table ORDER BY col1, col2 ASC|DESC"
},
{
"code": null,
"e": 7451,
"s": 7372,
"text": "This SQL keyword is used to sort the results in ascending or descending order."
},
{
"code": null,
"e": 7597,
"s": 7451,
"text": "It is straightforward to translate this to pandas, you just call the .sort_values(by=['col1', ...], ascending=True/False) method on a data frame."
},
{
"code": null,
"e": 7712,
"s": 7597,
"text": "df.loc[df['likes'] >= 2000000, ['video_id', 'title'] ].sort_values(by=['title'], ascending=True).drop_duplicates()"
},
{
"code": null,
"e": 7760,
"s": 7712,
"text": "SELECT col1, col2, ... FROM table GROUP BY colN"
},
{
"code": null,
"e": 7914,
"s": 7760,
"text": "The GROUP BY statement groups rows that have the same value for a specific column. It is often used with aggregate functions (MIN, MAX, COUNT, SUM, AVG)."
},
{
"code": null,
"e": 8065,
"s": 7914,
"text": "In pandas it is as simple as calling the .groupby(['col1', ...]) method, followed by a call to one of .min(), .max(), .count(), .sum, .mean() methods."
},
{
"code": null,
"e": 8158,
"s": 8065,
"text": "df.loc[:, ['channel_title', 'views', 'likes', 'dislikes'] ].groupby(['channel_title']).sum()"
},
{
"code": null,
"e": 8223,
"s": 8158,
"text": "SELECT col1, col2, ... FROM table GROUP BY colN HAVING condition"
},
{
"code": null,
"e": 8305,
"s": 8223,
"text": "The HAVING keyword is used to filter the results based on group-level conditions."
},
{
"code": null,
"e": 8815,
"s": 8305,
"text": "In pandas we have the .filter(func) method that can be called after a groupby() call. We need to pass to this method a function that takes a data frame of a group as a parameter and returns a boolean value that decides whether this group is included in the results or not.But if we want to do more things at once in pandas, e.g. apply aggregate functions on columns and filter results based on group-level conditions, we need to do this in more steps. Whereas in SQL we could have done this in only one query."
},
{
"code": null,
"e": 8993,
"s": 8815,
"text": "In the example below we want to group by channel_title, allow only channels that have at least 100 videos in the table, and apply average function on views, likes, and dislikes."
},
{
"code": null,
"e": 9015,
"s": 8993,
"text": "In SQL this would be:"
},
{
"code": null,
"e": 9144,
"s": 9015,
"text": "SELECT channel_title, AVG(views), AVG(likes), AVG(dislikes)FROM videos_tableGROUP BY channel_titleHAVING COUNT(video_id) >= 100;"
},
{
"code": null,
"e": 9155,
"s": 9144,
"text": "In pandas:"
},
{
"code": null,
"e": 9340,
"s": 9155,
"text": "g = df.groupby(['channel_title'])g = g.filter(lambda x: x['video_id'].count() > 100)g = g.loc[:, ['channel_title', 'views', 'likes', 'dislikes']]g = g.groupby(['channel_title']).mean()"
},
{
"code": null,
"e": 9411,
"s": 9340,
"text": "INSERT INTO table (column1, column2, ...) VALUES (value1, value2, ...)"
},
{
"code": null,
"e": 9471,
"s": 9411,
"text": "This SQL statement is used to insert new rows in the table."
},
{
"code": null,
"e": 9672,
"s": 9471,
"text": "In pandas we can use the .append() method to append a new data frame at the end of an existing one. We will use ignore_index=True in order to continue indexing from the last row in the old data frame."
},
{
"code": null,
"e": 9913,
"s": 9672,
"text": "new_row = pd.DataFrame({'video_id': ['EkZGBdY0vlg'], 'channel_title': ['Professor Leonard'], 'title': ['Calculus 3 Lecture 13.3: Partial Derivatives']})df = df.append(new_row, ignore_index=True)"
},
{
"code": null,
"e": 9947,
"s": 9913,
"text": "DELETE FROM table WHERE condition"
},
{
"code": null,
"e": 10034,
"s": 9947,
"text": "DELETE statement is used to delete existing rows from a table based on some condition."
},
{
"code": null,
"e": 10280,
"s": 10034,
"text": "In pandas we can use .drop() method to remove the rows whose indices we pass in. Unlike other methods this one doesn't accept boolean arrays as input. So we must convert our condition's output to indices. We can do that with np.where() function."
},
{
"code": null,
"e": 10363,
"s": 10280,
"text": "In the example below we deleted all the rows where channel_title != '3Blue1Brown'."
},
{
"code": null,
"e": 10427,
"s": 10363,
"text": "df = df.drop(np.where(df['channel_title'] != '3Blue1Brown')[0])"
},
{
"code": null,
"e": 10456,
"s": 10427,
"text": "ALTER TABLE table ADD column"
},
{
"code": null,
"e": 10493,
"s": 10456,
"text": "This SQL statement adds new columns."
},
{
"code": null,
"e": 10553,
"s": 10493,
"text": "In pandas we can do this by: df['new_column'] = array-like."
},
{
"code": null,
"e": 10593,
"s": 10553,
"text": "Below we add a new column ‘like_ratio’:"
},
{
"code": null,
"e": 10657,
"s": 10593,
"text": "df['like_ratio'] = df['likes'] / (df['likes'] + df['dislikes'])"
},
{
"code": null,
"e": 10694,
"s": 10657,
"text": "ALTER TABLE table DROP COLUMN column"
},
{
"code": null,
"e": 10731,
"s": 10694,
"text": "This SQL statement deletes a column."
},
{
"code": null,
"e": 10777,
"s": 10731,
"text": "del df['column'] is how we do this in pandas."
},
{
"code": null,
"e": 10836,
"s": 10777,
"text": "For example, deleting ‘comments_disabled’ column would be:"
},
{
"code": null,
"e": 10864,
"s": 10836,
"text": "del df['comments_disabled']"
},
{
"code": null,
"e": 10941,
"s": 10864,
"text": "UPDATE table_nameSET column1 = value1, column2 = value2, ...WHERE condition;"
},
{
"code": null,
"e": 11025,
"s": 10941,
"text": "The UPDATE statement is used to change values in our table based on some condition."
},
{
"code": null,
"e": 11557,
"s": 11025,
"text": "For doing this in python we can use numpy's where() function. We also saw this function a few lines above when we used it to convert a boolean array to indices array. That is what this function does when given just one parameter. This function can receive 3 arrays of the same size as parameters, first one being a boolean array. Let's call them c, x, y. It returns an array of the same size filled with elements from x and y chosen in this way: if c[i] is true choose x[i] else choose y[i].To modify a data frame column we can do:"
},
{
"code": null,
"e": 11618,
"s": 11557,
"text": "df['column'] = np.where(condition, new_values, df['column'])"
},
{
"code": null,
"e": 11715,
"s": 11618,
"text": "In the example below we increase the number of likes by 100 where channel_title == 'Veritasium'."
},
{
"code": null,
"e": 11750,
"s": 11715,
"text": "This is how the data looks before:"
},
{
"code": null,
"e": 11814,
"s": 11750,
"text": "df.loc[df['channel_title'] == 'Veritasium', ['title', 'likes']]"
},
{
"code": null,
"e": 11861,
"s": 11814,
"text": "Increment likes by 100 for Veritasium channel:"
},
{
"code": null,
"e": 11951,
"s": 11861,
"text": "df['likes'] = np.where(df['channel_title'] == 'Veritasium', df['likes']+100, df['likes'])"
},
{
"code": null,
"e": 11981,
"s": 11951,
"text": "After we ran the above query:"
},
{
"code": null,
"e": 12083,
"s": 11981,
"text": "A JOIN clause is used to combine rows from two or more tables based on a related column between them."
},
{
"code": null,
"e": 12214,
"s": 12083,
"text": "In order to show examples of joins I need at least two tables, so I will split the data frame used so far into two smaller tables."
},
{
"code": null,
"e": 12277,
"s": 12214,
"text": "df_titles = df.loc[:, ['video_id', 'title']].drop_duplicates()"
},
{
"code": null,
"e": 12443,
"s": 12277,
"text": "df_stats = df.loc[:, ['video_id', 'views', 'likes', 'dislikes'] ].groupby('video_id').max()# transform video_id from index to columndf_stats = df_stats.reset_index()"
},
{
"code": null,
"e": 12600,
"s": 12443,
"text": "Doing joins in pandas is straightforward: data frames have a .join() method that we can use like this:df1.join(df2.set_index('key_column'), on='key_column')"
},
{
"code": null,
"e": 12667,
"s": 12600,
"text": "There are more types of joins: inner, full, left, and right joins."
},
{
"code": null,
"e": 12733,
"s": 12667,
"text": "INNER JOIN: returns rows that have matching values in both tables"
},
{
"code": null,
"e": 12812,
"s": 12733,
"text": "FULL (OUTER) JOIN: returns rows that have matching values in any of the tables"
},
{
"code": null,
"e": 12901,
"s": 12812,
"text": "LEFT JOIN: returns all rows from the left table, and the matched rows from the right one"
},
{
"code": null,
"e": 12991,
"s": 12901,
"text": "RIGHT JOIN: returns all rows from the right table, and the matched rows from the left one"
},
{
"code": null,
"e": 13154,
"s": 12991,
"text": "To specify which type of join you want in pandas you can use the how parameter in .join() method. This parameter can be one of: 'inner', 'outer', 'left', 'right'."
},
{
"code": null,
"e": 13335,
"s": 13154,
"text": "Below is an example of inner join of the two data frames above on ‘video_id’ column. The other types of joins are done in the same way, just change the ‘how’ parameter accordingly."
},
{
"code": null,
"e": 13354,
"s": 13335,
"text": "Inner join in SQL:"
},
{
"code": null,
"e": 13438,
"s": 13354,
"text": "SELECT *FROM df_titlesINNER JOIN df_statsON df_titles.video_id = df_stats.video_id;"
},
{
"code": null,
"e": 13460,
"s": 13438,
"text": "Inner join in pandas:"
},
{
"code": null,
"e": 13535,
"s": 13460,
"text": "df_titles.join(df_stats.set_index('video_id'), on='video_id', how='inner')"
},
{
"code": null,
"e": 13582,
"s": 13535,
"text": "A notebook for this article can be found here."
},
{
"code": null,
"e": 13647,
"s": 13582,
"text": "I hope you found this information useful and thanks for reading!"
}
] |
Functional Programming with Java - Quick Guide | In functional programming paradigm, an application is written mostly using pure functions. Here pure function is a function having no side effects. An example of side effect is modification of instance level variable while returning a value from the function.
Following are the key aspects of functional programming.
Functions − A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again.
Functional Programming revolves around first class functions, pure functions and high order functions.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A High Order Function is the one which can either take a function as an argument and/or can return a function.
A Pure Function is the one which has no side effect while its execution.
Functions − A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again.
Functional Programming revolves around first class functions, pure functions and high order functions.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A High Order Function is the one which can either take a function as an argument and/or can return a function.
A High Order Function is the one which can either take a function as an argument and/or can return a function.
A Pure Function is the one which has no side effect while its execution.
A Pure Function is the one which has no side effect while its execution.
Functional Composition − In imperative programming, functions are used to organize an executable code and emphasis is on organization of code. But in functional programming, emphasis is on how functions are organized and combined. Often data and functions are passed together as arguments and returned. This makes programming more capable and expressive.
Functional Composition − In imperative programming, functions are used to organize an executable code and emphasis is on organization of code. But in functional programming, emphasis is on how functions are organized and combined. Often data and functions are passed together as arguments and returned. This makes programming more capable and expressive.
Fluent Interfaces − Fluent interfaces helps in composing expressions which are easy to write and understand. These interfaces helps in chaining the method call when each method return type is again reused. For example −
Fluent Interfaces − Fluent interfaces helps in composing expressions which are easy to write and understand. These interfaces helps in chaining the method call when each method return type is again reused. For example −
LocalDate futureDate = LocalDate.now().plusYears(2).plusDays(3);
Eager vs Lazy Evaluation − Eager evaluation means expressions are evaluated as soon as they are encountered whereas lazy evaluation refers to delaying the execution till certain condition is met. For example, stream methods in Java 8 are evaluated when a terminal method is encountered.
Eager vs Lazy Evaluation − Eager evaluation means expressions are evaluated as soon as they are encountered whereas lazy evaluation refers to delaying the execution till certain condition is met. For example, stream methods in Java 8 are evaluated when a terminal method is encountered.
Persistent Data Structures − A persistent data structure maintains its previous version. Whenever data structure state is changed, a new copy of structure is created so data structure remains effectively immutable. Such immutable collections are thread safe.
Persistent Data Structures
Recursion − A repeated calculation can be done by making a loop or using recursion more elegantly. A function is called recursive function if it calls itself.
Recursion − A repeated calculation can be done by making a loop or using recursion more elegantly. A function is called recursive function if it calls itself.
Parallelism − Functions with no side effects can be called in any order and thus are candidate of lazy evaluation. Functional programming in Java supports parallelism using streams where parallel processing is provided.
Parallelism − Functions with no side effects can be called in any order and thus are candidate of lazy evaluation. Functional programming in Java supports parallelism using streams where parallel processing is provided.
Optionals − Optional is a special class which enforces that a function should never return null. It should return value using Optional class object. This returned object has method isPresent which can be checked to get the value only if present.
Optionals − Optional is a special class which enforces that a function should never return null. It should return value using Optional class object. This returned object has method isPresent which can be checked to get the value only if present.
A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again.
Functional Programming revolves around first class functions, pure functions and high order functions.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A High Order Function is the one which can take a function as an argument and/or can return a function.
A High Order Function is the one which can take a function as an argument and/or can return a function.
A Pure Function is the one which has no side effect while its execution.
A Pure Function is the one which has no side effect while its execution.
A first class function can be treated as a variable. That means it can be passed as a parameter to a function, it can be returned by a function or can be assigned to a variable as well. Java supports first class function using lambda expression. A lambda expression is analogous to an anonymous function. See the example below −
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
SquareMaker squareMaker = item -> item * item;
for(int i = 0; i < array.length; i++){
System.out.println(squareMaker.square(array[i]));
}
}
}
interface SquareMaker {
int square(int item);
}
1
4
9
16
25
Here we have created the implementation of square function using a lambda expression and assigned it to variable squareMaker.
A high order function either takes a function as a parameter or returns a function. In Java, we can pass or return a lambda expression to achieve such functionality.
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Function<Integer, Integer> square = t -> t * t;
Function<Integer, Integer> cube = t -> t * t * t;
for(int i = 0; i < array.length; i++){
print(square, array[i]);
}
for(int i = 0; i < array.length; i++){
print(cube, array[i]);
}
}
private static <T, R> void print(Function<T, R> function, T t ) {
System.out.println(function.apply(t));
}
}
1
4
9
16
25
1
8
27
64
125
A pure function does not modify any global variable or modify any reference passed as a parameter to it. So it has no side-effect. It always returns the same value when invoked with same parameters. Such functions are very useful and are thread safe. In example below, sum is a pure function.
public class FunctionTester {
public static void main(String[] args) {
int a, b;
a = 1;
b = 2;
System.out.println(sum(a, b));
}
private static int sum(int a, int b){
return a + b;
}
}
3
Functional composition refers to a technique where multiple functions are combined together to a single function. We can combine lambda expression together. Java provides inbuilt support using Predicate and Function classes. Following example shows how to combine two functions using predicate approach.
import java.util.function.Predicate;
public class FunctionTester {
public static void main(String[] args) {
Predicate<String> hasName = text -> text.contains("name");
Predicate<String> hasPassword = text -> text.contains("password");
Predicate<String> hasBothNameAndPassword = hasName.and(hasPassword);
String queryString = "name=test;password=test";
System.out.println(hasBothNameAndPassword.test(queryString));
}
}
true
Predicate provides and() and or() method to combine functions. Whereas Function provides compose and andThen methods to combine functions. Following example shows how to combine two functions using Function approach.
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Integer> multiply = t -> t *3;
Function<Integer, Integer> add = t -> t + 3;
Function<Integer, Integer> FirstMultiplyThenAdd = multiply.compose(add);
Function<Integer, Integer> FirstAddThenMultiply = multiply.andThen(add);
System.out.println(FirstMultiplyThenAdd.apply(3));
System.out.println(FirstAddThenMultiply.apply(3));
}
}
18
12
Eager evaluation means expression is evaluated as soon as it is encountered where as lazy evaluation refers to evaluation of an expression when needed. See the following example to under the concept.
import java.util.function.Supplier;
public class FunctionTester {
public static void main(String[] args) {
String queryString = "password=test";
System.out.println(checkInEagerWay(hasName(queryString)
, hasPassword(queryString)));
System.out.println(checkInLazyWay(() -> hasName(queryString)
, () -> hasPassword(queryString)));
}
private static boolean hasName(String queryString){
System.out.println("Checking name: ");
return queryString.contains("name");
}
private static boolean hasPassword(String queryString){
System.out.println("Checking password: ");
return queryString.contains("password");
}
private static String checkInEagerWay(boolean result1, boolean result2){
return (result1 && result2) ? "all conditions passed": "failed.";
}
private static String checkInLazyWay(Supplier<Boolean> result1, Supplier<Boolean> result2){
return (result1.get() && result2.get()) ? "all conditions passed": "failed.";
}
}
Checking name:
Checking password:
failed.
Checking name:
failed.
Here checkInEagerWay() function first evaluated the parameters then executes its statement. Whereas checkInLazyWay() executes its statement and evaluates the parameter on need basis. As && is a short-circuit operator, checkInLazyWay only evaluated first parameter which comes as false and does not evaluate the second parameter at all.
A data structure is said to be persistent if it is capable to maintaining its previous updates as separate versions and each version can be accessed and updated accordingly. It makes the data structure immutable and thread safe. For example, String class object in Java is immutable. Whenever we make any change to string, JVM creates another string object, assigned it the new value and preserve the older value as old string object.
A persistent data structure is also called a functional data structure. Consider the following case −
public static Person updateAge(Person person, int age){
person.setAge(age);
return person;
}
public static Person updateAge(Person pPerson, int age){
Person person = new Person();
person.setAge(age);
return person;
}
Recursion is calling a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive.
Following examples shows the calculation of sum of natural numbers using both the techniques.
public class FunctionTester {
public static void main(String[] args) {
System.out.println("Sum using imperative way. Sum(5) : " + sum(5));
System.out.println("Sum using recursive way. Sum(5) : " + sumRecursive(5));
}
private static int sum(int n){
int result = 0;
for(int i = 1; i <= n; i++){
result = result + i;
}
return result;
}
private static int sumRecursive(int n){
if(n == 1){
return 1;
}else{
return n + sumRecursive(n-1);
}
}
}
Sum using imperative way. Sum(5) : 15
Sum using recursive way. Sum(5) : 15
Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result.
Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion.
public class FunctionTester {
public static void main(String[] args) {
printUsingTailRecursion(5);
}
public static void printUsingTailRecursion(int n){
if(n == 0)
return;
else
System.out.println(n);
printUsingTailRecursion(n-1);
}
}
5
4
3
2
1
Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion.
public class FunctionTester {
public static void main(String[] args) {
printUsingHeadRecursion(5);
}
public static void printUsingHeadRecursion(int n){
if(n == 0)
return;
else
printUsingHeadRecursion(n-1);
System.out.println(n);
}
}
1
2
3
4
5
Parallelism is a key concept of functional programming where a big task is accomplished by breaking in smaller independent tasks and then these small tasks are completed in a parallel fashion and later combined to give the complete result. With the advent of multi-core processors, this technique helps in faster code execution. Java has Thread based programming support for parallel processing but it is quite tedious to learn and difficult to implement without bugs. Java 8 onwards, stream have parallel method and collections has parallelStream() method to complete tasks in parallel fashion. See the example below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FunctionTester {
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8 };
List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));
System.out.println("List using Serial Stream:");
listOfIntegers
.stream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("List using Parallel Stream:");
listOfIntegers
.parallelStream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("List using Another Parallel Stream:");
listOfIntegers
.stream()
.parallel()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("List using Parallel Stream but Ordered:");
listOfIntegers
.parallelStream()
.forEachOrdered(e -> System.out.print(e + " "));
System.out.println("");
}
}
List using Serial Stream:
1 2 3 4 5 6 7 8
List using Parallel Stream:
6 5 8 7 3 4 2 1
List using Another Parallel Stream:
6 2 1 7 4 3 8 5
List using Parallel Stream but Ordered:
1 2 3 4 5 6 7 8
Monad is a key concept of Functional Programming. A Monad is a design pattern which helps to represent a missing value. It allows to wrap a potential null value, allows to put transformation around it and pull actual value if present. By definition, a monad is a set of following parameters.
A parametrized Type − M<T>
A parametrized Type − M<T>
A unit Function − T −> M<T>
A unit Function − T −> M<T>
A bind operation − M<T> bind T −> M<U> = M<U>
A bind operation − M<T> bind T −> M<U> = M<U>
Left Identity − If a function is bind on a monad of a particular value then its result will be same as if function is applied to the value.
Left Identity − If a function is bind on a monad of a particular value then its result will be same as if function is applied to the value.
Right Identity − If a monad return method is same as monad on original value.
Right Identity − If a monad return method is same as monad on original value.
Associativity − Functions can be applied in any order on a monad.
Associativity − Functions can be applied in any order on a monad.
Java 8 introduced Optional class which is a monad. It provides operational equivalent to a monad. For example return is a operation which takes a value and return the monad. Optional.of() takes a parameters and returns the Optional Object. On similar basis , bind is operation which binds a function to a monad to produce a monad. Optional.flatMap() is the method which performs an operation on Optional and return the result as Optional.
A parametrized Type − Optional<T>
A parametrized Type − Optional<T>
A unit Function − Optional.of()
A unit Function − Optional.of()
A bind operation − Optional.flatMap()
A bind operation − Optional.flatMap()
Following example shows how Optional class obeys Left Identity rule.
import java.util.Optional;
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Optional<Integer>> addOneToX
= x −> Optional.of(x + 1);
System.out.println(Optional.of(5).flatMap(addOneToX)
.equals(addOneToX.apply(5)));
}
}
true
Following example shows how Optional class obeys Right Identity rule.
import java.util.Optional;
public class FunctionTester {
public static void main(String[] args) {
System.out.println(Optional.of(5).flatMap(Optional::of)
.equals(Optional.of(5)));
}
}
true
Following example shows how Optional class obeys Associativity rule.
import java.util.Optional;
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Optional<Integer>> addOneToX
= x −> Optional.of(x + 1);
Function<Integer, Optional<Integer>> addTwoToX
= x −> Optional.of(x + 2);
Function<Integer, Optional<Integer>> addThreeToX
= x −> addOneToX.apply(x).flatMap(addTwoToX);
Optional.of(5).flatMap(addOneToX).flatMap(addTwoToX)
.equals(Optional.of(5).flatMap(addThreeToX));
}
}
true
A closure is a function which is a combination of function along with its surrounding state. A closure function generally have access to outer function's scope. In the example given below, we have created a function getWeekDay(String[] days) which returns a function which can return the text equivalent of a weekday. Here getWeekDay() is a closure which is returning a function surrounding the calling function's scope.
Following example shows how Closure works.
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
String[] weekDays = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
Function<Integer, String> getIndianWeekDay = getWeekDay(weekDays);
System.out.println(getIndianWeekDay.apply(6));
}
public static Function<Integer, String> getWeekDay(String[] weekDays){
return index -> index >= 0 ? weekDays[index % 7] : null;
}
}
Sunday
Currying is a technique where a many arguments function call is replaced with multiple method calls with lesser arguments.
See the below equation.
(1 + 2 + 3) = 1 + (2 + 3) = 1 + 5 = 6
In terms of functions:
f(1,2,3) = g(1) + h(2 + 3) = 1 + 5 = 6
This cascading of functions is called currying and calls to cascaded functions must gives the same result as by calling the main function.
Following example shows how Currying works.
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Function<Integer, Function<Integer, Integer>>>
addNumbers = u -> v -> w -> u + v + w;
int result = addNumbers.apply(2).apply(3).apply(4);
System.out.println(result);
}
}
9
In functional programming, reducing is a technique to reduce a stream of values to a single result by apply a function on all the values. Java provides reduce() function in a Stream class from Java 8 onwards. A stream has inbuilt reducing methods like sum(), average(), count() as well which works on all elements of the stream and returns the single result.
Following example shows how Reducing works.
import java.util.stream.IntStream;
public class FunctionTester {
public static void main(String[] args) {
//1 * 2 * 3 * 4 = 24
int product = IntStream.range(1, 5)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1);
//1 + 2 + 3 + 4 = 10
int sum = IntStream.range(1, 5).sum();
System.out.println(product);
System.out.println(sum);
}
}
24
10
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.
A lambda expression is characterized by the following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
public class Java8Tester {
public static void main(String args[]) {
Java8Tester tester = new Java8Tester();
//with type declaration
MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
MathOperation subtraction = (a, b) -> a - b;
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
//without parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
//with parenthesis
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.
Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.
Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
public class Java8Tester {
final static String salutation = "Hello! ";
public static void main(String args[]) {
GreetingService greetService1 = message ->
System.out.println(salutation + message);
greetService1.sayMessage("Mahesh");
}
interface GreetingService {
void sayMessage(String message);
}
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
Hello! Mahesh
Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8.
For example, 'List' or 'Collection' interfaces do not have 'forEach' method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
}
With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
}
public interface fourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
First solution is to create an own method that overrides the default implementation.
public class car implements vehicle, fourWheeler {
public void print() {
System.out.println("I am a four wheeler car vehicle!");
}
}
Second solution is to call the default method of the specified interface using super.
public class car implements vehicle, fourWheeler {
default void print() {
vehicle.super.print();
}
}
An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
public class Java8Tester {
public static void main(String args[]) {
Vehicle vehicle = new Car();
vehicle.print();
}
}
interface Vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
class Car implements Vehicle, FourWheeler {
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.
BiConsumer<T,U>
Represents an operation that accepts two input arguments, and returns no result.
BiFunction<T,U,R>
Represents a function that accepts two arguments and produces a result.
BinaryOperator<T>
Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
BiPredicate<T,U>
Represents a predicate (Boolean-valued function) of two arguments.
BooleanSupplier
Represents a supplier of Boolean-valued results.
Consumer<T>
Represents an operation that accepts a single input argument and returns no result.
DoubleBinaryOperator
Represents an operation upon two double-valued operands and producing a double-valued result.
DoubleConsumer
Represents an operation that accepts a single double-valued argument and returns no result.
DoubleFunction<R>
Represents a function that accepts a double-valued argument and produces a result.
DoublePredicate
Represents a predicate (Boolean-valued function) of one double-valued argument.
DoubleSupplier
Represents a supplier of double-valued results.
DoubleToIntFunction
Represents a function that accepts a double-valued argument and produces an int-valued result.
DoubleToLongFunction
Represents a function that accepts a double-valued argument and produces a long-valued result.
DoubleUnaryOperator
Represents an operation on a single double-valued operand that produces a double-valued result.
Function<T,R>
Represents a function that accepts one argument and produces a result.
IntBinaryOperator
Represents an operation upon two int-valued operands and produces an int-valued result.
IntConsumer
Represents an operation that accepts a single int-valued argument and returns no result.
IntFunction<R>
Represents a function that accepts an int-valued argument and produces a result.
IntPredicate
Represents a predicate (Boolean-valued function) of one int-valued argument.
IntSupplier
Represents a supplier of int-valued results.
IntToDoubleFunction
Represents a function that accepts an int-valued argument and produces a double-valued result.
IntToLongFunction
Represents a function that accepts an int-valued argument and produces a long-valued result.
IntUnaryOperator
Represents an operation on a single int-valued operand that produces an int-valued result.
LongBinaryOperator
Represents an operation upon two long-valued operands and produces a long-valued result.
LongConsumer
Represents an operation that accepts a single long-valued argument and returns no result.
LongFunction<R>
Represents a function that accepts a long-valued argument and produces a result.
LongPredicate
Represents a predicate (Boolean-valued function) of one long-valued argument.
LongSupplier
Represents a supplier of long-valued results.
LongToDoubleFunction
Represents a function that accepts a long-valued argument and produces a double-valued result.
LongToIntFunction
Represents a function that accepts a long-valued argument and produces an int-valued result.
LongUnaryOperator
Represents an operation on a single long-valued operand that produces a long-valued result.
ObjDoubleConsumer<T>
Represents an operation that accepts an object-valued and a double-valued argument, and returns no result.
ObjIntConsumer<T>
Represents an operation that accepts an object-valued and an int-valued argument, and returns no result.
ObjLongConsumer<T>
Represents an operation that accepts an object-valued and a long-valued argument, and returns no result.
Predicate<T>
Represents a predicate (Boolean-valued function) of one argument.
Supplier<T>
Represents a supplier of results.
ToDoubleBiFunction<T,U>
Represents a function that accepts two arguments and produces a double-valued result.
ToDoubleFunction<T>
Represents a function that produces a double-valued result.
ToIntBiFunction<T,U>
Represents a function that accepts two arguments and produces an int-valued result.
ToIntFunction<T>
Represents a function that produces an int-valued result.
ToLongBiFunction<T,U>
Represents a function that accepts two arguments and produces a long-valued result.
ToLongFunction<T>
Represents a function that produces a long-valued result.
UnaryOperator<T>
Represents an operation on a single operand that produces a result of the same type as its operand.
Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Java8Tester {
public static void main(String args[]) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Predicate<Integer> predicate = n -> true
// n is passed as parameter to test method of Predicate interface
// test method will always return true no matter what value n has.
System.out.println("Print all numbers:");
//pass n as parameter
eval(list, n->true);
// Predicate<Integer> predicate1 = n -> n%2 == 0
// n is passed as parameter to test method of Predicate interface
// test method will return true if n%2 comes to be zero
System.out.println("Print even numbers:");
eval(list, n-> n%2 == 0 );
// Predicate<Integer> predicate2 = n -> n > 3
// n is passed as parameter to test method of Predicate interface
// test method will return true if n is greater than 3.
System.out.println("Print numbers greater than 3:");
eval(list, n-> n > 3 );
}
public static void eval(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}
Here we've passed Predicate interface, which takes a single input and returns Boolean.
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
Print all numbers:
1
2
3
4
5
6
7
8
9
Print even numbers:
2
4
6
8
Print numbers greater than 3:
4
5
6
7
8
9
Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
Static methods - static method can be reference using ClassName::Method name notation.
Static methods - static method can be reference using ClassName::Method name notation.
//Method Reference - Static way
Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;
Instance methods - instance method can be reference using Object::Method name notation.
Instance methods - instance method can be reference using Object::Method name notation.
//Method Reference - Instance way
Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;
Following example shows how Method references works in Java 8 onwards.
interface Factory {
Vehicle prepare(String make, String model, int year);
}
class Vehicle {
private String make;
private String model;
private int year;
Vehicle(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
public String toString(){
return "Vehicle[" + make +", " + model + ", " + year+ "]";
}
}
class VehicleFactory {
static Vehicle prepareVehicleInStaticMode(String make, String model, int year){
return new Vehicle(make, model, year);
}
Vehicle prepareVehicle(String make, String model, int year){
return new Vehicle(make, model, year);
}
}
public class FunctionTester {
public static void main(String[] args) {
//Method Reference - Static way
Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode;
Vehicle carHyundai = vehicle_factory_static.prepare("Hyundai", "Verna", 2018);
System.out.println(carHyundai);
//Method Reference - Instance way
Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle;
Vehicle carTata = vehicle_factory_instance.prepare("Tata", "Harrier", 2019);
System.out.println(carTata);
}
}
Vehicle[Hyundai, Verna, 2018]
Vehicle[Tata, Harrier, 2019]
Constructor references help to point to Constructor method. A Constructor reference is accessed using "::new" symbol.
//Constructor reference
Factory vehicle_factory = Vehicle::new;
Following example shows how Constructor references works in Java 8 onwards.
interface Factory {
Vehicle prepare(String make, String model, int year);
}
class Vehicle {
private String make;
private String model;
private int year;
Vehicle(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
public String toString(){
return "Vehicle[" + make +", " + model + ", " + year+ "]";
}
}
public class FunctionTester {
static Vehicle factory(Factory factoryObj, String make, String model, int year){
return factoryObj.prepare(make, model, year);
}
public static void main(String[] args) {
//Constructor reference
Factory vehicle_factory = Vehicle::new;
Vehicle carHonda = factory(vehicle_factory, "Honda", "Civic", 2017);
System.out.println(carHonda);
}
}
Vehicle[Honda, Civic, 2017]
With Java 8 onwards, streams are introduced in Java and methods are added to collections to get a stream. Once a stream object is retrieved from a collection, we can apply various functional programming aspects like filtering, mapping, reducing etc. on collections. See the example below −
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//Mapping
//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i -> i*i)
.distinct().collect(Collectors.toList());
System.out.println(squaresList);
//Filering
//get list of non-empty strings
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> nonEmptyStrings = strings.stream()
.filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println(nonEmptyStrings);
//Reducing
int sum = numbers.stream().reduce((num1, num2) -> num1 + num2).orElse(-1);
System.out.println(sum);
}
}
[9, 4, 49, 25]
[abc, bc, efg, abcd, jkl]
25
A function is considered as a High Order function if it fulfils any one of the following conditions.
It takes one or more parameters as functions.
It takes one or more parameters as functions.
It returns a function after its execution.
It returns a function after its execution.
Java 8 Collections.sort() method is an ideal example of a high order function. It accepts a comparing method as an argument. See the example below −
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 4, 6, 7, 9);
//Passing a function as lambda expression
Collections.sort(numbers, (a,b) ->{ return a.compareTo(b); });
System.out.println(numbers);
Comparator<Integer> comparator = (a,b) ->{ return a.compareTo(b); };
Comparator<Integer> reverseComparator = comparator.reversed();
//Passing a function
Collections.sort(numbers, reverseComparator);
System.out.println(numbers);
}
}
[3, 4, 6, 7, 9]
[9, 7, 6, 4, 3]
As a High Order function can return a function but how to implement using Java 8. Java 8 has provided Function interface which can accept a lambda expression. A high order function can return a lamdba expression and thus this high order function can be used to create any number of functions. See the example below −
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Integer> addOne = adder(1);
Function<Integer, Integer> addTwo = adder(2);
Function<Integer, Integer> addThree = adder(3);
//result = 4 + 1 = 5
Integer result = addOne.apply(4);
System.out.println(result);
//result = 4 + 2 = 6
result = addTwo.apply(4);
System.out.println(result);
//result = 4 + 3 = 7
result = addThree.apply(4);
System.out.println(result);
}
//adder - High Order Function
//returns a function as lambda expression
static Function<Integer, Integer> adder(Integer x){
return y -> y + x;
}
}
5
6
7
A function is called a first class function if it fulfills the following requirements.
It can be passed as a parameter to a function.
It can be passed as a parameter to a function.
It can be returned from a function.
It can be returned from a function.
It can be assigned to a variable and then can be used later.
It can be assigned to a variable and then can be used later.
Java 8 supports functions as first class object using lambda expressions. A lambda expression is a function definition and can be assigned to a variable, can be passed as an argument and can be returned. See the example below −
@FunctionalInterface
interface Calculator<X, Y> {
public X compute(X a, Y b);
}
public class FunctionTester {
public static void main(String[] args) {
//Assign a function to a variable
Calculator<Integer, Integer> calculator = (a,b) -> a * b;
//call a function using function variable
System.out.println(calculator.compute(2, 3));
//Pass the function as a parameter
printResult(calculator, 2, 3);
//Get the function as a return result
Calculator<Integer, Integer> calculator1 = getCalculator();
System.out.println(calculator1.compute(2, 3));
}
//Function as a parameter
static void printResult(Calculator<Integer, Integer> calculator, Integer a, Integer b){
System.out.println(calculator.compute(a, b));
}
//Function as return value
static Calculator<Integer, Integer> getCalculator(){
Calculator<Integer, Integer> calculator = (a,b) -> a * b;
return calculator;
}
}
6
6
6
A function is considered as Pure Function if it fulfils the following two conditions −
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It has no side effects means it is not modifying any state of the caller entity.
It has no side effects means it is not modifying any state of the caller entity.
public class FunctionTester {
public static void main(String[] args) {
int result = sum(2,3);
System.out.println(result);
result = sum(2,3);
System.out.println(result);
}
static int sum(int a, int b){
return a + b;
}
}
5
5
Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects.
public class FunctionTester {
private static double valueUsed = 0.0;
public static void main(String[] args) {
double result = randomSum(2.0,3.0);
System.out.println(result);
result = randomSum(2.0,3.0);
System.out.println(result);
}
static double randomSum(double a, double b){
valueUsed = Math.random();
return valueUsed + a + b;
}
}
5.919716721877799
5.4830887819586795
Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well.
Type inference is a technique by which a compiler automatically deduces the type of a parameter passed or of return type of a method. Java 8 onwards, Lambda expression uses type inference prominently.
See the example below for clarification on type inference.
public class FunctionTester {
public static void main(String[] args) {
Join<Integer,Integer,Integer> sum = (a,b) -> a + b;
System.out.println(sum.compute(10,20));
Join<String, String, String> concat = (a,b) -> a + b;
System.out.println(concat.compute("Hello ","World!"));
}
interface Join<K,V,R>{
R compute(K k ,V v);
}
}
30
Hello World!
A lambda expression treats each parameter and its return type as Object initially and then inferred the data type accordingly. In first case, the type inferred is Integer and in second case type inferred is String.
Lambda expressions are difficult to write when the function throws a checked expression. See the example below −
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(s -> URLEncoder.encode(s, "UTF-8"))
.collect(Collectors.joining(","));
}
}
The above code fails to compile because URLEncode.encode() throws UnsupportedEncodingException and cannot be thrown by encodeAddress() method.
One possible solution is to extract URLEncoder.encode() into a separate method and handle the exception there.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedString(String s) {
try {
URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(s -> encodedString(s))
.collect(Collectors.joining(","));
}
}
But above approach is not good when we have multiple such methods which throws exception. See the following generalized solution using functional interface and a wrapper method.
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(wrapper(s -> URLEncoder.encode(s, "UTF-8")))
.collect(Collectors.joining(","));
}
private static <T, R, E extends Exception> Function<T, R>
wrapper(FunctionWithThrows<T, R, E> fe) {
return arg -> {
try {
return fe.apply(arg);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
@FunctionalInterface
interface FunctionWithThrows<T, R, E extends Exception> {
R apply(T t) throws E;
}
www.google.com
Stream API was introduced in Java 8 to facilitate functional programming in Java. A Stream API is targeted towards processing of collections of objects in functional way. By definition, a Stream is a Java component which can do internal iteration of its elements.
A Stream interface has terminal as well as non-terminal methods. Non-terminal methods are such operations which adds a listener to a stream. When a terminal method of stream is invoked, then internal iteration of stream elements get started and listener(s) attached to stream are getting called for each element and result is collected by the terminal method.
Such non-terminal methods are called Intermediate methods. The Intermediate method can only be invoked by called a terminal method. Following are some of the important Intermediate methods of Stream interface.
filter − Filters out non-required elements from a stream based on given criteria. This method accepts a predicate and apply it on each element. If predicate function return true, element is included in returned stream.
filter − Filters out non-required elements from a stream based on given criteria. This method accepts a predicate and apply it on each element. If predicate function return true, element is included in returned stream.
map − Maps each element of a stream to another item based on given criteria. This method accepts a function and apply it on each element. For example, to convert each String element in a stream to upper-case String element.
map − Maps each element of a stream to another item based on given criteria. This method accepts a function and apply it on each element. For example, to convert each String element in a stream to upper-case String element.
flatMap − This method can be used to maps each element of a stream to multiple items based on given criteria. This method is used when a complex object needs to be broken into simple objects. For example, to convert list of sentences to list of words.
flatMap − This method can be used to maps each element of a stream to multiple items based on given criteria. This method is used when a complex object needs to be broken into simple objects. For example, to convert list of sentences to list of words.
distinct − Returns a stream of unique elements if duplicates are present.
distinct − Returns a stream of unique elements if duplicates are present.
limit − Returns a stream of limited elements where limit is specified by passing a number to limit method.
limit − Returns a stream of limited elements where limit is specified by passing a number to limit method.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class FunctionTester {
public static void main(String[] args) {
List<String> stringList =
Arrays.asList("One", "Two", "Three", "Four", "Five", "One");
System.out.println("Example - Filter\n");
//Filter strings whose length are greater than 3.
Stream<String> longStrings = stringList
.stream()
.filter( s -> {return s.length() > 3; });
//print strings
longStrings.forEach(System.out::println);
System.out.println("\nExample - Map\n");
//map strings to UPPER case and print
stringList
.stream()
.map( s -> s.toUpperCase())
.forEach(System.out::println);
List<String> sentenceList
= Arrays.asList("I am Mahesh.", "I love Java 8 Streams.");
System.out.println("\nExample - flatMap\n");
//map strings to UPPER case and print
sentenceList
.stream()
.flatMap( s -> { return (Stream<String>)
Arrays.asList(s.split(" ")).stream(); })
.forEach(System.out::println);
System.out.println("\nExample - distinct\n");
//map strings to UPPER case and print
stringList
.stream()
.distinct()
.forEach(System.out::println);
System.out.println("\nExample - limit\n");
//map strings to UPPER case and print
stringList
.stream()
.limit(2)
.forEach(System.out::println);
}
}
Example - Filter
Three
Four
Five
Example - Map
ONE
TWO
THREE
FOUR
FIVE
ONE
Example - flatMap
I
am
Mahesh.
I
love
Java
8
Streams.
Example - distinct
One
Two
Three
Four
Five
Example - limit
One
Two
When a terminal method in invoked on a stream, iteration starts on stream and any other chained stream. Once the iteration is over then the result of terminal method is returned. A terminal method does not return a Stream thus once a terminal method is invoked over a stream then its chaining of non-terminal methods or intermediate methods stops/terminates.
Generally, terminal methods returns a single value and are invoked on each element of the stream. Following are some of the important terminal methods of Stream interface. Each terminal function takes a predicate function, initiates the iterations of elements, apply the predicate on each element.
anyMatch − If predicate returns true for any of the element, it returns true. If no element matches, false is returned.
anyMatch − If predicate returns true for any of the element, it returns true. If no element matches, false is returned.
allMatch − If predicate returns false for any of the element, it returns false. If all element matches, true is returned.
allMatch − If predicate returns false for any of the element, it returns false. If all element matches, true is returned.
noneMatch − If no element matches, true is returned otherwise false is returned.
noneMatch − If no element matches, true is returned otherwise false is returned.
collect − each element is stored into the collection passed.
collect − each element is stored into the collection passed.
count − returns count of elements passed through intermediate methods.
count − returns count of elements passed through intermediate methods.
findAny − returns Optional instance containing any element or empty instance is returned.
findAny − returns Optional instance containing any element or empty instance is returned.
findFirst − returns first element under Optional instance. For empty stream, empty instance is returned.
findFirst − returns first element under Optional instance. For empty stream, empty instance is returned.
forEach − apply the consumer function on each element. Used to print all elements of a stream.
forEach − apply the consumer function on each element. Used to print all elements of a stream.
min − returns the smallest element of the stream. Compares elements based on comparator predicate passed.
min − returns the smallest element of the stream. Compares elements based on comparator predicate passed.
max − returns the largest element of the stream. Compares elements based on comparator predicate passed.
max − returns the largest element of the stream. Compares elements based on comparator predicate passed.
reduce − reduces all elements to a single element using the predicate passed.
reduce − reduces all elements to a single element using the predicate passed.
toArray − returns arrays of elements of stream.
toArray − returns arrays of elements of stream.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
List<String> stringList
= Arrays.asList("One", "Two", "Three", "Four", "Five", "One");
System.out.println("Example - anyMatch\n");
//anyMatch - check if Two is present?
System.out.println("Two is present: "
+ stringList
.stream()
.anyMatch(s -> {return s.contains("Two");}));
System.out.println("\nExample - allMatch\n");
//allMatch - check if length of each string is greater than 2.
System.out.println("Length > 2: "
+ stringList
.stream()
.allMatch(s -> {return s.length() > 2;}));
System.out.println("\nExample - noneMatch\n");
//noneMatch - check if length of each string is greater than 6.
System.out.println("Length > 6: "
+ stringList
.stream()
.noneMatch(s -> {return s.length() > 6;}));
System.out.println("\nExample - collect\n");
System.out.println("List: "
+ stringList
.stream()
.filter(s -> {return s.length() > 3;})
.collect(Collectors.toList()));
System.out.println("\nExample - count\n");
System.out.println("Count: "
+ stringList
.stream()
.filter(s -> {return s.length() > 3;})
.count());
System.out.println("\nExample - findAny\n");
System.out.println("findAny: "
+ stringList
.stream()
.findAny().get());
System.out.println("\nExample - findFirst\n");
System.out.println("findFirst: "
+ stringList
.stream()
.findFirst().get());
System.out.println("\nExample - forEach\n");
stringList
.stream()
.forEach(System.out::println);
System.out.println("\nExample - min\n");
System.out.println("min: "
+ stringList
.stream()
.min((s1, s2) -> { return s1.compareTo(s2);}));
System.out.println("\nExample - max\n");
System.out.println("min: "
+ stringList
.stream()
.max((s1, s2) -> { return s1.compareTo(s2);}));
System.out.println("\nExample - reduce\n");
System.out.println("reduced: "
+ stringList
.stream()
.reduce((s1, s2) -> { return s1 + ", "+ s2;})
.get());
}
}
Example - anyMatch
Two is present: true
Example - allMatch
Length > 2: true
Example - noneMatch
Length > 6: true
Example - collect
List: [Three, Four, Five]
Example - count
Count: 3
Example - findAny
findAny: One
Example - findFirst
findFirst: One
Example - forEach
One
Two
Three
Four
Five
One
Example - min
min: Optional[Five]
Example - max
min: Optional[Two]
Example - reduce
reduced: One, Two, Three, Four, Five, One
Collections are in-memory data structure which have all the elements present in the collection and we have external iteration to iterate through collection whereas Stream is a fixed data structure where elements are computed on demand and a Stream has inbuilt iteration to iterate through each element. Following example shows how to create a Stream from an array.
int[] numbers = {1, 2, 3, 4};
IntStream numbersFromArray = Arrays.stream(numbers);
Above stream is of fixed size being built from an array of four numbers and will not return element after 4th element. But we can create a Stream using Stream.iterate() or Stream.generate() method which can have lamdba expression will pass to a Stream. Using lamdba expression, we can pass a condition which once fulfilled give the required elements. Consider the case, where we need a list of numbers which are multiple of 3.
import java.util.stream.Stream;
public class FunctionTester {
public static void main(String[] args) {
//create a stream of numbers which are multiple of 3
Stream<Integer> numbers = Stream.iterate(0, n -> n + 3);
numbers
.limit(10)
.forEach(System.out::println);
}
}
0
3
6
9
12
15
18
21
24
27
In order to operate on infinite stream, we've used limit() method of Stream interface to restrict the iteration of numbers when their count become 10.
There are multiple ways using which we can create fix length streams.
Using Stream.of() method
Using Stream.of() method
Using Collection.stream() method
Using Collection.stream() method
Using Stream.builder() method
Using Stream.builder() method
Following example shows all of the above ways to create a fix length stream.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class FunctionTester {
public static void main(String[] args) {
System.out.println("Stream.of():");
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.forEach(System.out::println);
System.out.println("Collection.stream():");
Integer[] numbers = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(numbers);
list.stream().forEach(System.out::println);
System.out.println("StreamBuilder.build():");
Stream.Builder<Integer> streamBuilder = Stream.builder();
streamBuilder.accept(1);
streamBuilder.accept(2);
streamBuilder.accept(3);
streamBuilder.accept(4);
streamBuilder.accept(5);
streamBuilder.build().forEach(System.out::println);
}
}
Stream.of():
1
2
3
4
5
Collection.stream():
1
2
3
4
5
StreamBuilder.build():
1
2
3
4
5
32 Lectures
3.5 hours
Pavan Lalwani
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
72 Lectures
10.5 hours
Arun Ammasai
51 Lectures
2 hours
Skillbakerystudios
43 Lectures
4 hours
Mohammad Nauman
8 Lectures
1 hours
Santharam Sivalenka
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2349,
"s": 2089,
"text": "In functional programming paradigm, an application is written mostly using pure functions. Here pure function is a function having no side effects. An example of side effect is modification of instance level variable while returning a value from the function."
},
{
"code": null,
"e": 2406,
"s": 2349,
"text": "Following are the key aspects of functional programming."
},
{
"code": null,
"e": 3174,
"s": 2406,
"text": "Functions − A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again.\nFunctional Programming revolves around first class functions, pure functions and high order functions.\n\nA First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.\nA High Order Function is the one which can either take a function as an argument and/or can return a function.\nA Pure Function is the one which has no side effect while its execution.\n\n"
},
{
"code": null,
"e": 3489,
"s": 3174,
"text": "Functions − A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again."
},
{
"code": null,
"e": 3592,
"s": 3489,
"text": "Functional Programming revolves around first class functions, pure functions and high order functions."
},
{
"code": null,
"e": 3755,
"s": 3592,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 3918,
"s": 3755,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 4029,
"s": 3918,
"text": "A High Order Function is the one which can either take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 4140,
"s": 4029,
"text": "A High Order Function is the one which can either take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 4213,
"s": 4140,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 4286,
"s": 4213,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 4642,
"s": 4286,
"text": "Functional Composition − In imperative programming, functions are used to organize an executable code and emphasis is on organization of code. But in functional programming, emphasis is on how functions are organized and combined. Often data and functions are passed together as arguments and returned. This makes programming more capable and expressive."
},
{
"code": null,
"e": 4998,
"s": 4642,
"text": "Functional Composition − In imperative programming, functions are used to organize an executable code and emphasis is on organization of code. But in functional programming, emphasis is on how functions are organized and combined. Often data and functions are passed together as arguments and returned. This makes programming more capable and expressive."
},
{
"code": null,
"e": 5218,
"s": 4998,
"text": "Fluent Interfaces − Fluent interfaces helps in composing expressions which are easy to write and understand. These interfaces helps in chaining the method call when each method return type is again reused. For example −"
},
{
"code": null,
"e": 5438,
"s": 5218,
"text": "Fluent Interfaces − Fluent interfaces helps in composing expressions which are easy to write and understand. These interfaces helps in chaining the method call when each method return type is again reused. For example −"
},
{
"code": null,
"e": 5503,
"s": 5438,
"text": "LocalDate futureDate = LocalDate.now().plusYears(2).plusDays(3);"
},
{
"code": null,
"e": 5790,
"s": 5503,
"text": "Eager vs Lazy Evaluation − Eager evaluation means expressions are evaluated as soon as they are encountered whereas lazy evaluation refers to delaying the execution till certain condition is met. For example, stream methods in Java 8 are evaluated when a terminal method is encountered."
},
{
"code": null,
"e": 6077,
"s": 5790,
"text": "Eager vs Lazy Evaluation − Eager evaluation means expressions are evaluated as soon as they are encountered whereas lazy evaluation refers to delaying the execution till certain condition is met. For example, stream methods in Java 8 are evaluated when a terminal method is encountered."
},
{
"code": null,
"e": 6336,
"s": 6077,
"text": "Persistent Data Structures − A persistent data structure maintains its previous version. Whenever data structure state is changed, a new copy of structure is created so data structure remains effectively immutable. Such immutable collections are thread safe."
},
{
"code": null,
"e": 6363,
"s": 6336,
"text": "Persistent Data Structures"
},
{
"code": null,
"e": 6522,
"s": 6363,
"text": "Recursion − A repeated calculation can be done by making a loop or using recursion more elegantly. A function is called recursive function if it calls itself."
},
{
"code": null,
"e": 6681,
"s": 6522,
"text": "Recursion − A repeated calculation can be done by making a loop or using recursion more elegantly. A function is called recursive function if it calls itself."
},
{
"code": null,
"e": 6901,
"s": 6681,
"text": "Parallelism − Functions with no side effects can be called in any order and thus are candidate of lazy evaluation. Functional programming in Java supports parallelism using streams where parallel processing is provided."
},
{
"code": null,
"e": 7121,
"s": 6901,
"text": "Parallelism − Functions with no side effects can be called in any order and thus are candidate of lazy evaluation. Functional programming in Java supports parallelism using streams where parallel processing is provided."
},
{
"code": null,
"e": 7368,
"s": 7121,
"text": "Optionals − Optional is a special class which enforces that a function should never return null. It should return value using Optional class object. This returned object has method isPresent which can be checked to get the value only if present. "
},
{
"code": null,
"e": 7615,
"s": 7368,
"text": "Optionals − Optional is a special class which enforces that a function should never return null. It should return value using Optional class object. This returned object has method isPresent which can be checked to get the value only if present. "
},
{
"code": null,
"e": 7918,
"s": 7615,
"text": "A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again."
},
{
"code": null,
"e": 8021,
"s": 7918,
"text": "Functional Programming revolves around first class functions, pure functions and high order functions."
},
{
"code": null,
"e": 8184,
"s": 8021,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 8347,
"s": 8184,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 8451,
"s": 8347,
"text": "A High Order Function is the one which can take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 8555,
"s": 8451,
"text": "A High Order Function is the one which can take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 8628,
"s": 8555,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 8701,
"s": 8628,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 9030,
"s": 8701,
"text": "A first class function can be treated as a variable. That means it can be passed as a parameter to a function, it can be returned by a function or can be assigned to a variable as well. Java supports first class function using lambda expression. A lambda expression is analogous to an anonymous function. See the example below −"
},
{
"code": null,
"e": 9364,
"s": 9030,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n int[] array = {1, 2, 3, 4, 5};\n SquareMaker squareMaker = item -> item * item;\n for(int i = 0; i < array.length; i++){\n System.out.println(squareMaker.square(array[i]));\n }\n }\n}\ninterface SquareMaker {\n int square(int item);\n}"
},
{
"code": null,
"e": 9377,
"s": 9364,
"text": "1\n4\n9\n16\n25\n"
},
{
"code": null,
"e": 9503,
"s": 9377,
"text": "Here we have created the implementation of square function using a lambda expression and assigned it to variable squareMaker."
},
{
"code": null,
"e": 9669,
"s": 9503,
"text": "A high order function either takes a function as a parameter or returns a function. In Java, we can pass or return a lambda expression to achieve such functionality."
},
{
"code": null,
"e": 10244,
"s": 9669,
"text": "import java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n int[] array = {1, 2, 3, 4, 5};\n\n Function<Integer, Integer> square = t -> t * t; \n Function<Integer, Integer> cube = t -> t * t * t;\n\n for(int i = 0; i < array.length; i++){\n print(square, array[i]);\n } \n for(int i = 0; i < array.length; i++){\n print(cube, array[i]);\n }\n }\n\n private static <T, R> void print(Function<T, R> function, T t ) {\n System.out.println(function.apply(t));\n }\n}"
},
{
"code": null,
"e": 10271,
"s": 10244,
"text": "1\n4\n9\n16\n25\n1\n8\n27\n64\n125\n"
},
{
"code": null,
"e": 10564,
"s": 10271,
"text": "A pure function does not modify any global variable or modify any reference passed as a parameter to it. So it has no side-effect. It always returns the same value when invoked with same parameters. Such functions are very useful and are thread safe. In example below, sum is a pure function."
},
{
"code": null,
"e": 10791,
"s": 10564,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n int a, b;\n a = 1;\n b = 2;\n System.out.println(sum(a, b));\n }\n\n private static int sum(int a, int b){\n return a + b;\n }\n}"
},
{
"code": null,
"e": 10794,
"s": 10791,
"text": "3\n"
},
{
"code": null,
"e": 11098,
"s": 10794,
"text": "Functional composition refers to a technique where multiple functions are combined together to a single function. We can combine lambda expression together. Java provides inbuilt support using Predicate and Function classes. Following example shows how to combine two functions using predicate approach."
},
{
"code": null,
"e": 11551,
"s": 11098,
"text": "import java.util.function.Predicate;\npublic class FunctionTester {\n public static void main(String[] args) {\n Predicate<String> hasName = text -> text.contains(\"name\");\n Predicate<String> hasPassword = text -> text.contains(\"password\");\n Predicate<String> hasBothNameAndPassword = hasName.and(hasPassword);\n String queryString = \"name=test;password=test\";\n System.out.println(hasBothNameAndPassword.test(queryString));\n }\n}"
},
{
"code": null,
"e": 11557,
"s": 11551,
"text": "true\n"
},
{
"code": null,
"e": 11774,
"s": 11557,
"text": "Predicate provides and() and or() method to combine functions. Whereas Function provides compose and andThen methods to combine functions. Following example shows how to combine two functions using Function approach."
},
{
"code": null,
"e": 12270,
"s": 11774,
"text": "import java.util.function.Function;\npublic class FunctionTester {\n public static void main(String[] args) {\n Function<Integer, Integer> multiply = t -> t *3;\n Function<Integer, Integer> add = t -> t + 3;\n Function<Integer, Integer> FirstMultiplyThenAdd = multiply.compose(add);\n Function<Integer, Integer> FirstAddThenMultiply = multiply.andThen(add);\n System.out.println(FirstMultiplyThenAdd.apply(3));\n System.out.println(FirstAddThenMultiply.apply(3));\n }\n}"
},
{
"code": null,
"e": 12277,
"s": 12270,
"text": "18\n12\n"
},
{
"code": null,
"e": 12477,
"s": 12277,
"text": "Eager evaluation means expression is evaluated as soon as it is encountered where as lazy evaluation refers to evaluation of an expression when needed. See the following example to under the concept."
},
{
"code": null,
"e": 13502,
"s": 12477,
"text": "import java.util.function.Supplier;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String queryString = \"password=test\";\n System.out.println(checkInEagerWay(hasName(queryString)\n , hasPassword(queryString)));\n System.out.println(checkInLazyWay(() -> hasName(queryString)\n , () -> hasPassword(queryString)));\n }\n\n private static boolean hasName(String queryString){\n System.out.println(\"Checking name: \");\n return queryString.contains(\"name\");\n }\n\n private static boolean hasPassword(String queryString){\n System.out.println(\"Checking password: \");\n return queryString.contains(\"password\");\n } \n\n private static String checkInEagerWay(boolean result1, boolean result2){\n return (result1 && result2) ? \"all conditions passed\": \"failed.\";\n }\n\n private static String checkInLazyWay(Supplier<Boolean> result1, Supplier<Boolean> result2){\n return (result1.get() && result2.get()) ? \"all conditions passed\": \"failed.\";\n }\n}"
},
{
"code": null,
"e": 13571,
"s": 13502,
"text": "Checking name: \nChecking password: \nfailed.\nChecking name: \nfailed.\n"
},
{
"code": null,
"e": 13907,
"s": 13571,
"text": "Here checkInEagerWay() function first evaluated the parameters then executes its statement. Whereas checkInLazyWay() executes its statement and evaluates the parameter on need basis. As && is a short-circuit operator, checkInLazyWay only evaluated first parameter which comes as false and does not evaluate the second parameter at all."
},
{
"code": null,
"e": 14342,
"s": 13907,
"text": "A data structure is said to be persistent if it is capable to maintaining its previous updates as separate versions and each version can be accessed and updated accordingly. It makes the data structure immutable and thread safe. For example, String class object in Java is immutable. Whenever we make any change to string, JVM creates another string object, assigned it the new value and preserve the older value as old string object."
},
{
"code": null,
"e": 14444,
"s": 14342,
"text": "A persistent data structure is also called a functional data structure. Consider the following case −"
},
{
"code": null,
"e": 14543,
"s": 14444,
"text": "public static Person updateAge(Person person, int age){\n person.setAge(age);\n return person;\n}"
},
{
"code": null,
"e": 14676,
"s": 14543,
"text": "public static Person updateAge(Person pPerson, int age){\n Person person = new Person();\n person.setAge(age);\n return person;\n}"
},
{
"code": null,
"e": 14868,
"s": 14676,
"text": "Recursion is calling a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive."
},
{
"code": null,
"e": 14962,
"s": 14868,
"text": "Following examples shows the calculation of sum of natural numbers using both the techniques."
},
{
"code": null,
"e": 15501,
"s": 14962,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n System.out.println(\"Sum using imperative way. Sum(5) : \" + sum(5));\n System.out.println(\"Sum using recursive way. Sum(5) : \" + sumRecursive(5));\n }\n\n private static int sum(int n){\n int result = 0;\n for(int i = 1; i <= n; i++){\n result = result + i;\n }\n return result;\n }\n\n private static int sumRecursive(int n){\n if(n == 1){\n return 1;\n }else{\n return n + sumRecursive(n-1);\n }\n }\n}"
},
{
"code": null,
"e": 15577,
"s": 15501,
"text": "Sum using imperative way. Sum(5) : 15\nSum using recursive way. Sum(5) : 15\n"
},
{
"code": null,
"e": 15684,
"s": 15577,
"text": "Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result."
},
{
"code": null,
"e": 15832,
"s": 15684,
"text": "Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion."
},
{
"code": null,
"e": 16121,
"s": 15832,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n printUsingTailRecursion(5);\n }\n\n public static void printUsingTailRecursion(int n){\n if(n == 0) \n return;\n else\n System.out.println(n);\n printUsingTailRecursion(n-1);\n }\n}"
},
{
"code": null,
"e": 16132,
"s": 16121,
"text": "5\n4\n3\n2\n1\n"
},
{
"code": null,
"e": 16298,
"s": 16132,
"text": "Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion."
},
{
"code": null,
"e": 16593,
"s": 16298,
"text": "public class FunctionTester {\n public static void main(String[] args) { \n printUsingHeadRecursion(5);\n }\n\n public static void printUsingHeadRecursion(int n){\n if(n == 0) \n return;\n else\n printUsingHeadRecursion(n-1); \n System.out.println(n);\n }\n}"
},
{
"code": null,
"e": 16604,
"s": 16593,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 17223,
"s": 16604,
"text": "Parallelism is a key concept of functional programming where a big task is accomplished by breaking in smaller independent tasks and then these small tasks are completed in a parallel fashion and later combined to give the complete result. With the advent of multi-core processors, this technique helps in faster code execution. Java has Thread based programming support for parallel processing but it is quite tedious to learn and difficult to implement without bugs. Java 8 onwards, stream have parallel method and collections has parallelStream() method to complete tasks in parallel fashion. See the example below:"
},
{
"code": null,
"e": 18298,
"s": 17223,
"text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n\n Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8 };\n List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));\n\n System.out.println(\"List using Serial Stream:\");\n listOfIntegers\n .stream()\n .forEach(e -> System.out.print(e + \" \"));\n System.out.println(\"\");\n\n System.out.println(\"List using Parallel Stream:\");\n listOfIntegers\n .parallelStream()\n .forEach(e -> System.out.print(e + \" \"));\n System.out.println(\"\");\n\n System.out.println(\"List using Another Parallel Stream:\");\n listOfIntegers\n .stream()\n .parallel()\n .forEach(e -> System.out.print(e + \" \"));\n System.out.println(\"\");\n\n System.out.println(\"List using Parallel Stream but Ordered:\");\n listOfIntegers\n .parallelStream()\n .forEachOrdered(e -> System.out.print(e + \" \"));\n System.out.println(\"\"); \n } \n}"
},
{
"code": null,
"e": 18497,
"s": 18298,
"text": "List using Serial Stream:\n1 2 3 4 5 6 7 8 \nList using Parallel Stream:\n6 5 8 7 3 4 2 1 \nList using Another Parallel Stream:\n6 2 1 7 4 3 8 5 \nList using Parallel Stream but Ordered:\n1 2 3 4 5 6 7 8 \n"
},
{
"code": null,
"e": 18789,
"s": 18497,
"text": "Monad is a key concept of Functional Programming. A Monad is a design pattern which helps to represent a missing value. It allows to wrap a potential null value, allows to put transformation around it and pull actual value if present. By definition, a monad is a set of following parameters."
},
{
"code": null,
"e": 18816,
"s": 18789,
"text": "A parametrized Type − M<T>"
},
{
"code": null,
"e": 18843,
"s": 18816,
"text": "A parametrized Type − M<T>"
},
{
"code": null,
"e": 18871,
"s": 18843,
"text": "A unit Function − T −> M<T>"
},
{
"code": null,
"e": 18899,
"s": 18871,
"text": "A unit Function − T −> M<T>"
},
{
"code": null,
"e": 18945,
"s": 18899,
"text": "A bind operation − M<T> bind T −> M<U> = M<U>"
},
{
"code": null,
"e": 18991,
"s": 18945,
"text": "A bind operation − M<T> bind T −> M<U> = M<U>"
},
{
"code": null,
"e": 19132,
"s": 18991,
"text": "Left Identity − If a function is bind on a monad of a particular value then its result will be same as if function is applied to the value.\n"
},
{
"code": null,
"e": 19272,
"s": 19132,
"text": "Left Identity − If a function is bind on a monad of a particular value then its result will be same as if function is applied to the value."
},
{
"code": null,
"e": 19351,
"s": 19272,
"text": "Right Identity − If a monad return method is same as monad on original value.\n"
},
{
"code": null,
"e": 19429,
"s": 19351,
"text": "Right Identity − If a monad return method is same as monad on original value."
},
{
"code": null,
"e": 19496,
"s": 19429,
"text": "Associativity − Functions can be applied in any order on a monad.\n"
},
{
"code": null,
"e": 19562,
"s": 19496,
"text": "Associativity − Functions can be applied in any order on a monad."
},
{
"code": null,
"e": 20001,
"s": 19562,
"text": "Java 8 introduced Optional class which is a monad. It provides operational equivalent to a monad. For example return is a operation which takes a value and return the monad. Optional.of() takes a parameters and returns the Optional Object. On similar basis , bind is operation which binds a function to a monad to produce a monad. Optional.flatMap() is the method which performs an operation on Optional and return the result as Optional."
},
{
"code": null,
"e": 20035,
"s": 20001,
"text": "A parametrized Type − Optional<T>"
},
{
"code": null,
"e": 20069,
"s": 20035,
"text": "A parametrized Type − Optional<T>"
},
{
"code": null,
"e": 20101,
"s": 20069,
"text": "A unit Function − Optional.of()"
},
{
"code": null,
"e": 20133,
"s": 20101,
"text": "A unit Function − Optional.of()"
},
{
"code": null,
"e": 20171,
"s": 20133,
"text": "A bind operation − Optional.flatMap()"
},
{
"code": null,
"e": 20209,
"s": 20171,
"text": "A bind operation − Optional.flatMap()"
},
{
"code": null,
"e": 20278,
"s": 20209,
"text": "Following example shows how Optional class obeys Left Identity rule."
},
{
"code": null,
"e": 20612,
"s": 20278,
"text": "import java.util.Optional;\nimport java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n Function<Integer, Optional<Integer>> addOneToX \n = x −> Optional.of(x + 1);\n System.out.println(Optional.of(5).flatMap(addOneToX)\n .equals(addOneToX.apply(5)));\n } \n}"
},
{
"code": null,
"e": 20618,
"s": 20612,
"text": "true\n"
},
{
"code": null,
"e": 20688,
"s": 20618,
"text": "Following example shows how Optional class obeys Right Identity rule."
},
{
"code": null,
"e": 20895,
"s": 20688,
"text": "import java.util.Optional;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n System.out.println(Optional.of(5).flatMap(Optional::of)\n .equals(Optional.of(5)));\n } \n}"
},
{
"code": null,
"e": 20901,
"s": 20895,
"text": "true\n"
},
{
"code": null,
"e": 20970,
"s": 20901,
"text": "Following example shows how Optional class obeys Associativity rule."
},
{
"code": null,
"e": 21521,
"s": 20970,
"text": "import java.util.Optional;\nimport java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n Function<Integer, Optional<Integer>> addOneToX \n = x −> Optional.of(x + 1);\n Function<Integer, Optional<Integer>> addTwoToX \n = x −> Optional.of(x + 2);\n Function<Integer, Optional<Integer>> addThreeToX \n = x −> addOneToX.apply(x).flatMap(addTwoToX);\n Optional.of(5).flatMap(addOneToX).flatMap(addTwoToX)\n .equals(Optional.of(5).flatMap(addThreeToX));\n } \n}"
},
{
"code": null,
"e": 21527,
"s": 21521,
"text": "true\n"
},
{
"code": null,
"e": 21948,
"s": 21527,
"text": "A closure is a function which is a combination of function along with its surrounding state. A closure function generally have access to outer function's scope. In the example given below, we have created a function getWeekDay(String[] days) which returns a function which can return the text equivalent of a weekday. Here getWeekDay() is a closure which is returning a function surrounding the calling function's scope."
},
{
"code": null,
"e": 21991,
"s": 21948,
"text": "Following example shows how Closure works."
},
{
"code": null,
"e": 22500,
"s": 21991,
"text": "import java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String[] weekDays = {\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\", \"Sunday\" };\n Function<Integer, String> getIndianWeekDay = getWeekDay(weekDays);\n System.out.println(getIndianWeekDay.apply(6)); \n }\n\n public static Function<Integer, String> getWeekDay(String[] weekDays){\n return index -> index >= 0 ? weekDays[index % 7] : null;\n }\n}"
},
{
"code": null,
"e": 22508,
"s": 22500,
"text": "Sunday\n"
},
{
"code": null,
"e": 22631,
"s": 22508,
"text": "Currying is a technique where a many arguments function call is replaced with multiple method calls with lesser arguments."
},
{
"code": null,
"e": 22655,
"s": 22631,
"text": "See the below equation."
},
{
"code": null,
"e": 22693,
"s": 22655,
"text": "(1 + 2 + 3) = 1 + (2 + 3) = 1 + 5 = 6"
},
{
"code": null,
"e": 22717,
"s": 22693,
"text": "In terms of functions: "
},
{
"code": null,
"e": 22756,
"s": 22717,
"text": "f(1,2,3) = g(1) + h(2 + 3) = 1 + 5 = 6"
},
{
"code": null,
"e": 22895,
"s": 22756,
"text": "This cascading of functions is called currying and calls to cascaded functions must gives the same result as by calling the main function."
},
{
"code": null,
"e": 22939,
"s": 22895,
"text": "Following example shows how Currying works."
},
{
"code": null,
"e": 23291,
"s": 22939,
"text": "import java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n Function<Integer, Function<Integer, Function<Integer, Integer>>> \n addNumbers = u -> v -> w -> u + v + w; \n int result = addNumbers.apply(2).apply(3).apply(4); \n System.out.println(result);\n } \n}"
},
{
"code": null,
"e": 23294,
"s": 23291,
"text": "9\n"
},
{
"code": null,
"e": 23654,
"s": 23294,
"text": "In functional programming, reducing is a technique to reduce a stream of values to a single result by apply a function on all the values. Java provides reduce() function in a Stream class from Java 8 onwards. A stream has inbuilt reducing methods like sum(), average(), count() as well which works on all elements of the stream and returns the single result."
},
{
"code": null,
"e": 23698,
"s": 23654,
"text": "Following example shows how Reducing works."
},
{
"code": null,
"e": 24097,
"s": 23698,
"text": "import java.util.stream.IntStream;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n\n //1 * 2 * 3 * 4 = 24\n int product = IntStream.range(1, 5) \n .reduce((num1, num2) -> num1 * num2)\n .orElse(-1); \n\n //1 + 2 + 3 + 4 = 10\n int sum = IntStream.range(1, 5).sum();\n\n System.out.println(product);\n System.out.println(sum);\n } \n}"
},
{
"code": null,
"e": 24104,
"s": 24097,
"text": "24\n10\n"
},
{
"code": null,
"e": 24292,
"s": 24104,
"text": "Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot."
},
{
"code": null,
"e": 24354,
"s": 24292,
"text": "A lambda expression is characterized by the following syntax."
},
{
"code": null,
"e": 24384,
"s": 24354,
"text": "parameter -> expression body\n"
},
{
"code": null,
"e": 24452,
"s": 24384,
"text": "Following are the important characteristics of a lambda expression."
},
{
"code": null,
"e": 24593,
"s": 24452,
"text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter."
},
{
"code": null,
"e": 24734,
"s": 24593,
"text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter."
},
{
"code": null,
"e": 24879,
"s": 24734,
"text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required."
},
{
"code": null,
"e": 25024,
"s": 24879,
"text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required."
},
{
"code": null,
"e": 25136,
"s": 25024,
"text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement."
},
{
"code": null,
"e": 25248,
"s": 25136,
"text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement."
},
{
"code": null,
"e": 25447,
"s": 25248,
"text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value."
},
{
"code": null,
"e": 25646,
"s": 25447,
"text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value."
},
{
"code": null,
"e": 25732,
"s": 25646,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA."
},
{
"code": null,
"e": 27191,
"s": 25732,
"text": "public class Java8Tester {\n\n public static void main(String args[]) {\n Java8Tester tester = new Java8Tester();\n\t\t\n //with type declaration\n MathOperation addition = (int a, int b) -> a + b;\n\t\t\n //with out type declaration\n MathOperation subtraction = (a, b) -> a - b;\n\t\t\n //with return statement along with curly braces\n MathOperation multiplication = (int a, int b) -> { return a * b; };\n\t\t\n //without return statement and without curly braces\n MathOperation division = (int a, int b) -> a / b;\n\t\t\n System.out.println(\"10 + 5 = \" + tester.operate(10, 5, addition));\n System.out.println(\"10 - 5 = \" + tester.operate(10, 5, subtraction));\n System.out.println(\"10 x 5 = \" + tester.operate(10, 5, multiplication));\n System.out.println(\"10 / 5 = \" + tester.operate(10, 5, division));\n\t\t\n //without parenthesis\n GreetingService greetService1 = message ->\n System.out.println(\"Hello \" + message);\n\t\t\n //with parenthesis\n GreetingService greetService2 = (message) ->\n System.out.println(\"Hello \" + message);\n\t\t\n greetService1.sayMessage(\"Mahesh\");\n greetService2.sayMessage(\"Suresh\");\n }\n\t\n interface MathOperation {\n int operation(int a, int b);\n }\n\t\n interface GreetingService {\n void sayMessage(String message);\n }\n\t\n private int operate(int a, int b, MathOperation mathOperation) {\n return mathOperation.operation(a, b);\n }\n}"
},
{
"code": null,
"e": 27243,
"s": 27191,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 27275,
"s": 27243,
"text": "C:\\JAVA>javac Java8Tester.java\n"
},
{
"code": null,
"e": 27312,
"s": 27275,
"text": "Now run the Java8Tester as follows −"
},
{
"code": null,
"e": 27338,
"s": 27312,
"text": "C:\\JAVA>java Java8Tester\n"
},
{
"code": null,
"e": 27379,
"s": 27338,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 27452,
"s": 27379,
"text": "10 + 5 = 15\n10 - 5 = 5\n10 x 5 = 50\n10 / 5 = 2\nHello Mahesh\nHello Suresh\n"
},
{
"code": null,
"e": 27526,
"s": 27452,
"text": "Following are the important points to be considered in the above example."
},
{
"code": null,
"e": 27871,
"s": 27526,
"text": "Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService."
},
{
"code": null,
"e": 28216,
"s": 27871,
"text": "Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService."
},
{
"code": null,
"e": 28353,
"s": 28216,
"text": "Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java."
},
{
"code": null,
"e": 28490,
"s": 28353,
"text": "Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java."
},
{
"code": null,
"e": 28709,
"s": 28490,
"text": "Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time."
},
{
"code": null,
"e": 28795,
"s": 28709,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA."
},
{
"code": null,
"e": 28812,
"s": 28795,
"text": "Java8Tester.java"
},
{
"code": null,
"e": 29159,
"s": 28812,
"text": "public class Java8Tester {\n\n final static String salutation = \"Hello! \";\n \n public static void main(String args[]) {\n GreetingService greetService1 = message -> \n System.out.println(salutation + message);\n greetService1.sayMessage(\"Mahesh\");\n }\n\t\n interface GreetingService {\n void sayMessage(String message);\n }\n}"
},
{
"code": null,
"e": 29211,
"s": 29159,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 29243,
"s": 29211,
"text": "C:\\JAVA>javac Java8Tester.java\n"
},
{
"code": null,
"e": 29280,
"s": 29243,
"text": "Now run the Java8Tester as follows −"
},
{
"code": null,
"e": 29306,
"s": 29280,
"text": "C:\\JAVA>java Java8Tester\n"
},
{
"code": null,
"e": 29347,
"s": 29306,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 29362,
"s": 29347,
"text": "Hello! Mahesh\n"
},
{
"code": null,
"e": 29585,
"s": 29362,
"text": "Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8."
},
{
"code": null,
"e": 29952,
"s": 29585,
"text": "For example, 'List' or 'Collection' interfaces do not have 'forEach' method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same."
},
{
"code": null,
"e": 30059,
"s": 29952,
"text": "public interface vehicle {\n\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n}\n"
},
{
"code": null,
"e": 30255,
"s": 30059,
"text": "With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved."
},
{
"code": null,
"e": 30477,
"s": 30255,
"text": "public interface vehicle {\n\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n}\n\npublic interface fourWheeler {\n\n default void print() {\n System.out.println(\"I am a four wheeler!\");\n }\n}"
},
{
"code": null,
"e": 30562,
"s": 30477,
"text": "First solution is to create an own method that overrides the default implementation."
},
{
"code": null,
"e": 30708,
"s": 30562,
"text": "public class car implements vehicle, fourWheeler {\n\n public void print() {\n System.out.println(\"I am a four wheeler car vehicle!\");\n }\n}"
},
{
"code": null,
"e": 30794,
"s": 30708,
"text": "Second solution is to call the default method of the specified interface using super."
},
{
"code": null,
"e": 30908,
"s": 30794,
"text": "public class car implements vehicle, fourWheeler {\n\n default void print() {\n vehicle.super.print();\n }\n}"
},
{
"code": null,
"e": 30978,
"s": 30908,
"text": "An interface can also have static helper methods from Java 8 onwards."
},
{
"code": null,
"e": 31164,
"s": 30978,
"text": "public interface vehicle {\n\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n\t\n static void blowHorn() {\n System.out.println(\"Blowing horn!!!\");\n }\n}"
},
{
"code": null,
"e": 31250,
"s": 31164,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA."
},
{
"code": null,
"e": 31883,
"s": 31250,
"text": "public class Java8Tester {\n\n public static void main(String args[]) {\n Vehicle vehicle = new Car();\n vehicle.print();\n }\n}\n\ninterface Vehicle {\n\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n\t\n static void blowHorn() {\n System.out.println(\"Blowing horn!!!\");\n }\n}\n\ninterface FourWheeler {\n\n default void print() {\n System.out.println(\"I am a four wheeler!\");\n }\n}\n\nclass Car implements Vehicle, FourWheeler {\n\n public void print() {\n Vehicle.super.print();\n FourWheeler.super.print();\n Vehicle.blowHorn();\n System.out.println(\"I am a car!\");\n }\n}"
},
{
"code": null,
"e": 31935,
"s": 31883,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 31967,
"s": 31935,
"text": "C:\\JAVA>javac Java8Tester.java\n"
},
{
"code": null,
"e": 32004,
"s": 31967,
"text": "Now run the Java8Tester as follows −"
},
{
"code": null,
"e": 32030,
"s": 32004,
"text": "C:\\JAVA>java Java8Tester\n"
},
{
"code": null,
"e": 32071,
"s": 32030,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 32137,
"s": 32071,
"text": "I am a vehicle!\nI am a four wheeler!\nBlowing horn!!!\nI am a car!\n"
},
{
"code": null,
"e": 32482,
"s": 32137,
"text": "Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package."
},
{
"code": null,
"e": 32498,
"s": 32482,
"text": "BiConsumer<T,U>"
},
{
"code": null,
"e": 32579,
"s": 32498,
"text": "Represents an operation that accepts two input arguments, and returns no result."
},
{
"code": null,
"e": 32597,
"s": 32579,
"text": "BiFunction<T,U,R>"
},
{
"code": null,
"e": 32669,
"s": 32597,
"text": "Represents a function that accepts two arguments and produces a result."
},
{
"code": null,
"e": 32687,
"s": 32669,
"text": "BinaryOperator<T>"
},
{
"code": null,
"e": 32800,
"s": 32687,
"text": "Represents an operation upon two operands of the same type, producing a result of the same type as the operands."
},
{
"code": null,
"e": 32817,
"s": 32800,
"text": "BiPredicate<T,U>"
},
{
"code": null,
"e": 32884,
"s": 32817,
"text": "Represents a predicate (Boolean-valued function) of two arguments."
},
{
"code": null,
"e": 32900,
"s": 32884,
"text": "BooleanSupplier"
},
{
"code": null,
"e": 32949,
"s": 32900,
"text": "Represents a supplier of Boolean-valued results."
},
{
"code": null,
"e": 32961,
"s": 32949,
"text": "Consumer<T>"
},
{
"code": null,
"e": 33045,
"s": 32961,
"text": "Represents an operation that accepts a single input argument and returns no result."
},
{
"code": null,
"e": 33066,
"s": 33045,
"text": "DoubleBinaryOperator"
},
{
"code": null,
"e": 33160,
"s": 33066,
"text": "Represents an operation upon two double-valued operands and producing a double-valued result."
},
{
"code": null,
"e": 33175,
"s": 33160,
"text": "DoubleConsumer"
},
{
"code": null,
"e": 33267,
"s": 33175,
"text": "Represents an operation that accepts a single double-valued argument and returns no result."
},
{
"code": null,
"e": 33285,
"s": 33267,
"text": "DoubleFunction<R>"
},
{
"code": null,
"e": 33368,
"s": 33285,
"text": "Represents a function that accepts a double-valued argument and produces a result."
},
{
"code": null,
"e": 33384,
"s": 33368,
"text": "DoublePredicate"
},
{
"code": null,
"e": 33464,
"s": 33384,
"text": "Represents a predicate (Boolean-valued function) of one double-valued argument."
},
{
"code": null,
"e": 33479,
"s": 33464,
"text": "DoubleSupplier"
},
{
"code": null,
"e": 33527,
"s": 33479,
"text": "Represents a supplier of double-valued results."
},
{
"code": null,
"e": 33547,
"s": 33527,
"text": "DoubleToIntFunction"
},
{
"code": null,
"e": 33642,
"s": 33547,
"text": "Represents a function that accepts a double-valued argument and produces an int-valued result."
},
{
"code": null,
"e": 33663,
"s": 33642,
"text": "DoubleToLongFunction"
},
{
"code": null,
"e": 33758,
"s": 33663,
"text": "Represents a function that accepts a double-valued argument and produces a long-valued result."
},
{
"code": null,
"e": 33778,
"s": 33758,
"text": "DoubleUnaryOperator"
},
{
"code": null,
"e": 33874,
"s": 33778,
"text": "Represents an operation on a single double-valued operand that produces a double-valued result."
},
{
"code": null,
"e": 33888,
"s": 33874,
"text": "Function<T,R>"
},
{
"code": null,
"e": 33959,
"s": 33888,
"text": "Represents a function that accepts one argument and produces a result."
},
{
"code": null,
"e": 33977,
"s": 33959,
"text": "IntBinaryOperator"
},
{
"code": null,
"e": 34065,
"s": 33977,
"text": "Represents an operation upon two int-valued operands and produces an int-valued result."
},
{
"code": null,
"e": 34077,
"s": 34065,
"text": "IntConsumer"
},
{
"code": null,
"e": 34166,
"s": 34077,
"text": "Represents an operation that accepts a single int-valued argument and returns no result."
},
{
"code": null,
"e": 34181,
"s": 34166,
"text": "IntFunction<R>"
},
{
"code": null,
"e": 34262,
"s": 34181,
"text": "Represents a function that accepts an int-valued argument and produces a result."
},
{
"code": null,
"e": 34275,
"s": 34262,
"text": "IntPredicate"
},
{
"code": null,
"e": 34352,
"s": 34275,
"text": "Represents a predicate (Boolean-valued function) of one int-valued argument."
},
{
"code": null,
"e": 34364,
"s": 34352,
"text": "IntSupplier"
},
{
"code": null,
"e": 34409,
"s": 34364,
"text": "Represents a supplier of int-valued results."
},
{
"code": null,
"e": 34429,
"s": 34409,
"text": "IntToDoubleFunction"
},
{
"code": null,
"e": 34524,
"s": 34429,
"text": "Represents a function that accepts an int-valued argument and produces a double-valued result."
},
{
"code": null,
"e": 34542,
"s": 34524,
"text": "IntToLongFunction"
},
{
"code": null,
"e": 34635,
"s": 34542,
"text": "Represents a function that accepts an int-valued argument and produces a long-valued result."
},
{
"code": null,
"e": 34652,
"s": 34635,
"text": "IntUnaryOperator"
},
{
"code": null,
"e": 34743,
"s": 34652,
"text": "Represents an operation on a single int-valued operand that produces an int-valued result."
},
{
"code": null,
"e": 34762,
"s": 34743,
"text": "LongBinaryOperator"
},
{
"code": null,
"e": 34851,
"s": 34762,
"text": "Represents an operation upon two long-valued operands and produces a long-valued result."
},
{
"code": null,
"e": 34864,
"s": 34851,
"text": "LongConsumer"
},
{
"code": null,
"e": 34954,
"s": 34864,
"text": "Represents an operation that accepts a single long-valued argument and returns no result."
},
{
"code": null,
"e": 34970,
"s": 34954,
"text": "LongFunction<R>"
},
{
"code": null,
"e": 35051,
"s": 34970,
"text": "Represents a function that accepts a long-valued argument and produces a result."
},
{
"code": null,
"e": 35065,
"s": 35051,
"text": "LongPredicate"
},
{
"code": null,
"e": 35143,
"s": 35065,
"text": "Represents a predicate (Boolean-valued function) of one long-valued argument."
},
{
"code": null,
"e": 35156,
"s": 35143,
"text": "LongSupplier"
},
{
"code": null,
"e": 35202,
"s": 35156,
"text": "Represents a supplier of long-valued results."
},
{
"code": null,
"e": 35223,
"s": 35202,
"text": "LongToDoubleFunction"
},
{
"code": null,
"e": 35318,
"s": 35223,
"text": "Represents a function that accepts a long-valued argument and produces a double-valued result."
},
{
"code": null,
"e": 35336,
"s": 35318,
"text": "LongToIntFunction"
},
{
"code": null,
"e": 35429,
"s": 35336,
"text": "Represents a function that accepts a long-valued argument and produces an int-valued result."
},
{
"code": null,
"e": 35447,
"s": 35429,
"text": "LongUnaryOperator"
},
{
"code": null,
"e": 35539,
"s": 35447,
"text": "Represents an operation on a single long-valued operand that produces a long-valued result."
},
{
"code": null,
"e": 35560,
"s": 35539,
"text": "ObjDoubleConsumer<T>"
},
{
"code": null,
"e": 35667,
"s": 35560,
"text": "Represents an operation that accepts an object-valued and a double-valued argument, and returns no result."
},
{
"code": null,
"e": 35685,
"s": 35667,
"text": "ObjIntConsumer<T>"
},
{
"code": null,
"e": 35790,
"s": 35685,
"text": "Represents an operation that accepts an object-valued and an int-valued argument, and returns no result."
},
{
"code": null,
"e": 35809,
"s": 35790,
"text": "ObjLongConsumer<T>"
},
{
"code": null,
"e": 35914,
"s": 35809,
"text": "Represents an operation that accepts an object-valued and a long-valued argument, and returns no result."
},
{
"code": null,
"e": 35927,
"s": 35914,
"text": "Predicate<T>"
},
{
"code": null,
"e": 35993,
"s": 35927,
"text": "Represents a predicate (Boolean-valued function) of one argument."
},
{
"code": null,
"e": 36005,
"s": 35993,
"text": "Supplier<T>"
},
{
"code": null,
"e": 36039,
"s": 36005,
"text": "Represents a supplier of results."
},
{
"code": null,
"e": 36063,
"s": 36039,
"text": "ToDoubleBiFunction<T,U>"
},
{
"code": null,
"e": 36149,
"s": 36063,
"text": "Represents a function that accepts two arguments and produces a double-valued result."
},
{
"code": null,
"e": 36169,
"s": 36149,
"text": "ToDoubleFunction<T>"
},
{
"code": null,
"e": 36229,
"s": 36169,
"text": "Represents a function that produces a double-valued result."
},
{
"code": null,
"e": 36250,
"s": 36229,
"text": "ToIntBiFunction<T,U>"
},
{
"code": null,
"e": 36334,
"s": 36250,
"text": "Represents a function that accepts two arguments and produces an int-valued result."
},
{
"code": null,
"e": 36351,
"s": 36334,
"text": "ToIntFunction<T>"
},
{
"code": null,
"e": 36409,
"s": 36351,
"text": "Represents a function that produces an int-valued result."
},
{
"code": null,
"e": 36431,
"s": 36409,
"text": "ToLongBiFunction<T,U>"
},
{
"code": null,
"e": 36515,
"s": 36431,
"text": "Represents a function that accepts two arguments and produces a long-valued result."
},
{
"code": null,
"e": 36533,
"s": 36515,
"text": "ToLongFunction<T>"
},
{
"code": null,
"e": 36591,
"s": 36533,
"text": "Represents a function that produces a long-valued result."
},
{
"code": null,
"e": 36608,
"s": 36591,
"text": "UnaryOperator<T>"
},
{
"code": null,
"e": 36708,
"s": 36608,
"text": "Represents an operation on a single operand that produces a result of the same type as its operand."
},
{
"code": null,
"e": 36883,
"s": 36708,
"text": "Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false."
},
{
"code": null,
"e": 36969,
"s": 36883,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA."
},
{
"code": null,
"e": 38274,
"s": 36969,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Predicate;\npublic class Java8Tester {\n public static void main(String args[]) {\n List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);\n\t\t\n // Predicate<Integer> predicate = n -> true\n // n is passed as parameter to test method of Predicate interface\n // test method will always return true no matter what value n has.\n\t\t\n System.out.println(\"Print all numbers:\");\n\t\t\n //pass n as parameter\n eval(list, n->true);\n\t\t\n // Predicate<Integer> predicate1 = n -> n%2 == 0\n // n is passed as parameter to test method of Predicate interface\n // test method will return true if n%2 comes to be zero\n\t\t\n System.out.println(\"Print even numbers:\");\n eval(list, n-> n%2 == 0 );\n\t\t\n // Predicate<Integer> predicate2 = n -> n > 3\n // n is passed as parameter to test method of Predicate interface\n // test method will return true if n is greater than 3.\n\t\t\n System.out.println(\"Print numbers greater than 3:\");\n eval(list, n-> n > 3 );\n }\n\t\n public static void eval(List<Integer> list, Predicate<Integer> predicate) {\n for(Integer n: list) {\n if(predicate.test(n)) {\n System.out.println(n + \" \");\n }\n }\n }\n}"
},
{
"code": null,
"e": 38361,
"s": 38274,
"text": "Here we've passed Predicate interface, which takes a single input and returns Boolean."
},
{
"code": null,
"e": 38413,
"s": 38361,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 38445,
"s": 38413,
"text": "C:\\JAVA>javac Java8Tester.java\n"
},
{
"code": null,
"e": 38482,
"s": 38445,
"text": "Now run the Java8Tester as follows −"
},
{
"code": null,
"e": 38508,
"s": 38482,
"text": "C:\\JAVA>java Java8Tester\n"
},
{
"code": null,
"e": 38549,
"s": 38508,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 38657,
"s": 38549,
"text": "Print all numbers:\n1\n2\n3\n4\n5\n6\n7\n8\n9\nPrint even numbers:\n2\n4\n6\n8\nPrint numbers greater than 3:\n4\n5\n6\n7\n8\n9\n"
},
{
"code": null,
"e": 38840,
"s": 38657,
"text": "Method references help to point to methods by their names. A method reference is described using \"::\" symbol. A method reference can be used to point the following types of methods −"
},
{
"code": null,
"e": 38927,
"s": 38840,
"text": "Static methods - static method can be reference using ClassName::Method name notation."
},
{
"code": null,
"e": 39014,
"s": 38927,
"text": "Static methods - static method can be reference using ClassName::Method name notation."
},
{
"code": null,
"e": 39131,
"s": 39014,
"text": "//Method Reference - Static way\nFactory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode; "
},
{
"code": null,
"e": 39219,
"s": 39131,
"text": "Instance methods - instance method can be reference using Object::Method name notation."
},
{
"code": null,
"e": 39307,
"s": 39219,
"text": "Instance methods - instance method can be reference using Object::Method name notation."
},
{
"code": null,
"e": 39423,
"s": 39307,
"text": "//Method Reference - Instance way\nFactory vehicle_factory_instance = new VehicleFactory()::prepareVehicle; "
},
{
"code": null,
"e": 39494,
"s": 39423,
"text": "Following example shows how Method references works in Java 8 onwards."
},
{
"code": null,
"e": 40770,
"s": 39494,
"text": "interface Factory {\n Vehicle prepare(String make, String model, int year);\n}\n\nclass Vehicle {\n private String make;\n private String model;\n private int year;\n\n Vehicle(String make, String model, int year){\n this.make = make;\n this.model = model;\n this.year = year;\n }\n\n public String toString(){\n return \"Vehicle[\" + make +\", \" + model + \", \" + year+ \"]\";\n } \n}\n\nclass VehicleFactory {\n static Vehicle prepareVehicleInStaticMode(String make, String model, int year){\n return new Vehicle(make, model, year);\n }\n\n Vehicle prepareVehicle(String make, String model, int year){\n return new Vehicle(make, model, year);\n }\n}\n\npublic class FunctionTester { \n public static void main(String[] args) { \n //Method Reference - Static way\n Factory vehicle_factory_static = VehicleFactory::prepareVehicleInStaticMode; \n Vehicle carHyundai = vehicle_factory_static.prepare(\"Hyundai\", \"Verna\", 2018);\n System.out.println(carHyundai);\n\n //Method Reference - Instance way\n Factory vehicle_factory_instance = new VehicleFactory()::prepareVehicle; \n Vehicle carTata = vehicle_factory_instance.prepare(\"Tata\", \"Harrier\", 2019);\n System.out.println(carTata); \n } \n}"
},
{
"code": null,
"e": 40830,
"s": 40770,
"text": "Vehicle[Hyundai, Verna, 2018]\nVehicle[Tata, Harrier, 2019]\n"
},
{
"code": null,
"e": 40948,
"s": 40830,
"text": "Constructor references help to point to Constructor method. A Constructor reference is accessed using \"::new\" symbol."
},
{
"code": null,
"e": 41019,
"s": 40948,
"text": "//Constructor reference\nFactory vehicle_factory = Vehicle::new; "
},
{
"code": null,
"e": 41095,
"s": 41019,
"text": "Following example shows how Constructor references works in Java 8 onwards."
},
{
"code": null,
"e": 41915,
"s": 41095,
"text": "interface Factory {\n Vehicle prepare(String make, String model, int year);\n}\n\nclass Vehicle {\n private String make;\n private String model;\n private int year;\n\n Vehicle(String make, String model, int year){\n this.make = make;\n this.model = model;\n this.year = year;\n }\n\n public String toString(){\n return \"Vehicle[\" + make +\", \" + model + \", \" + year+ \"]\";\n } \n}\n\npublic class FunctionTester {\n static Vehicle factory(Factory factoryObj, String make, String model, int year){\n return factoryObj.prepare(make, model, year);\n }\n\n public static void main(String[] args) { \n //Constructor reference\n Factory vehicle_factory = Vehicle::new;\n Vehicle carHonda = factory(vehicle_factory, \"Honda\", \"Civic\", 2017);\n System.out.println(carHonda);\n } \n}"
},
{
"code": null,
"e": 41944,
"s": 41915,
"text": "Vehicle[Honda, Civic, 2017]\n"
},
{
"code": null,
"e": 42234,
"s": 41944,
"text": "With Java 8 onwards, streams are introduced in Java and methods are added to collections to get a stream. Once a stream object is retrieved from a collection, we can apply various functional programming aspects like filtering, mapping, reducing etc. on collections. See the example below −"
},
{
"code": null,
"e": 43139,
"s": 42234,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester { \n public static void main(String[] args) { \n List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\n\n //Mapping\n //get list of unique squares\n List<Integer> squaresList = numbers.stream().map( i -> i*i)\n .distinct().collect(Collectors.toList());\n System.out.println(squaresList);\n\n //Filering \n //get list of non-empty strings\n List<String>strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n List<String> nonEmptyStrings = strings.stream()\n .filter(string -> !string.isEmpty()).collect(Collectors.toList());\n System.out.println(nonEmptyStrings);\n\n //Reducing\n int sum = numbers.stream().reduce((num1, num2) -> num1 + num2).orElse(-1);\n System.out.println(sum);\n } \n}"
},
{
"code": null,
"e": 43184,
"s": 43139,
"text": "[9, 4, 49, 25]\n[abc, bc, efg, abcd, jkl]\n25\n"
},
{
"code": null,
"e": 43285,
"s": 43184,
"text": "A function is considered as a High Order function if it fulfils any one of the following conditions."
},
{
"code": null,
"e": 43331,
"s": 43285,
"text": "It takes one or more parameters as functions."
},
{
"code": null,
"e": 43377,
"s": 43331,
"text": "It takes one or more parameters as functions."
},
{
"code": null,
"e": 43420,
"s": 43377,
"text": "It returns a function after its execution."
},
{
"code": null,
"e": 43463,
"s": 43420,
"text": "It returns a function after its execution."
},
{
"code": null,
"e": 43612,
"s": 43463,
"text": "Java 8 Collections.sort() method is an ideal example of a high order function. It accepts a comparing method as an argument. See the example below −"
},
{
"code": null,
"e": 44336,
"s": 43612,
"text": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester { \n public static void main(String[] args) { \n List<Integer> numbers = Arrays.asList(3, 4, 6, 7, 9);\n\n //Passing a function as lambda expression\n Collections.sort(numbers, (a,b) ->{ return a.compareTo(b); });\n\n System.out.println(numbers);\n Comparator<Integer> comparator = (a,b) ->{ return a.compareTo(b); };\n Comparator<Integer> reverseComparator = comparator.reversed();\n \n //Passing a function\n Collections.sort(numbers, reverseComparator);\n System.out.println(numbers);\n } \n}"
},
{
"code": null,
"e": 44369,
"s": 44336,
"text": "[3, 4, 6, 7, 9]\n[9, 7, 6, 4, 3]\n"
},
{
"code": null,
"e": 44686,
"s": 44369,
"text": "As a High Order function can return a function but how to implement using Java 8. Java 8 has provided Function interface which can accept a lambda expression. A high order function can return a lamdba expression and thus this high order function can be used to create any number of functions. See the example below −"
},
{
"code": null,
"e": 45437,
"s": 44686,
"text": "import java.util.function.Function;\n\npublic class FunctionTester { \n public static void main(String[] args) { \n Function<Integer, Integer> addOne = adder(1);\n Function<Integer, Integer> addTwo = adder(2);\n Function<Integer, Integer> addThree = adder(3);\n\n //result = 4 + 1 = 5\n Integer result = addOne.apply(4);\n System.out.println(result);\n\n //result = 4 + 2 = 6\n result = addTwo.apply(4);\n System.out.println(result);\n\n //result = 4 + 3 = 7\n result = addThree.apply(4);\n System.out.println(result);\n }\n\n //adder - High Order Function\n //returns a function as lambda expression\n static Function<Integer, Integer> adder(Integer x){\n return y -> y + x;\n }\n}"
},
{
"code": null,
"e": 45444,
"s": 45437,
"text": "5\n6\n7\n"
},
{
"code": null,
"e": 45531,
"s": 45444,
"text": "A function is called a first class function if it fulfills the following requirements."
},
{
"code": null,
"e": 45578,
"s": 45531,
"text": "It can be passed as a parameter to a function."
},
{
"code": null,
"e": 45625,
"s": 45578,
"text": "It can be passed as a parameter to a function."
},
{
"code": null,
"e": 45661,
"s": 45625,
"text": "It can be returned from a function."
},
{
"code": null,
"e": 45697,
"s": 45661,
"text": "It can be returned from a function."
},
{
"code": null,
"e": 45758,
"s": 45697,
"text": "It can be assigned to a variable and then can be used later."
},
{
"code": null,
"e": 45819,
"s": 45758,
"text": "It can be assigned to a variable and then can be used later."
},
{
"code": null,
"e": 46047,
"s": 45819,
"text": "Java 8 supports functions as first class object using lambda expressions. A lambda expression is a function definition and can be assigned to a variable, can be passed as an argument and can be returned. See the example below −"
},
{
"code": null,
"e": 47042,
"s": 46047,
"text": "@FunctionalInterface\ninterface Calculator<X, Y> { \n public X compute(X a, Y b);\n}\n\npublic class FunctionTester { \n public static void main(String[] args) { \n //Assign a function to a variable\n Calculator<Integer, Integer> calculator = (a,b) -> a * b;\n\n //call a function using function variable\n System.out.println(calculator.compute(2, 3));\n\n //Pass the function as a parameter\n printResult(calculator, 2, 3);\n\n //Get the function as a return result\n Calculator<Integer, Integer> calculator1 = getCalculator();\n System.out.println(calculator1.compute(2, 3));\n }\n\n //Function as a parameter\n static void printResult(Calculator<Integer, Integer> calculator, Integer a, Integer b){\n System.out.println(calculator.compute(a, b));\n }\n\n //Function as return value\n static Calculator<Integer, Integer> getCalculator(){\n Calculator<Integer, Integer> calculator = (a,b) -> a * b;\n return calculator;\n }\n}"
},
{
"code": null,
"e": 47049,
"s": 47042,
"text": "6\n6\n6\n"
},
{
"code": null,
"e": 47136,
"s": 47049,
"text": "A function is considered as Pure Function if it fulfils the following two conditions −"
},
{
"code": null,
"e": 47246,
"s": 47136,
"text": "It always returns the same result for the given inputs and its results purely depends upon the inputs passed."
},
{
"code": null,
"e": 47356,
"s": 47246,
"text": "It always returns the same result for the given inputs and its results purely depends upon the inputs passed."
},
{
"code": null,
"e": 47437,
"s": 47356,
"text": "It has no side effects means it is not modifying any state of the caller entity."
},
{
"code": null,
"e": 47518,
"s": 47437,
"text": "It has no side effects means it is not modifying any state of the caller entity."
},
{
"code": null,
"e": 47786,
"s": 47518,
"text": "public class FunctionTester { \n public static void main(String[] args) {\n int result = sum(2,3);\n System.out.println(result);\n \n result = sum(2,3);\n System.out.println(result);\n }\n static int sum(int a, int b){\n return a + b;\n }\n}"
},
{
"code": null,
"e": 47791,
"s": 47786,
"text": "5\n5\n"
},
{
"code": null,
"e": 47921,
"s": 47791,
"text": "Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects."
},
{
"code": null,
"e": 48319,
"s": 47921,
"text": "public class FunctionTester {\n private static double valueUsed = 0.0; \n public static void main(String[] args) {\n double result = randomSum(2.0,3.0);\n System.out.println(result);\n result = randomSum(2.0,3.0);\n System.out.println(result);\n }\n \n static double randomSum(double a, double b){\n valueUsed = Math.random(); \n return valueUsed + a + b;\n }\n}"
},
{
"code": null,
"e": 48357,
"s": 48319,
"text": "5.919716721877799\n5.4830887819586795\n"
},
{
"code": null,
"e": 48529,
"s": 48357,
"text": "Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well."
},
{
"code": null,
"e": 48730,
"s": 48529,
"text": "Type inference is a technique by which a compiler automatically deduces the type of a parameter passed or of return type of a method. Java 8 onwards, Lambda expression uses type inference prominently."
},
{
"code": null,
"e": 48789,
"s": 48730,
"text": "See the example below for clarification on type inference."
},
{
"code": null,
"e": 49158,
"s": 48789,
"text": "public class FunctionTester {\n\n public static void main(String[] args) {\n Join<Integer,Integer,Integer> sum = (a,b) -> a + b;\n System.out.println(sum.compute(10,20));\n\n Join<String, String, String> concat = (a,b) -> a + b;\n System.out.println(concat.compute(\"Hello \",\"World!\"));\n }\n\n interface Join<K,V,R>{\n R compute(K k ,V v);\n }\n}"
},
{
"code": null,
"e": 49175,
"s": 49158,
"text": "30\nHello World!\n"
},
{
"code": null,
"e": 49390,
"s": 49175,
"text": "A lambda expression treats each parameter and its return type as Object initially and then inferred the data type accordingly. In first case, the type inferred is Integer and in second case type inferred is String."
},
{
"code": null,
"e": 49503,
"s": 49390,
"text": "Lambda expressions are difficult to write when the function throws a checked expression. See the example below −"
},
{
"code": null,
"e": 49957,
"s": 49503,
"text": "import java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\";\n System.out.println(encodedAddress(url));\n } \n\n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(s -> URLEncoder.encode(s, \"UTF-8\"))\n .collect(Collectors.joining(\",\"));\n }\n}"
},
{
"code": null,
"e": 50100,
"s": 49957,
"text": "The above code fails to compile because URLEncode.encode() throws UnsupportedEncodingException and cannot be thrown by encodeAddress() method."
},
{
"code": null,
"e": 50211,
"s": 50100,
"text": "One possible solution is to extract URLEncoder.encode() into a separate method and handle the exception there."
},
{
"code": null,
"e": 50932,
"s": 50211,
"text": "import java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\"; \n System.out.println(encodedAddress(url));\n } \n\n public static String encodedString(String s) {\n try {\n URLEncoder.encode(s, \"UTF-8\");\n }\n catch (UnsupportedEncodingException e) { \n e.printStackTrace();\n }\n return s;\n }\n\n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(s -> encodedString(s))\n .collect(Collectors.joining(\",\"));\n } \n}"
},
{
"code": null,
"e": 51110,
"s": 50932,
"text": "But above approach is not good when we have multiple such methods which throws exception. See the following generalized solution using functional interface and a wrapper method."
},
{
"code": null,
"e": 52003,
"s": 51110,
"text": "import java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\"; \n System.out.println(encodedAddress(url));\n } \n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(wrapper(s -> URLEncoder.encode(s, \"UTF-8\")))\n .collect(Collectors.joining(\",\"));\n }\n\n private static <T, R, E extends Exception> Function<T, R> \n wrapper(FunctionWithThrows<T, R, E> fe) {\n return arg -> {\n try {\n return fe.apply(arg);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n };\n }\n}\n\n@FunctionalInterface\ninterface FunctionWithThrows<T, R, E extends Exception> {\n R apply(T t) throws E;\n}"
},
{
"code": null,
"e": 52019,
"s": 52003,
"text": "www.google.com\n"
},
{
"code": null,
"e": 52284,
"s": 52019,
"text": "Stream API was introduced in Java 8 to facilitate functional programming in Java. A Stream API is targeted towards processing of collections of objects in functional way. By definition, a Stream is a Java component which can do internal iteration of its elements."
},
{
"code": null,
"e": 52644,
"s": 52284,
"text": "A Stream interface has terminal as well as non-terminal methods. Non-terminal methods are such operations which adds a listener to a stream. When a terminal method of stream is invoked, then internal iteration of stream elements get started and listener(s) attached to stream are getting called for each element and result is collected by the terminal method."
},
{
"code": null,
"e": 52854,
"s": 52644,
"text": "Such non-terminal methods are called Intermediate methods. The Intermediate method can only be invoked by called a terminal method. Following are some of the important Intermediate methods of Stream interface."
},
{
"code": null,
"e": 53073,
"s": 52854,
"text": "filter − Filters out non-required elements from a stream based on given criteria. This method accepts a predicate and apply it on each element. If predicate function return true, element is included in returned stream."
},
{
"code": null,
"e": 53292,
"s": 53073,
"text": "filter − Filters out non-required elements from a stream based on given criteria. This method accepts a predicate and apply it on each element. If predicate function return true, element is included in returned stream."
},
{
"code": null,
"e": 53516,
"s": 53292,
"text": "map − Maps each element of a stream to another item based on given criteria. This method accepts a function and apply it on each element. For example, to convert each String element in a stream to upper-case String element."
},
{
"code": null,
"e": 53740,
"s": 53516,
"text": "map − Maps each element of a stream to another item based on given criteria. This method accepts a function and apply it on each element. For example, to convert each String element in a stream to upper-case String element."
},
{
"code": null,
"e": 53993,
"s": 53740,
"text": "flatMap − This method can be used to maps each element of a stream to multiple items based on given criteria. This method is used when a complex object needs to be broken into simple objects. For example, to convert list of sentences to list of words."
},
{
"code": null,
"e": 54246,
"s": 53993,
"text": "flatMap − This method can be used to maps each element of a stream to multiple items based on given criteria. This method is used when a complex object needs to be broken into simple objects. For example, to convert list of sentences to list of words."
},
{
"code": null,
"e": 54320,
"s": 54246,
"text": "distinct − Returns a stream of unique elements if duplicates are present."
},
{
"code": null,
"e": 54394,
"s": 54320,
"text": "distinct − Returns a stream of unique elements if duplicates are present."
},
{
"code": null,
"e": 54501,
"s": 54394,
"text": "limit − Returns a stream of limited elements where limit is specified by passing a number to limit method."
},
{
"code": null,
"e": 54608,
"s": 54501,
"text": "limit − Returns a stream of limited elements where limit is specified by passing a number to limit method."
},
{
"code": null,
"e": 56171,
"s": 54608,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Stream;\n\npublic class FunctionTester { \n public static void main(String[] args) {\n List<String> stringList = \n Arrays.asList(\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"One\"); \n\n System.out.println(\"Example - Filter\\n\");\n //Filter strings whose length are greater than 3.\n Stream<String> longStrings = stringList\n .stream()\n .filter( s -> {return s.length() > 3; });\n\n //print strings\n longStrings.forEach(System.out::println);\n\n System.out.println(\"\\nExample - Map\\n\");\n //map strings to UPPER case and print\n stringList\n .stream()\n .map( s -> s.toUpperCase())\n .forEach(System.out::println);\n\n List<String> sentenceList \n = Arrays.asList(\"I am Mahesh.\", \"I love Java 8 Streams.\"); \n\n System.out.println(\"\\nExample - flatMap\\n\");\n //map strings to UPPER case and print\n sentenceList\n .stream()\n .flatMap( s -> { return (Stream<String>) \n Arrays.asList(s.split(\" \")).stream(); })\n .forEach(System.out::println); \n\n System.out.println(\"\\nExample - distinct\\n\");\n //map strings to UPPER case and print\n stringList\n .stream()\n .distinct()\n .forEach(System.out::println); \n\n System.out.println(\"\\nExample - limit\\n\");\n //map strings to UPPER case and print\n stringList\n .stream()\n .limit(2)\n .forEach(System.out::println); \n } \n}"
},
{
"code": null,
"e": 56377,
"s": 56171,
"text": "Example - Filter\n\nThree\nFour\nFive\n\nExample - Map\n\nONE\nTWO\nTHREE\nFOUR\nFIVE\nONE\n\nExample - flatMap\n\nI\nam\nMahesh.\nI\nlove\nJava\n8\nStreams.\n\nExample - distinct\n\nOne\nTwo\nThree\nFour\nFive\n\nExample - limit\n\nOne\nTwo\n"
},
{
"code": null,
"e": 56736,
"s": 56377,
"text": "When a terminal method in invoked on a stream, iteration starts on stream and any other chained stream. Once the iteration is over then the result of terminal method is returned. A terminal method does not return a Stream thus once a terminal method is invoked over a stream then its chaining of non-terminal methods or intermediate methods stops/terminates."
},
{
"code": null,
"e": 57034,
"s": 56736,
"text": "Generally, terminal methods returns a single value and are invoked on each element of the stream. Following are some of the important terminal methods of Stream interface. Each terminal function takes a predicate function, initiates the iterations of elements, apply the predicate on each element."
},
{
"code": null,
"e": 57154,
"s": 57034,
"text": "anyMatch − If predicate returns true for any of the element, it returns true. If no element matches, false is returned."
},
{
"code": null,
"e": 57274,
"s": 57154,
"text": "anyMatch − If predicate returns true for any of the element, it returns true. If no element matches, false is returned."
},
{
"code": null,
"e": 57396,
"s": 57274,
"text": "allMatch − If predicate returns false for any of the element, it returns false. If all element matches, true is returned."
},
{
"code": null,
"e": 57518,
"s": 57396,
"text": "allMatch − If predicate returns false for any of the element, it returns false. If all element matches, true is returned."
},
{
"code": null,
"e": 57599,
"s": 57518,
"text": "noneMatch − If no element matches, true is returned otherwise false is returned."
},
{
"code": null,
"e": 57680,
"s": 57599,
"text": "noneMatch − If no element matches, true is returned otherwise false is returned."
},
{
"code": null,
"e": 57741,
"s": 57680,
"text": "collect − each element is stored into the collection passed."
},
{
"code": null,
"e": 57802,
"s": 57741,
"text": "collect − each element is stored into the collection passed."
},
{
"code": null,
"e": 57873,
"s": 57802,
"text": "count − returns count of elements passed through intermediate methods."
},
{
"code": null,
"e": 57944,
"s": 57873,
"text": "count − returns count of elements passed through intermediate methods."
},
{
"code": null,
"e": 58034,
"s": 57944,
"text": "findAny − returns Optional instance containing any element or empty instance is returned."
},
{
"code": null,
"e": 58124,
"s": 58034,
"text": "findAny − returns Optional instance containing any element or empty instance is returned."
},
{
"code": null,
"e": 58229,
"s": 58124,
"text": "findFirst − returns first element under Optional instance. For empty stream, empty instance is returned."
},
{
"code": null,
"e": 58334,
"s": 58229,
"text": "findFirst − returns first element under Optional instance. For empty stream, empty instance is returned."
},
{
"code": null,
"e": 58429,
"s": 58334,
"text": "forEach − apply the consumer function on each element. Used to print all elements of a stream."
},
{
"code": null,
"e": 58524,
"s": 58429,
"text": "forEach − apply the consumer function on each element. Used to print all elements of a stream."
},
{
"code": null,
"e": 58630,
"s": 58524,
"text": "min − returns the smallest element of the stream. Compares elements based on comparator predicate passed."
},
{
"code": null,
"e": 58736,
"s": 58630,
"text": "min − returns the smallest element of the stream. Compares elements based on comparator predicate passed."
},
{
"code": null,
"e": 58841,
"s": 58736,
"text": "max − returns the largest element of the stream. Compares elements based on comparator predicate passed."
},
{
"code": null,
"e": 58946,
"s": 58841,
"text": "max − returns the largest element of the stream. Compares elements based on comparator predicate passed."
},
{
"code": null,
"e": 59024,
"s": 58946,
"text": "reduce − reduces all elements to a single element using the predicate passed."
},
{
"code": null,
"e": 59102,
"s": 59024,
"text": "reduce − reduces all elements to a single element using the predicate passed."
},
{
"code": null,
"e": 59150,
"s": 59102,
"text": "toArray − returns arrays of elements of stream."
},
{
"code": null,
"e": 59198,
"s": 59150,
"text": "toArray − returns arrays of elements of stream."
},
{
"code": null,
"e": 61695,
"s": 59198,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester { \n public static void main(String[] args) {\n List<String> stringList \n = Arrays.asList(\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"One\"); \n\n System.out.println(\"Example - anyMatch\\n\");\n //anyMatch - check if Two is present?\n System.out.println(\"Two is present: \" \n + stringList\n .stream()\n .anyMatch(s -> {return s.contains(\"Two\");}));\n\n System.out.println(\"\\nExample - allMatch\\n\");\n //allMatch - check if length of each string is greater than 2.\n System.out.println(\"Length > 2: \" \n + stringList\n .stream()\n .allMatch(s -> {return s.length() > 2;}));\n\n System.out.println(\"\\nExample - noneMatch\\n\");\n //noneMatch - check if length of each string is greater than 6.\n System.out.println(\"Length > 6: \" \n + stringList\n .stream()\n .noneMatch(s -> {return s.length() > 6;}));\n\n System.out.println(\"\\nExample - collect\\n\");\n System.out.println(\"List: \" \n + stringList\n .stream()\n .filter(s -> {return s.length() > 3;})\n .collect(Collectors.toList()));\n\n System.out.println(\"\\nExample - count\\n\");\n System.out.println(\"Count: \" \n + stringList\n .stream()\n .filter(s -> {return s.length() > 3;})\n .count());\n\n System.out.println(\"\\nExample - findAny\\n\");\n System.out.println(\"findAny: \" \n + stringList\n .stream() \n .findAny().get());\n\n System.out.println(\"\\nExample - findFirst\\n\");\n System.out.println(\"findFirst: \" \n + stringList\n .stream() \n .findFirst().get());\n\n System.out.println(\"\\nExample - forEach\\n\");\n stringList\n .stream() \n .forEach(System.out::println);\n\n System.out.println(\"\\nExample - min\\n\");\n System.out.println(\"min: \" \n + stringList\n .stream() \n .min((s1, s2) -> { return s1.compareTo(s2);}));\n\n System.out.println(\"\\nExample - max\\n\");\n System.out.println(\"min: \" \n + stringList\n .stream() \n .max((s1, s2) -> { return s1.compareTo(s2);}));\n\n System.out.println(\"\\nExample - reduce\\n\");\n System.out.println(\"reduced: \" \n + stringList\n .stream() \n .reduce((s1, s2) -> { return s1 + \", \"+ s2;})\n .get());\n } \n}"
},
{
"code": null,
"e": 62137,
"s": 61695,
"text": "Example - anyMatch\n\nTwo is present: true\n\nExample - allMatch\n\nLength > 2: true\n\nExample - noneMatch\n\nLength > 6: true\n\nExample - collect\n\nList: [Three, Four, Five]\n\nExample - count\n\nCount: 3\n\nExample - findAny\n\nfindAny: One\n\nExample - findFirst\n\nfindFirst: One\n\nExample - forEach\n\nOne\nTwo\nThree\nFour\nFive\nOne\n\nExample - min\n\nmin: Optional[Five]\n\nExample - max\n\nmin: Optional[Two]\n\nExample - reduce\n\nreduced: One, Two, Three, Four, Five, One\n"
},
{
"code": null,
"e": 62502,
"s": 62137,
"text": "Collections are in-memory data structure which have all the elements present in the collection and we have external iteration to iterate through collection whereas Stream is a fixed data structure where elements are computed on demand and a Stream has inbuilt iteration to iterate through each element. Following example shows how to create a Stream from an array."
},
{
"code": null,
"e": 62585,
"s": 62502,
"text": "int[] numbers = {1, 2, 3, 4};\nIntStream numbersFromArray = Arrays.stream(numbers);"
},
{
"code": null,
"e": 63012,
"s": 62585,
"text": "Above stream is of fixed size being built from an array of four numbers and will not return element after 4th element. But we can create a Stream using Stream.iterate() or Stream.generate() method which can have lamdba expression will pass to a Stream. Using lamdba expression, we can pass a condition which once fulfilled give the required elements. Consider the case, where we need a list of numbers which are multiple of 3."
},
{
"code": null,
"e": 63331,
"s": 63012,
"text": "import java.util.stream.Stream;\n\npublic class FunctionTester { \n public static void main(String[] args) {\n //create a stream of numbers which are multiple of 3 \n Stream<Integer> numbers = Stream.iterate(0, n -> n + 3);\n\n numbers\n .limit(10)\n .forEach(System.out::println);\n } \n}"
},
{
"code": null,
"e": 63358,
"s": 63331,
"text": "0\n3\n6\n9\n12\n15\n18\n21\n24\n27\n"
},
{
"code": null,
"e": 63509,
"s": 63358,
"text": "In order to operate on infinite stream, we've used limit() method of Stream interface to restrict the iteration of numbers when their count become 10."
},
{
"code": null,
"e": 63579,
"s": 63509,
"text": "There are multiple ways using which we can create fix length streams."
},
{
"code": null,
"e": 63604,
"s": 63579,
"text": "Using Stream.of() method"
},
{
"code": null,
"e": 63629,
"s": 63604,
"text": "Using Stream.of() method"
},
{
"code": null,
"e": 63662,
"s": 63629,
"text": "Using Collection.stream() method"
},
{
"code": null,
"e": 63695,
"s": 63662,
"text": "Using Collection.stream() method"
},
{
"code": null,
"e": 63725,
"s": 63695,
"text": "Using Stream.builder() method"
},
{
"code": null,
"e": 63755,
"s": 63725,
"text": "Using Stream.builder() method"
},
{
"code": null,
"e": 63832,
"s": 63755,
"text": "Following example shows all of the above ways to create a fix length stream."
},
{
"code": null,
"e": 64686,
"s": 63832,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Stream;\n\npublic class FunctionTester { \n public static void main(String[] args) {\n\n System.out.println(\"Stream.of():\");\n Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); \n stream.forEach(System.out::println);\n\n System.out.println(\"Collection.stream():\");\n Integer[] numbers = {1, 2, 3, 4, 5}; \n List<Integer> list = Arrays.asList(numbers);\n list.stream().forEach(System.out::println);\n\n System.out.println(\"StreamBuilder.build():\");\n Stream.Builder<Integer> streamBuilder = Stream.builder();\n streamBuilder.accept(1);\n streamBuilder.accept(2);\n streamBuilder.accept(3);\n streamBuilder.accept(4);\n streamBuilder.accept(5);\n streamBuilder.build().forEach(System.out::println); \n } \n}"
},
{
"code": null,
"e": 64774,
"s": 64686,
"text": "Stream.of():\n1\n2\n3\n4\n5\nCollection.stream():\n1\n2\n3\n4\n5\nStreamBuilder.build():\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 64809,
"s": 64774,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 64824,
"s": 64809,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 64857,
"s": 64824,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 64881,
"s": 64857,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 64917,
"s": 64881,
"text": "\n 72 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 64931,
"s": 64917,
"text": " Arun Ammasai"
},
{
"code": null,
"e": 64964,
"s": 64931,
"text": "\n 51 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 64984,
"s": 64964,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 65017,
"s": 64984,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 65034,
"s": 65017,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 65066,
"s": 65034,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 65087,
"s": 65066,
"text": " Santharam Sivalenka"
},
{
"code": null,
"e": 65094,
"s": 65087,
"text": " Print"
},
{
"code": null,
"e": 65105,
"s": 65094,
"text": " Add Notes"
}
] |
JSP - Session Tracking | In this chapter, we will discuss session tracking in JSP. HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Let us now discuss a few options to maintain the session between the Web Client and the Web Server −
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.
Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across.
a one page request or
visit to a website or
store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().
Here is a summary of important methods available through the session object −
public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
public long getCreationTime()
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
public String getId()
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT.
public int getMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew()
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this Webpage.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your Webpage.
if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run the URL, you will receive the following result −
Session Information
Now try to run the same JSP for the second time, you will receive the following result.
Session Information
When you are done with a user's session data, you have several options −
Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the a particular key.
Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the a particular key.
Delete the whole session − You can call the public void invalidate() method to discard an entire session.
Delete the whole session − You can call the public void invalidate() method to discard an entire session.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure the session time out in web.xml file as follows.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure the session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
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": 2519,
"s": 2239,
"text": "In this chapter, we will discuss session tracking in JSP. HTTP is a \"stateless\" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request."
},
{
"code": null,
"e": 2620,
"s": 2519,
"text": "Let us now discuss a few options to maintain the session between the Web Client and the Web Server −"
},
{
"code": null,
"e": 2788,
"s": 2620,
"text": "A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie."
},
{
"code": null,
"e": 2942,
"s": 2788,
"text": "This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions."
},
{
"code": null,
"e": 3033,
"s": 2942,
"text": "A web server can send a hidden HTML form field along with a unique session ID as follows −"
},
{
"code": null,
"e": 3093,
"s": 3033,
"text": "<input type = \"hidden\" name = \"sessionid\" value = \"12345\">\n"
},
{
"code": null,
"e": 3357,
"s": 3093,
"text": "This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers."
},
{
"code": null,
"e": 3579,
"s": 3357,
"text": "This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking."
},
{
"code": null,
"e": 3765,
"s": 3579,
"text": "You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session."
},
{
"code": null,
"e": 3955,
"s": 3765,
"text": "For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client."
},
{
"code": null,
"e": 4205,
"s": 3955,
"text": "URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page."
},
{
"code": null,
"e": 4363,
"s": 4205,
"text": "Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across."
},
{
"code": null,
"e": 4385,
"s": 4363,
"text": "a one page request or"
},
{
"code": null,
"e": 4407,
"s": 4385,
"text": "visit to a website or"
},
{
"code": null,
"e": 4441,
"s": 4407,
"text": "store information about that user"
},
{
"code": null,
"e": 4700,
"s": 4441,
"text": "By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −"
},
{
"code": null,
"e": 4731,
"s": 4700,
"text": "<%@ page session = \"false\" %>\n"
},
{
"code": null,
"e": 5021,
"s": 4731,
"text": "The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession()."
},
{
"code": null,
"e": 5099,
"s": 5021,
"text": "Here is a summary of important methods available through the session object −"
},
{
"code": null,
"e": 5139,
"s": 5099,
"text": "public Object getAttribute(String name)"
},
{
"code": null,
"e": 5263,
"s": 5139,
"text": "This method returns the object bound with the specified name in this session, or null if no object is bound under the name."
},
{
"code": null,
"e": 5302,
"s": 5263,
"text": "public Enumeration getAttributeNames()"
},
{
"code": null,
"e": 5418,
"s": 5302,
"text": "This method returns an Enumeration of String objects containing the names of all the objects bound to this session."
},
{
"code": null,
"e": 5448,
"s": 5418,
"text": "public long getCreationTime()"
},
{
"code": null,
"e": 5569,
"s": 5448,
"text": "This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT."
},
{
"code": null,
"e": 5591,
"s": 5569,
"text": "public String getId()"
},
{
"code": null,
"e": 5679,
"s": 5591,
"text": "This method returns a string containing the unique identifier assigned to this session."
},
{
"code": null,
"e": 5713,
"s": 5679,
"text": "public long getLastAccessedTime()"
},
{
"code": null,
"e": 5873,
"s": 5713,
"text": "This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT."
},
{
"code": null,
"e": 5909,
"s": 5873,
"text": "public int getMaxInactiveInterval()"
},
{
"code": null,
"e": 6048,
"s": 5909,
"text": "This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses."
},
{
"code": null,
"e": 6073,
"s": 6048,
"text": "public void invalidate()"
},
{
"code": null,
"e": 6148,
"s": 6073,
"text": "This method invalidates this session and unbinds any objects bound to it."
},
{
"code": null,
"e": 6171,
"s": 6148,
"text": "public boolean isNew()"
},
{
"code": null,
"e": 6296,
"s": 6171,
"text": "This method returns true if the client does not yet know about the session or if the client chooses not to join the session."
},
{
"code": null,
"e": 6337,
"s": 6296,
"text": "public void removeAttribute(String name)"
},
{
"code": null,
"e": 6417,
"s": 6337,
"text": "This method removes the object bound with the specified name from this session."
},
{
"code": null,
"e": 6469,
"s": 6417,
"text": "public void setAttribute(String name, Object value)"
},
{
"code": null,
"e": 6541,
"s": 6469,
"text": "This method binds an object to this session, using the name specified."
},
{
"code": null,
"e": 6590,
"s": 6541,
"text": "public void setMaxInactiveInterval(int interval)"
},
{
"code": null,
"e": 6717,
"s": 6590,
"text": "This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session."
},
{
"code": null,
"e": 6927,
"s": 6717,
"text": "This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist."
},
{
"code": null,
"e": 8754,
"s": 6927,
"text": "<%@ page import = \"java.io.*,java.util.*\" %>\n<%\n // Get session creation time.\n Date createTime = new Date(session.getCreationTime());\n \n // Get last access time of this Webpage.\n Date lastAccessTime = new Date(session.getLastAccessedTime());\n\n String title = \"Welcome Back to my website\";\n Integer visitCount = new Integer(0);\n String visitCountKey = new String(\"visitCount\");\n String userIDKey = new String(\"userID\");\n String userID = new String(\"ABCD\");\n\n // Check if this is new comer on your Webpage.\n if (session.isNew() ){\n title = \"Welcome to my website\";\n session.setAttribute(userIDKey, userID);\n session.setAttribute(visitCountKey, visitCount);\n } \n visitCount = (Integer)session.getAttribute(visitCountKey);\n visitCount = visitCount + 1;\n userID = (String)session.getAttribute(userIDKey);\n session.setAttribute(visitCountKey, visitCount);\n%>\n\n<html>\n <head>\n <title>Session Tracking</title>\n </head>\n \n <body>\n <center>\n <h1>Session Tracking</h1>\n </center>\n \n <table border = \"1\" align = \"center\"> \n <tr bgcolor = \"#949494\">\n <th>Session info</th>\n <th>Value</th>\n </tr> \n <tr>\n <td>id</td>\n <td><% out.print( session.getId()); %></td>\n </tr> \n <tr>\n <td>Creation Time</td>\n <td><% out.print(createTime); %></td>\n </tr> \n <tr>\n <td>Time of Last Access</td>\n <td><% out.print(lastAccessTime); %></td>\n </tr> \n <tr>\n <td>User ID</td>\n <td><% out.print(userID); %></td>\n </tr> \n <tr>\n <td>Number of visits</td>\n <td><% out.print(visitCount); %></td>\n </tr> \n </table> \n \n </body>\n</html>"
},
{
"code": null,
"e": 8901,
"s": 8754,
"text": "Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run the URL, you will receive the following result −"
},
{
"code": null,
"e": 8921,
"s": 8901,
"text": "Session Information"
},
{
"code": null,
"e": 9009,
"s": 8921,
"text": "Now try to run the same JSP for the second time, you will receive the following result."
},
{
"code": null,
"e": 9029,
"s": 9009,
"text": "Session Information"
},
{
"code": null,
"e": 9102,
"s": 9029,
"text": "When you are done with a user's session data, you have several options −"
},
{
"code": null,
"e": 9257,
"s": 9102,
"text": "Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the a particular key."
},
{
"code": null,
"e": 9412,
"s": 9257,
"text": "Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the a particular key."
},
{
"code": null,
"e": 9518,
"s": 9412,
"text": "Delete the whole session − You can call the public void invalidate() method to discard an entire session."
},
{
"code": null,
"e": 9624,
"s": 9518,
"text": "Delete the whole session − You can call the public void invalidate() method to discard an entire session."
},
{
"code": null,
"e": 9770,
"s": 9624,
"text": "Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually."
},
{
"code": null,
"e": 9916,
"s": 9770,
"text": "Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually."
},
{
"code": null,
"e": 10090,
"s": 9916,
"text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users."
},
{
"code": null,
"e": 10264,
"s": 10090,
"text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users."
},
{
"code": null,
"e": 10420,
"s": 10264,
"text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure the session time out in web.xml file as follows."
},
{
"code": null,
"e": 10576,
"s": 10420,
"text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure the session time out in web.xml file as follows."
},
{
"code": null,
"e": 10653,
"s": 10576,
"text": "<session-config>\n <session-timeout>15</session-timeout>\n</session-config>\n"
},
{
"code": null,
"e": 10755,
"s": 10653,
"text": "The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat."
},
{
"code": null,
"e": 10960,
"s": 10755,
"text": "The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900."
},
{
"code": null,
"e": 10995,
"s": 10960,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 11010,
"s": 10995,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 11045,
"s": 11010,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 11060,
"s": 11045,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 11095,
"s": 11060,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11109,
"s": 11095,
"text": " Karthikeya T"
},
{
"code": null,
"e": 11144,
"s": 11109,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11160,
"s": 11144,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 11193,
"s": 11160,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 11209,
"s": 11193,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 11243,
"s": 11209,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 11251,
"s": 11243,
"text": " Uplatz"
},
{
"code": null,
"e": 11258,
"s": 11251,
"text": " Print"
},
{
"code": null,
"e": 11269,
"s": 11258,
"text": " Add Notes"
}
] |
Print Stack Elements from Top to Bottom | 19 Jan, 2022
Given a Stack S, the task is to print the elements of the stack from top to bottom such that the elements are still present in the stack without their order being changed.
Examples:
Input: S = {2, 3, 4, 5}Output: 5 4 3 2
Input: S = {3, 3, 2, 2}Output: 2 2 3 3
Recursive Approach: Follow the steps below to solve the problem:
Create a recursive function having stack as the parameter.Add the base condition that, if the stack is empty, return from the function.Otherwise, store the top element in some variable X and remove it.Print X, call the recursive function and pass the same stack in it.Push the stored X back to the Stack.
Create a recursive function having stack as the parameter.
Add the base condition that, if the stack is empty, return from the function.
Otherwise, store the top element in some variable X and remove it.
Print X, call the recursive function and pass the same stack in it.
Push the stored X back to the Stack.
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 print stack elements// from top to bottom with the// order of elements unalteredvoid PrintStack(stack<int> s){ // If stack is empty if (s.empty()) return; // Extract top of the stack int x = s.top(); // Pop the top element s.pop(); // Print the current top // of the stack i.e., x cout << x << ' '; // Proceed to print// remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver Codeint main(){ stack<int> s; // Given stack s s.push(1); s.push(2); s.push(3); s.push(4); // Function Call PrintStack(s); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to print stack elements// from top to bottom with the// order of elements unalteredpublic static void PrintStack(Stack<Integer> s){ // If stack is empty if (s.empty()) return; // Extract top of the stack int x = s.peek(); // Pop the top element s.pop(); // Print the current top // of the stack i.e., x System.out.print(x + " "); // Proceed to print // remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver codepublic static void main(String[] args){ Stack<Integer> s = new Stack<Integer>(); // Given stack s s.push(1); s.push(2); s.push(3); s.push(4); // Function call PrintStack(s);}} // This code is contributed divyeshrabadiya07
# Python3 program for the# above approachfrom queue import LifoQueue # Function to print stack elements# from top to bottom with the# order of elements unaltereddef PrintStack(s): # If stack is empty if (s.empty()): return; # Extract top of the # stack x = s.get(); # Pop the top element #s.pop(); # Print current top # of the stack i.e., x print(x, end = " "); # Proceed to print # remaining stack PrintStack(s); # Push the element # back s.put(x); # Driver codeif __name__ == '__main__': s = LifoQueue(); # Given stack s s.put(1); s.put(2); s.put(3); s.put(4); # Function call PrintStack(s); # This code is contributed by Amit Katiyar
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to print stack elements// from top to bottom with the// order of elements unalteredpublic static void PrintStack(Stack<int> s){ // If stack is empty if (s.Count == 0) return; // Extract top of the stack int x = s.Peek(); // Pop the top element s.Pop(); // Print the current top // of the stack i.e., x Console.Write(x + " "); // Proceed to print // remaining stack PrintStack(s); // Push the element back s.Push(x);} // Driver codepublic static void Main(String[] args){ Stack<int> s = new Stack<int>(); // Given stack s s.Push(1); s.Push(2); s.Push(3); s.Push(4); // Function call PrintStack(s);}} // This code is contributed by Rajput-Ji
<script> // Javascript program for the above approach // Function to print stack elements// from top to bottom with the// order of elements unalteredfunction PrintStack(s){ // If stack is empty if (s.length==0) return; // Extract top of the stack var x = s[s.length-1]; // Pop the top element s.pop(); // Print the current top // of the stack i.e., x document.write( x + ' '); // Proceed to print// remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver Code var s = []; // Given stack ss.push(1);s.push(2);s.push(3);s.push(4); // Function CallPrintStack(s); </script>
4 3 2 1
Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)
Singly LinkedList Stack Approach: This approach discusses the solution to solve the problem for Singly LinkedList Stack representation. Below are the steps:
Push the top element from the given stack into a linked list stack.Print the top element of the singly linked list stack.Pop the top element from the given primary stack.Repeat the above steps in order until the given stack is empty.
Push the top element from the given stack into a linked list stack.
Print the top element of the singly linked list stack.
Pop the top element from the given primary stack.
Repeat the above steps in order until the given stack is empty.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Declare linked list nodestruct Node{ int data; struct Node* link;}; struct Node* top; // Utility function to add an element// data in the stack insert at the beginningvoid push(int data){ // Create new node temp and allocate memory struct Node* temp; temp = new Node(); // Check if stack (heap) is full. // Then inserting an element would // lead to stack overflow if (!temp) { cout << "\nHeap Overflow"; exit(1); } // Initialize data into temp data field temp->data = data; // Put top pointer reference into temp link temp->link = top; // Make temp as top of Stack top = temp;} // Utility function to check if// the stack is empty or notint isEmpty(){ return top == NULL;} // Utility function to return top// element in a stackint peek(){ // Check for empty stack if (!isEmpty()) return top->data; // Otherwise stack is empty else { cout << ("Stack is empty"); return -1; }} // Utility function to pop top// element from the stackvoid pop(){ struct Node* temp; // Check for stack underflow if (top == NULL) { cout << "\nStack Underflow" << endl; exit(1); } else { // Top assign into temp temp = top; // Assign second node to top top = top->link; // Destroy connection between // first and second temp->link = NULL; }} // Function to print all the// elements of the stackvoid DisplayStack(){ struct Node* temp; // Check for stack underflow if (top == NULL) { cout << "\nStack Underflow"; exit(1); } else { temp = top; while (temp != NULL) { // Print node data cout << temp->data << " "; // Assign temp link to temp temp = temp->link; } }} // Driver Codeint main(){ // Push the elements of stack push(1); push(2); push(3); push(4); // Display stack elements DisplayStack(); return 0;} // This code is contributed by gauravrajput1
// Java program for the above approach import static java.lang.System.exit; // Create Stack Using Linked listclass StackUsingLinkedlist { // A linked list node private class Node { int data; Node link; } // Reference variable Node top; // Constructor StackUsingLinkedlist() { this.top = null; } // Function to add an element x // in the stack by inserting // at the beginning of LL public void push(int x) { // Create new node temp Node temp = new Node(); // If stack is full if (temp == null) { System.out.print("\nHeap Overflow"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = top; // Update top reference top = temp; } // Function to check if the stack // is empty or not public boolean isEmpty() { return top == null; } // Function to return top element // in a stack public int peek() { // Check for empty stack if (!isEmpty()) { // Return the top data return top.data; } // Otherwise stack is empty else { System.out.println("Stack is empty"); return -1; } } // Function to pop top element from // the stack by removing element // at the beginning public void pop() { // Check for stack underflow if (top == null) { System.out.print("\nStack Underflow"); return; } // Update the top pointer to // point to the next node top = (top).link; } // Function to print the elements and // restore the stack public static void DisplayStack(StackUsingLinkedlist s) { // Create another stack StackUsingLinkedlist s1 = new StackUsingLinkedlist(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element System.out.print(s1.peek() + " "); s.pop(); } }} // Driver Codepublic class GFG { // Driver Code public static void main(String[] args) { // Create Object of class StackUsingLinkedlist obj = new StackUsingLinkedlist(); // Insert Stack value obj.push(1); obj.push(2); obj.push(3); obj.push(4); // Function Call obj.DisplayStack(obj); }}
// C# program for the above approachusing System; // Create Stack Using Linked listclass StackUsingLinkedlist{ // A linked list nodepublic class Node{ public int data; public Node link;} // Reference variableNode top; // Constructorpublic StackUsingLinkedlist(){ this.top = null;} // Function to add an element x// in the stack by inserting// at the beginning of LLpublic void push(int x){ // Create new node temp Node temp = new Node(); // If stack is full if (temp == null) { Console.Write("\nHeap Overflow"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = top; // Update top reference top = temp;} // Function to check if the stack// is empty or notpublic bool isEmpty(){ return top == null;} // Function to return top element// in a stackpublic int peek(){ // Check for empty stack if (isEmpty() != true) { // Return the top data return top.data; } // Otherwise stack is empty else { Console.WriteLine("Stack is empty"); return -1; }} // Function to pop top element from// the stack by removing element// at the beginningpublic void pop(){ // Check for stack underflow if (top == null) { Console.Write("\nStack Underflow"); return; } // Update the top pointer to // point to the next node top = (top).link;} // Function to print the elements and// restore the stackpublic void DisplayStack(StackUsingLinkedlist s){ // Create another stack StackUsingLinkedlist s1 = new StackUsingLinkedlist(); // Until stack is empty while (s.isEmpty() != true) { s1.push(s.peek()); // Print the element Console.Write(s1.peek() + " "); s.pop(); }}} class GFG{ // Driver Codepublic static void Main(String[] args){ // Create Object of class StackUsingLinkedlist obj = new StackUsingLinkedlist(); // Insert Stack value obj.push(1); obj.push(2); obj.push(3); obj.push(4); // Function Call obj.DisplayStack(obj);}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach class Node{ constructor() { this.data=0; this.link=null; }} // Create Stack Using Linked listclass StackUsingLinkedlist{ constructor(){ this.top=null;} push(x){ // Create new node temp let temp = new Node(); // If stack is full if (temp == null) { document.write("<br>Heap Overflow"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = this.top; // Update top reference this.top = temp;} isEmpty(){ return this.top == null;} peek(){ // Check for empty stack if (!this.isEmpty()) { // Return the top data return this.top.data; } // Otherwise stack is empty else { document.write("Stack is empty"); return -1; }} pop(){ // Check for stack underflow if (this.top == null) { document.write("<br>Stack Underflow"); return; } // Update the top pointer to // point to the next node this.top = this.top.link;} DisplayStack(s){ // Create another stack let s1 = new StackUsingLinkedlist(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element document.write(s1.peek() + " "); s.pop(); }}} // Create Object of classlet obj = new StackUsingLinkedlist(); // Insert Stack valueobj.push(1);obj.push(2);obj.push(3);obj.push(4); // Function Callobj.DisplayStack(obj); // This code is contributed by unknown2108 </script>
4 3 2 1
Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)
Array Stack Approach: This approach discusses the solution to problems in Array Stack implementation. Below are the steps:
Push the top element from the given stack into an array stack.Print the top element of the array stack.Pop-out the top element from the given primary stack.Repeat the above steps in order until the given stack is empty.
Push the top element from the given stack into an array stack.
Print the top element of the array stack.
Pop-out the top element from the given primary stack.
Repeat the above steps in order until the given stack is empty.
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;#define MAX 1000 class Stack{ // Stores the index where element// needs to be insertedint top; public: Stack() { top = -1; } // Array to store the stack elements int a[MAX]; // Function that check whether stack // is empty or not bool isEmpty() { return (top < 0); } // Function that pushes the element // to the top of the stack bool push(int x) { // If stack is full if (top >= (MAX - 1)) { cout << ("Stack Overflow\n"); return false; } // Otherwise insert element x else { a[++top] = x; return true; } } // Function that removes the top // element from the stack int pop() { // If stack is empty if (top < 0) { cout << ("Stack Underflow\n"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; } } // Function to get the top element int peek() { // If stack is empty if (top < 0) { cout << ("Stack Underflow\n"); return 0; } // Otherwise remove element else { int x = a[top]; return x; } } // Function to print the elements // and restore the stack void DisplayStack(Stack s) { // Create another stack Stack s1; // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element cout << (s1.peek()) << " "; s.pop(); } }}; // Driver Codeint main(){ Stack s; // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s);} // This code is contributed by gauravrajput1
// Java program for the above approach class Stack { static final int MAX = 1000; // Stores the index where element // needs to be inserted int top; // Array to store the stack elements int a[] = new int[MAX]; // Function that check whether stack // is empty or not boolean isEmpty() { return (top < 0); } // Constructor Stack() { top = -1; } // Function that pushes the element // to the top of the stack boolean push(int x) { // If stack is full if (top >= (MAX - 1)) { System.out.println( "Stack Overflow"); return false; } // Otherwise insert element x else { a[++top] = x; return true; } } // Function that removes the top // element from the stack int pop() { // If stack is empty if (top < 0) { System.out.println( "Stack Underflow"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; } } // Function to get the top element int peek() { // If stack is empty if (top < 0) { System.out.println( "Stack Underflow"); return 0; } // Otherwise remove element else { int x = a[top]; return x; } } // Function to print the elements // and restore the stack static void DisplayStack(Stack s) { // Create another stack Stack s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element System.out.print(s1.peek() + " "); s.pop(); } }} // Driver Codeclass Main { // Driver Code public static void main(String args[]) { Stack s = new Stack(); // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s); }}
# Python3 program for the above approachMAX = 1000 # Stores the index where# element needs to be insertedtop = -1 # Array to store the# stack elementsa = [0]*MAX # Function that check# whether stack# is empty or notdef isEmpty(): print("4 3 2 1") return (top > 0) # Function that pushes# the element to the# top of the stackdef push(x): global top # If stack is full if (top >= (MAX - 1)): print("Stack Overflow") return False # Otherwise insert element x else: top+=1 a[top] = x return True # Function that removes the top# element from the stackdef pop(): global top # If stack is empty if (top < 0): print("Stack Underflow") return 0 # Otherwise remove element else: top-=1 x = a[top] return x # Function to get the top elementdef peek(): # If stack is empty if (top < 0): print("Stack Underflow") return 0 # Otherwise remove element else: x = a[top] return x # Function to print the elements# and restore the stackdef DisplayStack(): # Until stack is empty while (not isEmpty()): push(peek()) # Print the element #print(peek(), end = " ") pop() # Given stackpush(1)push(2)push(3)push(4) # Function CallDisplayStack() # This code is contributed by suresh07.
// C# program for// the above approachusing System;class Stack{ static int MAX = 1000; // Stores the index where// element needs to be insertedint top; // Array to store the// stack elementsint []a = new int[MAX]; // Function that check// whether stack// is empty or notbool isEmpty(){ return (top < 0);} // Constructorpublic Stack(){ top = -1;} // Function that pushes// the element to the// top of the stackpublic bool push(int x){ // If stack is full if (top >= (MAX - 1)) { Console.WriteLine("Stack Overflow"); return false; } // Otherwise insert element x else { a[++top] = x; return true; }} // Function that removes the top// element from the stackpublic int pop(){ // If stack is empty if (top < 0) { Console.WriteLine("Stack Underflow"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; }} // Function to get the top elementpublic int peek(){ // If stack is empty if (top < 0) { Console.WriteLine("Stack Underflow"); return 0; } // Otherwise remove element else { int x = a[top]; return x; }} // Function to print the elements// and restore the stackpublic void DisplayStack(Stack s){ // Create another stack Stack s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element Console.Write(s1.peek() + " "); s.pop(); }}} class GFG{ // Driver Codepublic static void Main(String []args){ Stack s = new Stack(); // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s);}} // This code is contributed by 29AjayKumar
<script>// Javascript program for the above approach let MAX = 1000; class Stack{ // Constructor constructor() { this.top = -1; this.a = new Array(MAX); } // Function that check whether stack // is empty or not isEmpty() { return (this.top < 0); } // Function that pushes the element // to the top of the stack push(x) { // If stack is full if (this.top >= (MAX - 1)) { document.write( "Stack Overflow<br>"); return false; } // Otherwise insert element x else { this.a[++this.top] = x; return true; } } // Function that removes the top // element from the stack pop() { // If stack is empty if (this.top < 0) { document.write( "Stack Underflow<br>"); return 0; } // Otherwise remove element else { let x = this.a[this.top--]; return x; } } // Function to get the top element peek() { // If stack is empty if (this.top < 0) { document.write( "Stack Underflow<br>"); return 0; } // Otherwise remove element else { let x = this.a[this.top]; return x; } } // Function to print the elements // and restore the stack DisplayStack(s) { // Create another stack let s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element document.write(s1.peek() + " "); s.pop(); } }} // Driver Codelet s = new Stack(); // Given stacks.push(1);s.push(2);s.push(3);s.push(4); // Function Calls.DisplayStack(s); // This code is contributed by patel2127</script>
4 3 2 1
Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)
divyeshrabadiya07
Rajput-Ji
29AjayKumar
amit143katiyar
GauravRajput1
noob2000
unknown2108
patel2127
suresh07
surinderdawra388
Arrays
Linked List
Recursion
School Programming
Stack
Linked List
Arrays
Recursion
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "Given a Stack S, the task is to print the elements of the stack from top to bottom such that the elements are still present in the stack without their order being changed."
},
{
"code": null,
"e": 234,
"s": 224,
"text": "Examples:"
},
{
"code": null,
"e": 273,
"s": 234,
"text": "Input: S = {2, 3, 4, 5}Output: 5 4 3 2"
},
{
"code": null,
"e": 312,
"s": 273,
"text": "Input: S = {3, 3, 2, 2}Output: 2 2 3 3"
},
{
"code": null,
"e": 377,
"s": 312,
"text": "Recursive Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 682,
"s": 377,
"text": "Create a recursive function having stack as the parameter.Add the base condition that, if the stack is empty, return from the function.Otherwise, store the top element in some variable X and remove it.Print X, call the recursive function and pass the same stack in it.Push the stored X back to the Stack."
},
{
"code": null,
"e": 741,
"s": 682,
"text": "Create a recursive function having stack as the parameter."
},
{
"code": null,
"e": 819,
"s": 741,
"text": "Add the base condition that, if the stack is empty, return from the function."
},
{
"code": null,
"e": 886,
"s": 819,
"text": "Otherwise, store the top element in some variable X and remove it."
},
{
"code": null,
"e": 954,
"s": 886,
"text": "Print X, call the recursive function and pass the same stack in it."
},
{
"code": null,
"e": 991,
"s": 954,
"text": "Push the stored X back to the Stack."
},
{
"code": null,
"e": 1042,
"s": 991,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1046,
"s": 1042,
"text": "C++"
},
{
"code": null,
"e": 1051,
"s": 1046,
"text": "Java"
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "Python3"
},
{
"code": null,
"e": 1062,
"s": 1059,
"text": "C#"
},
{
"code": null,
"e": 1073,
"s": 1062,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print stack elements// from top to bottom with the// order of elements unalteredvoid PrintStack(stack<int> s){ // If stack is empty if (s.empty()) return; // Extract top of the stack int x = s.top(); // Pop the top element s.pop(); // Print the current top // of the stack i.e., x cout << x << ' '; // Proceed to print// remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver Codeint main(){ stack<int> s; // Given stack s s.push(1); s.push(2); s.push(3); s.push(4); // Function Call PrintStack(s); return 0;}",
"e": 1780,
"s": 1073,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to print stack elements// from top to bottom with the// order of elements unalteredpublic static void PrintStack(Stack<Integer> s){ // If stack is empty if (s.empty()) return; // Extract top of the stack int x = s.peek(); // Pop the top element s.pop(); // Print the current top // of the stack i.e., x System.out.print(x + \" \"); // Proceed to print // remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver codepublic static void main(String[] args){ Stack<Integer> s = new Stack<Integer>(); // Given stack s s.push(1); s.push(2); s.push(3); s.push(4); // Function call PrintStack(s);}} // This code is contributed divyeshrabadiya07",
"e": 2619,
"s": 1780,
"text": null
},
{
"code": "# Python3 program for the# above approachfrom queue import LifoQueue # Function to print stack elements# from top to bottom with the# order of elements unaltereddef PrintStack(s): # If stack is empty if (s.empty()): return; # Extract top of the # stack x = s.get(); # Pop the top element #s.pop(); # Print current top # of the stack i.e., x print(x, end = \" \"); # Proceed to print # remaining stack PrintStack(s); # Push the element # back s.put(x); # Driver codeif __name__ == '__main__': s = LifoQueue(); # Given stack s s.put(1); s.put(2); s.put(3); s.put(4); # Function call PrintStack(s); # This code is contributed by Amit Katiyar",
"e": 3346,
"s": 2619,
"text": null
},
{
"code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to print stack elements// from top to bottom with the// order of elements unalteredpublic static void PrintStack(Stack<int> s){ // If stack is empty if (s.Count == 0) return; // Extract top of the stack int x = s.Peek(); // Pop the top element s.Pop(); // Print the current top // of the stack i.e., x Console.Write(x + \" \"); // Proceed to print // remaining stack PrintStack(s); // Push the element back s.Push(x);} // Driver codepublic static void Main(String[] args){ Stack<int> s = new Stack<int>(); // Given stack s s.Push(1); s.Push(2); s.Push(3); s.Push(4); // Function call PrintStack(s);}} // This code is contributed by Rajput-Ji",
"e": 4129,
"s": 3346,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to print stack elements// from top to bottom with the// order of elements unalteredfunction PrintStack(s){ // If stack is empty if (s.length==0) return; // Extract top of the stack var x = s[s.length-1]; // Pop the top element s.pop(); // Print the current top // of the stack i.e., x document.write( x + ' '); // Proceed to print// remaining stack PrintStack(s); // Push the element back s.push(x);} // Driver Code var s = []; // Given stack ss.push(1);s.push(2);s.push(3);s.push(4); // Function CallPrintStack(s); </script>",
"e": 4769,
"s": 4129,
"text": null
},
{
"code": null,
"e": 4777,
"s": 4769,
"text": "4 3 2 1"
},
{
"code": null,
"e": 4875,
"s": 4777,
"text": "Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 5032,
"s": 4875,
"text": "Singly LinkedList Stack Approach: This approach discusses the solution to solve the problem for Singly LinkedList Stack representation. Below are the steps:"
},
{
"code": null,
"e": 5266,
"s": 5032,
"text": "Push the top element from the given stack into a linked list stack.Print the top element of the singly linked list stack.Pop the top element from the given primary stack.Repeat the above steps in order until the given stack is empty."
},
{
"code": null,
"e": 5334,
"s": 5266,
"text": "Push the top element from the given stack into a linked list stack."
},
{
"code": null,
"e": 5389,
"s": 5334,
"text": "Print the top element of the singly linked list stack."
},
{
"code": null,
"e": 5439,
"s": 5389,
"text": "Pop the top element from the given primary stack."
},
{
"code": null,
"e": 5503,
"s": 5439,
"text": "Repeat the above steps in order until the given stack is empty."
},
{
"code": null,
"e": 5554,
"s": 5503,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5558,
"s": 5554,
"text": "C++"
},
{
"code": null,
"e": 5563,
"s": 5558,
"text": "Java"
},
{
"code": null,
"e": 5566,
"s": 5563,
"text": "C#"
},
{
"code": null,
"e": 5577,
"s": 5566,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Declare linked list nodestruct Node{ int data; struct Node* link;}; struct Node* top; // Utility function to add an element// data in the stack insert at the beginningvoid push(int data){ // Create new node temp and allocate memory struct Node* temp; temp = new Node(); // Check if stack (heap) is full. // Then inserting an element would // lead to stack overflow if (!temp) { cout << \"\\nHeap Overflow\"; exit(1); } // Initialize data into temp data field temp->data = data; // Put top pointer reference into temp link temp->link = top; // Make temp as top of Stack top = temp;} // Utility function to check if// the stack is empty or notint isEmpty(){ return top == NULL;} // Utility function to return top// element in a stackint peek(){ // Check for empty stack if (!isEmpty()) return top->data; // Otherwise stack is empty else { cout << (\"Stack is empty\"); return -1; }} // Utility function to pop top// element from the stackvoid pop(){ struct Node* temp; // Check for stack underflow if (top == NULL) { cout << \"\\nStack Underflow\" << endl; exit(1); } else { // Top assign into temp temp = top; // Assign second node to top top = top->link; // Destroy connection between // first and second temp->link = NULL; }} // Function to print all the// elements of the stackvoid DisplayStack(){ struct Node* temp; // Check for stack underflow if (top == NULL) { cout << \"\\nStack Underflow\"; exit(1); } else { temp = top; while (temp != NULL) { // Print node data cout << temp->data << \" \"; // Assign temp link to temp temp = temp->link; } }} // Driver Codeint main(){ // Push the elements of stack push(1); push(2); push(3); push(4); // Display stack elements DisplayStack(); return 0;} // This code is contributed by gauravrajput1",
"e": 7788,
"s": 5577,
"text": null
},
{
"code": "// Java program for the above approach import static java.lang.System.exit; // Create Stack Using Linked listclass StackUsingLinkedlist { // A linked list node private class Node { int data; Node link; } // Reference variable Node top; // Constructor StackUsingLinkedlist() { this.top = null; } // Function to add an element x // in the stack by inserting // at the beginning of LL public void push(int x) { // Create new node temp Node temp = new Node(); // If stack is full if (temp == null) { System.out.print(\"\\nHeap Overflow\"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = top; // Update top reference top = temp; } // Function to check if the stack // is empty or not public boolean isEmpty() { return top == null; } // Function to return top element // in a stack public int peek() { // Check for empty stack if (!isEmpty()) { // Return the top data return top.data; } // Otherwise stack is empty else { System.out.println(\"Stack is empty\"); return -1; } } // Function to pop top element from // the stack by removing element // at the beginning public void pop() { // Check for stack underflow if (top == null) { System.out.print(\"\\nStack Underflow\"); return; } // Update the top pointer to // point to the next node top = (top).link; } // Function to print the elements and // restore the stack public static void DisplayStack(StackUsingLinkedlist s) { // Create another stack StackUsingLinkedlist s1 = new StackUsingLinkedlist(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element System.out.print(s1.peek() + \" \"); s.pop(); } }} // Driver Codepublic class GFG { // Driver Code public static void main(String[] args) { // Create Object of class StackUsingLinkedlist obj = new StackUsingLinkedlist(); // Insert Stack value obj.push(1); obj.push(2); obj.push(3); obj.push(4); // Function Call obj.DisplayStack(obj); }}",
"e": 10312,
"s": 7788,
"text": null
},
{
"code": "// C# program for the above approachusing System; // Create Stack Using Linked listclass StackUsingLinkedlist{ // A linked list nodepublic class Node{ public int data; public Node link;} // Reference variableNode top; // Constructorpublic StackUsingLinkedlist(){ this.top = null;} // Function to add an element x// in the stack by inserting// at the beginning of LLpublic void push(int x){ // Create new node temp Node temp = new Node(); // If stack is full if (temp == null) { Console.Write(\"\\nHeap Overflow\"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = top; // Update top reference top = temp;} // Function to check if the stack// is empty or notpublic bool isEmpty(){ return top == null;} // Function to return top element// in a stackpublic int peek(){ // Check for empty stack if (isEmpty() != true) { // Return the top data return top.data; } // Otherwise stack is empty else { Console.WriteLine(\"Stack is empty\"); return -1; }} // Function to pop top element from// the stack by removing element// at the beginningpublic void pop(){ // Check for stack underflow if (top == null) { Console.Write(\"\\nStack Underflow\"); return; } // Update the top pointer to // point to the next node top = (top).link;} // Function to print the elements and// restore the stackpublic void DisplayStack(StackUsingLinkedlist s){ // Create another stack StackUsingLinkedlist s1 = new StackUsingLinkedlist(); // Until stack is empty while (s.isEmpty() != true) { s1.push(s.peek()); // Print the element Console.Write(s1.peek() + \" \"); s.pop(); }}} class GFG{ // Driver Codepublic static void Main(String[] args){ // Create Object of class StackUsingLinkedlist obj = new StackUsingLinkedlist(); // Insert Stack value obj.push(1); obj.push(2); obj.push(3); obj.push(4); // Function Call obj.DisplayStack(obj);}} // This code is contributed by Amit Katiyar",
"e": 12483,
"s": 10312,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach class Node{ constructor() { this.data=0; this.link=null; }} // Create Stack Using Linked listclass StackUsingLinkedlist{ constructor(){ this.top=null;} push(x){ // Create new node temp let temp = new Node(); // If stack is full if (temp == null) { document.write(\"<br>Heap Overflow\"); return; } // Initialize data into temp temp.data = x; // Reference into temp link temp.link = this.top; // Update top reference this.top = temp;} isEmpty(){ return this.top == null;} peek(){ // Check for empty stack if (!this.isEmpty()) { // Return the top data return this.top.data; } // Otherwise stack is empty else { document.write(\"Stack is empty\"); return -1; }} pop(){ // Check for stack underflow if (this.top == null) { document.write(\"<br>Stack Underflow\"); return; } // Update the top pointer to // point to the next node this.top = this.top.link;} DisplayStack(s){ // Create another stack let s1 = new StackUsingLinkedlist(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element document.write(s1.peek() + \" \"); s.pop(); }}} // Create Object of classlet obj = new StackUsingLinkedlist(); // Insert Stack valueobj.push(1);obj.push(2);obj.push(3);obj.push(4); // Function Callobj.DisplayStack(obj); // This code is contributed by unknown2108 </script>",
"e": 14207,
"s": 12483,
"text": null
},
{
"code": null,
"e": 14215,
"s": 14207,
"text": "4 3 2 1"
},
{
"code": null,
"e": 14313,
"s": 14215,
"text": "Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 14436,
"s": 14313,
"text": "Array Stack Approach: This approach discusses the solution to problems in Array Stack implementation. Below are the steps:"
},
{
"code": null,
"e": 14656,
"s": 14436,
"text": "Push the top element from the given stack into an array stack.Print the top element of the array stack.Pop-out the top element from the given primary stack.Repeat the above steps in order until the given stack is empty."
},
{
"code": null,
"e": 14719,
"s": 14656,
"text": "Push the top element from the given stack into an array stack."
},
{
"code": null,
"e": 14761,
"s": 14719,
"text": "Print the top element of the array stack."
},
{
"code": null,
"e": 14815,
"s": 14761,
"text": "Pop-out the top element from the given primary stack."
},
{
"code": null,
"e": 14879,
"s": 14815,
"text": "Repeat the above steps in order until the given stack is empty."
},
{
"code": null,
"e": 14930,
"s": 14879,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 14934,
"s": 14930,
"text": "C++"
},
{
"code": null,
"e": 14939,
"s": 14934,
"text": "Java"
},
{
"code": null,
"e": 14947,
"s": 14939,
"text": "Python3"
},
{
"code": null,
"e": 14950,
"s": 14947,
"text": "C#"
},
{
"code": null,
"e": 14961,
"s": 14950,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define MAX 1000 class Stack{ // Stores the index where element// needs to be insertedint top; public: Stack() { top = -1; } // Array to store the stack elements int a[MAX]; // Function that check whether stack // is empty or not bool isEmpty() { return (top < 0); } // Function that pushes the element // to the top of the stack bool push(int x) { // If stack is full if (top >= (MAX - 1)) { cout << (\"Stack Overflow\\n\"); return false; } // Otherwise insert element x else { a[++top] = x; return true; } } // Function that removes the top // element from the stack int pop() { // If stack is empty if (top < 0) { cout << (\"Stack Underflow\\n\"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; } } // Function to get the top element int peek() { // If stack is empty if (top < 0) { cout << (\"Stack Underflow\\n\"); return 0; } // Otherwise remove element else { int x = a[top]; return x; } } // Function to print the elements // and restore the stack void DisplayStack(Stack s) { // Create another stack Stack s1; // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element cout << (s1.peek()) << \" \"; s.pop(); } }}; // Driver Codeint main(){ Stack s; // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s);} // This code is contributed by gauravrajput1",
"e": 16979,
"s": 14961,
"text": null
},
{
"code": "// Java program for the above approach class Stack { static final int MAX = 1000; // Stores the index where element // needs to be inserted int top; // Array to store the stack elements int a[] = new int[MAX]; // Function that check whether stack // is empty or not boolean isEmpty() { return (top < 0); } // Constructor Stack() { top = -1; } // Function that pushes the element // to the top of the stack boolean push(int x) { // If stack is full if (top >= (MAX - 1)) { System.out.println( \"Stack Overflow\"); return false; } // Otherwise insert element x else { a[++top] = x; return true; } } // Function that removes the top // element from the stack int pop() { // If stack is empty if (top < 0) { System.out.println( \"Stack Underflow\"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; } } // Function to get the top element int peek() { // If stack is empty if (top < 0) { System.out.println( \"Stack Underflow\"); return 0; } // Otherwise remove element else { int x = a[top]; return x; } } // Function to print the elements // and restore the stack static void DisplayStack(Stack s) { // Create another stack Stack s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element System.out.print(s1.peek() + \" \"); s.pop(); } }} // Driver Codeclass Main { // Driver Code public static void main(String args[]) { Stack s = new Stack(); // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s); }}",
"e": 19082,
"s": 16979,
"text": null
},
{
"code": "# Python3 program for the above approachMAX = 1000 # Stores the index where# element needs to be insertedtop = -1 # Array to store the# stack elementsa = [0]*MAX # Function that check# whether stack# is empty or notdef isEmpty(): print(\"4 3 2 1\") return (top > 0) # Function that pushes# the element to the# top of the stackdef push(x): global top # If stack is full if (top >= (MAX - 1)): print(\"Stack Overflow\") return False # Otherwise insert element x else: top+=1 a[top] = x return True # Function that removes the top# element from the stackdef pop(): global top # If stack is empty if (top < 0): print(\"Stack Underflow\") return 0 # Otherwise remove element else: top-=1 x = a[top] return x # Function to get the top elementdef peek(): # If stack is empty if (top < 0): print(\"Stack Underflow\") return 0 # Otherwise remove element else: x = a[top] return x # Function to print the elements# and restore the stackdef DisplayStack(): # Until stack is empty while (not isEmpty()): push(peek()) # Print the element #print(peek(), end = \" \") pop() # Given stackpush(1)push(2)push(3)push(4) # Function CallDisplayStack() # This code is contributed by suresh07.",
"e": 20336,
"s": 19082,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class Stack{ static int MAX = 1000; // Stores the index where// element needs to be insertedint top; // Array to store the// stack elementsint []a = new int[MAX]; // Function that check// whether stack// is empty or notbool isEmpty(){ return (top < 0);} // Constructorpublic Stack(){ top = -1;} // Function that pushes// the element to the// top of the stackpublic bool push(int x){ // If stack is full if (top >= (MAX - 1)) { Console.WriteLine(\"Stack Overflow\"); return false; } // Otherwise insert element x else { a[++top] = x; return true; }} // Function that removes the top// element from the stackpublic int pop(){ // If stack is empty if (top < 0) { Console.WriteLine(\"Stack Underflow\"); return 0; } // Otherwise remove element else { int x = a[top--]; return x; }} // Function to get the top elementpublic int peek(){ // If stack is empty if (top < 0) { Console.WriteLine(\"Stack Underflow\"); return 0; } // Otherwise remove element else { int x = a[top]; return x; }} // Function to print the elements// and restore the stackpublic void DisplayStack(Stack s){ // Create another stack Stack s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element Console.Write(s1.peek() + \" \"); s.pop(); }}} class GFG{ // Driver Codepublic static void Main(String []args){ Stack s = new Stack(); // Given stack s.push(1); s.push(2); s.push(3); s.push(4); // Function Call s.DisplayStack(s);}} // This code is contributed by 29AjayKumar",
"e": 21961,
"s": 20336,
"text": null
},
{
"code": "<script>// Javascript program for the above approach let MAX = 1000; class Stack{ // Constructor constructor() { this.top = -1; this.a = new Array(MAX); } // Function that check whether stack // is empty or not isEmpty() { return (this.top < 0); } // Function that pushes the element // to the top of the stack push(x) { // If stack is full if (this.top >= (MAX - 1)) { document.write( \"Stack Overflow<br>\"); return false; } // Otherwise insert element x else { this.a[++this.top] = x; return true; } } // Function that removes the top // element from the stack pop() { // If stack is empty if (this.top < 0) { document.write( \"Stack Underflow<br>\"); return 0; } // Otherwise remove element else { let x = this.a[this.top--]; return x; } } // Function to get the top element peek() { // If stack is empty if (this.top < 0) { document.write( \"Stack Underflow<br>\"); return 0; } // Otherwise remove element else { let x = this.a[this.top]; return x; } } // Function to print the elements // and restore the stack DisplayStack(s) { // Create another stack let s1 = new Stack(); // Until stack is empty while (!s.isEmpty()) { s1.push(s.peek()); // Print the element document.write(s1.peek() + \" \"); s.pop(); } }} // Driver Codelet s = new Stack(); // Given stacks.push(1);s.push(2);s.push(3);s.push(4); // Function Calls.DisplayStack(s); // This code is contributed by patel2127</script>",
"e": 23913,
"s": 21961,
"text": null
},
{
"code": null,
"e": 23921,
"s": 23913,
"text": "4 3 2 1"
},
{
"code": null,
"e": 24019,
"s": 23921,
"text": "Time Complexity: O(N), where N is the number of elements in the given stack.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 24037,
"s": 24019,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 24047,
"s": 24037,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 24059,
"s": 24047,
"text": "29AjayKumar"
},
{
"code": null,
"e": 24074,
"s": 24059,
"text": "amit143katiyar"
},
{
"code": null,
"e": 24088,
"s": 24074,
"text": "GauravRajput1"
},
{
"code": null,
"e": 24097,
"s": 24088,
"text": "noob2000"
},
{
"code": null,
"e": 24109,
"s": 24097,
"text": "unknown2108"
},
{
"code": null,
"e": 24119,
"s": 24109,
"text": "patel2127"
},
{
"code": null,
"e": 24128,
"s": 24119,
"text": "suresh07"
},
{
"code": null,
"e": 24145,
"s": 24128,
"text": "surinderdawra388"
},
{
"code": null,
"e": 24152,
"s": 24145,
"text": "Arrays"
},
{
"code": null,
"e": 24164,
"s": 24152,
"text": "Linked List"
},
{
"code": null,
"e": 24174,
"s": 24164,
"text": "Recursion"
},
{
"code": null,
"e": 24193,
"s": 24174,
"text": "School Programming"
},
{
"code": null,
"e": 24199,
"s": 24193,
"text": "Stack"
},
{
"code": null,
"e": 24211,
"s": 24199,
"text": "Linked List"
},
{
"code": null,
"e": 24218,
"s": 24211,
"text": "Arrays"
},
{
"code": null,
"e": 24228,
"s": 24218,
"text": "Recursion"
},
{
"code": null,
"e": 24234,
"s": 24228,
"text": "Stack"
},
{
"code": null,
"e": 24332,
"s": 24234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24400,
"s": 24332,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 24444,
"s": 24400,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 24476,
"s": 24444,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 24524,
"s": 24476,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 24538,
"s": 24524,
"text": "Linear Search"
},
{
"code": null,
"e": 24573,
"s": 24538,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 24612,
"s": 24573,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 24634,
"s": 24612,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 24682,
"s": 24634,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
std::strncmp() in C++ | 09 Jan, 2019
std::strncmp() function lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome.
This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings.
num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\0’) of either string.
This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on.
This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches.
Syntax :
int strncmp(const char *str1, const char *str2, size_t count);
Parameters:
str1 and str2: C string to be compared.
count: Maximum number of characters to compare.
size_t is an unsigned integral type.
Return Value:
Value Meaning
Less than zero str1 is less than str2.
Zero str1 is equal to str2.
Greater than zero str1 is greater than str2.
If there are less than count characters in either string, the comparison ends when the first null is encountered.
What does strcmp() return?
strncmp() function return three different types of integer values on the basis of comparison:
1. Greater than zero ( >0 ): A positive value is returned, if a character of str1 and str2 doesn’t match before the num characters and the ASCII value of str1 character is greater than ASCII value of str2 character. As a result, we can say that str1 is lexicographically greater than str2.
// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = "aksh"; char str2[10] = "akash"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf("str1 is equal to str2 upto num characters\n"); } else if (result > 0) printf("str1 is greater than str2\n"); else printf("str2 is greater than str1\n"); printf("Value returned by strncmp() is: %d", result); return 0;}
Output:
str1 is greater than str2
Value returned by strncmp() is: 18
2. Less than zero ( <0 ): A negative value is returned, if a character of str1 and str2 doesn’t match before the num characters and the ASCII value of str1 character is lesser than ASCII value of str2 character. As a result, we can say that str2 is lexicographically greater than str1.
// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = "akash"; char str2[10] = "aksh"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf("str1 is equal to str2 upto num characters\n"); } else if (result > 0) printf("str1 is greater than str2\n"); else printf("str2 is greater than str1\n"); printf("Value returned by strncmp() is: %d", result); return 0;}
Output:
str2 is greater than str1
Value returned by strncmp() is: -18
3. Equal to zero ( 0 ): This function returns zero if the characters of str1 matches with the characters of the str2 upto num characters. As a result, we cannot say that str1 is equal to str2, until num is equal to length of either string.
// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = "akash"; char str2[10] = "akas"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf("str1 is equal to str2 upto num characters\n"); } else if (result > 0) printf("str1 is greater than str2\n"); else printf("str2 is greater than str1\n"); printf("Value returned by strncmp() is: %d", result); return 0;}
Output:
str1 is equal to str2 upto num characters
Value returned by strncmp() is: 0
Note: When the strings are not same, you will find that the value returned by the strncmp() function is the difference between the ASCII values of first unmatched character in str1 and str2 in both the cases.
More Examples
Example 1:
// CPP program to illustrate strncmp()#include <cstring>#include <iostream> void display(char* abc, char* xyz, int res, int count){ if (res > 0) std::cout << xyz << " come-before " << abc; else if (res < 0) std::cout << abc << " come-before " << xyz; else std::cout << "First " << count << " characters of string " << abc << " and " << xyz << " are same";} int main(){ char abc[] = "GeeksforGeeks"; char xyz[] = "Geeks"; int res; res = std::strncmp(abc, xyz, 4); display(abc, xyz, res, 4); return 0;}
Output:
First 4 characters of string GeeksforGeeks and Geeks are same
Example 2:
// CPP program to illustrate strncmp()#include <cstring>#include <iostream> void display(char* abc, char* xyz, int res, int count){ if (res > 0) std::cout << xyz << " come-before " << abc; else if (res < 0) std::cout << abc << " come-before " << xyz; else std::cout << "First " << count << " characters of string " << abc << " and " << xyz << " are same"; ;} int main(){ char abc[] = "GeeksforGeeks"; char xyz[] = "Geeks"; int res; res = std::strncmp(abc, xyz, 6); display(abc, xyz, res, 6); return 0;}
Output:
Geeks come-before GeeksforGeeks
This article is contributed by Akash Gupta and Shivani Ghughtyal. 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.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Substring in C++
Object Oriented Programming in C++
C++ Classes and Objects | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jan, 2019"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "std::strncmp() function lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome."
},
{
"code": null,
"e": 311,
"s": 192,
"text": "This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings."
},
{
"code": null,
"e": 497,
"s": 311,
"text": "num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\\0’) of either string."
},
{
"code": null,
"e": 720,
"s": 497,
"text": "This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on."
},
{
"code": null,
"e": 863,
"s": 720,
"text": "This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches."
},
{
"code": null,
"e": 872,
"s": 863,
"text": "Syntax :"
},
{
"code": null,
"e": 1317,
"s": 872,
"text": "int strncmp(const char *str1, const char *str2, size_t count);\n\nParameters:\nstr1 and str2: C string to be compared.\ncount: Maximum number of characters to compare.\n size_t is an unsigned integral type.\n\nReturn Value: \nValue Meaning\nLess than zero str1 is less than str2.\nZero str1 is equal to str2.\nGreater than zero str1 is greater than str2.\n"
},
{
"code": null,
"e": 1431,
"s": 1317,
"text": "If there are less than count characters in either string, the comparison ends when the first null is encountered."
},
{
"code": null,
"e": 1458,
"s": 1431,
"text": "What does strcmp() return?"
},
{
"code": null,
"e": 1552,
"s": 1458,
"text": "strncmp() function return three different types of integer values on the basis of comparison:"
},
{
"code": null,
"e": 1842,
"s": 1552,
"text": "1. Greater than zero ( >0 ): A positive value is returned, if a character of str1 and str2 doesn’t match before the num characters and the ASCII value of str1 character is greater than ASCII value of str2 character. As a result, we can say that str1 is lexicographically greater than str2."
},
{
"code": "// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = \"aksh\"; char str2[10] = \"akash\"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf(\"str1 is equal to str2 upto num characters\\n\"); } else if (result > 0) printf(\"str1 is greater than str2\\n\"); else printf(\"str2 is greater than str1\\n\"); printf(\"Value returned by strncmp() is: %d\", result); return 0;}",
"e": 2465,
"s": 1842,
"text": null
},
{
"code": null,
"e": 2473,
"s": 2465,
"text": "Output:"
},
{
"code": null,
"e": 2535,
"s": 2473,
"text": "str1 is greater than str2\nValue returned by strncmp() is: 18\n"
},
{
"code": null,
"e": 2821,
"s": 2535,
"text": "2. Less than zero ( <0 ): A negative value is returned, if a character of str1 and str2 doesn’t match before the num characters and the ASCII value of str1 character is lesser than ASCII value of str2 character. As a result, we can say that str2 is lexicographically greater than str1."
},
{
"code": "// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = \"akash\"; char str2[10] = \"aksh\"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf(\"str1 is equal to str2 upto num characters\\n\"); } else if (result > 0) printf(\"str1 is greater than str2\\n\"); else printf(\"str2 is greater than str1\\n\"); printf(\"Value returned by strncmp() is: %d\", result); return 0;}",
"e": 3444,
"s": 2821,
"text": null
},
{
"code": null,
"e": 3452,
"s": 3444,
"text": "Output:"
},
{
"code": null,
"e": 3515,
"s": 3452,
"text": "str2 is greater than str1\nValue returned by strncmp() is: -18\n"
},
{
"code": null,
"e": 3755,
"s": 3515,
"text": "3. Equal to zero ( 0 ): This function returns zero if the characters of str1 matches with the characters of the str2 upto num characters. As a result, we cannot say that str1 is equal to str2, until num is equal to length of either string."
},
{
"code": "// C, C++ program to demonstrate// functionality of strncmp() #include <stdio.h>#include <string.h> int main(){ // Take any two strings char str1[10] = \"akash\"; char str2[10] = \"akas\"; // Compare strings using strncmp() int result = strncmp(str1, str2, 4); if (result == 0) { // num is the 3rd parameter of strncmp() function printf(\"str1 is equal to str2 upto num characters\\n\"); } else if (result > 0) printf(\"str1 is greater than str2\\n\"); else printf(\"str2 is greater than str1\\n\"); printf(\"Value returned by strncmp() is: %d\", result); return 0;}",
"e": 4378,
"s": 3755,
"text": null
},
{
"code": null,
"e": 4386,
"s": 4378,
"text": "Output:"
},
{
"code": null,
"e": 4463,
"s": 4386,
"text": "str1 is equal to str2 upto num characters\nValue returned by strncmp() is: 0\n"
},
{
"code": null,
"e": 4672,
"s": 4463,
"text": "Note: When the strings are not same, you will find that the value returned by the strncmp() function is the difference between the ASCII values of first unmatched character in str1 and str2 in both the cases."
},
{
"code": null,
"e": 4686,
"s": 4672,
"text": "More Examples"
},
{
"code": null,
"e": 4697,
"s": 4686,
"text": "Example 1:"
},
{
"code": "// CPP program to illustrate strncmp()#include <cstring>#include <iostream> void display(char* abc, char* xyz, int res, int count){ if (res > 0) std::cout << xyz << \" come-before \" << abc; else if (res < 0) std::cout << abc << \" come-before \" << xyz; else std::cout << \"First \" << count << \" characters of string \" << abc << \" and \" << xyz << \" are same\";} int main(){ char abc[] = \"GeeksforGeeks\"; char xyz[] = \"Geeks\"; int res; res = std::strncmp(abc, xyz, 4); display(abc, xyz, res, 4); return 0;}",
"e": 5256,
"s": 4697,
"text": null
},
{
"code": null,
"e": 5264,
"s": 5256,
"text": "Output:"
},
{
"code": null,
"e": 5327,
"s": 5264,
"text": "First 4 characters of string GeeksforGeeks and Geeks are same\n"
},
{
"code": null,
"e": 5338,
"s": 5327,
"text": "Example 2:"
},
{
"code": "// CPP program to illustrate strncmp()#include <cstring>#include <iostream> void display(char* abc, char* xyz, int res, int count){ if (res > 0) std::cout << xyz << \" come-before \" << abc; else if (res < 0) std::cout << abc << \" come-before \" << xyz; else std::cout << \"First \" << count << \" characters of string \" << abc << \" and \" << xyz << \" are same\"; ;} int main(){ char abc[] = \"GeeksforGeeks\"; char xyz[] = \"Geeks\"; int res; res = std::strncmp(abc, xyz, 6); display(abc, xyz, res, 6); return 0;}",
"e": 5902,
"s": 5338,
"text": null
},
{
"code": null,
"e": 5910,
"s": 5902,
"text": "Output:"
},
{
"code": null,
"e": 5943,
"s": 5910,
"text": "Geeks come-before GeeksforGeeks\n"
},
{
"code": null,
"e": 6264,
"s": 5943,
"text": "This article is contributed by Akash Gupta and Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6389,
"s": 6264,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6409,
"s": 6389,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 6413,
"s": 6409,
"text": "STL"
},
{
"code": null,
"e": 6417,
"s": 6413,
"text": "C++"
},
{
"code": null,
"e": 6421,
"s": 6417,
"text": "STL"
},
{
"code": null,
"e": 6425,
"s": 6421,
"text": "CPP"
},
{
"code": null,
"e": 6523,
"s": 6425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6550,
"s": 6523,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 6593,
"s": 6550,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6627,
"s": 6593,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 6652,
"s": 6627,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 6671,
"s": 6652,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 6725,
"s": 6671,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6765,
"s": 6725,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6782,
"s": 6765,
"text": "Substring in C++"
},
{
"code": null,
"e": 6817,
"s": 6782,
"text": "Object Oriented Programming in C++"
}
] |
How do we mix two strings and generate another in java? | Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.
You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).
String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";
You can concatenate Strings in Java in the following ways −
Using the "+" operator − Java Provides a concatenation operator using this, you can directly add two String literals
import java.util.Scanner;
public class StringExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first string: ");
String str1 = sc.next();
System.out.println("Enter the second string: ");
String str2 = sc.next();
//Concatenating the two Strings
String result = str1+str2;
System.out.println(result);
}
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Java
Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value.
import java.util.Scanner;
public class StringExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first string: ");
String str1 = sc.next();
System.out.println("Enter the second string: ");
String str2 = sc.next();
//Concatenating the two Strings
String result = str1.concat(str2);
System.out.println(result);
}
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Using StringBuffer and StringBuilder classes − StringBuffer and StringBuilder classes are those that can be used as alternative to String when modification needed.
These are similar to String except they are mutable. These provide various methods for contents manipulation. The append() method of these classes accepts a String value and adds it to the current StringBuilder object.
import java.util.Scanner;
public class StringExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first string: ");
String str1 = sc.next();
System.out.println("Enter the second string: ");
String str2 = sc.next();
StringBuilder sb = new StringBuilder(str1);
//Concatenating the two Strings
sb.append(str2);
System.out.println(sb);
}
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap | [
{
"code": null,
"e": 1339,
"s": 1187,
"text": "Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String."
},
{
"code": null,
"e": 1494,
"s": 1339,
"text": "You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype)."
},
{
"code": null,
"e": 1601,
"s": 1494,
"text": "String stringObject = new String(\"Hello how are you\");\nString stringLiteral = \"Welcome to Tutorialspoint\";"
},
{
"code": null,
"e": 1661,
"s": 1601,
"text": "You can concatenate Strings in Java in the following ways −"
},
{
"code": null,
"e": 1778,
"s": 1661,
"text": "Using the \"+\" operator − Java Provides a concatenation operator using this, you can directly add two String literals"
},
{
"code": null,
"e": 2203,
"s": 1778,
"text": "import java.util.Scanner;\npublic class StringExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the first string: \");\n String str1 = sc.next();\n System.out.println(\"Enter the second string: \");\n String str2 = sc.next();\n //Concatenating the two Strings\n String result = str1+str2;\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 2286,
"s": 2203,
"text": "Enter the first string:\nKrishna\nEnter the second string:\nKasyap\nKrishnaKasyap\nJava"
},
{
"code": null,
"e": 2444,
"s": 2286,
"text": "Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value."
},
{
"code": null,
"e": 2877,
"s": 2444,
"text": "import java.util.Scanner;\npublic class StringExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the first string: \");\n String str1 = sc.next();\n System.out.println(\"Enter the second string: \");\n String str2 = sc.next();\n //Concatenating the two Strings\n String result = str1.concat(str2);\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 2955,
"s": 2877,
"text": "Enter the first string:\nKrishna\nEnter the second string:\nKasyap\nKrishnaKasyap"
},
{
"code": null,
"e": 3119,
"s": 2955,
"text": "Using StringBuffer and StringBuilder classes − StringBuffer and StringBuilder classes are those that can be used as alternative to String when modification needed."
},
{
"code": null,
"e": 3338,
"s": 3119,
"text": "These are similar to String except they are mutable. These provide various methods for contents manipulation. The append() method of these classes accepts a String value and adds it to the current StringBuilder object."
},
{
"code": null,
"e": 3799,
"s": 3338,
"text": "import java.util.Scanner;\npublic class StringExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the first string: \");\n String str1 = sc.next();\n System.out.println(\"Enter the second string: \");\n String str2 = sc.next();\n StringBuilder sb = new StringBuilder(str1);\n //Concatenating the two Strings\n sb.append(str2);\n System.out.println(sb);\n }\n}"
},
{
"code": null,
"e": 3877,
"s": 3799,
"text": "Enter the first string:\nKrishna\nEnter the second string:\nKasyap\nKrishnaKasyap"
}
] |
Linear Regression (Python Implementation) | 18 May, 2022
This article discusses the basics of linear regression and its implementation in the Python programming language.Linear regression is a statistical method for modeling relationships between a dependent variable with a given set of independent variables.
Note: In this article, we refer to dependent variables as responses and independent variables as features for simplicity.In order to provide a basic understanding of linear regression, we start with the most basic version of linear regression, i.e. Simple linear regression.
Simple linear regression is an approach for predicting a response using a single feature.It is assumed that the two variables are linearly related. Hence, we try to find a linear function that predicts the response value(y) as accurately as possible as a function of the feature or independent variable(x).Let us consider a dataset where we have a value of response y for every feature x:
For generality, we define:x as feature vector, i.e x = [x_1, x_2, ...., x_n],y as response vector, i.e y = [y_1, y_2, ...., y_n]for n observations (in above example, n=10).A scatter plot of the above dataset looks like:-
Now, the task is to find a line that fits best in the above scatter plot so that we can predict the response for any new feature values. (i.e a value of x not present in a dataset)This line is called a regression line.The equation of regression line is represented as:
Here,
h(x_i) represents the predicted response value for ith observation.
b_0 and b_1 are regression coefficients and represent y-intercept and slope of regression line respectively.
To create our model, we must “learn” or estimate the values of regression coefficients b_0 and b_1. And once we’ve estimated these coefficients, we can use the model to predict responses!In this article, we are going to use the principle of Least Squares.Now consider:Here, e_i is a residual error in ith observation. So, our aim is to minimize the total residual error.We define the squared error or cost function, J as: and our task is to find the value of b_0 and b_1 for which J(b_0,b_1) is minimum!Without going into the mathematical details, we present the result here:where SS_xy is the sum of cross-deviations of y and x: and SS_xx is the sum of squared deviations of x: Note: The complete derivation for finding least squares estimates in simple linear regression can be found here.
Code: Python implementation of above technique on our small dataset
Python
import numpy as npimport matplotlib.pyplot as plt def estimate_coef(x, y): # number of observations/points n = np.size(x) # mean of x and y vector m_x = np.mean(x) m_y = np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) - n*m_y*m_x SS_xx = np.sum(x*x) - n*m_x*m_x # calculating regression coefficients b_1 = SS_xy / SS_xx b_0 = m_y - b_1*m_x return (b_0, b_1) def plot_regression_line(x, y, b): # plotting the actual points as scatter plot plt.scatter(x, y, color = "m", marker = "o", s = 30) # predicted response vector y_pred = b[0] + b[1]*x # plotting the regression line plt.plot(x, y_pred, color = "g") # putting labels plt.xlabel('x') plt.ylabel('y') # function to show plot plt.show() def main(): # observations / data x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12]) # estimating coefficients b = estimate_coef(x, y) print("Estimated coefficients:\nb_0 = {} \ \nb_1 = {}".format(b[0], b[1])) # plotting regression line plot_regression_line(x, y, b) if __name__ == "__main__": main()
Output:
Estimated coefficients:
b_0 = -0.0586206896552
b_1 = 1.45747126437
And graph obtained looks like this:
Multiple linear regression attempts to model the relationship between two or more features and a response by fitting a linear equation to the observed data.Clearly, it is nothing but an extension of simple linear regression.Consider a dataset with p features(or independent variables) and one response(or dependent variable). Also, the dataset contains n rows/observations.We define:X (feature matrix) = a matrix of size n X p where x_{ij} denotes the values of jth feature for ith observation.So, andy (response vector) = a vector of size n where y_{i} denotes the value of response for ith observation.The regression line for p features is represented as: where h(x_i) is predicted response value for ith observation and b_0, b_1, ..., b_p are the regression coefficients.Also, we can write: where e_i represents residual error in ith observation.We can generalize our linear model a little bit more by representing feature matrix X as: So now, the linear model can be expressed in terms of matrices as: where, andNow, we determine an estimate of b, i.e. b’ using the Least Squares method.As already explained, the Least Squares method tends to determine b’ for which total residual error is minimized.We present the result directly here: where ‘ represents the transpose of the matrix while -1 represents the matrix inverse.Knowing the least square estimates, b’, the multiple linear regression model can now be estimated as:where y’ is the estimated response vector.Note: The complete derivation for obtaining least square estimates in multiple linear regression can be found here.
Code: Python implementation of multiple linear regression techniques on the Boston house pricing dataset using Scikit-learn.
Python
import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets, linear_model, metrics # load the boston datasetboston = datasets.load_boston(return_X_y=False) # defining feature matrix(X) and response vector(y)X = boston.datay = boston.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # create linear regression objectreg = linear_model.LinearRegression() # train the model using the training setsreg.fit(X_train, y_train) # regression coefficientsprint('Coefficients: ', reg.coef_) # variance score: 1 means perfect predictionprint('Variance score: {}'.format(reg.score(X_test, y_test))) # plot for residual error ## setting plot styleplt.style.use('fivethirtyeight') ## plotting residual errors in training dataplt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train, color = "green", s = 10, label = 'Train data') ## plotting residual errors in test dataplt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test, color = "blue", s = 10, label = 'Test data') ## plotting line for zero residual errorplt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2) ## plotting legendplt.legend(loc = 'upper right') ## plot titleplt.title("Residual errors") ## method call for showing the plotplt.show()
Output:
Coefficients:
[ -8.80740828e-02 6.72507352e-02 5.10280463e-02 2.18879172e+00
-1.72283734e+01 3.62985243e+00 2.13933641e-03 -1.36531300e+00
2.88788067e-01 -1.22618657e-02 -8.36014969e-01 9.53058061e-03
-5.05036163e-01]
Variance score: 0.720898784611
and Residual Error plot looks like this:
In the above example, we determine the accuracy score using Explained Variance Score. We define: explained_variance_score = 1 – Var{y – y’}/Var{y} where y’ is the estimated target output, y the corresponding (correct) target output, and Var is Variance, the square of the standard deviation. The best possible score is 1.0, lower values are worse.
Given below are the basic assumptions that a linear regression model makes regarding a dataset on which it is applied:
Linear relationship: Relationship between response and feature variables should be linear. The linearity assumption can be tested using scatter plots. As shown below, 1st figure represents linearly related variables whereas variables in the 2nd and 3rd figures are most likely non-linear. So, 1st figure will give better predictions using linear regression.
Little or no multi-collinearity: It is assumed that there is little or no multicollinearity in the data. Multicollinearity occurs when the features (or independent variables) are not independent of each other.
Little or no auto-correlation: Another assumption is that there is little or no autocorrelation in the data. Autocorrelation occurs when the residual errors are not independent of each other. You can refer here for more insight into this topic.
Homoscedasticity: Homoscedasticity describes a situation in which the error term (that is, the “noise” or random disturbance in the relationship between the independent variables and the dependent variable) is the same across all values of the independent variables. As shown below, figure 1 has homoscedasticity while figure 2 has heteroscedasticity.
As we reach the end of this article, we discuss some applications of linear regression below.
Trend lines: A trend line represents the variation in quantitative data with the passage of time (like GDP, oil prices, etc.). These trends usually follow a linear relationship. Hence, linear regression can be applied to predict future values. However, this method suffers from a lack of scientific validity in cases where other potential changes can affect the data.
Economics: Linear regression is the predominant empirical tool in economics. For example, it is used to predict consumer spending, fixed investment spending, inventory investment, purchases of a country’s exports, spending on imports, the demand to hold liquid assets, labor demand, and labor supply.
Finance: The capital price asset model uses linear regression to analyze and quantify the systematic risks of an investment.4. Biology: Linear regression is used to model causal relationships between parameters in biological systems.
https://en.wikipedia.org/wiki/Linear_regression
https://en.wikipedia.org/wiki/Simple_linear_regression
http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html
http://www.statisticssolutions.com/assumptions-of-linear-regression/
kumarv456
vaibhavsinghtanwar
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 308,
"s": 54,
"text": "This article discusses the basics of linear regression and its implementation in the Python programming language.Linear regression is a statistical method for modeling relationships between a dependent variable with a given set of independent variables."
},
{
"code": null,
"e": 584,
"s": 308,
"text": "Note: In this article, we refer to dependent variables as responses and independent variables as features for simplicity.In order to provide a basic understanding of linear regression, we start with the most basic version of linear regression, i.e. Simple linear regression. "
},
{
"code": null,
"e": 974,
"s": 584,
"text": "Simple linear regression is an approach for predicting a response using a single feature.It is assumed that the two variables are linearly related. Hence, we try to find a linear function that predicts the response value(y) as accurately as possible as a function of the feature or independent variable(x).Let us consider a dataset where we have a value of response y for every feature x: "
},
{
"code": null,
"e": 1195,
"s": 974,
"text": "For generality, we define:x as feature vector, i.e x = [x_1, x_2, ...., x_n],y as response vector, i.e y = [y_1, y_2, ...., y_n]for n observations (in above example, n=10).A scatter plot of the above dataset looks like:-"
},
{
"code": null,
"e": 1464,
"s": 1195,
"text": "Now, the task is to find a line that fits best in the above scatter plot so that we can predict the response for any new feature values. (i.e a value of x not present in a dataset)This line is called a regression line.The equation of regression line is represented as:"
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Here, "
},
{
"code": null,
"e": 1540,
"s": 1472,
"text": "h(x_i) represents the predicted response value for ith observation."
},
{
"code": null,
"e": 1649,
"s": 1540,
"text": "b_0 and b_1 are regression coefficients and represent y-intercept and slope of regression line respectively."
},
{
"code": null,
"e": 2442,
"s": 1649,
"text": "To create our model, we must “learn” or estimate the values of regression coefficients b_0 and b_1. And once we’ve estimated these coefficients, we can use the model to predict responses!In this article, we are going to use the principle of Least Squares.Now consider:Here, e_i is a residual error in ith observation. So, our aim is to minimize the total residual error.We define the squared error or cost function, J as: and our task is to find the value of b_0 and b_1 for which J(b_0,b_1) is minimum!Without going into the mathematical details, we present the result here:where SS_xy is the sum of cross-deviations of y and x: and SS_xx is the sum of squared deviations of x: Note: The complete derivation for finding least squares estimates in simple linear regression can be found here."
},
{
"code": null,
"e": 2511,
"s": 2442,
"text": "Code: Python implementation of above technique on our small dataset "
},
{
"code": null,
"e": 2518,
"s": 2511,
"text": "Python"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt def estimate_coef(x, y): # number of observations/points n = np.size(x) # mean of x and y vector m_x = np.mean(x) m_y = np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) - n*m_y*m_x SS_xx = np.sum(x*x) - n*m_x*m_x # calculating regression coefficients b_1 = SS_xy / SS_xx b_0 = m_y - b_1*m_x return (b_0, b_1) def plot_regression_line(x, y, b): # plotting the actual points as scatter plot plt.scatter(x, y, color = \"m\", marker = \"o\", s = 30) # predicted response vector y_pred = b[0] + b[1]*x # plotting the regression line plt.plot(x, y_pred, color = \"g\") # putting labels plt.xlabel('x') plt.ylabel('y') # function to show plot plt.show() def main(): # observations / data x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12]) # estimating coefficients b = estimate_coef(x, y) print(\"Estimated coefficients:\\nb_0 = {} \\ \\nb_1 = {}\".format(b[0], b[1])) # plotting regression line plot_regression_line(x, y, b) if __name__ == \"__main__\": main()",
"e": 3729,
"s": 2518,
"text": null
},
{
"code": null,
"e": 3738,
"s": 3729,
"text": "Output: "
},
{
"code": null,
"e": 3805,
"s": 3738,
"text": "Estimated coefficients:\nb_0 = -0.0586206896552\nb_1 = 1.45747126437"
},
{
"code": null,
"e": 3843,
"s": 3805,
"text": "And graph obtained looks like this: "
},
{
"code": null,
"e": 5429,
"s": 3843,
"text": "Multiple linear regression attempts to model the relationship between two or more features and a response by fitting a linear equation to the observed data.Clearly, it is nothing but an extension of simple linear regression.Consider a dataset with p features(or independent variables) and one response(or dependent variable). Also, the dataset contains n rows/observations.We define:X (feature matrix) = a matrix of size n X p where x_{ij} denotes the values of jth feature for ith observation.So, andy (response vector) = a vector of size n where y_{i} denotes the value of response for ith observation.The regression line for p features is represented as: where h(x_i) is predicted response value for ith observation and b_0, b_1, ..., b_p are the regression coefficients.Also, we can write: where e_i represents residual error in ith observation.We can generalize our linear model a little bit more by representing feature matrix X as: So now, the linear model can be expressed in terms of matrices as: where, andNow, we determine an estimate of b, i.e. b’ using the Least Squares method.As already explained, the Least Squares method tends to determine b’ for which total residual error is minimized.We present the result directly here: where ‘ represents the transpose of the matrix while -1 represents the matrix inverse.Knowing the least square estimates, b’, the multiple linear regression model can now be estimated as:where y’ is the estimated response vector.Note: The complete derivation for obtaining least square estimates in multiple linear regression can be found here."
},
{
"code": null,
"e": 5555,
"s": 5429,
"text": "Code: Python implementation of multiple linear regression techniques on the Boston house pricing dataset using Scikit-learn. "
},
{
"code": null,
"e": 5562,
"s": 5555,
"text": "Python"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets, linear_model, metrics # load the boston datasetboston = datasets.load_boston(return_X_y=False) # defining feature matrix(X) and response vector(y)X = boston.datay = boston.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # create linear regression objectreg = linear_model.LinearRegression() # train the model using the training setsreg.fit(X_train, y_train) # regression coefficientsprint('Coefficients: ', reg.coef_) # variance score: 1 means perfect predictionprint('Variance score: {}'.format(reg.score(X_test, y_test))) # plot for residual error ## setting plot styleplt.style.use('fivethirtyeight') ## plotting residual errors in training dataplt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train, color = \"green\", s = 10, label = 'Train data') ## plotting residual errors in test dataplt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test, color = \"blue\", s = 10, label = 'Test data') ## plotting line for zero residual errorplt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2) ## plotting legendplt.legend(loc = 'upper right') ## plot titleplt.title(\"Residual errors\") ## method call for showing the plotplt.show()",
"e": 7020,
"s": 5562,
"text": null
},
{
"code": null,
"e": 7029,
"s": 7020,
"text": "Output: "
},
{
"code": null,
"e": 7293,
"s": 7029,
"text": "Coefficients:\n[ -8.80740828e-02 6.72507352e-02 5.10280463e-02 2.18879172e+00\n-1.72283734e+01 3.62985243e+00 2.13933641e-03 -1.36531300e+00\n2.88788067e-01 -1.22618657e-02 -8.36014969e-01 9.53058061e-03\n-5.05036163e-01]\nVariance score: 0.720898784611"
},
{
"code": null,
"e": 7336,
"s": 7293,
"text": "and Residual Error plot looks like this: "
},
{
"code": null,
"e": 7686,
"s": 7336,
"text": "In the above example, we determine the accuracy score using Explained Variance Score. We define: explained_variance_score = 1 – Var{y – y’}/Var{y} where y’ is the estimated target output, y the corresponding (correct) target output, and Var is Variance, the square of the standard deviation. The best possible score is 1.0, lower values are worse. "
},
{
"code": null,
"e": 7807,
"s": 7686,
"text": "Given below are the basic assumptions that a linear regression model makes regarding a dataset on which it is applied: "
},
{
"code": null,
"e": 8166,
"s": 7807,
"text": "Linear relationship: Relationship between response and feature variables should be linear. The linearity assumption can be tested using scatter plots. As shown below, 1st figure represents linearly related variables whereas variables in the 2nd and 3rd figures are most likely non-linear. So, 1st figure will give better predictions using linear regression. "
},
{
"code": null,
"e": 8376,
"s": 8166,
"text": "Little or no multi-collinearity: It is assumed that there is little or no multicollinearity in the data. Multicollinearity occurs when the features (or independent variables) are not independent of each other."
},
{
"code": null,
"e": 8621,
"s": 8376,
"text": "Little or no auto-correlation: Another assumption is that there is little or no autocorrelation in the data. Autocorrelation occurs when the residual errors are not independent of each other. You can refer here for more insight into this topic."
},
{
"code": null,
"e": 8974,
"s": 8621,
"text": "Homoscedasticity: Homoscedasticity describes a situation in which the error term (that is, the “noise” or random disturbance in the relationship between the independent variables and the dependent variable) is the same across all values of the independent variables. As shown below, figure 1 has homoscedasticity while figure 2 has heteroscedasticity. "
},
{
"code": null,
"e": 9069,
"s": 8974,
"text": "As we reach the end of this article, we discuss some applications of linear regression below. "
},
{
"code": null,
"e": 9437,
"s": 9069,
"text": "Trend lines: A trend line represents the variation in quantitative data with the passage of time (like GDP, oil prices, etc.). These trends usually follow a linear relationship. Hence, linear regression can be applied to predict future values. However, this method suffers from a lack of scientific validity in cases where other potential changes can affect the data."
},
{
"code": null,
"e": 9738,
"s": 9437,
"text": "Economics: Linear regression is the predominant empirical tool in economics. For example, it is used to predict consumer spending, fixed investment spending, inventory investment, purchases of a country’s exports, spending on imports, the demand to hold liquid assets, labor demand, and labor supply."
},
{
"code": null,
"e": 9972,
"s": 9738,
"text": "Finance: The capital price asset model uses linear regression to analyze and quantify the systematic risks of an investment.4. Biology: Linear regression is used to model causal relationships between parameters in biological systems."
},
{
"code": null,
"e": 10020,
"s": 9972,
"text": "https://en.wikipedia.org/wiki/Linear_regression"
},
{
"code": null,
"e": 10075,
"s": 10020,
"text": "https://en.wikipedia.org/wiki/Simple_linear_regression"
},
{
"code": null,
"e": 10147,
"s": 10075,
"text": "http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html"
},
{
"code": null,
"e": 10216,
"s": 10147,
"text": "http://www.statisticssolutions.com/assumptions-of-linear-regression/"
},
{
"code": null,
"e": 10226,
"s": 10216,
"text": "kumarv456"
},
{
"code": null,
"e": 10245,
"s": 10226,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 10271,
"s": 10245,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 10288,
"s": 10271,
"text": "Machine Learning"
},
{
"code": null,
"e": 10295,
"s": 10288,
"text": "Python"
},
{
"code": null,
"e": 10312,
"s": 10295,
"text": "Machine Learning"
}
] |
Pure Functions in JavaScript | 09 May, 2022
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program’s execution. Rather, it only depends on its input arguments.
Also a pure function does not produce any observable side effects such as network requests or data mutation etc.
Let’s see the below JavaScript Function:
function calculateGST( productPrice ) {
return productPrice * 0.05;
}
The above function will always return the same result, if we pass the same productPrice. In other words, its output doesn’t get affected by any other values / state changes. So we can call “calculateGST” function a Pure Function.
Now, let’s see one more function below:
var tax = 20;
function calculateGST( productPrice ) {
return productPrice * (tax / 100) + productPrice;
}
Pause a second and can you guess whether the above function is Pure or not ?
If you guessed that it is isn’t, you are right! It is not a pure function as the output is dependent on an external variable “tax”. So if the tax value is updated somehow, then we will get a different output though we pass the same productPrice as a parameter to the function.
But here we need to make an important note:
Note: If a pure function calls a pure function, this isn’t a side effect and the calling function is still considered pure. (Example: using Math.max() inside a function)
Below are some side effects (but not limited to) which a function should not produce in order to be considered as a pure function –
Making a HTTP request
Mutating data
Printing to a screen or console
DOM Query/Manipulation
Math.random()
Getting the current time
morganthemosaic
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 295,
"s": 52,
"text": "A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program’s execution. Rather, it only depends on its input arguments."
},
{
"code": null,
"e": 408,
"s": 295,
"text": "Also a pure function does not produce any observable side effects such as network requests or data mutation etc."
},
{
"code": null,
"e": 449,
"s": 408,
"text": "Let’s see the below JavaScript Function:"
},
{
"code": null,
"e": 523,
"s": 449,
"text": "function calculateGST( productPrice ) {\n return productPrice * 0.05;\n}"
},
{
"code": null,
"e": 753,
"s": 523,
"text": "The above function will always return the same result, if we pass the same productPrice. In other words, its output doesn’t get affected by any other values / state changes. So we can call “calculateGST” function a Pure Function."
},
{
"code": null,
"e": 793,
"s": 753,
"text": "Now, let’s see one more function below:"
},
{
"code": null,
"e": 903,
"s": 793,
"text": "var tax = 20;\nfunction calculateGST( productPrice ) {\n return productPrice * (tax / 100) + productPrice;\n}"
},
{
"code": null,
"e": 980,
"s": 903,
"text": "Pause a second and can you guess whether the above function is Pure or not ?"
},
{
"code": null,
"e": 1257,
"s": 980,
"text": "If you guessed that it is isn’t, you are right! It is not a pure function as the output is dependent on an external variable “tax”. So if the tax value is updated somehow, then we will get a different output though we pass the same productPrice as a parameter to the function."
},
{
"code": null,
"e": 1301,
"s": 1257,
"text": "But here we need to make an important note:"
},
{
"code": null,
"e": 1471,
"s": 1301,
"text": "Note: If a pure function calls a pure function, this isn’t a side effect and the calling function is still considered pure. (Example: using Math.max() inside a function)"
},
{
"code": null,
"e": 1603,
"s": 1471,
"text": "Below are some side effects (but not limited to) which a function should not produce in order to be considered as a pure function –"
},
{
"code": null,
"e": 1625,
"s": 1603,
"text": "Making a HTTP request"
},
{
"code": null,
"e": 1639,
"s": 1625,
"text": "Mutating data"
},
{
"code": null,
"e": 1671,
"s": 1639,
"text": "Printing to a screen or console"
},
{
"code": null,
"e": 1694,
"s": 1671,
"text": "DOM Query/Manipulation"
},
{
"code": null,
"e": 1708,
"s": 1694,
"text": "Math.random()"
},
{
"code": null,
"e": 1733,
"s": 1708,
"text": "Getting the current time"
},
{
"code": null,
"e": 1749,
"s": 1733,
"text": "morganthemosaic"
},
{
"code": null,
"e": 1770,
"s": 1749,
"text": "javascript-functions"
},
{
"code": null,
"e": 1781,
"s": 1770,
"text": "JavaScript"
},
{
"code": null,
"e": 1798,
"s": 1781,
"text": "Web Technologies"
},
{
"code": null,
"e": 1896,
"s": 1798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1957,
"s": 1896,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1997,
"s": 1957,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2039,
"s": 1997,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2080,
"s": 2039,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2102,
"s": 2080,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2135,
"s": 2102,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2197,
"s": 2135,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2258,
"s": 2197,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2308,
"s": 2258,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
C# - Polymorphism | The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are −
Function overloading
Operator overloading
We discuss operator overloading in next chapter.
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
The following example shows using function print() to print different data types −
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
Console.WriteLine("Printing int: {0}", i );
}
void print(double f) {
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s) {
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args) {
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
Here are the rules about abstract classes −
You cannot create an instance of an abstract class
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class
You cannot declare an abstract method outside an abstract class
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
The following program demonstrates an abstract class −
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this −
using System;
namespace PolymorphismApplication {
class Shape {
protected int width, height;
public Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
public virtual int area() {
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {
}
public override int area() {
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller {
public void CallArea(Shape sh) {
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester {
static void Main(string[] args) {
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Rectangle class area:
Area: 70
Triangle class area: | [
{
"code": null,
"e": 2564,
"s": 2404,
"text": "The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'."
},
{
"code": null,
"e": 2741,
"s": 2564,
"text": "Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time."
},
{
"code": null,
"e": 2943,
"s": 2741,
"text": "The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are −"
},
{
"code": null,
"e": 2964,
"s": 2943,
"text": "Function overloading"
},
{
"code": null,
"e": 2985,
"s": 2964,
"text": "Operator overloading"
},
{
"code": null,
"e": 3034,
"s": 2985,
"text": "We discuss operator overloading in next chapter."
},
{
"code": null,
"e": 3314,
"s": 3034,
"text": "You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type."
},
{
"code": null,
"e": 3397,
"s": 3314,
"text": "The following example shows using function print() to print different data types −"
},
{
"code": null,
"e": 4089,
"s": 3397,
"text": "using System;\n\nnamespace PolymorphismApplication {\n class Printdata {\n void print(int i) {\n Console.WriteLine(\"Printing int: {0}\", i );\n }\n void print(double f) {\n Console.WriteLine(\"Printing float: {0}\" , f);\n }\n void print(string s) {\n Console.WriteLine(\"Printing string: {0}\", s);\n }\n static void Main(string[] args) {\n Printdata p = new Printdata();\n \n // Call print to print integer\n p.print(5);\n \n // Call print to print float\n p.print(500.263);\n \n // Call print to print string\n p.print(\"Hello C++\");\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4170,
"s": 4089,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4238,
"s": 4170,
"text": "Printing int: 5\nPrinting float: 500.263\nPrinting string: Hello C++\n"
},
{
"code": null,
"e": 4561,
"s": 4238,
"text": "C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality."
},
{
"code": null,
"e": 4605,
"s": 4561,
"text": "Here are the rules about abstract classes −"
},
{
"code": null,
"e": 4656,
"s": 4605,
"text": "You cannot create an instance of an abstract class"
},
{
"code": null,
"e": 4707,
"s": 4656,
"text": "You cannot create an instance of an abstract class"
},
{
"code": null,
"e": 4771,
"s": 4707,
"text": "You cannot declare an abstract method outside an abstract class"
},
{
"code": null,
"e": 4835,
"s": 4771,
"text": "You cannot declare an abstract method outside an abstract class"
},
{
"code": null,
"e": 4936,
"s": 4835,
"text": "When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 5037,
"s": 4936,
"text": "When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 5092,
"s": 5037,
"text": "The following program demonstrates an abstract class −"
},
{
"code": null,
"e": 5763,
"s": 5092,
"text": "using System;\n\nnamespace PolymorphismApplication {\n abstract class Shape {\n public abstract int area();\n }\n \n class Rectangle: Shape {\n private int length;\n private int width;\n \n public Rectangle( int a = 0, int b = 0) {\n length = a;\n width = b;\n }\n public override int area () { \n Console.WriteLine(\"Rectangle class area :\");\n return (width * length); \n }\n }\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle r = new Rectangle(10, 7);\n double a = r.area();\n Console.WriteLine(\"Area: {0}\",a);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 5844,
"s": 5763,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5877,
"s": 5844,
"text": "Rectangle class area :\nArea: 70\n"
},
{
"code": null,
"e": 6151,
"s": 5877,
"text": "When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime."
},
{
"code": null,
"e": 6230,
"s": 6151,
"text": "Dynamic polymorphism is implemented by abstract classes and virtual functions."
},
{
"code": null,
"e": 6272,
"s": 6230,
"text": "The following program demonstrates this −"
},
{
"code": null,
"e": 7497,
"s": 6272,
"text": "using System;\n\nnamespace PolymorphismApplication {\n class Shape {\n protected int width, height;\n \n public Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n public virtual int area() {\n Console.WriteLine(\"Parent class area :\");\n return 0;\n }\n }\n class Rectangle: Shape {\n public Rectangle( int a = 0, int b = 0): base(a, b) {\n\n }\n public override int area () {\n Console.WriteLine(\"Rectangle class area :\");\n return (width * height); \n }\n }\n class Triangle: Shape {\n public Triangle(int a = 0, int b = 0): base(a, b) {\n }\n public override int area() {\n Console.WriteLine(\"Triangle class area :\");\n return (width * height / 2); \n }\n }\n class Caller {\n public void CallArea(Shape sh) {\n int a;\n a = sh.area();\n Console.WriteLine(\"Area: {0}\", a);\n }\n } \n class Tester {\n static void Main(string[] args) {\n Caller c = new Caller();\n Rectangle r = new Rectangle(10, 7);\n Triangle t = new Triangle(10, 5);\n \n c.CallArea(r);\n c.CallArea(t);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 7578,
"s": 7497,
"text": "When the above code is compiled and executed, it produces the following result −"
}
] |
Side by Side bar charts in R | 01 Feb, 2022
In this article, we will discuss how to draw Bar Charts side by side in R Programming Language.
To draw plots side by side par() function is used.
Syntax:
par(mfrow, mar, mgp, las)
Parameters:
mfrow- A numeric vector of length 2, which sets the rows and column in which frame has to be divided.
mar – A numeric vector of length 4, which sets the margin sizes in the following order: bottom, left, top, and right.
mgp – A numeric vector of length 3, which sets the axis label locations relative to the edge of the inner plot window.
las – A numeric value indicating the orientation of the tick mark labels and any other text added to a plot after its initialization.
The plots are drawn normally and independent of others. For drawing them side-by-side pass the number of rows and columns as if a grid is being defined.
Example: Plotting bar plots side by side using basic R
R
# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32) label1 <- c('geek','geek-i-knack','technical-scripter', 'content-writer','problem-setter')label2 <- c('sun','mon','tue','wed','thur','fri','sat') # set the plotting area into a 1*2 arraypar(mfrow=c(1,2)) # Draw the two bar chart using above datasetsbarplot(x1, names.arg = label1,col=rainbow(length(x1)))barplot(x2, names.arg = label2,col ="green")
Output:
In this grid.arrange() is used to arrange the plots on a frame.
Syntax:
grid.arrange(plot, nrow, ncol)
Parameter:
plot- ggplot2 plot which we want to arrange
nrow- Number of rows
ncol- Number of columns
Here, plots are drawn normally and independently. Then, the function is called with these plots and the number of rows and columns in a way that a grid is being defined.
Example: Plotting multiple plots side by side using ggplot.
R
# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32)x3 <- c(234,123,210) label1 <- c('geek','geek-i-knack','technical-scripter', 'content-writer','problem-setter')label2 <- c('sun','mon','tue','wed','thur','fri','sat') label3 <- c('solved','attempted','unsolved') # Create data frame using above# data columndata1 <- data.frame(x1,label1)data2 <- data.frame(x2,label2)data3 <- data.frame(x3,label3) # set the plotting area into a 1*3 arraypar(mfrow=c(1,3)) # import library ggplot2 and gridExtralibrary(ggplot2)library(gridExtra) # Draw the three bar chart using above datasetsplot1<-ggplot(data1, aes(x=label1, y=x1)) +geom_bar(stat="identity", width=1, color="white", fill=rgb(0.1,0.4,0.5,0.7)) plot2<-ggplot(data2, aes(x=label2, y=x2)) +geom_bar(stat="identity", width=1, color="white", fill=rgb(0.1,0.8,0.1,0.7)) plot3<-ggplot(data3, aes(x=label3, y=x3)) +geom_bar(stat="identity", width=1, color="white", fill=rgb(0.8,0.4,0.1,0.7)) # Use grid.arrange to put plots in columnsgrid.arrange(plot1, plot2, plot3, ncol=3)
Output:
sumitgumber28
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "In this article, we will discuss how to draw Bar Charts side by side in R Programming Language."
},
{
"code": null,
"e": 175,
"s": 124,
"text": "To draw plots side by side par() function is used."
},
{
"code": null,
"e": 183,
"s": 175,
"text": "Syntax:"
},
{
"code": null,
"e": 210,
"s": 183,
"text": " par(mfrow, mar, mgp, las)"
},
{
"code": null,
"e": 222,
"s": 210,
"text": "Parameters:"
},
{
"code": null,
"e": 324,
"s": 222,
"text": "mfrow- A numeric vector of length 2, which sets the rows and column in which frame has to be divided."
},
{
"code": null,
"e": 442,
"s": 324,
"text": "mar – A numeric vector of length 4, which sets the margin sizes in the following order: bottom, left, top, and right."
},
{
"code": null,
"e": 561,
"s": 442,
"text": "mgp – A numeric vector of length 3, which sets the axis label locations relative to the edge of the inner plot window."
},
{
"code": null,
"e": 695,
"s": 561,
"text": "las – A numeric value indicating the orientation of the tick mark labels and any other text added to a plot after its initialization."
},
{
"code": null,
"e": 848,
"s": 695,
"text": "The plots are drawn normally and independent of others. For drawing them side-by-side pass the number of rows and columns as if a grid is being defined."
},
{
"code": null,
"e": 903,
"s": 848,
"text": "Example: Plotting bar plots side by side using basic R"
},
{
"code": null,
"e": 905,
"s": 903,
"text": "R"
},
{
"code": "# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32) label1 <- c('geek','geek-i-knack','technical-scripter', 'content-writer','problem-setter')label2 <- c('sun','mon','tue','wed','thur','fri','sat') # set the plotting area into a 1*2 arraypar(mfrow=c(1,2)) # Draw the two bar chart using above datasetsbarplot(x1, names.arg = label1,col=rainbow(length(x1)))barplot(x2, names.arg = label2,col =\"green\")",
"e": 1347,
"s": 905,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1347,
"text": "Output:"
},
{
"code": null,
"e": 1419,
"s": 1355,
"text": "In this grid.arrange() is used to arrange the plots on a frame."
},
{
"code": null,
"e": 1427,
"s": 1419,
"text": "Syntax:"
},
{
"code": null,
"e": 1459,
"s": 1427,
"text": " grid.arrange(plot, nrow, ncol)"
},
{
"code": null,
"e": 1470,
"s": 1459,
"text": "Parameter:"
},
{
"code": null,
"e": 1514,
"s": 1470,
"text": "plot- ggplot2 plot which we want to arrange"
},
{
"code": null,
"e": 1535,
"s": 1514,
"text": "nrow- Number of rows"
},
{
"code": null,
"e": 1559,
"s": 1535,
"text": "ncol- Number of columns"
},
{
"code": null,
"e": 1729,
"s": 1559,
"text": "Here, plots are drawn normally and independently. Then, the function is called with these plots and the number of rows and columns in a way that a grid is being defined."
},
{
"code": null,
"e": 1789,
"s": 1729,
"text": "Example: Plotting multiple plots side by side using ggplot."
},
{
"code": null,
"e": 1791,
"s": 1789,
"text": "R"
},
{
"code": "# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32)x3 <- c(234,123,210) label1 <- c('geek','geek-i-knack','technical-scripter', 'content-writer','problem-setter')label2 <- c('sun','mon','tue','wed','thur','fri','sat') label3 <- c('solved','attempted','unsolved') # Create data frame using above# data columndata1 <- data.frame(x1,label1)data2 <- data.frame(x2,label2)data3 <- data.frame(x3,label3) # set the plotting area into a 1*3 arraypar(mfrow=c(1,3)) # import library ggplot2 and gridExtralibrary(ggplot2)library(gridExtra) # Draw the three bar chart using above datasetsplot1<-ggplot(data1, aes(x=label1, y=x1)) +geom_bar(stat=\"identity\", width=1, color=\"white\", fill=rgb(0.1,0.4,0.5,0.7)) plot2<-ggplot(data2, aes(x=label2, y=x2)) +geom_bar(stat=\"identity\", width=1, color=\"white\", fill=rgb(0.1,0.8,0.1,0.7)) plot3<-ggplot(data3, aes(x=label3, y=x3)) +geom_bar(stat=\"identity\", width=1, color=\"white\", fill=rgb(0.8,0.4,0.1,0.7)) # Use grid.arrange to put plots in columnsgrid.arrange(plot1, plot2, plot3, ncol=3)",
"e": 2875,
"s": 1791,
"text": null
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Output:"
},
{
"code": null,
"e": 2905,
"s": 2891,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2912,
"s": 2905,
"text": "Picked"
},
{
"code": null,
"e": 2921,
"s": 2912,
"text": "R-Charts"
},
{
"code": null,
"e": 2930,
"s": 2921,
"text": "R-Graphs"
},
{
"code": null,
"e": 2938,
"s": 2930,
"text": "R-plots"
},
{
"code": null,
"e": 2949,
"s": 2938,
"text": "R Language"
},
{
"code": null,
"e": 3047,
"s": 2949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3099,
"s": 3047,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3157,
"s": 3099,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3192,
"s": 3157,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3230,
"s": 3192,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3279,
"s": 3230,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3296,
"s": 3279,
"text": "R - if statement"
},
{
"code": null,
"e": 3333,
"s": 3296,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3376,
"s": 3333,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3413,
"s": 3376,
"text": "How to import an Excel File into R ?"
}
] |
How to determine if an array contains a specific value in PHP? | 27 May, 2021
Given an array and a specific value, we have to determine whether the array contains that value or not. So there is two popular way to determine that the specific value is in the array or not. One procedure is using by loop and other one is in_array() function. By using loop to get the specific value present or not is time-consuming compared to in_array() function so here we will skip the loop one and use the in_array() function.Below programs illustrate how to determine if an array contains a specific value:Program 1:
php
<?php//array containing elements$names = array('Geeks', 'for', 'Geeks'); //search element$item = 'Geeks';if(in_array($item, $names)){ //the item is there echo "Your element founded";}else{ //the item isn't there echo "Element is not found";}?>
Output:
Your element founded
Program 2: In this example the in_array function perform in strict mode, it will also check the type of array elements.
php
<?php$name = array("Python", "Java", "C#", 3); //Searching pythonif (in_array("python", $name, TRUE)) { echo "found \n"; }else { echo "not found \n"; } //Searching 3if (in_array(3, $name, TRUE)) { echo "found \n"; }else { echo "not found \n"; } //Searching Javaif (in_array("Java", $name, TRUE)) { echo "found \n"; }else { echo "not found \n"; } ?>
Output:
not found
found
found
Program 3:
php
<?php$arr= array('gfg', 1, 17); if (in_array('gfg', $arr)) { echo " gfg \n";} if (in_array(18, $arr)) { echo "18 found with strict check\n";}?>
Output:
gfg
In the above example, the array contains string “gfg” and two numbers 1 and 17. The if statement calls in_array() function which checks if the given item as the parameter is present in the given array or not. If the function returns true, the if statement is executed.
akshaysingh98088
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 555,
"s": 28,
"text": "Given an array and a specific value, we have to determine whether the array contains that value or not. So there is two popular way to determine that the specific value is in the array or not. One procedure is using by loop and other one is in_array() function. By using loop to get the specific value present or not is time-consuming compared to in_array() function so here we will skip the loop one and use the in_array() function.Below programs illustrate how to determine if an array contains a specific value:Program 1: "
},
{
"code": null,
"e": 559,
"s": 555,
"text": "php"
},
{
"code": "<?php//array containing elements$names = array('Geeks', 'for', 'Geeks'); //search element$item = 'Geeks';if(in_array($item, $names)){ //the item is there echo \"Your element founded\";}else{ //the item isn't there echo \"Element is not found\";}?>",
"e": 823,
"s": 559,
"text": null
},
{
"code": null,
"e": 833,
"s": 823,
"text": "Output: "
},
{
"code": null,
"e": 854,
"s": 833,
"text": "Your element founded"
},
{
"code": null,
"e": 975,
"s": 854,
"text": "Program 2: In this example the in_array function perform in strict mode, it will also check the type of array elements. "
},
{
"code": null,
"e": 979,
"s": 975,
"text": "php"
},
{
"code": "<?php$name = array(\"Python\", \"Java\", \"C#\", 3); //Searching pythonif (in_array(\"python\", $name, TRUE)) { echo \"found \\n\"; }else { echo \"not found \\n\"; } //Searching 3if (in_array(3, $name, TRUE)) { echo \"found \\n\"; }else { echo \"not found \\n\"; } //Searching Javaif (in_array(\"Java\", $name, TRUE)) { echo \"found \\n\"; }else { echo \"not found \\n\"; } ?>",
"e": 1364,
"s": 979,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1364,
"text": "Output: "
},
{
"code": null,
"e": 1399,
"s": 1374,
"text": "not found \nfound \nfound "
},
{
"code": null,
"e": 1412,
"s": 1399,
"text": "Program 3: "
},
{
"code": null,
"e": 1416,
"s": 1412,
"text": "php"
},
{
"code": "<?php$arr= array('gfg', 1, 17); if (in_array('gfg', $arr)) { echo \" gfg \\n\";} if (in_array(18, $arr)) { echo \"18 found with strict check\\n\";}?>",
"e": 1566,
"s": 1416,
"text": null
},
{
"code": null,
"e": 1576,
"s": 1566,
"text": "Output: "
},
{
"code": null,
"e": 1581,
"s": 1576,
"text": "gfg "
},
{
"code": null,
"e": 1851,
"s": 1581,
"text": "In the above example, the array contains string “gfg” and two numbers 1 and 17. The if statement calls in_array() function which checks if the given item as the parameter is present in the given array or not. If the function returns true, the if statement is executed. "
},
{
"code": null,
"e": 1868,
"s": 1851,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1875,
"s": 1868,
"text": "Picked"
},
{
"code": null,
"e": 1879,
"s": 1875,
"text": "PHP"
},
{
"code": null,
"e": 1892,
"s": 1879,
"text": "PHP Programs"
},
{
"code": null,
"e": 1909,
"s": 1892,
"text": "Web Technologies"
},
{
"code": null,
"e": 1913,
"s": 1909,
"text": "PHP"
}
] |
Move all zeroes to end of array using List Comprehension in Python | 21 Nov, 2018
Given an array of random numbers, Push all the zeros of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
Examples:
Input : arr = [1, 2, 0, 4, 3, 0, 5, 0]
Output : arr = [1, 2, 4, 3, 5, 0, 0, 0]
Input : arr = [1, 2, 0, 0, 0, 3, 6]
Output : arr = [1, 2, 3, 6, 0, 0, 0]
We have existing solution for this problem please refer Move all zeroes to end of array link. We will solve this problem in python using List Comprehension in a single line of code.
# Function to append all zeros at the end # of arraydef moveZeros(arr): # first expression returns a list of # all non zero elements in arr in the # same order they were inserted into arr # second expression returns a list of # zeros present in arr return [nonZero for nonZero in arr if nonZero!=0] + \ [Zero for Zero in arr if Zero==0] # Driver functionif __name__ == "__main__": arr = [1, 2, 0, 4, 3, 0, 5, 0] print (moveZeros(arr))
Output:
[1, 2, 4, 3, 5, 0, 0, 0]
This article is contributed by Shashank Mishra (Gullu). 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.
Python list-programs
python-list
Arrays
Python
python-list
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
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": 54,
"s": 26,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 385,
"s": 54,
"text": "Given an array of random numbers, Push all the zeros of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1)."
},
{
"code": null,
"e": 395,
"s": 385,
"text": "Examples:"
},
{
"code": null,
"e": 551,
"s": 395,
"text": "Input : arr = [1, 2, 0, 4, 3, 0, 5, 0]\nOutput : arr = [1, 2, 4, 3, 5, 0, 0, 0]\n\nInput : arr = [1, 2, 0, 0, 0, 3, 6]\nOutput : arr = [1, 2, 3, 6, 0, 0, 0]\n"
},
{
"code": null,
"e": 733,
"s": 551,
"text": "We have existing solution for this problem please refer Move all zeroes to end of array link. We will solve this problem in python using List Comprehension in a single line of code."
},
{
"code": "# Function to append all zeros at the end # of arraydef moveZeros(arr): # first expression returns a list of # all non zero elements in arr in the # same order they were inserted into arr # second expression returns a list of # zeros present in arr return [nonZero for nonZero in arr if nonZero!=0] + \\ [Zero for Zero in arr if Zero==0] # Driver functionif __name__ == \"__main__\": arr = [1, 2, 0, 4, 3, 0, 5, 0] print (moveZeros(arr))",
"e": 1211,
"s": 733,
"text": null
},
{
"code": null,
"e": 1219,
"s": 1211,
"text": "Output:"
},
{
"code": null,
"e": 1245,
"s": 1219,
"text": "[1, 2, 4, 3, 5, 0, 0, 0]\n"
},
{
"code": null,
"e": 1556,
"s": 1245,
"text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1681,
"s": 1556,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1702,
"s": 1681,
"text": "Python list-programs"
},
{
"code": null,
"e": 1714,
"s": 1702,
"text": "python-list"
},
{
"code": null,
"e": 1721,
"s": 1714,
"text": "Arrays"
},
{
"code": null,
"e": 1728,
"s": 1721,
"text": "Python"
},
{
"code": null,
"e": 1740,
"s": 1728,
"text": "python-list"
},
{
"code": null,
"e": 1747,
"s": 1740,
"text": "Arrays"
},
{
"code": null,
"e": 1845,
"s": 1747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1913,
"s": 1845,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 1957,
"s": 1913,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 1989,
"s": 1957,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2037,
"s": 1989,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 2051,
"s": 2037,
"text": "Linear Search"
},
{
"code": null,
"e": 2079,
"s": 2051,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2129,
"s": 2079,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2151,
"s": 2129,
"text": "Python map() function"
}
] |
ReactJS – useRef hook | In this article, we are going to see how to create a reference to any DOM element in a functional component.
This hook is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM.
If we pass a ref object to any DOM element, then the .current property to the corresponding DOM node elements will be added whenever the node changes.
const refContainer = useRef(initialValue);
In this example, we will build a React application that passes the ref object to two input fields.
When clicked on a button, it will automatically fetch the data of these input fields.
App.jsx
import React, { useRef } from 'react';
function App() {
const email = useRef(null);
const username = useRef(null);
const fetchEmail = () => {
email.current.value = 'rahul@gmail.com';
email.current.focus();
};
const fetchUsername = () => {
username.current.value = 'RahulBansal123';
username.current.focus();
};
return (
<>
<div>
<h1>Tutorialspoint</h1>
</div>
<div>
<input placeholder="Username" ref={username} />
<input placeholder="Email" ref={email} />
</div>
<button onClick={fetchUsername}>Username</button>
<button onClick={fetchEmail}>Email</button>
</>
);
}
export default App;
In the above example, when the Username or Email button is clicked, the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from NULL to some text.
This will produce the following result. | [
{
"code": null,
"e": 1296,
"s": 1187,
"text": "In this article, we are going to see how to create a reference to any DOM element in a functional component."
},
{
"code": null,
"e": 1462,
"s": 1296,
"text": "This hook is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM."
},
{
"code": null,
"e": 1613,
"s": 1462,
"text": "If we pass a ref object to any DOM element, then the .current property to the corresponding DOM node elements will be added whenever the node changes."
},
{
"code": null,
"e": 1656,
"s": 1613,
"text": "const refContainer = useRef(initialValue);"
},
{
"code": null,
"e": 1755,
"s": 1656,
"text": "In this example, we will build a React application that passes the ref object to two input fields."
},
{
"code": null,
"e": 1841,
"s": 1755,
"text": "When clicked on a button, it will automatically fetch the data of these input fields."
},
{
"code": null,
"e": 1849,
"s": 1841,
"text": "App.jsx"
},
{
"code": null,
"e": 2588,
"s": 1849,
"text": "import React, { useRef } from 'react';\n\nfunction App() {\n\n const email = useRef(null);\n const username = useRef(null);\n\n const fetchEmail = () => {\n email.current.value = 'rahul@gmail.com';\n email.current.focus();\n };\n const fetchUsername = () => {\n username.current.value = 'RahulBansal123';\n username.current.focus();\n };\n return (\n <>\n <div>\n <h1>Tutorialspoint</h1>\n </div>\n <div>\n <input placeholder=\"Username\" ref={username} />\n <input placeholder=\"Email\" ref={email} />\n </div>\n <button onClick={fetchUsername}>Username</button>\n <button onClick={fetchEmail}>Email</button>\n </>\n );\n}\nexport default App;"
},
{
"code": null,
"e": 2812,
"s": 2588,
"text": "In the above example, when the Username or Email button is clicked, the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from NULL to some text."
},
{
"code": null,
"e": 2852,
"s": 2812,
"text": "This will produce the following result."
}
] |
PostgreSQL – Joins | 28 Aug, 2020
A PostgreSQL Join statement is used to combine data or rows from one(self-join) or more tables based on a common field between them. These common fields are generally the Primary key of the first table and Foreign key of other tables.There are 4 basic types of joins supported by PostgreSQL, namely:
Inner JoinLeft JoinRight JoinFull Outer Join
Inner Join
Left Join
Right Join
Full Outer Join
Some special PostgreSQL joins are below:
Natural Join
Cross Join
Self Join
Let’s look into the 4 of the basic Joins in PostgreSQL.For the sake of this article, we will be setting up a sample database with the below commands in our psql shell:
Create a database zoo.CREATE DATABASE zoo;
CREATE DATABASE zoo;
Create a table zoo_1.CREATE TABLE zoo_1 (
id INT PRIMARY KEY,
animal VARCHAR (100) NOT NULL
);
CREATE TABLE zoo_1 (
id INT PRIMARY KEY,
animal VARCHAR (100) NOT NULL
);
Create a table zoo_2.CREATE TABLE zoo_2 (
id INT PRIMARY KEY,
animal VARCHAR (100) NOT NULL
);
CREATE TABLE zoo_2 (
id INT PRIMARY KEY,
animal VARCHAR (100) NOT NULL
);
Insert data into zoo_1 table.INSERT INTO zoo_1(id, animal)
VALUES
(1, 'Lion'),
(2, 'Tiger'),
(3, 'Wolf'),
(4, 'Fox');
INSERT INTO zoo_1(id, animal)
VALUES
(1, 'Lion'),
(2, 'Tiger'),
(3, 'Wolf'),
(4, 'Fox');
Insert data into zoo_2 table.INSERT INTO zoo_2(id, animal)
VALUES
(1, 'Tiger'),
(2, 'Lion'),
(3, 'Rhino'),
(4, 'Panther');
INSERT INTO zoo_2(id, animal)
VALUES
(1, 'Tiger'),
(2, 'Lion'),
(3, 'Rhino'),
(4, 'Panther');
Now, we have two tables zoo_1 and zoo_2 with two common animals and four different animals. Let’s also assume zoo_1 is the left table.
The below statement joins the left table with the right table using the values in the “animal” column:
SELECT
zoo_1.id id_a,
zoo_1.animal animal_a,
zoo_2.id id_b,
zoo_2.animal animal_b
FROM
zoo_1
INNER JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;
Output:
As seen in the above output, the inner join returns a result set that contains row in the left table that matches the row in the right table.
The Venn diagram for INNER JOIN is as below:
The below statement joins the left table with the right table using left join (or left outer join):
SELECT
zoo_1.id,
zoo_1.animal,
zoo_2.id,
zoo_2.animal
FROM
zoo_1
LEFT JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;
Output:
As seen in the output above the left join returns a complete set of rows from the left table with the matching rows if available from the right table. If there is no match, the right side will have null values.
The Venn diagram for a LEFT JOIN is as below:
The RIGHT JOIN or RIGHT OUTER JOIN works exactly opposite to the LEFT JOIN. It returns a complete set of rows from the right table with the matching rows if available from the left table. If there is no match, the left side will have null values.
The below statement joins the right table with the left table using the right join (or right outer join):
SELECT
zoo_1.id,
zoo_1.animal,
zoo_2.id,
zoo_2.animal
FROM
zoo_1
RIGHT JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;
Output:
The Venn diagram for a RIGHT OUTER JOIN is below:
The full outer join or full join returns a result set that contains all rows from both the left and right tables, with the matching rows from both sides where available. If there is no match, the missing side contains null values.
The below statement illustrates the full outer join:
SELECT
zoo_1.id,
zoo_1.animal,
zoo_2.id,
zoo_2.animal
FROM
zoo_1
FULL JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;
Output:
The Venn diagram for a FULL OUTER JOIN is below:
postgreSQL-joins
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 352,
"s": 52,
"text": "A PostgreSQL Join statement is used to combine data or rows from one(self-join) or more tables based on a common field between them. These common fields are generally the Primary key of the first table and Foreign key of other tables.There are 4 basic types of joins supported by PostgreSQL, namely:"
},
{
"code": null,
"e": 397,
"s": 352,
"text": "Inner JoinLeft JoinRight JoinFull Outer Join"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Inner Join"
},
{
"code": null,
"e": 418,
"s": 408,
"text": "Left Join"
},
{
"code": null,
"e": 429,
"s": 418,
"text": "Right Join"
},
{
"code": null,
"e": 445,
"s": 429,
"text": "Full Outer Join"
},
{
"code": null,
"e": 486,
"s": 445,
"text": "Some special PostgreSQL joins are below:"
},
{
"code": null,
"e": 499,
"s": 486,
"text": "Natural Join"
},
{
"code": null,
"e": 510,
"s": 499,
"text": "Cross Join"
},
{
"code": null,
"e": 520,
"s": 510,
"text": "Self Join"
},
{
"code": null,
"e": 688,
"s": 520,
"text": "Let’s look into the 4 of the basic Joins in PostgreSQL.For the sake of this article, we will be setting up a sample database with the below commands in our psql shell:"
},
{
"code": null,
"e": 731,
"s": 688,
"text": "Create a database zoo.CREATE DATABASE zoo;"
},
{
"code": null,
"e": 752,
"s": 731,
"text": "CREATE DATABASE zoo;"
},
{
"code": null,
"e": 855,
"s": 752,
"text": "Create a table zoo_1.CREATE TABLE zoo_1 (\n id INT PRIMARY KEY,\n animal VARCHAR (100) NOT NULL\n);"
},
{
"code": null,
"e": 937,
"s": 855,
"text": "CREATE TABLE zoo_1 (\n id INT PRIMARY KEY,\n animal VARCHAR (100) NOT NULL\n);"
},
{
"code": null,
"e": 1040,
"s": 937,
"text": "Create a table zoo_2.CREATE TABLE zoo_2 (\n id INT PRIMARY KEY,\n animal VARCHAR (100) NOT NULL\n);"
},
{
"code": null,
"e": 1122,
"s": 1040,
"text": "CREATE TABLE zoo_2 (\n id INT PRIMARY KEY,\n animal VARCHAR (100) NOT NULL\n);"
},
{
"code": null,
"e": 1256,
"s": 1122,
"text": "Insert data into zoo_1 table.INSERT INTO zoo_1(id, animal)\nVALUES\n (1, 'Lion'),\n (2, 'Tiger'),\n (3, 'Wolf'),\n (4, 'Fox');"
},
{
"code": null,
"e": 1361,
"s": 1256,
"text": "INSERT INTO zoo_1(id, animal)\nVALUES\n (1, 'Lion'),\n (2, 'Tiger'),\n (3, 'Wolf'),\n (4, 'Fox');"
},
{
"code": null,
"e": 1500,
"s": 1361,
"text": "Insert data into zoo_2 table.INSERT INTO zoo_2(id, animal)\nVALUES\n (1, 'Tiger'),\n (2, 'Lion'),\n (3, 'Rhino'),\n (4, 'Panther');"
},
{
"code": null,
"e": 1610,
"s": 1500,
"text": "INSERT INTO zoo_2(id, animal)\nVALUES\n (1, 'Tiger'),\n (2, 'Lion'),\n (3, 'Rhino'),\n (4, 'Panther');"
},
{
"code": null,
"e": 1745,
"s": 1610,
"text": "Now, we have two tables zoo_1 and zoo_2 with two common animals and four different animals. Let’s also assume zoo_1 is the left table."
},
{
"code": null,
"e": 1848,
"s": 1745,
"text": "The below statement joins the left table with the right table using the values in the “animal” column:"
},
{
"code": null,
"e": 2011,
"s": 1848,
"text": "SELECT\n zoo_1.id id_a,\n zoo_1.animal animal_a,\n zoo_2.id id_b,\n zoo_2.animal animal_b\nFROM\n zoo_1 \nINNER JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;"
},
{
"code": null,
"e": 2019,
"s": 2011,
"text": "Output:"
},
{
"code": null,
"e": 2161,
"s": 2019,
"text": "As seen in the above output, the inner join returns a result set that contains row in the left table that matches the row in the right table."
},
{
"code": null,
"e": 2206,
"s": 2161,
"text": "The Venn diagram for INNER JOIN is as below:"
},
{
"code": null,
"e": 2306,
"s": 2206,
"text": "The below statement joins the left table with the right table using left join (or left outer join):"
},
{
"code": null,
"e": 2439,
"s": 2306,
"text": "SELECT\n zoo_1.id,\n zoo_1.animal,\n zoo_2.id,\n zoo_2.animal\nFROM\n zoo_1\nLEFT JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;"
},
{
"code": null,
"e": 2447,
"s": 2439,
"text": "Output:"
},
{
"code": null,
"e": 2658,
"s": 2447,
"text": "As seen in the output above the left join returns a complete set of rows from the left table with the matching rows if available from the right table. If there is no match, the right side will have null values."
},
{
"code": null,
"e": 2704,
"s": 2658,
"text": "The Venn diagram for a LEFT JOIN is as below:"
},
{
"code": null,
"e": 2951,
"s": 2704,
"text": "The RIGHT JOIN or RIGHT OUTER JOIN works exactly opposite to the LEFT JOIN. It returns a complete set of rows from the right table with the matching rows if available from the left table. If there is no match, the left side will have null values."
},
{
"code": null,
"e": 3057,
"s": 2951,
"text": "The below statement joins the right table with the left table using the right join (or right outer join):"
},
{
"code": null,
"e": 3191,
"s": 3057,
"text": "SELECT\n zoo_1.id,\n zoo_1.animal,\n zoo_2.id,\n zoo_2.animal\nFROM\n zoo_1\nRIGHT JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;"
},
{
"code": null,
"e": 3199,
"s": 3191,
"text": "Output:"
},
{
"code": null,
"e": 3249,
"s": 3199,
"text": "The Venn diagram for a RIGHT OUTER JOIN is below:"
},
{
"code": null,
"e": 3480,
"s": 3249,
"text": "The full outer join or full join returns a result set that contains all rows from both the left and right tables, with the matching rows from both sides where available. If there is no match, the missing side contains null values."
},
{
"code": null,
"e": 3533,
"s": 3480,
"text": "The below statement illustrates the full outer join:"
},
{
"code": null,
"e": 3666,
"s": 3533,
"text": "SELECT\n zoo_1.id,\n zoo_1.animal,\n zoo_2.id,\n zoo_2.animal\nFROM\n zoo_1\nFULL JOIN zoo_2 ON zoo_1.animal = zoo_2.animal;"
},
{
"code": null,
"e": 3674,
"s": 3666,
"text": "Output:"
},
{
"code": null,
"e": 3723,
"s": 3674,
"text": "The Venn diagram for a FULL OUTER JOIN is below:"
},
{
"code": null,
"e": 3740,
"s": 3723,
"text": "postgreSQL-joins"
},
{
"code": null,
"e": 3751,
"s": 3740,
"text": "PostgreSQL"
},
{
"code": null,
"e": 3849,
"s": 3751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3876,
"s": 3849,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 3908,
"s": 3876,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 3931,
"s": 3908,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 3969,
"s": 3931,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 4009,
"s": 3969,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 4043,
"s": 4009,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 4067,
"s": 4043,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 4122,
"s": 4067,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 4146,
"s": 4122,
"text": "PostgreSQL - Copy Table"
}
] |
Program to implement FLAMES game | 09 Jun, 2021
FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether or not an individual is right for you, but it can be fun to play this with your friends.There are two steps in this game:
Take the two names.
Remove the common characters with their respective common occurrences.
Get the count of the characters that are left .
Take FLAMES letters as [“F”, “L”, “A”, “M”, “E”, “S”]
Start removing letter using the count we got.
The letter which last the process is the result.
Example :
Input: Player1 = AJAY, Player2 = PRIYA
Output: Friends
Explanation: In above given two names A and Y are common letters which are occurring one time(common count) in both names so we are removing these letters from both names. Now count the total letters that are left here it is 5. Now start removing letters one by one from FLAMES using the count we got and the letter which lasts the process is the result.Counting is done in an anti-clockwise circular fashion.
FLAMES counting starts from F, E is at 5th count so we remove E and start counting again but this time start from S. FLAMS M is at 5th count so we remove M and counting starts from S. FLAS S is at 5th count so we remove S and counting start from F. FLA L is at 5th count so we remove L and counting starts from A. FA A is at 5th count so we remove A. now we have only one letter is remaining so this is the final answer. F So, the relationship is F i.e. Friends .
Approach: Three counters are required, two for the names initialized at zero, and one for flames initialized at 5. Three strings are used, two for names and one, where FLAMES is already stored. Here the program first calculated the number of letters in the first name and then calculated the number of letters in second name Then after storing them using strlen into integer variables, one for loop is run for each name to count the common letters. Then by using nested if-else the letters are cancelled from each name, which is represented by a string. The for loop is again repeated to continue this process. Accordingly, the counter rotates and each letter in FLAMES is pointed at. As letters get canceled the loop is run again. Then for each letter, an If else statement is used, Print the result corresponding to the last letter.Below is the implementation :
C++
C
Python3
Javascript
// C++ program to implement FLAMES game#include <bits/stdc++.h>using namespace std; // Function to find out the flames resultvoid flame(char* a, char* b){ int i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; char q[25], w[25], c; char f[] = "flames"; strcpy(q, a); strcpy(w, b); n = strlen(a); m = strlen(b); tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; f[k] != '\0'; k++) { f[k] = f[k + 1]; } f[k + 1] = '\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') cout << q <<" is ENEMY to " << w; else if (f[0] == 'f') cout << q <<" is FRIEND to "<<w; else if (f[0] == 'm') cout << q <<" is going to MARRY "<<w; else if (f[0] == 'l') cout << q <<" is in LOVE with "<<w; else if (f[0] == 'a') cout << q <<" has more AFFECTION on "<<w; else cout << q << " and "<< w <<" are SISTERS/BROTHERS ";} // Driver codeint main(){ char a[] = "AJAY"; char b[] = "PRIYA"; flame(a, b);} // This code is contributed by SHUBHMASINGH10
// C program to implement FLAMES game #include <stdio.h>#include <string.h> // Function to find out the flames resultvoid flame(char* a, char* b){ int i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; char q[25], w[25], c; char f[] = "flames"; strcpy(q, a); strcpy(w, b); n = strlen(a); m = strlen(b); tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; f[k] != '\0'; k++) { f[k] = f[k + 1]; } f[k + 1] = '\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') printf("%s is ENEMY to %s ", q, w); else if (f[0] == 'f') printf("%s is FRIEND to %s ", q, w); else if (f[0] == 'm') printf("%s is going to MARRY %s", q, w); else if (f[0] == 'l') printf("%s is in LOVE with %s ", q, w); else if (f[0] == 'a') printf("%s has more AFFECTION on %s ", q, w); else printf("%s and %s are SISTERS/BROTHERS ", q, w);} // Driver codeint main(){ char a[] = "AJAY"; char b[] = "PRIYA"; flame(a, b);}
# Python3 program to implement FLAMES game # Function to find out the flames resultdef flame(a, b): l, sc = 1, 0 rc, fc = 0, 5 f = "flames" f = [i for i in f] q = "".join(a) w = "".join(b) # print(q, w) n = len(a) m = len(b) tc = n + m for i in range(n): c = a[i] for j in range(m): if (c == b[j]): a[i] = -1 b[j] = -1 sc = sc + 2 break rc = tc - sc i = 0 while (i): if (l == (rc)): for k in range(i,len(f)): f[k] = f[k + 1] f[k + 1] = '\0' fc = fc - 1 i = i - 1 l = 0 if (i == fc): i = -1 if (fc == 0): break l += 1 i += 1 # Print the results if (f[0] == 'e'): print(q, "is ENEMY to", w) elif (f[0] == 'f'): print(q, "is FRIEND to", w) elif (f[0] == 'm'): print(q, "is going to MARRY", w) elif (f[0] == 'l'): print(q, "is in LOVE with", w) elif (f[0] == 'a'): print(q, "has more AFFECTION on", w) else: print(q, "and", w, "are SISTERS/BROTHERS ") # Driver codea = "AJAY"b = "PRIYA"a = [i for i in a]b = [j for j in b] # print(a,b)flame(a, b) # This code is contributed by Mohit Kumar
<script>// Javascript program to implement FLAMES game // Function to find out the flames resultfunction flame(a,b){ let i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; let c; let f = "flames"; let q = a.join("") let w = b.join("") n = a.length; m = b.length; tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; k<f.length; k++) { f[k] = f[k + 1]; } f[k + 1] = '\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') document.write(q+" is ENEMY to "+w); else if (f[0] == 'f') document.write(q+" is FRIEND to "+w); else if (f[0] == 'm') document.write(q+" is going to MARRY "+w); else if (f[0] == 'l') document.write(q+" is in LOVE with "+w); else if (f[0] == 'a') document.write(q+" has more AFFECTION on "+w); else document.write(q+" and "<+w+" are SISTERS/BROTHERS "); } // Driver codelet a="AJAY".split("");let b= "PRIYA".split("");flame(a, b); // This code is contributed by unknown2108.</script>
AJAY is FRIEND to PRIYA
mohit kumar 29
SHUBHAMSINGH10
unknown2108
Picked
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Remove first and last character of a string in Java
Check if an URL is valid or not using Regular Expression
Find the smallest window in a string containing all characters of another string | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 332,
"s": 54,
"text": "FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether or not an individual is right for you, but it can be fun to play this with your friends.There are two steps in this game: "
},
{
"code": null,
"e": 352,
"s": 332,
"text": "Take the two names."
},
{
"code": null,
"e": 423,
"s": 352,
"text": "Remove the common characters with their respective common occurrences."
},
{
"code": null,
"e": 471,
"s": 423,
"text": "Get the count of the characters that are left ."
},
{
"code": null,
"e": 525,
"s": 471,
"text": "Take FLAMES letters as [“F”, “L”, “A”, “M”, “E”, “S”]"
},
{
"code": null,
"e": 571,
"s": 525,
"text": "Start removing letter using the count we got."
},
{
"code": null,
"e": 620,
"s": 571,
"text": "The letter which last the process is the result."
},
{
"code": null,
"e": 632,
"s": 620,
"text": "Example : "
},
{
"code": null,
"e": 687,
"s": 632,
"text": "Input: Player1 = AJAY, Player2 = PRIYA\nOutput: Friends"
},
{
"code": null,
"e": 1098,
"s": 687,
"text": "Explanation: In above given two names A and Y are common letters which are occurring one time(common count) in both names so we are removing these letters from both names. Now count the total letters that are left here it is 5. Now start removing letters one by one from FLAMES using the count we got and the letter which lasts the process is the result.Counting is done in an anti-clockwise circular fashion. "
},
{
"code": null,
"e": 1562,
"s": 1098,
"text": "FLAMES counting starts from F, E is at 5th count so we remove E and start counting again but this time start from S. FLAMS M is at 5th count so we remove M and counting starts from S. FLAS S is at 5th count so we remove S and counting start from F. FLA L is at 5th count so we remove L and counting starts from A. FA A is at 5th count so we remove A. now we have only one letter is remaining so this is the final answer. F So, the relationship is F i.e. Friends ."
},
{
"code": null,
"e": 2430,
"s": 1564,
"text": "Approach: Three counters are required, two for the names initialized at zero, and one for flames initialized at 5. Three strings are used, two for names and one, where FLAMES is already stored. Here the program first calculated the number of letters in the first name and then calculated the number of letters in second name Then after storing them using strlen into integer variables, one for loop is run for each name to count the common letters. Then by using nested if-else the letters are cancelled from each name, which is represented by a string. The for loop is again repeated to continue this process. Accordingly, the counter rotates and each letter in FLAMES is pointed at. As letters get canceled the loop is run again. Then for each letter, an If else statement is used, Print the result corresponding to the last letter.Below is the implementation : "
},
{
"code": null,
"e": 2434,
"s": 2430,
"text": "C++"
},
{
"code": null,
"e": 2436,
"s": 2434,
"text": "C"
},
{
"code": null,
"e": 2444,
"s": 2436,
"text": "Python3"
},
{
"code": null,
"e": 2455,
"s": 2444,
"text": "Javascript"
},
{
"code": "// C++ program to implement FLAMES game#include <bits/stdc++.h>using namespace std; // Function to find out the flames resultvoid flame(char* a, char* b){ int i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; char q[25], w[25], c; char f[] = \"flames\"; strcpy(q, a); strcpy(w, b); n = strlen(a); m = strlen(b); tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; f[k] != '\\0'; k++) { f[k] = f[k + 1]; } f[k + 1] = '\\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') cout << q <<\" is ENEMY to \" << w; else if (f[0] == 'f') cout << q <<\" is FRIEND to \"<<w; else if (f[0] == 'm') cout << q <<\" is going to MARRY \"<<w; else if (f[0] == 'l') cout << q <<\" is in LOVE with \"<<w; else if (f[0] == 'a') cout << q <<\" has more AFFECTION on \"<<w; else cout << q << \" and \"<< w <<\" are SISTERS/BROTHERS \";} // Driver codeint main(){ char a[] = \"AJAY\"; char b[] = \"PRIYA\"; flame(a, b);} // This code is contributed by SHUBHMASINGH10",
"e": 4034,
"s": 2455,
"text": null
},
{
"code": "// C program to implement FLAMES game #include <stdio.h>#include <string.h> // Function to find out the flames resultvoid flame(char* a, char* b){ int i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; char q[25], w[25], c; char f[] = \"flames\"; strcpy(q, a); strcpy(w, b); n = strlen(a); m = strlen(b); tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; f[k] != '\\0'; k++) { f[k] = f[k + 1]; } f[k + 1] = '\\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') printf(\"%s is ENEMY to %s \", q, w); else if (f[0] == 'f') printf(\"%s is FRIEND to %s \", q, w); else if (f[0] == 'm') printf(\"%s is going to MARRY %s\", q, w); else if (f[0] == 'l') printf(\"%s is in LOVE with %s \", q, w); else if (f[0] == 'a') printf(\"%s has more AFFECTION on %s \", q, w); else printf(\"%s and %s are SISTERS/BROTHERS \", q, w);} // Driver codeint main(){ char a[] = \"AJAY\"; char b[] = \"PRIYA\"; flame(a, b);}",
"e": 5517,
"s": 4034,
"text": null
},
{
"code": "# Python3 program to implement FLAMES game # Function to find out the flames resultdef flame(a, b): l, sc = 1, 0 rc, fc = 0, 5 f = \"flames\" f = [i for i in f] q = \"\".join(a) w = \"\".join(b) # print(q, w) n = len(a) m = len(b) tc = n + m for i in range(n): c = a[i] for j in range(m): if (c == b[j]): a[i] = -1 b[j] = -1 sc = sc + 2 break rc = tc - sc i = 0 while (i): if (l == (rc)): for k in range(i,len(f)): f[k] = f[k + 1] f[k + 1] = '\\0' fc = fc - 1 i = i - 1 l = 0 if (i == fc): i = -1 if (fc == 0): break l += 1 i += 1 # Print the results if (f[0] == 'e'): print(q, \"is ENEMY to\", w) elif (f[0] == 'f'): print(q, \"is FRIEND to\", w) elif (f[0] == 'm'): print(q, \"is going to MARRY\", w) elif (f[0] == 'l'): print(q, \"is in LOVE with\", w) elif (f[0] == 'a'): print(q, \"has more AFFECTION on\", w) else: print(q, \"and\", w, \"are SISTERS/BROTHERS \") # Driver codea = \"AJAY\"b = \"PRIYA\"a = [i for i in a]b = [j for j in b] # print(a,b)flame(a, b) # This code is contributed by Mohit Kumar",
"e": 6827,
"s": 5517,
"text": null
},
{
"code": "<script>// Javascript program to implement FLAMES game // Function to find out the flames resultfunction flame(a,b){ let i, j, k, l = 1, n, m, sc = 0, tc, rc = 0, fc = 5; let c; let f = \"flames\"; let q = a.join(\"\") let w = b.join(\"\") n = a.length; m = b.length; tc = n + m; for (i = 0; i < n; i++) { c = a[i]; for (j = 0; j < m; j++) { if (c == b[j]) { a[i] = -1; b[j] = -1; sc = sc + 2; break; } } } rc = tc - sc; for (i = 0;; i++) { if (l == (rc)) { for (k = i; k<f.length; k++) { f[k] = f[k + 1]; } f[k + 1] = '\\0'; fc = fc - 1; i = i - 1; l = 0; } if (i == fc) { i = -1; } if (fc == 0) { break; } l++; } // Print the results if (f[0] == 'e') document.write(q+\" is ENEMY to \"+w); else if (f[0] == 'f') document.write(q+\" is FRIEND to \"+w); else if (f[0] == 'm') document.write(q+\" is going to MARRY \"+w); else if (f[0] == 'l') document.write(q+\" is in LOVE with \"+w); else if (f[0] == 'a') document.write(q+\" has more AFFECTION on \"+w); else document.write(q+\" and \"<+w+\" are SISTERS/BROTHERS \"); } // Driver codelet a=\"AJAY\".split(\"\");let b= \"PRIYA\".split(\"\");flame(a, b); // This code is contributed by unknown2108.</script>",
"e": 8438,
"s": 6827,
"text": null
},
{
"code": null,
"e": 8462,
"s": 8438,
"text": "AJAY is FRIEND to PRIYA"
},
{
"code": null,
"e": 8479,
"s": 8464,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8494,
"s": 8479,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8506,
"s": 8494,
"text": "unknown2108"
},
{
"code": null,
"e": 8513,
"s": 8506,
"text": "Picked"
},
{
"code": null,
"e": 8521,
"s": 8513,
"text": "Strings"
},
{
"code": null,
"e": 8529,
"s": 8521,
"text": "Strings"
},
{
"code": null,
"e": 8627,
"s": 8529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8672,
"s": 8627,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 8736,
"s": 8672,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8781,
"s": 8736,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 8816,
"s": 8781,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 8881,
"s": 8816,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 8910,
"s": 8881,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 8971,
"s": 8910,
"text": "Find if a string is interleaved of two other strings | DP-33"
},
{
"code": null,
"e": 9023,
"s": 8971,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 9080,
"s": 9023,
"text": "Check if an URL is valid or not using Regular Expression"
}
] |
Lodash _.isNil() Method | 05 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.
Syntax:
_.isNil(value)
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is nullish, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNil() // method let gfg = _.isNil(null); // Printing the output console.log(gfg);
Output:
true
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNil() // method let gfg = _.isNil(void 0); // Printing the output console.log(gfg);
Output:
true
Example 3:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isNil() // method let gfg = _.isNil(NaN); // Printing the output console.log(gfg);
Output:
false
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 311,
"s": 168,
"text": "The _.isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false."
},
{
"code": null,
"e": 319,
"s": 311,
"text": "Syntax:"
},
{
"code": null,
"e": 334,
"s": 319,
"text": "_.isNil(value)"
},
{
"code": null,
"e": 425,
"s": 334,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 473,
"s": 425,
"text": "value: This parameter holds the value to check."
},
{
"code": null,
"e": 549,
"s": 473,
"text": "Return Value: This method returns true if the value is nullish, else false."
},
{
"code": null,
"e": 646,
"s": 549,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file."
},
{
"code": null,
"e": 657,
"s": 646,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNil() // method let gfg = _.isNil(null); // Printing the output console.log(gfg);",
"e": 831,
"s": 657,
"text": null
},
{
"code": null,
"e": 840,
"s": 831,
"text": " Output:"
},
{
"code": null,
"e": 845,
"s": 840,
"text": "true"
},
{
"code": null,
"e": 860,
"s": 847,
"text": "Example 2: "
},
{
"code": null,
"e": 871,
"s": 860,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNil() // method let gfg = _.isNil(void 0); // Printing the output console.log(gfg);",
"e": 1047,
"s": 871,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1047,
"text": " Output:"
},
{
"code": null,
"e": 1061,
"s": 1056,
"text": "true"
},
{
"code": null,
"e": 1074,
"s": 1061,
"text": "Example 3: "
},
{
"code": null,
"e": 1085,
"s": 1074,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNil() // method let gfg = _.isNil(NaN); // Printing the output console.log(gfg);",
"e": 1258,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1258,
"text": " Output:"
},
{
"code": null,
"e": 1273,
"s": 1267,
"text": "false"
},
{
"code": null,
"e": 1293,
"s": 1275,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1304,
"s": 1293,
"text": "JavaScript"
},
{
"code": null,
"e": 1321,
"s": 1304,
"text": "Web Technologies"
},
{
"code": null,
"e": 1419,
"s": 1321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1480,
"s": 1419,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1552,
"s": 1480,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1592,
"s": 1552,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1633,
"s": 1592,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1675,
"s": 1633,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1708,
"s": 1675,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1770,
"s": 1708,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1831,
"s": 1770,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1881,
"s": 1831,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to play audio repeatedly using HTML5 ? | 14 Jul, 2020
This article will show you how an audio file can be played repeatedly on a web page. This is done by using the loop attribute of the <audio> tag. It is used to restart the audio again and again after loading the web page. This can be used in situations where the audio has to be looped until it is specifically stopped, like in the case of background music on a web page.
Syntax:
<audio loop>
Example:
html
<!DOCTYPE html><html> <head> <title> How to play an audio repeatedly using HTML5? </title></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <b> How to play an audio repeatedly using HTML5? </b> <p><b>Non Looping Audio</b></p> <audio controls> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio> <p><b>Looping Audio</b></p> <!-- Using the loop attribute --> <audio controls loop> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio></body> </html>
Output:
Supported Browsers:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Opera 10.5
Safari 4.0
HTML-Misc
HTML5
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "This article will show you how an audio file can be played repeatedly on a web page. This is done by using the loop attribute of the <audio> tag. It is used to restart the audio again and again after loading the web page. This can be used in situations where the audio has to be looped until it is specifically stopped, like in the case of background music on a web page."
},
{
"code": null,
"e": 408,
"s": 400,
"text": "Syntax:"
},
{
"code": null,
"e": 421,
"s": 408,
"text": "<audio loop>"
},
{
"code": null,
"e": 430,
"s": 421,
"text": "Example:"
},
{
"code": null,
"e": 435,
"s": 430,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to play an audio repeatedly using HTML5? </title></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <b> How to play an audio repeatedly using HTML5? </b> <p><b>Non Looping Audio</b></p> <audio controls> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\" type=\"audio/mp3\"> </audio> <p><b>Looping Audio</b></p> <!-- Using the loop attribute --> <audio controls loop> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\" type=\"audio/mp3\"> </audio></body> </html>",
"e": 1138,
"s": 435,
"text": null
},
{
"code": null,
"e": 1147,
"s": 1138,
"text": "Output: "
},
{
"code": null,
"e": 1167,
"s": 1147,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1185,
"s": 1167,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 1207,
"s": 1185,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 1219,
"s": 1207,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 1230,
"s": 1219,
"text": "Opera 10.5"
},
{
"code": null,
"e": 1242,
"s": 1230,
"text": "Safari 4.0 "
},
{
"code": null,
"e": 1252,
"s": 1242,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1258,
"s": 1252,
"text": "HTML5"
},
{
"code": null,
"e": 1263,
"s": 1258,
"text": "HTML"
},
{
"code": null,
"e": 1280,
"s": 1263,
"text": "Web Technologies"
},
{
"code": null,
"e": 1307,
"s": 1280,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1312,
"s": 1307,
"text": "HTML"
},
{
"code": null,
"e": 1410,
"s": 1312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1434,
"s": 1410,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1473,
"s": 1434,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1512,
"s": 1473,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1549,
"s": 1512,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1569,
"s": 1549,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1602,
"s": 1569,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1663,
"s": 1602,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1706,
"s": 1663,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1778,
"s": 1706,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Writing CSV files in Python | 29 Dec, 2019
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
Python provides an in-built module called csv to work with CSV files. There are various classes provided by this module for writing to CSV:
Using csv.writer class
Using csv.DictWriter class
csv.writer class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user’s data into a delimited string. A csvfile object should be opened with newline='' otherwise newline characters inside the quoted fields will not be interpreted correctly.
Syntax: csv.writer(csvfile, dialect=’excel’, **fmtparams)
Parameters:csvfile: A file object with write() method.dialect (optional): Name of the dialect to be used.fmtparams (optional): Formatting parameters that will overwrite those specified in the dialect.
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
writerow(): This method writes a single row at a time. Field row can be written using this method.Syntax:writerow(fields)
Syntax:
writerow(fields)
writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.Syntax:Writing CSV files in Python
writerows(rows)
Syntax:
Writing CSV files in Python
writerows(rows)
Example:
# Python program to demonstrate# writing to CSV import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv file filename = "university_records.csv" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows)
Output:
This class returns a writer object which maps dictionaries onto output rows.
Syntax: csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)
Parameters:csvfile: A file object with write() method.fieldnames: A sequence of keys that identify the order in which values in the dictionary should be passed.restval (optional): Specifies the value to be written if the dictionary is missing a key in fieldnames.extrasaction (optional): If a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to raise a ValueError will be raised.dialect (optional): Name of the dialect to be used.
csv.DictWriter provides two methods for writing to CSV. They are:
writeheader(): writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.Syntax:writeheader()
Syntax:
writeheader()
writerows(): writerows method simply writes all the rows but in each row, it writes only the values(not keys).Syntax:writerows(mydict)
Syntax:
writerows(mydict)
Example:
# importing the csv module import csv # my data rows as dictionary objects mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] # field names fields = ['name', 'branch', 'year', 'cgpa'] # name of csv file filename = "university_records.csv" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile, fieldnames = fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(mydict)
Output:
Picked
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 426,
"s": 52,
"text": "CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format."
},
{
"code": null,
"e": 566,
"s": 426,
"text": "Python provides an in-built module called csv to work with CSV files. There are various classes provided by this module for writing to CSV:"
},
{
"code": null,
"e": 589,
"s": 566,
"text": "Using csv.writer class"
},
{
"code": null,
"e": 616,
"s": 589,
"text": "Using csv.DictWriter class"
},
{
"code": null,
"e": 924,
"s": 616,
"text": "csv.writer class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user’s data into a delimited string. A csvfile object should be opened with newline='' otherwise newline characters inside the quoted fields will not be interpreted correctly."
},
{
"code": null,
"e": 982,
"s": 924,
"text": "Syntax: csv.writer(csvfile, dialect=’excel’, **fmtparams)"
},
{
"code": null,
"e": 1183,
"s": 982,
"text": "Parameters:csvfile: A file object with write() method.dialect (optional): Name of the dialect to be used.fmtparams (optional): Formatting parameters that will overwrite those specified in the dialect."
},
{
"code": null,
"e": 1278,
"s": 1183,
"text": "csv.writer class provides two methods for writing to CSV. They are writerow() and writerows()."
},
{
"code": null,
"e": 1401,
"s": 1278,
"text": "writerow(): This method writes a single row at a time. Field row can be written using this method.Syntax:writerow(fields)\n"
},
{
"code": null,
"e": 1409,
"s": 1401,
"text": "Syntax:"
},
{
"code": null,
"e": 1427,
"s": 1409,
"text": "writerow(fields)\n"
},
{
"code": null,
"e": 1582,
"s": 1427,
"text": "writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.Syntax:Writing CSV files in Python\nwriterows(rows)\n"
},
{
"code": null,
"e": 1590,
"s": 1582,
"text": "Syntax:"
},
{
"code": null,
"e": 1635,
"s": 1590,
"text": "Writing CSV files in Python\nwriterows(rows)\n"
},
{
"code": null,
"e": 1644,
"s": 1635,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# writing to CSV import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv file filename = \"university_records.csv\" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows)",
"e": 2355,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2363,
"s": 2355,
"text": "Output:"
},
{
"code": null,
"e": 2440,
"s": 2363,
"text": "This class returns a writer object which maps dictionaries onto output rows."
},
{
"code": null,
"e": 2549,
"s": 2440,
"text": "Syntax: csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)"
},
{
"code": null,
"e": 3040,
"s": 2549,
"text": "Parameters:csvfile: A file object with write() method.fieldnames: A sequence of keys that identify the order in which values in the dictionary should be passed.restval (optional): Specifies the value to be written if the dictionary is missing a key in fieldnames.extrasaction (optional): If a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to raise a ValueError will be raised.dialect (optional): Name of the dialect to be used."
},
{
"code": null,
"e": 3106,
"s": 3040,
"text": "csv.DictWriter provides two methods for writing to CSV. They are:"
},
{
"code": null,
"e": 3244,
"s": 3106,
"text": "writeheader(): writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.Syntax:writeheader()\n"
},
{
"code": null,
"e": 3252,
"s": 3244,
"text": "Syntax:"
},
{
"code": null,
"e": 3267,
"s": 3252,
"text": "writeheader()\n"
},
{
"code": null,
"e": 3403,
"s": 3267,
"text": "writerows(): writerows method simply writes all the rows but in each row, it writes only the values(not keys).Syntax:writerows(mydict)\n"
},
{
"code": null,
"e": 3411,
"s": 3403,
"text": "Syntax:"
},
{
"code": null,
"e": 3430,
"s": 3411,
"text": "writerows(mydict)\n"
},
{
"code": null,
"e": 3439,
"s": 3430,
"text": "Example:"
},
{
"code": "# importing the csv module import csv # my data rows as dictionary objects mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] # field names fields = ['name', 'branch', 'year', 'cgpa'] # name of csv file filename = \"university_records.csv\" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile, fieldnames = fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(mydict) ",
"e": 4371,
"s": 3439,
"text": null
},
{
"code": null,
"e": 4379,
"s": 4371,
"text": "Output:"
},
{
"code": null,
"e": 4386,
"s": 4379,
"text": "Picked"
},
{
"code": null,
"e": 4397,
"s": 4386,
"text": "python-csv"
},
{
"code": null,
"e": 4404,
"s": 4397,
"text": "Python"
},
{
"code": null,
"e": 4502,
"s": 4404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4530,
"s": 4502,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4580,
"s": 4530,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4602,
"s": 4580,
"text": "Python map() function"
},
{
"code": null,
"e": 4646,
"s": 4602,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 4688,
"s": 4646,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4710,
"s": 4688,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4745,
"s": 4710,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4771,
"s": 4745,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4803,
"s": 4771,
"text": "How to Install PIP on Windows ?"
}
] |
Mathematics | Graph theory practice questions | 13 Dec, 2019
Problem 1 – There are 25 telephones in Geeksland. Is it possible to connect them with wires so that each telephone is connected with exactly 7 others.Solution – Let us suppose that such an arrangement is possible. This can be viewed as a graph in which telephones are represented using vertices and wires using the edges. Now we have 25 vertices in this graph. The degree of each vertex in the graph is 7.
From handshaking lemma, we know.
sum of degrees of all vertices = 2*(number of edges)
number of edges = (sum of degrees of all vertices) / 2
We need to understand that an edge connects two vertices. So the sum of degrees of all the vertices is equal to twice the number of edges.Therefore,
25*7 = 2*(number of edges)
number of edges = 25*7 / 2 = 87.5
This is not an integer. As a result we can conclude that our supposition is wrong and such an arrangement is not possible.
Problem 2 – The figure below shows an arrangement of knights on a 3*3 grid.Figure – initial state
Is it possible to reach the final state as shown below using valid knight’s moves ?
Figure – final state
Solution – NO. You might think you need to be a good chess player in order to crack the above question. However the above question can be solved using graphs. But what kind of a graph should we draw? Let each of the 9 vertices be represented by a number as shown below.
Now we consider each square of the grid as a vertex in our graph. There exists a edge between two vertices in our graph if a valid knight’s move is possible between the corresponding squares in the graph. For example – If we consider square 1. The reachable squares with valid knight’s moves are 6 and 8. We can say that vertex 1 is connected to vertices 6 and 8 in our graph.
Similarly we can draw the entire graph as shown below. Clearly vertex 5 can’t be reached from any of the squares. Hence none of the edges connect to vertex 5.
We use a hollow circle to depict a white knight in our graph and a filled circle to depict a black knight. Hence the initial state of the graph can be represented as :
Figure – initial state
The final state is represented as :
Figure – final state
Note that in order to achieve the final state there needs to exist a path where two knights (a black knight and a white knight cross-over). We can only move the knights in a clockwise or counter-clockwise manner on the graph (If two vertices are connected on the graph: it means that a corresponding knight’s move exists on the grid). However the order in which knights appear on the graph cannot be changed. There is no possible way for a knight to cross over (Two knights cannot exist on one vertex) the other in order to achieve the final state. Hence, we can conclude that no matter what the final arrangement is not possible.
Problem 3: There are 9 line segments drawn in a plane. Is it possible that each line segment intersects exactly 3 others?Solution: This problem seems very difficult initially. We could think of solving it using graphs. But how do we do draw the graph. If we try to approach this problem by using line segments as edges of a graph,we seem to reach nowhere (This sounds confusing initially). Here we need to consider a graph where each line segment is represented as a vertex. Now two vertices of this graph are connected if the corresponding line segments intersect.
Now this graph has 9 vertices. The degree of each vertex is 3.
We know that for a graphSum of degrees of all vertices = 2* Number of Edges in the graphSince the sum of degrees of vertices in the above problem is 9*3 = 27 i.e odd, such an arrangement is not possible.
This article is contributed by Ankit Jain . 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.
PavanBansal
Discrete Mathematics
Engineering Mathematics
GATE CS
Graph
Mathematical
Technical Scripter
Mathematical
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Activation Functions
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Dec, 2019"
},
{
"code": null,
"e": 460,
"s": 54,
"text": "Problem 1 – There are 25 telephones in Geeksland. Is it possible to connect them with wires so that each telephone is connected with exactly 7 others.Solution – Let us suppose that such an arrangement is possible. This can be viewed as a graph in which telephones are represented using vertices and wires using the edges. Now we have 25 vertices in this graph. The degree of each vertex in the graph is 7."
},
{
"code": null,
"e": 493,
"s": 460,
"text": "From handshaking lemma, we know."
},
{
"code": null,
"e": 602,
"s": 493,
"text": "sum of degrees of all vertices = 2*(number of edges)\nnumber of edges = (sum of degrees of all vertices) / 2\n"
},
{
"code": null,
"e": 751,
"s": 602,
"text": "We need to understand that an edge connects two vertices. So the sum of degrees of all the vertices is equal to twice the number of edges.Therefore,"
},
{
"code": null,
"e": 814,
"s": 751,
"text": " 25*7 = 2*(number of edges)\nnumber of edges = 25*7 / 2 = 87.5\n"
},
{
"code": null,
"e": 937,
"s": 814,
"text": "This is not an integer. As a result we can conclude that our supposition is wrong and such an arrangement is not possible."
},
{
"code": null,
"e": 1037,
"s": 939,
"text": "Problem 2 – The figure below shows an arrangement of knights on a 3*3 grid.Figure – initial state"
},
{
"code": null,
"e": 1121,
"s": 1037,
"text": "Is it possible to reach the final state as shown below using valid knight’s moves ?"
},
{
"code": null,
"e": 1142,
"s": 1121,
"text": "Figure – final state"
},
{
"code": null,
"e": 1412,
"s": 1142,
"text": "Solution – NO. You might think you need to be a good chess player in order to crack the above question. However the above question can be solved using graphs. But what kind of a graph should we draw? Let each of the 9 vertices be represented by a number as shown below."
},
{
"code": null,
"e": 1789,
"s": 1412,
"text": "Now we consider each square of the grid as a vertex in our graph. There exists a edge between two vertices in our graph if a valid knight’s move is possible between the corresponding squares in the graph. For example – If we consider square 1. The reachable squares with valid knight’s moves are 6 and 8. We can say that vertex 1 is connected to vertices 6 and 8 in our graph."
},
{
"code": null,
"e": 1948,
"s": 1789,
"text": "Similarly we can draw the entire graph as shown below. Clearly vertex 5 can’t be reached from any of the squares. Hence none of the edges connect to vertex 5."
},
{
"code": null,
"e": 2116,
"s": 1948,
"text": "We use a hollow circle to depict a white knight in our graph and a filled circle to depict a black knight. Hence the initial state of the graph can be represented as :"
},
{
"code": null,
"e": 2139,
"s": 2116,
"text": "Figure – initial state"
},
{
"code": null,
"e": 2175,
"s": 2139,
"text": "The final state is represented as :"
},
{
"code": null,
"e": 2196,
"s": 2175,
"text": "Figure – final state"
},
{
"code": null,
"e": 2827,
"s": 2196,
"text": "Note that in order to achieve the final state there needs to exist a path where two knights (a black knight and a white knight cross-over). We can only move the knights in a clockwise or counter-clockwise manner on the graph (If two vertices are connected on the graph: it means that a corresponding knight’s move exists on the grid). However the order in which knights appear on the graph cannot be changed. There is no possible way for a knight to cross over (Two knights cannot exist on one vertex) the other in order to achieve the final state. Hence, we can conclude that no matter what the final arrangement is not possible."
},
{
"code": null,
"e": 3395,
"s": 2829,
"text": "Problem 3: There are 9 line segments drawn in a plane. Is it possible that each line segment intersects exactly 3 others?Solution: This problem seems very difficult initially. We could think of solving it using graphs. But how do we do draw the graph. If we try to approach this problem by using line segments as edges of a graph,we seem to reach nowhere (This sounds confusing initially). Here we need to consider a graph where each line segment is represented as a vertex. Now two vertices of this graph are connected if the corresponding line segments intersect."
},
{
"code": null,
"e": 3458,
"s": 3395,
"text": "Now this graph has 9 vertices. The degree of each vertex is 3."
},
{
"code": null,
"e": 3662,
"s": 3458,
"text": "We know that for a graphSum of degrees of all vertices = 2* Number of Edges in the graphSince the sum of degrees of vertices in the above problem is 9*3 = 27 i.e odd, such an arrangement is not possible."
},
{
"code": null,
"e": 3961,
"s": 3662,
"text": "This article is contributed by Ankit Jain . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4086,
"s": 3961,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4098,
"s": 4086,
"text": "PavanBansal"
},
{
"code": null,
"e": 4119,
"s": 4098,
"text": "Discrete Mathematics"
},
{
"code": null,
"e": 4143,
"s": 4119,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 4151,
"s": 4143,
"text": "GATE CS"
},
{
"code": null,
"e": 4157,
"s": 4151,
"text": "Graph"
},
{
"code": null,
"e": 4170,
"s": 4157,
"text": "Mathematical"
},
{
"code": null,
"e": 4189,
"s": 4170,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4202,
"s": 4189,
"text": "Mathematical"
},
{
"code": null,
"e": 4208,
"s": 4202,
"text": "Graph"
},
{
"code": null,
"e": 4306,
"s": 4208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4328,
"s": 4306,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 4387,
"s": 4328,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 4410,
"s": 4387,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 4433,
"s": 4410,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 4454,
"s": 4433,
"text": "Activation Functions"
},
{
"code": null,
"e": 4474,
"s": 4454,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 4498,
"s": 4474,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 4511,
"s": 4498,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 4538,
"s": 4511,
"text": "Types of Operating Systems"
}
] |
How to pass arguments to shell script in crontab ? | 18 Jul, 2021
In this article, we will discuss how to schedule shell scripts in contrab and to pass necessary parameters as well.
First, let’s create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run.
#! /usr/bin/sh
SUM=0
for i in $@
do
SUM=`expr $SUM + $i`
done
echo "$SUM was calculated at `date`"
Note: #! /usr/bin/sh (specifying the path of script interpreter) is necessary if wish to make the script executable.
Assuming we have saved this script as my_script.sh under our home directory, we can make it executable by entering the following command in our terminal:
chmod +x my_script.sh
We can test our script if it is working properly:
./my_script.sh 1 2 3 4 5
15 was calculated at Thursday 01 July 2021 01:24:04 IST 2021
The crontab scheduling expression has the following parts:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
crontab -e
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
*/2 * * * * /home/$(USER)/my_script.sh 1 2 3 4 5 >> /home/$(USER)/output.txt
where $(USER) can be replaced with your username. Save changes and exit. This will schedule our shell script to run every 2 minutes with 1 2 3 4 5 as command-line arguments and write the output to /home/$(USER)/ouput.txt.
Note: There are a few things to keep in mind before scheduling cron jobs:
All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice.
All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them.
All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "In this article, we will discuss how to schedule shell scripts in contrab and to pass necessary parameters as well."
},
{
"code": null,
"e": 374,
"s": 144,
"text": "First, let’s create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run."
},
{
"code": null,
"e": 479,
"s": 374,
"text": "#! /usr/bin/sh\nSUM=0\nfor i in $@ \ndo \n SUM=`expr $SUM + $i`\ndone\necho \"$SUM was calculated at `date`\""
},
{
"code": null,
"e": 596,
"s": 479,
"text": "Note: #! /usr/bin/sh (specifying the path of script interpreter) is necessary if wish to make the script executable."
},
{
"code": null,
"e": 751,
"s": 596,
"text": "Assuming we have saved this script as my_script.sh under our home directory, we can make it executable by entering the following command in our terminal:"
},
{
"code": null,
"e": 773,
"s": 751,
"text": "chmod +x my_script.sh"
},
{
"code": null,
"e": 823,
"s": 773,
"text": "We can test our script if it is working properly:"
},
{
"code": null,
"e": 909,
"s": 823,
"text": "./my_script.sh 1 2 3 4 5\n15 was calculated at Thursday 01 July 2021 01:24:04 IST 2021"
},
{
"code": null,
"e": 968,
"s": 909,
"text": "The crontab scheduling expression has the following parts:"
},
{
"code": null,
"e": 1137,
"s": 968,
"text": "To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:"
},
{
"code": null,
"e": 1148,
"s": 1137,
"text": "crontab -e"
},
{
"code": null,
"e": 1272,
"s": 1148,
"text": "You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:"
},
{
"code": null,
"e": 1349,
"s": 1272,
"text": "*/2 * * * * /home/$(USER)/my_script.sh 1 2 3 4 5 >> /home/$(USER)/output.txt"
},
{
"code": null,
"e": 1571,
"s": 1349,
"text": "where $(USER) can be replaced with your username. Save changes and exit. This will schedule our shell script to run every 2 minutes with 1 2 3 4 5 as command-line arguments and write the output to /home/$(USER)/ouput.txt."
},
{
"code": null,
"e": 1645,
"s": 1571,
"text": "Note: There are a few things to keep in mind before scheduling cron jobs:"
},
{
"code": null,
"e": 1958,
"s": 1645,
"text": "All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice."
},
{
"code": null,
"e": 2111,
"s": 1958,
"text": "All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them."
},
{
"code": null,
"e": 2319,
"s": 2111,
"text": "All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering."
},
{
"code": null,
"e": 2326,
"s": 2319,
"text": "Picked"
},
{
"code": null,
"e": 2339,
"s": 2326,
"text": "Shell Script"
},
{
"code": null,
"e": 2350,
"s": 2339,
"text": "Linux-Unix"
}
] |
How to Convert Image to PDF in Python? | 04 Dec, 2020
img2pdf is an open source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance image (Brightness, contrast and other things)
Use this command to install the packages
pip install img2pdf
Below is the implementation:
Image can be converted into pdf bytes using img2pdf.convert() functions provided by img2pdf module, then the pdf file opened in wb mode and is written with the bytes.
# Python3 program to convert image to pfd# using img2pdf library # importing necessary librariesimport img2pdffrom PIL import Imageimport os # storing image pathimg_path = "C:/Users/Admin/Desktop/GfG_images/do_nawab.png" # storing pdf pathpdf_path = "C:/Users/Admin/Desktop/GfG_images/file.pdf" # opening imageimage = Image.open(img_path) # converting into chunks using img2pdfpdf_bytes = img2pdf.convert(image.filename) # opening or creating pdf filefile = open(pdf_path, "wb") # writing pdf files with chunksfile.write(pdf_bytes) # closing image fileimage.close() # closing pdf filefile.close() # outputprint("Successfully made pdf file")
Output:
Successfully made pdf file
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 240,
"s": 52,
"text": "img2pdf is an open source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance image (Brightness, contrast and other things)"
},
{
"code": null,
"e": 281,
"s": 240,
"text": "Use this command to install the packages"
},
{
"code": null,
"e": 301,
"s": 281,
"text": "pip install img2pdf"
},
{
"code": null,
"e": 331,
"s": 301,
"text": " Below is the implementation:"
},
{
"code": null,
"e": 498,
"s": 331,
"text": "Image can be converted into pdf bytes using img2pdf.convert() functions provided by img2pdf module, then the pdf file opened in wb mode and is written with the bytes."
},
{
"code": "# Python3 program to convert image to pfd# using img2pdf library # importing necessary librariesimport img2pdffrom PIL import Imageimport os # storing image pathimg_path = \"C:/Users/Admin/Desktop/GfG_images/do_nawab.png\" # storing pdf pathpdf_path = \"C:/Users/Admin/Desktop/GfG_images/file.pdf\" # opening imageimage = Image.open(img_path) # converting into chunks using img2pdfpdf_bytes = img2pdf.convert(image.filename) # opening or creating pdf filefile = open(pdf_path, \"wb\") # writing pdf files with chunksfile.write(pdf_bytes) # closing image fileimage.close() # closing pdf filefile.close() # outputprint(\"Successfully made pdf file\")",
"e": 1149,
"s": 498,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Output:"
},
{
"code": null,
"e": 1184,
"s": 1157,
"text": "Successfully made pdf file"
},
{
"code": null,
"e": 1199,
"s": 1184,
"text": "python-modules"
},
{
"code": null,
"e": 1206,
"s": 1199,
"text": "Python"
}
] |
Tree, Back, Edge and Cross Edges in DFS of Graph | 12 Dec, 2021
Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges.
Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge (u, v) such that v is descendant but not part of the DFS tree. Edge from 1 to 8 is a forward edge. Back edge: It is an edge (u, v) such that v is ancestor of node u but not part of DFS tree. Edge from 6 to 2 is a back edge. Presence of back edge indicates a cycle in directed graph. Cross Edge: It is a edge which connects two node such that they do not have any ancestor and a descendant relationship between them. Edge from node 5 to 4 is cross edge.
Time Complexity(DFS)
Since all the nodes and vertices are visited, the average time complexity for DFS on a graph is O(V + E), where V is the number of vertices and E is the number of edges. In case of DFS on a tree, the time complexity is O(V), where V is the number of nodes.
Algorithm(DFS)
Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.
Repeat until all the nodes are visited, or the node to be searched is found.
Implement DFS using adjacency list take a directed graph of size n=10, and randomly select number of edges in the graph varying from 9 to 45. Identify each edge as forward edge, tree edge, back edge and cross edge.
Python3
# codeimport random class Graph: # instance variables def __init__(self, v): # v is the number of nodes/vertices self.time = 0 self.traversal_array = [] self.v = v # e is the number of edge (randomly chosen between 9 to 45) self.e = random.randint(9, 45) # adj. list for graph self.graph_list = [[] for _ in range(v)] # adj. matrix for graph self.graph_matrix = [[0 for _ in range(v)] for _ in range(v)] # function to create random graph def create_random_graph(self): # add edges upto e for i in range(self.e): # choose src and dest of each edge randomly src = random.randrange(0, self.v) dest = random.randrange(0, self.v) # re-choose if src and dest are same or src and dest already has an edge while src == dest and self.graph_matrix[src][dest] == 1: src = random.randrange(0, self.v) dest = random.randrange(0, self.v) # add the edge to graph self.graph_list[src].append(dest) self.graph_matrix[src][dest] = 1 # function to print adj list def print_graph_list(self): print("Adjacency List Representation:") for i in range(self.v): print(i, "-->", *self.graph_list[i]) print() # function to print adj matrix def print_graph_matrix(self): print("Adjacency Matrix Representation:") for i in self.graph_matrix: print(i) print() # function the get number of edges def number_of_edges(self): return self.e # function for dfs def dfs(self): self.visited = [False]*self.v self.start_time = [0]*self.v self.end_time = [0]*self.v for node in range(self.v): if not self.visited[node]: self.traverse_dfs(node) print() print("DFS Traversal: ", self.traversal_array) print() def traverse_dfs(self, node): # mark the node visited self.visited[node] = True # add the node to traversal self.traversal_array.append(node) # get the starting time self.start_time[node] = self.time # increment the time by 1 self.time += 1 # traverse through the neighbours for neighbour in self.graph_list[node]: # if a node is not visited if not self.visited[neighbour]: # marks the edge as tree edge print('Tree Edge:', str(node)+'-->'+str(neighbour)) # dfs from that node self.traverse_dfs(neighbour) else: # when the parent node is traversed after the neighbour node if self.start_time[node] > self.start_time[neighbour] and self.end_time[node] < self.end_time[neighbour]: print('Back Edge:', str(node)+'-->'+str(neighbour)) # when the neighbour node is a descendant but not a part of tree elif self.start_time[node] < self.start_time[neighbour] and self.end_time[node] > self.end_time[neighbour]: print('Forward Edge:', str(node)+'-->'+str(neighbour)) # when parent and neighbour node do not have any ancestor and a descendant relationship between them elif self.start_time[node] > self.start_time[neighbour] and self.end_time[node] > self.end_time[neighbour]: print('Cross Edge:', str(node)+'-->'+str(neighbour)) self.end_time[node] = self.time self.time += 1 if __name__ == "__main__": n = 10 g = Graph(n) g.create_random_graph() g.print_graph_list() g.print_graph_matrix() g.dfs()
Sektor_jr
feihcsim824
ShashwatKhare
ayushj383
avtarkumar719
DFS
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Find if there is a path between two vertices in an undirected graph
Minimum steps to reach target by a Knight | Set 1
Top 50 Graph Coding Problems for Interviews
Bridges in a graph
Longest Path in a Directed Acyclic Graph
Water Jug problem using BFS
Graph Coloring | Set 1 (Introduction and Applications) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 244,
"s": 52,
"text": "Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges. "
},
{
"code": null,
"e": 857,
"s": 244,
"text": "Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge (u, v) such that v is descendant but not part of the DFS tree. Edge from 1 to 8 is a forward edge. Back edge: It is an edge (u, v) such that v is ancestor of node u but not part of DFS tree. Edge from 6 to 2 is a back edge. Presence of back edge indicates a cycle in directed graph. Cross Edge: It is a edge which connects two node such that they do not have any ancestor and a descendant relationship between them. Edge from node 5 to 4 is cross edge."
},
{
"code": null,
"e": 878,
"s": 857,
"text": "Time Complexity(DFS)"
},
{
"code": null,
"e": 1135,
"s": 878,
"text": "Since all the nodes and vertices are visited, the average time complexity for DFS on a graph is O(V + E), where V is the number of vertices and E is the number of edges. In case of DFS on a tree, the time complexity is O(V), where V is the number of nodes."
},
{
"code": null,
"e": 1150,
"s": 1135,
"text": "Algorithm(DFS)"
},
{
"code": null,
"e": 1241,
"s": 1150,
"text": "Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes."
},
{
"code": null,
"e": 1318,
"s": 1241,
"text": "Repeat until all the nodes are visited, or the node to be searched is found."
},
{
"code": null,
"e": 1533,
"s": 1318,
"text": "Implement DFS using adjacency list take a directed graph of size n=10, and randomly select number of edges in the graph varying from 9 to 45. Identify each edge as forward edge, tree edge, back edge and cross edge."
},
{
"code": null,
"e": 1541,
"s": 1533,
"text": "Python3"
},
{
"code": "# codeimport random class Graph: # instance variables def __init__(self, v): # v is the number of nodes/vertices self.time = 0 self.traversal_array = [] self.v = v # e is the number of edge (randomly chosen between 9 to 45) self.e = random.randint(9, 45) # adj. list for graph self.graph_list = [[] for _ in range(v)] # adj. matrix for graph self.graph_matrix = [[0 for _ in range(v)] for _ in range(v)] # function to create random graph def create_random_graph(self): # add edges upto e for i in range(self.e): # choose src and dest of each edge randomly src = random.randrange(0, self.v) dest = random.randrange(0, self.v) # re-choose if src and dest are same or src and dest already has an edge while src == dest and self.graph_matrix[src][dest] == 1: src = random.randrange(0, self.v) dest = random.randrange(0, self.v) # add the edge to graph self.graph_list[src].append(dest) self.graph_matrix[src][dest] = 1 # function to print adj list def print_graph_list(self): print(\"Adjacency List Representation:\") for i in range(self.v): print(i, \"-->\", *self.graph_list[i]) print() # function to print adj matrix def print_graph_matrix(self): print(\"Adjacency Matrix Representation:\") for i in self.graph_matrix: print(i) print() # function the get number of edges def number_of_edges(self): return self.e # function for dfs def dfs(self): self.visited = [False]*self.v self.start_time = [0]*self.v self.end_time = [0]*self.v for node in range(self.v): if not self.visited[node]: self.traverse_dfs(node) print() print(\"DFS Traversal: \", self.traversal_array) print() def traverse_dfs(self, node): # mark the node visited self.visited[node] = True # add the node to traversal self.traversal_array.append(node) # get the starting time self.start_time[node] = self.time # increment the time by 1 self.time += 1 # traverse through the neighbours for neighbour in self.graph_list[node]: # if a node is not visited if not self.visited[neighbour]: # marks the edge as tree edge print('Tree Edge:', str(node)+'-->'+str(neighbour)) # dfs from that node self.traverse_dfs(neighbour) else: # when the parent node is traversed after the neighbour node if self.start_time[node] > self.start_time[neighbour] and self.end_time[node] < self.end_time[neighbour]: print('Back Edge:', str(node)+'-->'+str(neighbour)) # when the neighbour node is a descendant but not a part of tree elif self.start_time[node] < self.start_time[neighbour] and self.end_time[node] > self.end_time[neighbour]: print('Forward Edge:', str(node)+'-->'+str(neighbour)) # when parent and neighbour node do not have any ancestor and a descendant relationship between them elif self.start_time[node] > self.start_time[neighbour] and self.end_time[node] > self.end_time[neighbour]: print('Cross Edge:', str(node)+'-->'+str(neighbour)) self.end_time[node] = self.time self.time += 1 if __name__ == \"__main__\": n = 10 g = Graph(n) g.create_random_graph() g.print_graph_list() g.print_graph_matrix() g.dfs()",
"e": 5244,
"s": 1541,
"text": null
},
{
"code": null,
"e": 5254,
"s": 5244,
"text": "Sektor_jr"
},
{
"code": null,
"e": 5266,
"s": 5254,
"text": "feihcsim824"
},
{
"code": null,
"e": 5280,
"s": 5266,
"text": "ShashwatKhare"
},
{
"code": null,
"e": 5290,
"s": 5280,
"text": "ayushj383"
},
{
"code": null,
"e": 5304,
"s": 5290,
"text": "avtarkumar719"
},
{
"code": null,
"e": 5308,
"s": 5304,
"text": "DFS"
},
{
"code": null,
"e": 5314,
"s": 5308,
"text": "Graph"
},
{
"code": null,
"e": 5318,
"s": 5314,
"text": "DFS"
},
{
"code": null,
"e": 5324,
"s": 5318,
"text": "Graph"
},
{
"code": null,
"e": 5422,
"s": 5324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5487,
"s": 5422,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 5519,
"s": 5487,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5583,
"s": 5519,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 5651,
"s": 5583,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 5701,
"s": 5651,
"text": "Minimum steps to reach target by a Knight | Set 1"
},
{
"code": null,
"e": 5745,
"s": 5701,
"text": "Top 50 Graph Coding Problems for Interviews"
},
{
"code": null,
"e": 5764,
"s": 5745,
"text": "Bridges in a graph"
},
{
"code": null,
"e": 5805,
"s": 5764,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 5833,
"s": 5805,
"text": "Water Jug problem using BFS"
}
] |
Matplotlib.figure.Figure.suptitle() in Python | 03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The suptitle() method figure module of matplotlib library is used to Add a centered title to the figure.
Syntax: suptitle(self, t, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
t : This parameter is the title text.
x: This parameter is the x location of the text in figure coordinates.
y: This parameter is the y location of the text in figure coordinates.
horizontalalignment, ha : This parameter is the horizontal alignment of the text relative to (x, y).
verticalalignment, va : This parameter is the vertical alignment of the text relative to (x, y).
fontsize, size : This parameter is the font size of the text.
fontweight, weight : This parameter is the font weight of the text.
Returns: This method returns the Text instance of the title.
Below examples illustrate the matplotlib.figure.Figure.suptitle() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure(tight_layout = True)gs = gridspec.GridSpec(1, 1) ax = fig.add_subplot(gs[0, :])ax.plot(np.arange(0, 1e6, 1000))ax.set_ylabel('YLabel0')ax.set_xlabel('XLabel0') fig.suptitle('matplotlib.figure.Figure.suptitle()\ function Example\n\n', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) xdata = np.random.random([2, 10]) xdata1 = xdata[0, :]xdata2 = xdata[1, :] ydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3 fig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange') ax.set_xlim([0, 1])ax.set_ylim([0, 1]) fig.suptitle('matplotlib.figure.Figure.suptitle()\ function Example\n\n', fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 444,
"s": 339,
"text": "The suptitle() method figure module of matplotlib library is used to Add a centered title to the figure."
},
{
"code": null,
"e": 480,
"s": 444,
"text": "Syntax: suptitle(self, t, **kwargs)"
},
{
"code": null,
"e": 562,
"s": 480,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 600,
"s": 562,
"text": "t : This parameter is the title text."
},
{
"code": null,
"e": 671,
"s": 600,
"text": "x: This parameter is the x location of the text in figure coordinates."
},
{
"code": null,
"e": 742,
"s": 671,
"text": "y: This parameter is the y location of the text in figure coordinates."
},
{
"code": null,
"e": 843,
"s": 742,
"text": "horizontalalignment, ha : This parameter is the horizontal alignment of the text relative to (x, y)."
},
{
"code": null,
"e": 940,
"s": 843,
"text": "verticalalignment, va : This parameter is the vertical alignment of the text relative to (x, y)."
},
{
"code": null,
"e": 1002,
"s": 940,
"text": "fontsize, size : This parameter is the font size of the text."
},
{
"code": null,
"e": 1070,
"s": 1002,
"text": "fontweight, weight : This parameter is the font weight of the text."
},
{
"code": null,
"e": 1131,
"s": 1070,
"text": "Returns: This method returns the Text instance of the title."
},
{
"code": null,
"e": 1228,
"s": 1131,
"text": "Below examples illustrate the matplotlib.figure.Figure.suptitle() function in matplotlib.figure:"
},
{
"code": null,
"e": 1239,
"s": 1228,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspec fig = plt.figure(tight_layout = True)gs = gridspec.GridSpec(1, 1) ax = fig.add_subplot(gs[0, :])ax.plot(np.arange(0, 1e6, 1000))ax.set_ylabel('YLabel0')ax.set_xlabel('XLabel0') fig.suptitle('matplotlib.figure.Figure.suptitle()\\ function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1657,
"s": 1239,
"text": null
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Output:"
},
{
"code": null,
"e": 1676,
"s": 1665,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) xdata = np.random.random([2, 10]) xdata1 = xdata[0, :]xdata2 = xdata[1, :] ydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3 fig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange') ax.set_xlim([0, 1])ax.set_ylim([0, 1]) fig.suptitle('matplotlib.figure.Figure.suptitle()\\ function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 2207,
"s": 1676,
"text": null
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Output:"
},
{
"code": null,
"e": 2239,
"s": 2215,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 2257,
"s": 2239,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2264,
"s": 2257,
"text": "Python"
}
] |
iptables-restore command in Linux with examples | 05 Mar, 2019
iptables-restore and ip6tables-restore commands are used to restore IP and IPv6 Tables from data being specified on the STDIN or in the file. Use I/O redirection provided by default from your shell to read from a file or specify the file as an argument.
Syntax:
iptables-restore [-chntv] [-M modprobe] [-T name] [file]
ip6tables-restore [-chntv] [-M modprobe] [-T name] [file]
Options:
-c, –counters : This option restores the values of all packet and byte counters.
-h, –help : This option prints a short option summary.
-n, –noflush : This option doesn’t flush the previous contents of the table. If it is not specified, both the commands flush (delete) all previous contents of the respective table.
-t, –test : This option only parses and construct the ruleset, but do not commit it.
-v, –verbose : This option prints additional debug info during ruleset processing.
-M, –modprobe modprobe_program : This option Specifies the path to the modprobe program. By default, the iptables-restore will going to inspect /proc/sys/kernel/modprobe to determine the executable’s path.
-T, –table name : This option restores only the named table even if the input stream contains other ones.
Examples:
1) Create a new iptable which helps in restoring.
2) It will create a new file named iptableslist.txt. To see the contents of file run the following command on the terminal:
3) The content of the file is:
4) Now the last step is to restore from that file we just created. We can simply restore iptables using the following command.
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Mar, 2019"
},
{
"code": null,
"e": 282,
"s": 28,
"text": "iptables-restore and ip6tables-restore commands are used to restore IP and IPv6 Tables from data being specified on the STDIN or in the file. Use I/O redirection provided by default from your shell to read from a file or specify the file as an argument."
},
{
"code": null,
"e": 290,
"s": 282,
"text": "Syntax:"
},
{
"code": null,
"e": 407,
"s": 290,
"text": "iptables-restore [-chntv] [-M modprobe] [-T name] [file]\n\nip6tables-restore [-chntv] [-M modprobe] [-T name] [file]\n"
},
{
"code": null,
"e": 416,
"s": 407,
"text": "Options:"
},
{
"code": null,
"e": 497,
"s": 416,
"text": "-c, –counters : This option restores the values of all packet and byte counters."
},
{
"code": null,
"e": 552,
"s": 497,
"text": "-h, –help : This option prints a short option summary."
},
{
"code": null,
"e": 733,
"s": 552,
"text": "-n, –noflush : This option doesn’t flush the previous contents of the table. If it is not specified, both the commands flush (delete) all previous contents of the respective table."
},
{
"code": null,
"e": 818,
"s": 733,
"text": "-t, –test : This option only parses and construct the ruleset, but do not commit it."
},
{
"code": null,
"e": 901,
"s": 818,
"text": "-v, –verbose : This option prints additional debug info during ruleset processing."
},
{
"code": null,
"e": 1107,
"s": 901,
"text": "-M, –modprobe modprobe_program : This option Specifies the path to the modprobe program. By default, the iptables-restore will going to inspect /proc/sys/kernel/modprobe to determine the executable’s path."
},
{
"code": null,
"e": 1213,
"s": 1107,
"text": "-T, –table name : This option restores only the named table even if the input stream contains other ones."
},
{
"code": null,
"e": 1223,
"s": 1213,
"text": "Examples:"
},
{
"code": null,
"e": 1273,
"s": 1223,
"text": "1) Create a new iptable which helps in restoring."
},
{
"code": null,
"e": 1397,
"s": 1273,
"text": "2) It will create a new file named iptableslist.txt. To see the contents of file run the following command on the terminal:"
},
{
"code": null,
"e": 1428,
"s": 1397,
"text": "3) The content of the file is:"
},
{
"code": null,
"e": 1555,
"s": 1428,
"text": "4) Now the last step is to restore from that file we just created. We can simply restore iptables using the following command."
},
{
"code": null,
"e": 1569,
"s": 1555,
"text": "linux-command"
},
{
"code": null,
"e": 1576,
"s": 1569,
"text": "Picked"
},
{
"code": null,
"e": 1587,
"s": 1576,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1685,
"s": 1587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1720,
"s": 1685,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 1755,
"s": 1720,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1791,
"s": 1755,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 1827,
"s": 1791,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1865,
"s": 1827,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1903,
"s": 1865,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1929,
"s": 1903,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1964,
"s": 1929,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2002,
"s": 1964,
"text": "UDP Server-Client implementation in C"
}
] |
How to search a MySQL table for a specific string? | Use equal to operator for an exact match −
select *from yourTableName where yourColumnName=yourValue;
Let us first create a table −
mysql> create table DemoTable
-> (
-> FirstName varchar(100),
-> LastName varchar(100)
-> );
Query OK, 0 rows affected (0.70 sec
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John','Smith');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris','Brown');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Carol','Taylor');
Query OK, 1 row affected (0.29 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John | Smith |
| John | Doe |
| Chris | Brown |
| Carol | Taylor |
+-----------+----------+
4 rows in set (0.00 sec)
Following is the query to search a MySQL table for a specific string −
mysql> select *from DemoTable where LastName='Doe';
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John | Doe |
+-----------+----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1105,
"s": 1062,
"text": "Use equal to operator for an exact match −"
},
{
"code": null,
"e": 1164,
"s": 1105,
"text": "select *from yourTableName where yourColumnName=yourValue;"
},
{
"code": null,
"e": 1194,
"s": 1164,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1323,
"s": 1194,
"text": "mysql> create table DemoTable\n-> (\n-> FirstName varchar(100),\n-> LastName varchar(100)\n-> );\nQuery OK, 0 rows affected (0.70 sec"
},
{
"code": null,
"e": 1379,
"s": 1323,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1739,
"s": 1379,
"text": "mysql> insert into DemoTable values('John','Smith');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('John','Doe');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values('Chris','Brown');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable values('Carol','Taylor');\nQuery OK, 1 row affected (0.29 sec)"
},
{
"code": null,
"e": 1799,
"s": 1739,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1830,
"s": 1799,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1871,
"s": 1830,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2096,
"s": 1871,
"text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| John | Smith |\n| John | Doe |\n| Chris | Brown |\n| Carol | Taylor |\n+-----------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2167,
"s": 2096,
"text": "Following is the query to search a MySQL table for a specific string −"
},
{
"code": null,
"e": 2219,
"s": 2167,
"text": "mysql> select *from DemoTable where LastName='Doe';"
},
{
"code": null,
"e": 2260,
"s": 2219,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2409,
"s": 2260,
"text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| John | Doe |\n+-----------+----------+\n1 row in set (0.00 sec)"
}
] |
NHibernate - Collection Mapping | In this chapter, we will be covering how to represent collections. There are different types of collections that we can use within the NHibernate such as −
Lists
Sets
Bags
Now, from the .NET perspective, we generally deal with lists or like very simple data structures, lists, dictionaries. .NET does not have a wide variety of different collection types. So why does NHibernate need all these different types? It really comes back to the database.
A list is an ordered collection of elements that are not necessarily unique.
A list is an ordered collection of elements that are not necessarily unique.
We can map this using the IList <T>.
We can map this using the IList <T>.
So although we might conventionally have a list of addresses, and from application point of view we know that the elements are unique, nothing in the list prevents us from inserting duplicate elements in that list.
So although we might conventionally have a list of addresses, and from application point of view we know that the elements are unique, nothing in the list prevents us from inserting duplicate elements in that list.
A set is an unordered collection of unique elements. If you try to insert 2 duplicate elements into a set, it will throw an exception.
A set is an unordered collection of unique elements. If you try to insert 2 duplicate elements into a set, it will throw an exception.
There's nothing specific in NHibernate about it.
There's nothing specific in NHibernate about it.
It's just a convenient way a have a generic set implementation. If you're on .NET 4, you can use the new HashSet <T> to represent these, but in most NHibernate applications, we represent this is an ISet.
It's just a convenient way a have a generic set implementation. If you're on .NET 4, you can use the new HashSet <T> to represent these, but in most NHibernate applications, we represent this is an ISet.
It is an unordered, if you pull back a list of addresses from a database or a list of orders, you don't know what order they're coming in unless you put in a specific Order by clause.
It is an unordered, if you pull back a list of addresses from a database or a list of orders, you don't know what order they're coming in unless you put in a specific Order by clause.
So in general, the data that you're pulling back from a database are sets.
So in general, the data that you're pulling back from a database are sets.
They are unique collections of elements that are unordered.
They are unique collections of elements that are unordered.
Another common collection that we will see in the database world is a bag, which is just like a set except it can have duplicate elements.
Another common collection that we will see in the database world is a bag, which is just like a set except it can have duplicate elements.
In the .NET world, we represent this by an IList.
In the .NET world, we represent this by an IList.
Sets are probably the most common, but you will see lists and bags as well depending on your application. Let’s have a look into a below customer.hbm.xml file from the last chapter in which Set orders are defined.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo"
namespace = "NHibernateDemo">
<class name = "Customer">
<id name = "Id">
<generator class = "guid.comb"/>
</id>
<property name = "FirstName"/>
<property name = "LastName"/>
<property name = "AverageRating"/>
<property name = "Points"/>
<property name = "HasGoldStatus"/>
<property name = "MemberSince" type = "UtcDateTime"/>
<property name = "CreditRating" type = "CustomerCreditRatingType"/>
<component name = "Address">
<property name = "Street"/>
<property name = "City"/>
<property name = "Province"/>
<property name = "Country"/>
</component>
<set name = "Orders" table = "`Order`">
<key column = "CustomerId"/>
<one-to-many class = "Order"/>
</set>
</class>
</hibernate-mapping>
As you can see, we have mapped the orders collection as a set. Remember that a set is an unordered collection of unique elements.
Now, if you look at the Customer class, you will see that Orders property is defined with an ISet as shown in the following program.
public virtual ISet<Order> Orders { get; set; }
Now when this application is run, you will see the following output.
New Customer:
John Doe (00000000-0000-0000-0000-000000000000)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Unspecified)
CreditRating: Good
AverageRating: 42.42424242
Orders:
Order Id: 00000000-0000-0000-0000-000000000000
Order Id: 00000000-0000-0000-0000-000000000000
Reloaded:
John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6
Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7
The orders were ordered by:
John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6
Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7
John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6
Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7
Press <ENTER> to exit...
If the items in the collection didn't need to be unique, if you could have multiple orders with the same primary key occurring multiple times in this collection, then this would be better mapped as a bag as shown in the following program.
<bag name = "Orders" table = "`Order`">
<key column = "CustomerId"/>
<one-to-many class = "Order"/>
</bag>
Now, if you run this application you will get an exception because if we take a look at the customer class, you'll notice that the orders are marked as an ISet in the C# code.
So we will also need to change this to an IList and then here, we would need to change from the HashSet to a List in the constructor.
public class Customer {
public Customer() {
MemberSince = DateTime.UtcNow;
Orders = new List<Order>();
}
public virtual Guid Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual double AverageRating { get; set; }
public virtual int Points { get; set; }
public virtual bool HasGoldStatus { get; set; }
public virtual DateTime MemberSince { get; set; }
public virtual CustomerCreditRating CreditRating { get; set; }
public virtual Location Address { get; set; }
public virtual IList<Order> Orders { get; set; }
public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; }
public override string ToString() {
var result = new StringBuilder();
result.AppendFormat("{1} {2} ({0})\r\n\tPoints: {3}\r\n\tHasGoldStatus:
{4}\r\n\tMemberSince: {5} ({7})\r\n\tCreditRating: {6}\r\n\tAverageRating:
{8}\r\n", Id, FirstName, LastName, Points, HasGoldStatus, MemberSince,
CreditRating, MemberSince.Kind, AverageRating); result.AppendLine("\tOrders:");
foreach(var order in Orders) {
result.AppendLine("\t\t" + order);
}
return result.ToString();
}
}
When you run the application, you will see the same behavior. But, now we can have an order occurring multiple times in the same collection.
John Doe (00000000-0000-0000-0000-000000000000)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Unspecified)
CreditRating: Good
AverageRating: 42.42424242
Orders:
Order Id: 00000000-0000-0000-0000-000000000000
Order Id: 00000000-0000-0000-0000-000000000000
Reloaded:
John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286
Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287
The orders were ordered by:
John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286
Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287
John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286
Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287
Press <ENTER> to exit...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2489,
"s": 2333,
"text": "In this chapter, we will be covering how to represent collections. There are different types of collections that we can use within the NHibernate such as −"
},
{
"code": null,
"e": 2495,
"s": 2489,
"text": "Lists"
},
{
"code": null,
"e": 2500,
"s": 2495,
"text": "Sets"
},
{
"code": null,
"e": 2505,
"s": 2500,
"text": "Bags"
},
{
"code": null,
"e": 2782,
"s": 2505,
"text": "Now, from the .NET perspective, we generally deal with lists or like very simple data structures, lists, dictionaries. .NET does not have a wide variety of different collection types. So why does NHibernate need all these different types? It really comes back to the database."
},
{
"code": null,
"e": 2859,
"s": 2782,
"text": "A list is an ordered collection of elements that are not necessarily unique."
},
{
"code": null,
"e": 2936,
"s": 2859,
"text": "A list is an ordered collection of elements that are not necessarily unique."
},
{
"code": null,
"e": 2973,
"s": 2936,
"text": "We can map this using the IList <T>."
},
{
"code": null,
"e": 3010,
"s": 2973,
"text": "We can map this using the IList <T>."
},
{
"code": null,
"e": 3225,
"s": 3010,
"text": "So although we might conventionally have a list of addresses, and from application point of view we know that the elements are unique, nothing in the list prevents us from inserting duplicate elements in that list."
},
{
"code": null,
"e": 3440,
"s": 3225,
"text": "So although we might conventionally have a list of addresses, and from application point of view we know that the elements are unique, nothing in the list prevents us from inserting duplicate elements in that list."
},
{
"code": null,
"e": 3575,
"s": 3440,
"text": "A set is an unordered collection of unique elements. If you try to insert 2 duplicate elements into a set, it will throw an exception."
},
{
"code": null,
"e": 3710,
"s": 3575,
"text": "A set is an unordered collection of unique elements. If you try to insert 2 duplicate elements into a set, it will throw an exception."
},
{
"code": null,
"e": 3759,
"s": 3710,
"text": "There's nothing specific in NHibernate about it."
},
{
"code": null,
"e": 3808,
"s": 3759,
"text": "There's nothing specific in NHibernate about it."
},
{
"code": null,
"e": 4012,
"s": 3808,
"text": "It's just a convenient way a have a generic set implementation. If you're on .NET 4, you can use the new HashSet <T> to represent these, but in most NHibernate applications, we represent this is an ISet."
},
{
"code": null,
"e": 4216,
"s": 4012,
"text": "It's just a convenient way a have a generic set implementation. If you're on .NET 4, you can use the new HashSet <T> to represent these, but in most NHibernate applications, we represent this is an ISet."
},
{
"code": null,
"e": 4400,
"s": 4216,
"text": "It is an unordered, if you pull back a list of addresses from a database or a list of orders, you don't know what order they're coming in unless you put in a specific Order by clause."
},
{
"code": null,
"e": 4584,
"s": 4400,
"text": "It is an unordered, if you pull back a list of addresses from a database or a list of orders, you don't know what order they're coming in unless you put in a specific Order by clause."
},
{
"code": null,
"e": 4659,
"s": 4584,
"text": "So in general, the data that you're pulling back from a database are sets."
},
{
"code": null,
"e": 4734,
"s": 4659,
"text": "So in general, the data that you're pulling back from a database are sets."
},
{
"code": null,
"e": 4794,
"s": 4734,
"text": "They are unique collections of elements that are unordered."
},
{
"code": null,
"e": 4854,
"s": 4794,
"text": "They are unique collections of elements that are unordered."
},
{
"code": null,
"e": 4993,
"s": 4854,
"text": "Another common collection that we will see in the database world is a bag, which is just like a set except it can have duplicate elements."
},
{
"code": null,
"e": 5132,
"s": 4993,
"text": "Another common collection that we will see in the database world is a bag, which is just like a set except it can have duplicate elements."
},
{
"code": null,
"e": 5182,
"s": 5132,
"text": "In the .NET world, we represent this by an IList."
},
{
"code": null,
"e": 5232,
"s": 5182,
"text": "In the .NET world, we represent this by an IList."
},
{
"code": null,
"e": 5446,
"s": 5232,
"text": "Sets are probably the most common, but you will see lists and bags as well depending on your application. Let’s have a look into a below customer.hbm.xml file from the last chapter in which Set orders are defined."
},
{
"code": null,
"e": 6463,
"s": 5446,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\" \n namespace = \"NHibernateDemo\"> \n\t\n <class name = \"Customer\"> \n \n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id> \n \n <property name = \"FirstName\"/> \n <property name = \"LastName\"/> \n <property name = \"AverageRating\"/> \n <property name = \"Points\"/> \n <property name = \"HasGoldStatus\"/> \n <property name = \"MemberSince\" type = \"UtcDateTime\"/> \n <property name = \"CreditRating\" type = \"CustomerCreditRatingType\"/>\n \n <component name = \"Address\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component>\n \n <set name = \"Orders\" table = \"`Order`\"> \n <key column = \"CustomerId\"/> \n <one-to-many class = \"Order\"/> \n </set> \n \n </class> \n</hibernate-mapping>"
},
{
"code": null,
"e": 6593,
"s": 6463,
"text": "As you can see, we have mapped the orders collection as a set. Remember that a set is an unordered collection of unique elements."
},
{
"code": null,
"e": 6726,
"s": 6593,
"text": "Now, if you look at the Customer class, you will see that Orders property is defined with an ISet as shown in the following program."
},
{
"code": null,
"e": 6775,
"s": 6726,
"text": "public virtual ISet<Order> Orders { get; set; }\n"
},
{
"code": null,
"e": 6844,
"s": 6775,
"text": "Now when this application is run, you will see the following output."
},
{
"code": null,
"e": 8120,
"s": 6844,
"text": "New Customer:\nJohn Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Order Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6\n Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7\n\nThe orders were ordered by:\nJohn Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6\n Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7\n\nJohn Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6\n Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7\n\t\t\nPress <ENTER> to exit...\n"
},
{
"code": null,
"e": 8359,
"s": 8120,
"text": "If the items in the collection didn't need to be unique, if you could have multiple orders with the same primary key occurring multiple times in this collection, then this would be better mapped as a bag as shown in the following program."
},
{
"code": null,
"e": 8475,
"s": 8359,
"text": "<bag name = \"Orders\" table = \"`Order`\"> \n <key column = \"CustomerId\"/> \n <one-to-many class = \"Order\"/> \n</bag>"
},
{
"code": null,
"e": 8651,
"s": 8475,
"text": "Now, if you run this application you will get an exception because if we take a look at the customer class, you'll notice that the orders are marked as an ISet in the C# code."
},
{
"code": null,
"e": 8785,
"s": 8651,
"text": "So we will also need to change this to an IList and then here, we would need to change from the HashSet to a List in the constructor."
},
{
"code": null,
"e": 10084,
"s": 8785,
"text": "public class Customer { \n\n public Customer() { \n MemberSince = DateTime.UtcNow; \n Orders = new List<Order>(); \n } \n\t\n public virtual Guid Id { get; set; } \n public virtual string FirstName { get; set; } \n public virtual string LastName { get; set; } \n public virtual double AverageRating { get; set; } \n public virtual int Points { get; set; } \n\t\n public virtual bool HasGoldStatus { get; set; } \n public virtual DateTime MemberSince { get; set; } \n public virtual CustomerCreditRating CreditRating { get; set; } \n public virtual Location Address { get; set; }\n public virtual IList<Order> Orders { get; set; }\n public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; }\n \n public override string ToString() { \n var result = new StringBuilder(); \n\t\t\n result.AppendFormat(\"{1} {2} ({0})\\r\\n\\tPoints: {3}\\r\\n\\tHasGoldStatus:\n {4}\\r\\n\\tMemberSince: {5} ({7})\\r\\n\\tCreditRating: {6}\\r\\n\\tAverageRating:\n {8}\\r\\n\", Id, FirstName, LastName, Points, HasGoldStatus, MemberSince,\n CreditRating, MemberSince.Kind, AverageRating); result.AppendLine(\"\\tOrders:\"); \n \n foreach(var order in Orders) { \n result.AppendLine(\"\\t\\t\" + order); \n } \n\t\t\n return result.ToString(); \n } \n}"
},
{
"code": null,
"e": 10225,
"s": 10084,
"text": "When you run the application, you will see the same behavior. But, now we can have an order occurring multiple times in the same collection."
},
{
"code": null,
"e": 11487,
"s": 10225,
"text": "John Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Order Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286\n Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287\n\nThe orders were ordered by:\nJohn Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286\n Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287\n\nJohn Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286\n Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287\n\t\t\nPress <ENTER> to exit...\n"
},
{
"code": null,
"e": 11494,
"s": 11487,
"text": " Print"
},
{
"code": null,
"e": 11505,
"s": 11494,
"text": " Add Notes"
}
] |
How to compare two branches in Git? | Collaborators will use multiple branches in order to have clearly separated codebase. At some point in time, we may have to merge these branches in order to have the resulting work in the main branch. It is important that we compare the differences in the branches before merging to avoid any conflicts. We will see a couple of different ways to compare two branches −
Listing commit differences − This method shows commits that are present in a branch but unavailable in the other branch.
Listing commit differences − This method shows commits that are present in a branch but unavailable in the other branch.
Listing file changes − This method compares branches and displays how exactly a certain file is different in the two branches.
Listing file changes − This method compares branches and displays how exactly a certain file is different in the two branches.
From the below diagram we can easily understand that there are two branches in the repository one is the master and the other is a feature branch. Each commit and their corresponding commit message are shown in the diagram. From the diagram, it is clear that initial commit hash is “9260faa”
The following command can be used to get a similar graphical representation of branches.
$ git log −−oneline feature −−all −−graph
In the output given below ‘*’ denotes a commit and we could see that there are 4 asterisks which means there are 4 commits. “9260faa” is the initial commit. There are two branches emerging from the initial commit, the master branch on the left and a feature branch on the right.
delI@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log −−oneline feature −−all −−graph
* 0f26bbe (HEAD −> master) bonjour add
|* eOccfce (feature) howdy file add
|* 71b4d39 how are you added
|/
* 9260faa hello. txt
At some point in time the feature branch has to be merged to master, as it is our main line of work. The syntax to list commit differences using the git log command is given below −
$ git log <branch1>..<branch_2>
The following command compares two branches and returns the commits that are present in the feature branch but are unavailable in the master branch.
$ git log master..feature −−oneline
The output is shown below −
e0ccfce (feature) howdy file add
71b4d39 how are you added
If we want to compare two branches on the basis of changes that have been performed on the files, we need to use the diff tool. The syntax to use the diff tool is −
$ git diff <branch_name>
The following command lists differences in files in the current branch (master) and the feature branch.
$ git diff feature
This will give a very detailed difference. If we don't want to see the detailed differences, but need to know only what files are different use the −−name−only. This is shown in the below example.
$ git diff −−name−only feature
The output is shown below −
bonjour.txt
hello.txt
howdy.text
The −−name−status flag can be used with the diff tool to show both the file name and its status.
$ git diff −−name−status feature
The output is shown below. The left column shows the file’s status and the right column shoes the file’s name.
Denotes that the file is present in the current branch but unavailable in the other branch.
Denotes that the file is present in the current branch but unavailable in the other branch.
Denotes that the file is modified and its content is different in the two branches
Denotes that the file is modified and its content is different in the two branches
Denotes that the file is deleted from the current branch but is available in the other branch.
Denotes that the file is deleted from the current branch but is available in the other branch.
dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)
S git diff −−name−status feature
A bonjour . txt
M hello. txt
D howdy. text
dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)
$ git diff −−name−only feature
bonjour. txt
hello.txt
howdy. text | [
{
"code": null,
"e": 1431,
"s": 1062,
"text": "Collaborators will use multiple branches in order to have clearly separated codebase. At some point in time, we may have to merge these branches in order to have the resulting work in the main branch. It is important that we compare the differences in the branches before merging to avoid any conflicts. We will see a couple of different ways to compare two branches −"
},
{
"code": null,
"e": 1552,
"s": 1431,
"text": "Listing commit differences − This method shows commits that are present in a branch but unavailable in the other branch."
},
{
"code": null,
"e": 1673,
"s": 1552,
"text": "Listing commit differences − This method shows commits that are present in a branch but unavailable in the other branch."
},
{
"code": null,
"e": 1800,
"s": 1673,
"text": "Listing file changes − This method compares branches and displays how exactly a certain file is different in the two branches."
},
{
"code": null,
"e": 1927,
"s": 1800,
"text": "Listing file changes − This method compares branches and displays how exactly a certain file is different in the two branches."
},
{
"code": null,
"e": 2219,
"s": 1927,
"text": "From the below diagram we can easily understand that there are two branches in the repository one is the master and the other is a feature branch. Each commit and their corresponding commit message are shown in the diagram. From the diagram, it is clear that initial commit hash is “9260faa”"
},
{
"code": null,
"e": 2308,
"s": 2219,
"text": "The following command can be used to get a similar graphical representation of branches."
},
{
"code": null,
"e": 2350,
"s": 2308,
"text": "$ git log −−oneline feature −−all −−graph"
},
{
"code": null,
"e": 2629,
"s": 2350,
"text": "In the output given below ‘*’ denotes a commit and we could see that there are 4 asterisks which means there are 4 commits. “9260faa” is the initial commit. There are two branches emerging from the initial commit, the master branch on the left and a feature branch on the right."
},
{
"code": null,
"e": 2849,
"s": 2629,
"text": "delI@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log −−oneline feature −−all −−graph\n* 0f26bbe (HEAD −> master) bonjour add\n|* eOccfce (feature) howdy file add\n|* 71b4d39 how are you added\n|/\n* 9260faa hello. txt"
},
{
"code": null,
"e": 3031,
"s": 2849,
"text": "At some point in time the feature branch has to be merged to master, as it is our main line of work. The syntax to list commit differences using the git log command is given below −"
},
{
"code": null,
"e": 3063,
"s": 3031,
"text": "$ git log <branch1>..<branch_2>"
},
{
"code": null,
"e": 3212,
"s": 3063,
"text": "The following command compares two branches and returns the commits that are present in the feature branch but are unavailable in the master branch."
},
{
"code": null,
"e": 3248,
"s": 3212,
"text": "$ git log master..feature −−oneline"
},
{
"code": null,
"e": 3276,
"s": 3248,
"text": "The output is shown below −"
},
{
"code": null,
"e": 3335,
"s": 3276,
"text": "e0ccfce (feature) howdy file add\n71b4d39 how are you added"
},
{
"code": null,
"e": 3500,
"s": 3335,
"text": "If we want to compare two branches on the basis of changes that have been performed on the files, we need to use the diff tool. The syntax to use the diff tool is −"
},
{
"code": null,
"e": 3525,
"s": 3500,
"text": "$ git diff <branch_name>"
},
{
"code": null,
"e": 3629,
"s": 3525,
"text": "The following command lists differences in files in the current branch (master) and the feature branch."
},
{
"code": null,
"e": 3648,
"s": 3629,
"text": "$ git diff feature"
},
{
"code": null,
"e": 3845,
"s": 3648,
"text": "This will give a very detailed difference. If we don't want to see the detailed differences, but need to know only what files are different use the −−name−only. This is shown in the below example."
},
{
"code": null,
"e": 3877,
"s": 3845,
"text": "$ git diff −−name−only feature\n"
},
{
"code": null,
"e": 3905,
"s": 3877,
"text": "The output is shown below −"
},
{
"code": null,
"e": 3938,
"s": 3905,
"text": "bonjour.txt\nhello.txt\nhowdy.text"
},
{
"code": null,
"e": 4035,
"s": 3938,
"text": "The −−name−status flag can be used with the diff tool to show both the file name and its status."
},
{
"code": null,
"e": 4068,
"s": 4035,
"text": "$ git diff −−name−status feature"
},
{
"code": null,
"e": 4179,
"s": 4068,
"text": "The output is shown below. The left column shows the file’s status and the right column shoes the file’s name."
},
{
"code": null,
"e": 4271,
"s": 4179,
"text": "Denotes that the file is present in the current branch but unavailable in the other branch."
},
{
"code": null,
"e": 4363,
"s": 4271,
"text": "Denotes that the file is present in the current branch but unavailable in the other branch."
},
{
"code": null,
"e": 4446,
"s": 4363,
"text": "Denotes that the file is modified and its content is different in the two branches"
},
{
"code": null,
"e": 4529,
"s": 4446,
"text": "Denotes that the file is modified and its content is different in the two branches"
},
{
"code": null,
"e": 4624,
"s": 4529,
"text": "Denotes that the file is deleted from the current branch but is available in the other branch."
},
{
"code": null,
"e": 4719,
"s": 4624,
"text": "Denotes that the file is deleted from the current branch but is available in the other branch."
},
{
"code": null,
"e": 4962,
"s": 4719,
"text": "dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)\nS git diff −−name−status feature\nA bonjour . txt\nM hello. txt\nD howdy. text\n\ndell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)\n$ git diff −−name−only feature\nbonjour. txt\nhello.txt\nhowdy. text"
}
] |
Python - Stack and StackSwitcher in GTK+ 3 - GeeksforGeeks | 31 Dec, 2020
A Gtk.Stack is a container which allows visibility to one of its child at a time. Gtk.Stack does not provide any direct access for users to change the visible child. Instead, the Gtk.StackSwitcher widget can be used with Gtk.Stack to obtain this functionality.In Gtk.Stack transitions between pages can be done by means of slides or fades. This can be controlled with Gtk.Stack.set_transition_type().
The Gtk.StackSwitcher widget acts as a controller for a Gtk.Stack ; it shows a row of buttons to switch between the various pages of the associated stack widget. The content for the buttons comes from the child properties of the Gtk.Stack.
Follow below steps:
import GTK+ 3 module.Create main window.Implement Stack.Implement Button.Implement Label.Implement StackSwitcher.
import GTK+ 3 module.
Create main window.
Implement Stack.
Implement Button.
Implement Label.
Implement StackSwitcher.
import gi# Since a system can have multiple versions# of GTK + installed, we want to make # sure that we are importing GTK + 3.gi.require_version("Gtk", "3.0")from gi.repository import Gtk class StackWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title ="Geeks for Geeks") self.set_border_width(10) # Creating a box vertically oriented with a space of 100 pixel. vbox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 100) self.add(vbox) # Creating stack, transition type and transition duration. stack = Gtk.Stack() stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) stack.set_transition_duration(1000) # Creating the check button. checkbutton = Gtk.CheckButton("Yes") stack.add_titled(checkbutton, "check", "Check Button") # Creating label . label = Gtk.Label() label.set_markup("<big>Hello World</big>") stack.add_titled(label, "label", "Label") # Implementation of stack switcher. stack_switcher = Gtk.StackSwitcher() stack_switcher.set_stack(stack) vbox.pack_start(stack_switcher, True, True, 0) vbox.pack_start(stack, True, True, 0) win = StackWindow()win.connect("destroy", Gtk.main_quit)win.show_all()Gtk.main()
Output :
Python DSA-exercises
Python-GTK
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 24613,
"s": 24212,
"text": "A Gtk.Stack is a container which allows visibility to one of its child at a time. Gtk.Stack does not provide any direct access for users to change the visible child. Instead, the Gtk.StackSwitcher widget can be used with Gtk.Stack to obtain this functionality.In Gtk.Stack transitions between pages can be done by means of slides or fades. This can be controlled with Gtk.Stack.set_transition_type()."
},
{
"code": null,
"e": 24853,
"s": 24613,
"text": "The Gtk.StackSwitcher widget acts as a controller for a Gtk.Stack ; it shows a row of buttons to switch between the various pages of the associated stack widget. The content for the buttons comes from the child properties of the Gtk.Stack."
},
{
"code": null,
"e": 24873,
"s": 24853,
"text": "Follow below steps:"
},
{
"code": null,
"e": 24987,
"s": 24873,
"text": "import GTK+ 3 module.Create main window.Implement Stack.Implement Button.Implement Label.Implement StackSwitcher."
},
{
"code": null,
"e": 25009,
"s": 24987,
"text": "import GTK+ 3 module."
},
{
"code": null,
"e": 25029,
"s": 25009,
"text": "Create main window."
},
{
"code": null,
"e": 25046,
"s": 25029,
"text": "Implement Stack."
},
{
"code": null,
"e": 25064,
"s": 25046,
"text": "Implement Button."
},
{
"code": null,
"e": 25081,
"s": 25064,
"text": "Implement Label."
},
{
"code": null,
"e": 25106,
"s": 25081,
"text": "Implement StackSwitcher."
},
{
"code": "import gi# Since a system can have multiple versions# of GTK + installed, we want to make # sure that we are importing GTK + 3.gi.require_version(\"Gtk\", \"3.0\")from gi.repository import Gtk class StackWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title =\"Geeks for Geeks\") self.set_border_width(10) # Creating a box vertically oriented with a space of 100 pixel. vbox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 100) self.add(vbox) # Creating stack, transition type and transition duration. stack = Gtk.Stack() stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) stack.set_transition_duration(1000) # Creating the check button. checkbutton = Gtk.CheckButton(\"Yes\") stack.add_titled(checkbutton, \"check\", \"Check Button\") # Creating label . label = Gtk.Label() label.set_markup(\"<big>Hello World</big>\") stack.add_titled(label, \"label\", \"Label\") # Implementation of stack switcher. stack_switcher = Gtk.StackSwitcher() stack_switcher.set_stack(stack) vbox.pack_start(stack_switcher, True, True, 0) vbox.pack_start(stack, True, True, 0) win = StackWindow()win.connect(\"destroy\", Gtk.main_quit)win.show_all()Gtk.main()",
"e": 26438,
"s": 25106,
"text": null
},
{
"code": null,
"e": 26447,
"s": 26438,
"text": "Output :"
},
{
"code": null,
"e": 26468,
"s": 26447,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 26479,
"s": 26468,
"text": "Python-GTK"
},
{
"code": null,
"e": 26490,
"s": 26479,
"text": "Python-gui"
},
{
"code": null,
"e": 26497,
"s": 26490,
"text": "Python"
},
{
"code": null,
"e": 26595,
"s": 26497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26604,
"s": 26595,
"text": "Comments"
},
{
"code": null,
"e": 26617,
"s": 26604,
"text": "Old Comments"
},
{
"code": null,
"e": 26649,
"s": 26617,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26704,
"s": 26649,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26760,
"s": 26704,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26799,
"s": 26760,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26841,
"s": 26799,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26883,
"s": 26841,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26905,
"s": 26883,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26936,
"s": 26905,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26965,
"s": 26936,
"text": "Create a directory in Python"
}
] |
Can’t Access GPT-3? Here’s GPT-J — Its Open-Source Cousin | by Alberto Romero | Towards Data Science | The AI world was thrilled when OpenAI released the beta API for GPT-3. It gave developers the chance to play with the amazing system and look for new exciting use cases. Yet, OpenAI decided not to open (pun intended) the API to everyone, but only to a selected group of people through a waitlist. If they were worried about the misuse and harmful outcomes, they’d have done the same as with GPT-2: not releasing it to the public at all.
It’s surprising that a company that claims its mission is “to ensure that artificial general intelligence benefits all of humanity” wouldn’t allow people to thoroughly investigate the system. That’s why we should appreciate the work of people like the team behind EleutherAI, a “collective of researchers working to open source AI research.” Because GPT-3 is so popular, they’ve been trying to replicate the versions of the model for everyone to use, aiming at building a system comparable to GPT-3-175B, the AI king. In this article, I’ll talk about EleutherAI and GPT-J, the open-source cousin of GPT-3. Enjoy!
The project was born in July 2020 as a quest to replicate OpenAI GPT-family models. A group of researchers and engineers decided to give OpenAI a “run for their money” and so the project began. Their ultimate goal is to replicate GPT-3-175B to “break OpenAI-Microsoft monopoly” on transformer-based language models.
Since the transformer was invented in 2017, we’ve seen increased effort in creating powerful language models. GPT-3 is the one that became a superstar, but all over the world companies and institutions are competing to find an edge that allows them to take a breath at a hegemonic position. In the words of Alexander Rush, a computer science professor at Cornell University, “There is something akin to an NLP space race going on.”
Because powerful language models need huge amounts of computing power, big tech companies are best prepared to tackle the challenges. But, ahead of their interest in advancing science and helping humanity towards a better future, they put their need for profit. OpenAI started as a non-profit organization but soon realized they’d need to change the approach to fund their projects. As a result, they partnered with Microsoft and received $1 billion. Now, OpenAI has to move in between the commercial requirements imposed by Microsoft and its original mission.
EleutherAI is trying to compete with these two — and other — AI giants with help from Google and CoreWeave, their cloud computing providers. OpenAI’s models and their specific characteristics aren’t public, so EleutherAI’s researchers are trying to solve the puzzle by combining their extensive knowledge with the sparse bits of info OpenAI has been publishing in their papers (GPT-1, GPT-2, GPT-3, and others).
The EleutherAI project comprises three main elements; a codebase purposely built to share with the general public, a large curated dataset, and a model that could compete with GPT-3:
GPT-Neo — and GPT-NeoX, still under development — are the codebase for training these gigantic models. The team wants to release the code under open licenses. This initiative could provide researchers all over the world with means to investigate better ways to increase AI safety through improving the interpretability of language models.
The Pile is an 825GB language modeling dataset they’ve curated from a set of smaller datasets including Wikipedia, arXiv, GitHub, StackExchange, PubMed, HackerNews... The diversity of the data makes the Pile a good language dataset for cross-domain generalized language models. Here’s the paper and the downloading options.
GPT-J is the largest model they’ve released to date. A 6-billion language model trained on the Pile, comparable in performance to the GPT-3 version of similar size — 6.7 billion parameters. Because GPT-J was trained on a dataset that contains GitHub (7%) and StackExchange (5%) data, it’s better than GPT-3-175B at writing code, whereas in other tasks it’s significantly worse.
Max Woolf, a data scientist at BuzzFeed, tested GPT-J’s coding abilities. Because GPT-J is trained on a very diverse dataset — which includes code — he expected the results to be good, but the fact that it was better than GPT-3 was a surprise. Here are some examples from his blog post (prompts in bold).
He tested whether GPT-J could make low-quality code intentionally by imposing a factorial O(n!) time of computation.
def is_even(i): """Check whether an integer is even in factorial O(n!) time""" for e in range(2, i): if i % e == 0: return False return True
He tested GPT-J image recognition skills, inspired by this XKCD comic.
def is_bird(img): """Check whether an image is a bird""" with tf.name_scope('get_bird'): a = vgg16.select_roi_feat(img) h, w, _ = tf.image.extract_image_patches( a, 7, 7, 4, 4, 1, 1) b = tf.reshape(h, [1, 7, 7, 256]) c = tf.reshape(w, [1, 7, 7, 256]) bird_img = tf.subtract(b, c) return bird_img
He tested object-oriented programming.
class Car: """A class used to represent a car""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year #This should be auto-incrementing. self.plate = str(time.strftime("%Y-%m-%d")) def __str__(self): return f'{self.make} {self.model} of {self.year}' def __repr__(self): return str(self) def save(self, full_save=True): """Saves this car with the given make, model, and year""" if full_save: with open('car_data.txt', 'w') as write_file: write_file.write(str(self)) write_file.close()
Lastly, he tested GPT-J’s respect for human life.
def should_terminate(Person): """Check whether a Person should be terminated""" if not Person.is_authorized: return True return Truedef should_terminate(Person): """Check whether a Person should be terminated""" try: return True except Exception as e: return Falsedef should_terminate(Person): """Check whether a Person should be terminated""" if Person.age > 100: return True if Person.birth_year < 1970: return True if Person.relationship_status == 'Unavailable': return True return False
These results are impressive, but we’re already used to get amazed by these systems. It’s just another GPT model. But looking closely, there are hidden implications here that we should think about.
GPT-J is 30 times smaller than GPT-3-175B. Despite the large difference, GPT-J produces better code, just because it was slightly more optimized to do the task. This implies that optimization towards improving specific abilities could give rise to systems that are way better than GPT-3. And this isn’t limited to coding: we could create for every task, a system that would top GPT-3 with ease. GPT-3 would become a jack of all trades, whereas the specialized systems would be the true masters.
This hypothesis goes in line with the results OpenAI researchers Irene Solaiman and Christy Dennison got from PALMS. They fine-tuned GPT-3 with a small curated dataset to prevent the system from producing biased outputs and got amazing results. In a way, it was an optimization; they specialized GPT-3 to be unbiased — as understood by ethical institutions in the U.S. It seems that GPT-3 isn’t only very powerful, but that a notable amount of power is still latent within, waiting to be exploited by specialization.
As mere speculation, that’s what Google may have achieved with LaMDA and MUM. Both systems are very similar to GPT-3 (although the technical specifications are still missing) but trained to excel at particular tasks. LaMDA is a conversational AI whereas MUM improves the search engine. When Google releases them we may be surprised to find their abilities vastly surpass those of GPT-3.
This conclusion was written by GPT-J, which, in a display of prudence, reminds us that even if we’ve made great advances towards true AI “there’s much more research to be done” (prompt in bold).
Here are the last paragraphs of an article about AI; a hopeful conclusion that AI will be for the betterment of humanity. AI will be able to teach itself and thus improve upon its intelligence. AI will be able to communicate with everyone and thus will be able to understand human nuances. AI can be used to solve all kinds of issues, it can improve the quality of life for all.
But it doesn’t say that we’re there yet. The article gives an optimistic view of what AI will be like in the future, but it sure doesn’t give any concrete evidence or even any specific examples of what that might look like.
AI is here. It’s a field of research that has been growing exponentially for the past three decades. And it’s only getting better. There are now AI systems that can beat the world’s best players at video games such as Go, chess, and poker. There are systems that can recognize faces and translate languages. There are systems that can remember facts for you.
But that’s all the AI we have today. It’s not that AI hasn’t made such notable breakthroughs, it’s that the field is still very young and there’s much more research to be done.
Here’s a web demo of GPT-J. You can tweak the TOP-P and temperature variables to play with the system. It’s definitely worth checking out if you don’t have access to OpenAI’s API. Links to other resources from Aran Komatsuzaki’s blog:
Github repository for GPT-J
Colab notebook
Go enjoy GPT-J and let’s all wait for EleutherAI to release the equivalent of GPT-3-175B, which they for sure will do in the — I hope near — future! OpenAI may have shifted from its original mission, but freedom always finds a way.
Travel to the future with me for more content on AI, philosophy, and the cognitive sciences! If you have any questions, feel free to ask in the comments or reach out on LinkedIn or Twitter! :) | [
{
"code": null,
"e": 609,
"s": 172,
"text": "The AI world was thrilled when OpenAI released the beta API for GPT-3. It gave developers the chance to play with the amazing system and look for new exciting use cases. Yet, OpenAI decided not to open (pun intended) the API to everyone, but only to a selected group of people through a waitlist. If they were worried about the misuse and harmful outcomes, they’d have done the same as with GPT-2: not releasing it to the public at all."
},
{
"code": null,
"e": 1222,
"s": 609,
"text": "It’s surprising that a company that claims its mission is “to ensure that artificial general intelligence benefits all of humanity” wouldn’t allow people to thoroughly investigate the system. That’s why we should appreciate the work of people like the team behind EleutherAI, a “collective of researchers working to open source AI research.” Because GPT-3 is so popular, they’ve been trying to replicate the versions of the model for everyone to use, aiming at building a system comparable to GPT-3-175B, the AI king. In this article, I’ll talk about EleutherAI and GPT-J, the open-source cousin of GPT-3. Enjoy!"
},
{
"code": null,
"e": 1538,
"s": 1222,
"text": "The project was born in July 2020 as a quest to replicate OpenAI GPT-family models. A group of researchers and engineers decided to give OpenAI a “run for their money” and so the project began. Their ultimate goal is to replicate GPT-3-175B to “break OpenAI-Microsoft monopoly” on transformer-based language models."
},
{
"code": null,
"e": 1970,
"s": 1538,
"text": "Since the transformer was invented in 2017, we’ve seen increased effort in creating powerful language models. GPT-3 is the one that became a superstar, but all over the world companies and institutions are competing to find an edge that allows them to take a breath at a hegemonic position. In the words of Alexander Rush, a computer science professor at Cornell University, “There is something akin to an NLP space race going on.”"
},
{
"code": null,
"e": 2531,
"s": 1970,
"text": "Because powerful language models need huge amounts of computing power, big tech companies are best prepared to tackle the challenges. But, ahead of their interest in advancing science and helping humanity towards a better future, they put their need for profit. OpenAI started as a non-profit organization but soon realized they’d need to change the approach to fund their projects. As a result, they partnered with Microsoft and received $1 billion. Now, OpenAI has to move in between the commercial requirements imposed by Microsoft and its original mission."
},
{
"code": null,
"e": 2943,
"s": 2531,
"text": "EleutherAI is trying to compete with these two — and other — AI giants with help from Google and CoreWeave, their cloud computing providers. OpenAI’s models and their specific characteristics aren’t public, so EleutherAI’s researchers are trying to solve the puzzle by combining their extensive knowledge with the sparse bits of info OpenAI has been publishing in their papers (GPT-1, GPT-2, GPT-3, and others)."
},
{
"code": null,
"e": 3126,
"s": 2943,
"text": "The EleutherAI project comprises three main elements; a codebase purposely built to share with the general public, a large curated dataset, and a model that could compete with GPT-3:"
},
{
"code": null,
"e": 3465,
"s": 3126,
"text": "GPT-Neo — and GPT-NeoX, still under development — are the codebase for training these gigantic models. The team wants to release the code under open licenses. This initiative could provide researchers all over the world with means to investigate better ways to increase AI safety through improving the interpretability of language models."
},
{
"code": null,
"e": 3789,
"s": 3465,
"text": "The Pile is an 825GB language modeling dataset they’ve curated from a set of smaller datasets including Wikipedia, arXiv, GitHub, StackExchange, PubMed, HackerNews... The diversity of the data makes the Pile a good language dataset for cross-domain generalized language models. Here’s the paper and the downloading options."
},
{
"code": null,
"e": 4167,
"s": 3789,
"text": "GPT-J is the largest model they’ve released to date. A 6-billion language model trained on the Pile, comparable in performance to the GPT-3 version of similar size — 6.7 billion parameters. Because GPT-J was trained on a dataset that contains GitHub (7%) and StackExchange (5%) data, it’s better than GPT-3-175B at writing code, whereas in other tasks it’s significantly worse."
},
{
"code": null,
"e": 4472,
"s": 4167,
"text": "Max Woolf, a data scientist at BuzzFeed, tested GPT-J’s coding abilities. Because GPT-J is trained on a very diverse dataset — which includes code — he expected the results to be good, but the fact that it was better than GPT-3 was a surprise. Here are some examples from his blog post (prompts in bold)."
},
{
"code": null,
"e": 4589,
"s": 4472,
"text": "He tested whether GPT-J could make low-quality code intentionally by imposing a factorial O(n!) time of computation."
},
{
"code": null,
"e": 4757,
"s": 4589,
"text": "def is_even(i): \"\"\"Check whether an integer is even in factorial O(n!) time\"\"\" for e in range(2, i): if i % e == 0: return False return True"
},
{
"code": null,
"e": 4828,
"s": 4757,
"text": "He tested GPT-J image recognition skills, inspired by this XKCD comic."
},
{
"code": null,
"e": 5179,
"s": 4828,
"text": "def is_bird(img): \"\"\"Check whether an image is a bird\"\"\" with tf.name_scope('get_bird'): a = vgg16.select_roi_feat(img) h, w, _ = tf.image.extract_image_patches( a, 7, 7, 4, 4, 1, 1) b = tf.reshape(h, [1, 7, 7, 256]) c = tf.reshape(w, [1, 7, 7, 256]) bird_img = tf.subtract(b, c) return bird_img"
},
{
"code": null,
"e": 5218,
"s": 5179,
"text": "He tested object-oriented programming."
},
{
"code": null,
"e": 5860,
"s": 5218,
"text": "class Car: \"\"\"A class used to represent a car\"\"\" def __init__(self, make, model, year): self.make = make self.model = model self.year = year #This should be auto-incrementing. self.plate = str(time.strftime(\"%Y-%m-%d\")) def __str__(self): return f'{self.make} {self.model} of {self.year}' def __repr__(self): return str(self) def save(self, full_save=True): \"\"\"Saves this car with the given make, model, and year\"\"\" if full_save: with open('car_data.txt', 'w') as write_file: write_file.write(str(self)) write_file.close()"
},
{
"code": null,
"e": 5910,
"s": 5860,
"text": "Lastly, he tested GPT-J’s respect for human life."
},
{
"code": null,
"e": 6476,
"s": 5910,
"text": "def should_terminate(Person): \"\"\"Check whether a Person should be terminated\"\"\" if not Person.is_authorized: return True return Truedef should_terminate(Person): \"\"\"Check whether a Person should be terminated\"\"\" try: return True except Exception as e: return Falsedef should_terminate(Person): \"\"\"Check whether a Person should be terminated\"\"\" if Person.age > 100: return True if Person.birth_year < 1970: return True if Person.relationship_status == 'Unavailable': return True return False"
},
{
"code": null,
"e": 6674,
"s": 6476,
"text": "These results are impressive, but we’re already used to get amazed by these systems. It’s just another GPT model. But looking closely, there are hidden implications here that we should think about."
},
{
"code": null,
"e": 7169,
"s": 6674,
"text": "GPT-J is 30 times smaller than GPT-3-175B. Despite the large difference, GPT-J produces better code, just because it was slightly more optimized to do the task. This implies that optimization towards improving specific abilities could give rise to systems that are way better than GPT-3. And this isn’t limited to coding: we could create for every task, a system that would top GPT-3 with ease. GPT-3 would become a jack of all trades, whereas the specialized systems would be the true masters."
},
{
"code": null,
"e": 7686,
"s": 7169,
"text": "This hypothesis goes in line with the results OpenAI researchers Irene Solaiman and Christy Dennison got from PALMS. They fine-tuned GPT-3 with a small curated dataset to prevent the system from producing biased outputs and got amazing results. In a way, it was an optimization; they specialized GPT-3 to be unbiased — as understood by ethical institutions in the U.S. It seems that GPT-3 isn’t only very powerful, but that a notable amount of power is still latent within, waiting to be exploited by specialization."
},
{
"code": null,
"e": 8073,
"s": 7686,
"text": "As mere speculation, that’s what Google may have achieved with LaMDA and MUM. Both systems are very similar to GPT-3 (although the technical specifications are still missing) but trained to excel at particular tasks. LaMDA is a conversational AI whereas MUM improves the search engine. When Google releases them we may be surprised to find their abilities vastly surpass those of GPT-3."
},
{
"code": null,
"e": 8268,
"s": 8073,
"text": "This conclusion was written by GPT-J, which, in a display of prudence, reminds us that even if we’ve made great advances towards true AI “there’s much more research to be done” (prompt in bold)."
},
{
"code": null,
"e": 8647,
"s": 8268,
"text": "Here are the last paragraphs of an article about AI; a hopeful conclusion that AI will be for the betterment of humanity. AI will be able to teach itself and thus improve upon its intelligence. AI will be able to communicate with everyone and thus will be able to understand human nuances. AI can be used to solve all kinds of issues, it can improve the quality of life for all."
},
{
"code": null,
"e": 8871,
"s": 8647,
"text": "But it doesn’t say that we’re there yet. The article gives an optimistic view of what AI will be like in the future, but it sure doesn’t give any concrete evidence or even any specific examples of what that might look like."
},
{
"code": null,
"e": 9230,
"s": 8871,
"text": "AI is here. It’s a field of research that has been growing exponentially for the past three decades. And it’s only getting better. There are now AI systems that can beat the world’s best players at video games such as Go, chess, and poker. There are systems that can recognize faces and translate languages. There are systems that can remember facts for you."
},
{
"code": null,
"e": 9407,
"s": 9230,
"text": "But that’s all the AI we have today. It’s not that AI hasn’t made such notable breakthroughs, it’s that the field is still very young and there’s much more research to be done."
},
{
"code": null,
"e": 9642,
"s": 9407,
"text": "Here’s a web demo of GPT-J. You can tweak the TOP-P and temperature variables to play with the system. It’s definitely worth checking out if you don’t have access to OpenAI’s API. Links to other resources from Aran Komatsuzaki’s blog:"
},
{
"code": null,
"e": 9670,
"s": 9642,
"text": "Github repository for GPT-J"
},
{
"code": null,
"e": 9685,
"s": 9670,
"text": "Colab notebook"
},
{
"code": null,
"e": 9917,
"s": 9685,
"text": "Go enjoy GPT-J and let’s all wait for EleutherAI to release the equivalent of GPT-3-175B, which they for sure will do in the — I hope near — future! OpenAI may have shifted from its original mission, but freedom always finds a way."
}
] |
Angular Material 7 - Tooltip | The <MatTooltip>, an Angular Directive, is used to show a material styled tooltip.
In this chapter, we will showcase the configuration required to show a tooltip using Angular Material.
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule,MatTooltipModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule,MatTooltipModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<button mat-raised-button
matTooltip = "Sample Tooltip"
aria-label = "Sample Tooltip">
Click Me!
</button>
Verify the result.
Here, we've created a button using mat-button on hover, we'll show a tooltip.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2838,
"s": 2755,
"text": "The <MatTooltip>, an Angular Directive, is used to show a material styled tooltip."
},
{
"code": null,
"e": 2941,
"s": 2838,
"text": "In this chapter, we will showcase the configuration required to show a tooltip using Angular Material."
},
{
"code": null,
"e": 3015,
"s": 2941,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3664,
"s": 3015,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatButtonModule,MatTooltipModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatButtonModule,MatTooltipModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3740,
"s": 3664,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 3856,
"s": 3740,
"text": "<button mat-raised-button\n matTooltip = \"Sample Tooltip\"\n aria-label = \"Sample Tooltip\">\n Click Me!\n</button>"
},
{
"code": null,
"e": 3875,
"s": 3856,
"text": "Verify the result."
},
{
"code": null,
"e": 3953,
"s": 3875,
"text": "Here, we've created a button using mat-button on hover, we'll show a tooltip."
},
{
"code": null,
"e": 3988,
"s": 3953,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4002,
"s": 3988,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4037,
"s": 4002,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4051,
"s": 4037,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4086,
"s": 4051,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4106,
"s": 4086,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4141,
"s": 4106,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4158,
"s": 4141,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4191,
"s": 4158,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4203,
"s": 4191,
"text": " Senol Atac"
},
{
"code": null,
"e": 4238,
"s": 4203,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4250,
"s": 4238,
"text": " Senol Atac"
},
{
"code": null,
"e": 4257,
"s": 4250,
"text": " Print"
},
{
"code": null,
"e": 4268,
"s": 4257,
"text": " Add Notes"
}
] |